text:
package water.api;

import hex.Model;
import water.*;
import water.exceptions.H2OIllegalArgumentException;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.ReflectionUtils;

import java.lang.reflect.Constructor;
import java.util.Arrays;

/**
 *

 * Base Schema Class for Keys.  Note that Key schemas are generally typed by the type of
 * object they point to (e.g., the front something like a Key<Frame>).
 *

 * The type parameters are a bit subtle, because we have several schemas that map to Key,
 * by type.  We want to be parameterized by the type of Keyed that we point to, but the
 * Iced type we pass up to Schema must be Iced, so that a lookup for a Schema for Key<T>
 * doesn't get an arbitrary subclass of KeyV1.
 */
public class KeyV3<I extends Iced, S extends KeyV3, K extends Keyed> extends Schema {
  @API(help="Name (string representation) for this Key.", direction = API.Direction.INOUT)
  public String name;

  @API(help="Name (string representation) for the type of Keyed this Key points to.", direction = API.Direction.INOUT)
  public String type;

  @API(help="URL for the resource that this Key points to, if one exists.", direction = API.Direction.INOUT)
  public String URL;

  public KeyV3() {
    __meta.schema_type = "Key<" + getKeyedClassType() + ">";
  }

  // need versioned
  public KeyV3(Key key) {
    this();
    if (null != key) {
      Class clz = getKeyedClass();
      Value v = DKV.get(key);

      if (null != v) {
        // Type checking of value from DKV
        if (Job.class.isAssignableFrom(clz) && !v.isJob())
          throw new H2OIllegalArgumentException("For Key: " + key + " expected a value of type Job; found a: " + v.theFreezableClass(), "For Key: " + key + " expected a value of type Job; found a: " + v.theFreezableClass() + " (" + clz + ")");
        else if (Frame.class.isAssignableFrom(clz) && !v.isFrame() && !v.isVec())
        // NOTE: we currently allow Vecs to be fetched via the /Frames endpoint, so this constraint is relaxed accordingly.  Note this means that if the user gets hold of a (hidden) Vec key and passes it to some other endpoint they will get an ugly error instead of an H2OIllegalArgumentException.
          throw new H2OIllegalArgumentException("For Key: " + key + " expected a value of type Frame; found a: " + v.theFreezableClass(), "For Key: " + key + " expected a value of type Frame; found a: " + v.theFreezableClass() + " (" + clz + ")");
        else if (Model.class.isAssignableFrom(clz) && !v.isModel())
          throw new H2OIllegalArgumentException("For Key: " + key + " expected a value of type Model; found a: " + v.theFreezableClass(), "For Key: " + key + " expected a value of type Model; found a: " + v.theFreezableClass() + " (" + clz + ")");
        else if (Vec.class.isAssignableFrom(clz) && !v.isVec())
          throw new H2OIllegalArgumentException("For Key: " + key + " expected a value of type Vec; found a: " + v.theFreezableClass(), "For Key: " + key + " expected a value of type Vec; found a: " + v.theFreezableClass() + " (" + clz + ")");
      }

      this.fillFromImpl(key);
    }
  }

  public static KeyV3 make(Class<? extends KeyV3> clz, Key key) {
    KeyV3 result = null;
    try {
      Constructor c = clz.getConstructor(Key.class);
      result = (KeyV3)c.newInstance(key);
    }
    catch (Exception e) {
      throw new H2OIllegalArgumentException("Caught exception trying to instantiate KeyV1 for class: " + clz.toString() + ": " + e + "; cause: " + e.getCause() + " " + Arrays.toString(e.getCause().getStackTrace()));
    }
    return result;
  }

  /** TODO: figure out the right KeyV1 class from the Key, so the type is set properly. */
  public static KeyV3 make(Key key) {
    return make(KeyV3.class, key);
  }

  /** Factory method which returns the correct KeyV1 for the given Keyed class (e.g., for Frame.class). */
  public static KeyV3 forKeyedClass(Class<? extends Keyed> keyed_class, Key key) {
    if (Job.class.isAssignableFrom(keyed_class))
      return KeyV3.make(JobKeyV3.class, key);
    else if (Frame.class.isAssignableFrom(keyed_class))
      return KeyV3.make(FrameKeyV3.class, key);
    else if (Model.class.isAssignableFrom(keyed_class))
      return KeyV3.make(ModelKeyV3.class, key);
    else if (Vec.class.isAssignableFrom(keyed_class))
      return KeyV3.make(VecKeyV3.class, key);
    else
      return KeyV3.make(KeyV3.class, key);
  }

  public static class JobKeyV3 extends KeyV3<Iced, JobKeyV3, Job> {
    public JobKeyV3() {}
    public JobKeyV3(Key<Job> key) {
      super(key);
    }
  }

  public static class FrameKeyV3 extends KeyV3<Iced, FrameKeyV3, Frame> {
    public FrameKeyV3() {}
    public FrameKeyV3(Key<Frame> key) { super(key); }
  }

  public static class ModelKeyV3 extends KeyV3<Iced, ModelKeyV3, Model> {
    public ModelKeyV3() {}
    public ModelKeyV3(Key<? extends Model> key) {
      super(key);
    }
  }

  public static class VecKeyV3 extends KeyV3<Iced, VecKeyV3, Vec> {
    public VecKeyV3() {
    }

    public VecKeyV3(Key<Vec> key) {
      super(key);
    }
  }

  @Override
  public S fillFromImpl(Iced i) {
    if (! (i instanceof Key))
      throw new H2OIllegalArgumentException("fillFromImpl", "key", i);

    Key key = (Key)i;

    if (null == key) return (S)this;

    this.name = key.toString();

    // Our type is generally determined by our type parameter, but some APIs use raw untyped KeyV1s to return multiple types.
    this.type = "Key<" + this.getKeyedClassType() + ">";

    if ("Keyed".equals(this.type)) {
      // get the actual type, if the key points to a value in the DKV
      String vc = key.valueClassSimple();
      if (null != vc) {
        this.type = "Key<" + vc + ">";
      }
    }

    Class<? extends Keyed> keyed_class = this.getKeyedClass();

    // TODO: this is kinda hackey; the handlers should register the types they can fetch.
    if (Job.class.isAssignableFrom(keyed_class))
      this.URL = "/" + Schema.getHighestSupportedVersion() + "/Jobs/" + key.toString();
    else if (Frame.class.isAssignableFrom(keyed_class))
      this.URL = "/" + Schema.getHighestSupportedVersion() + "/Frames/" + key.toString();
    else if (Model.class.isAssignableFrom(keyed_class))
      this.URL = "/" + Schema.getHighestSupportedVersion() + "/Models/" + key.toString();
    else if (Vec.class.isAssignableFrom(keyed_class))
      this.URL = null;
    else
      this.URL = null;

    return (S)this;
  }

  public static Class<? extends Keyed> getKeyedClass(Class<? extends KeyV3> clz) {
    // (Only) if we're a subclass of KeyV1 the Keyed class is type parameter 2.
    if (clz == KeyV3.class)
      return Keyed.class;
    return (Class<? extends Keyed>) ReflectionUtils.findActualClassParameter(clz, 2);
  }

  public Class<? extends Keyed> getKeyedClass() {
    return getKeyedClass(this.getClass());
  }

  public static String getKeyedClassType(Class<? extends KeyV3> clz) {
    Class<? extends Keyed> keyed_class = getKeyedClass(clz);
    return keyed_class.getSimpleName();
  }

  public String getKeyedClassType() {
    return getKeyedClassType(this.getClass());
  }

  public Key<K> key() {
    if (null == name) return null;

    return Key.make(this.name);
  }

  @Override public I createImpl() {
    return (I)Key.make(this.name);
  }

  @Override
  public String toString() {
    return type + " " + name;
  }
}


text:
<!DOCTYPE HTML>
<html>
<head>
    <title>Example</title>
    <script type="text/javascript">

        var myData = {
            name: "Adam",
        };

        console.log("Var: " + myData.weather);
        console.log("Prop: " + ("weather" in myData));

        myData.weather = "sunny";
        console.log("Var: " + myData.weather);
        console.log("Prop: " + ("weather" in myData));

        myData.weather = null;
        console.log("Var: " + myData.weather);
        console.log("Prop: " + ("weather" in myData));

    </script>
</head>
<body>
    This is a simple example
</body>
</html>

redpajama_set_name: RedPajamaGithub


text:
	<form class="validated-form container-fluid form wrapper col-md-10 col-md-offset-1" novalidate name="registration">

User Registration

			Username:
			<input class="form-control" id="username" name="username" type="text" data-ng-model="user.username" required/>

                Required.

			Password:
			<input class="form-control" id="password" type="password" name="password" data-ng-model="user.password" data-minlength="2" maxlength="100" required />

                Required.
                Password must be in range [2;100]

			Confimr Password:
			<input class="form-control" id="confirm-password" name="confirmPassword" type="password" data-ng-model="user.confirmPassword" required data-compare-to="user.password"/>

                Required.
                Password doesn't match!

			Name:
			<input class="form-control" id="name" name="name" type="text" data-ng-model="user.name" required />

                Required.

			Email:
			<input class="form-control" id="mail" name="email" type="email" data-ng-model="user.email" required />

                Required.
                Invaild email!

			Phone:
			<input class="form-control" id="phone" type="text" data-ng-model="user.phone" />

			Town:
            <select class="form-control" id="town" data-ng-model="user.townId">
                <option data-ng-repeat="town in towns" value="{{town.id}}">{{town.name}}</option>
            </select>

			<button data-ng-click="register()" data-ng-disabled="!registration.$valid" class="pull-left btn btn-default">Register</button>
			Login here

	</form>


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

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.

=cut

package EnsEMBL::Web::ViewConfig::Regulation::Evidence;

use strict;
use warnings;

use parent qw(EnsEMBL::Web::ViewConfig::RegulationPage);

sub init_cacheable {
  ## Abstract method implementation
  my $self = shift;

  $self->image_config_type('reg_summary');
  $self->set_default_options({'show_bottom_panel' => 'yes'});
  $self->title('Cell types');
}

sub field_order {
  ## Abstract method implementation
  ## No fields
}

1;


text:
.class public Lcom/mediatek/phone/recording/Recorder;
.super Ljava/lang/Object;
.source "Recorder.java"

# interfaces
.implements Landroid/media/MediaRecorder$OnErrorListener;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;
    }
.end annotation

# static fields
.field public static final IDLE_STATE:I = 0x0

.field public static final INTERNAL_ERROR:I = 0x2

.field public static final NO_ERROR:I = 0x0

.field public static final RECORDING_STATE:I = 0x1

.field static final SAMPLE_LENGTH_KEY:Ljava/lang/String; = "sample_length"

.field static final SAMPLE_PATH_KEY:Ljava/lang/String; = "sample_path"

.field static final SAMPLE_PREFIX:Ljava/lang/String; = "recording"

.field public static final SDCARD_ACCESS_ERROR:I = 0x1

.field private static final TAG:Ljava/lang/String; = "Recorder"

# instance fields
.field mOnStateChangedListener:Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;

.field mRecorder:Landroid/media/MediaRecorder;

.field mSampleFile:Ljava/io/File;

.field mSampleLength:J

.field mSampleStart:J

.field mState:I

# direct methods
.method public constructor <init>()V
    .locals 1

    .prologue
    .line 88
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 64
    const/4 v0, 0x0

    iput v0, p0, Lcom/mediatek/phone/recording/Recorder;->mState:I

    .line 89
    return-void
.end method

.method private setError(I)V
    .locals 1
    .parameter "error"

    .prologue
    .line 316
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mOnStateChangedListener:Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;

    if-eqz v0, :cond_0

    .line 317
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mOnStateChangedListener:Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;

    invoke-interface {v0, p1}, Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;->onError(I)V

    .line 319
    :cond_0
    return-void
.end method

.method private setState(I)V
    .locals 1
    .parameter "state"

    .prologue
    .line 294
    iget v0, p0, Lcom/mediatek/phone/recording/Recorder;->mState:I

    if-ne p1, v0, :cond_0

    .line 299
    :goto_0
    return-void

    .line 297
    :cond_0
    iput p1, p0, Lcom/mediatek/phone/recording/Recorder;->mState:I

    .line 298
    iget v0, p0, Lcom/mediatek/phone/recording/Recorder;->mState:I

    invoke-direct {p0, v0}, Lcom/mediatek/phone/recording/Recorder;->signalStateChanged(I)V

    goto :goto_0
.end method

.method private signalStateChanged(I)V
    .locals 1
    .parameter "state"

    .prologue
    .line 306
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mOnStateChangedListener:Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;

    if-eqz v0, :cond_0

    .line 307
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mOnStateChangedListener:Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;

    invoke-interface {v0, p1}, Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;->onStateChanged(I)V

    .line 309
    :cond_0
    return-void
.end method

# virtual methods
.method public clear()V
    .locals 2

    .prologue
    .line 202
    invoke-virtual {p0}, Lcom/mediatek/phone/recording/Recorder;->stop()V

    .line 204
    const-wide/16 v0, 0x0

    iput-wide v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleLength:J

    .line 206
    const/4 v0, 0x0

    invoke-direct {p0, v0}, Lcom/mediatek/phone/recording/Recorder;->signalStateChanged(I)V

    .line 207
    return-void
.end method

.method public delete()V
    .locals 2

    .prologue
    .line 186
    invoke-virtual {p0}, Lcom/mediatek/phone/recording/Recorder;->stop()V

    .line 188
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    if-eqz v0, :cond_0

    .line 189
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    invoke-virtual {v0}, Ljava/io/File;->delete()Z

    .line 191
    :cond_0
    const/4 v0, 0x0

    iput-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    .line 192
    const-wide/16 v0, 0x0

    iput-wide v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleLength:J

    .line 194
    const/4 v0, 0x0

    invoke-direct {p0, v0}, Lcom/mediatek/phone/recording/Recorder;->signalStateChanged(I)V

    .line 195
    return-void
.end method

.method public getMaxAmplitude()I
    .locals 2

    .prologue
    .line 105
    iget v0, p0, Lcom/mediatek/phone/recording/Recorder;->mState:I

    const/4 v1, 0x1

    if-eq v0, v1, :cond_0

    .line 106
    const/4 v0, 0x0

    .line 108
    :goto_0
    return v0

    :cond_0
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v0}, Landroid/media/MediaRecorder;->getMaxAmplitude()I

    move-result v0

    goto :goto_0
.end method

.method public log(Ljava/lang/String;)V
    .locals 1
    .parameter "msg"

    .prologue
    .line 334
    const-string v0, "Recorder"

    invoke-static {v0, p1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 335
    return-void
.end method

.method public onError(Landroid/media/MediaRecorder;II)V
    .locals 1
    .parameter "mp"
    .parameter "what"
    .parameter "extra"

    .prologue
    .line 325
    const-string v0, "onError"

    invoke-virtual {p0, v0}, Lcom/mediatek/phone/recording/Recorder;->log(Ljava/lang/String;)V

    .line 326
    const/4 v0, 0x1

    if-ne p2, v0, :cond_0

    .line 327
    invoke-virtual {p0}, Lcom/mediatek/phone/recording/Recorder;->stop()V

    .line 330
    :cond_0
    return-void
.end method

.method public progress()I
    .locals 4

    .prologue
    .line 160
    iget v0, p0, Lcom/mediatek/phone/recording/Recorder;->mState:I

    const/4 v1, 0x1

    if-ne v0, v1, :cond_0

    .line 161
    invoke-static {}, Ljava/lang/System;->currentTimeMillis()J

    move-result-wide v0

    iget-wide v2, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleStart:J

    sub-long/2addr v0, v2

    const-wide/16 v2, 0x3e8

    div-long/2addr v0, v2

    long-to-int v0, v0

    .line 163
    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public restoreState(Landroid/os/Bundle;)V
    .locals 7
    .parameter "recorderState"

    .prologue
    const-wide/16 v5, -0x1

    .line 116
    const-string v4, "sample_path"

    invoke-virtual {p1, v4}, Landroid/os/Bundle;->getString(Ljava/lang/String;)Ljava/lang/String;

    move-result-object v3

    .line 117
    .local v3, samplePath:Ljava/lang/String;
    if-nez v3, :cond_1

    .line 137
    :cond_0
    :goto_0
    return-void

    .line 120
    :cond_1
    const-string v4, "sample_length"

    invoke-virtual {p1, v4, v5, v6}, Landroid/os/Bundle;->getLong(Ljava/lang/String;J)J

    move-result-wide v1

    .line 121
    .local v1, sampleLength:J
    cmp-long v4, v1, v5

    if-eqz v4, :cond_0

    .line 124
    new-instance v0, Ljava/io/File;

    invoke-direct {v0, v3}, Ljava/io/File;-><init>(Ljava/lang/String;)V

    .line 125
    .local v0, file:Ljava/io/File;
    invoke-virtual {v0}, Ljava/io/File;->exists()Z

    move-result v4

    if-eqz v4, :cond_0

    .line 128
    iget-object v4, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    if-eqz v4, :cond_2

    iget-object v4, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    invoke-virtual {v4}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v0}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v5

    invoke-virtual {v4, v5}, Ljava/lang/String;->compareTo(Ljava/lang/String;)I

    move-result v4

    if-eqz v4, :cond_0

    .line 132
    :cond_2
    invoke-virtual {p0}, Lcom/mediatek/phone/recording/Recorder;->delete()V

    .line 133
    iput-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    .line 134
    iput-wide v1, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleLength:J

    .line 136
    const/4 v4, 0x0

    invoke-direct {p0, v4}, Lcom/mediatek/phone/recording/Recorder;->signalStateChanged(I)V

    goto :goto_0
.end method

.method public sampleFile()Ljava/io/File;
    .locals 1

    .prologue
    .line 179
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    return-object v0
.end method

.method public sampleLength()J
    .locals 2

    .prologue
    .line 171
    iget-wide v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleLength:J

    return-wide v0
.end method

.method public saveState(Landroid/os/Bundle;)V
    .locals 3
    .parameter "recorderState"

    .prologue
    .line 96
    const-string v0, "sample_path"

    iget-object v1, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    invoke-virtual {v1}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {p1, v0, v1}, Landroid/os/Bundle;->putString(Ljava/lang/String;Ljava/lang/String;)V

    .line 97
    const-string v0, "sample_length"

    iget-wide v1, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleLength:J

    invoke-virtual {p1, v0, v1, v2}, Landroid/os/Bundle;->putLong(Ljava/lang/String;J)V

    .line 98
    return-void
.end method

.method public setOnStateChangedListener(Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;)V
    .locals 0
    .parameter "listener"

    .prologue
    .line 144
    iput-object p1, p0, Lcom/mediatek/phone/recording/Recorder;->mOnStateChangedListener:Lcom/mediatek/phone/recording/Recorder$OnStateChangedListener;

    .line 145
    return-void
.end method

.method public startRecording(ILjava/lang/String;)V
    .locals 10
    .parameter "outputfileformat"
    .parameter "extension"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation

    .prologue
    const/4 v9, 0x1

    .line 216
    const-string v7, "startRecording"

    invoke-virtual {p0, v7}, Lcom/mediatek/phone/recording/Recorder;->log(Ljava/lang/String;)V

    .line 217
    invoke-virtual {p0}, Lcom/mediatek/phone/recording/Recorder;->stop()V

    .line 219
    new-instance v0, Ljava/text/SimpleDateFormat;

    const-string v7, "yyyy-MM-dd_HH.mm.ss"

    invoke-direct {v0, v7}, Ljava/text/SimpleDateFormat;-><init>(Ljava/lang/String;)V

    .line 220
    .local v0, dateFormat:Ljava/text/SimpleDateFormat;
    new-instance v7, Ljava/util/Date;

    invoke-direct {v7}, Ljava/util/Date;-><init>()V

    invoke-virtual {v0, v7}, Ljava/text/SimpleDateFormat;->format(Ljava/util/Date;)Ljava/lang/String;

    move-result-object v3

    .line 221
    .local v3, prefix:Ljava/lang/String;
    invoke-static {}, Lcom/android/phone/PhoneApp;->getInstance()Lcom/android/phone/PhoneApp;

    move-result-object v7

    const-string v8, "storage"

    invoke-virtual {v7, v8}, Lcom/android/phone/PhoneApp;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Landroid/os/storage/StorageManager;

    .line 223
    .local v6, storageManager:Landroid/os/storage/StorageManager;
    if-nez v6, :cond_0

    .line 224
    const-string v7, "-----story manager is null----"

    invoke-virtual {p0, v7}, Lcom/mediatek/phone/recording/Recorder;->log(Ljava/lang/String;)V

    .line 270
    :goto_0
    return-void

    .line 227
    :cond_0
    new-instance v4, Ljava/io/File;

    invoke-static {}, Landroid/os/storage/StorageManager;->getDefaultPath()Ljava/lang/String;

    move-result-object v7

    invoke-direct {v4, v7}, Ljava/io/File;-><init>(Ljava/lang/String;)V

    .line 229
    .local v4, sampleDir:Ljava/io/File;
    invoke-virtual {v4}, Ljava/io/File;->canWrite()Z

    move-result v7

    if-nez v7, :cond_1

    .line 230
    const-string v7, "Recorder"

    const-string v8, "----- file can\'t write!! ---"

    invoke-static {v7, v8}, Landroid/util/Log;->i(Ljava/lang/String;Ljava/lang/String;)I

    .line 232
    new-instance v4, Ljava/io/File;

    .end local v4           #sampleDir:Ljava/io/File;
    const-string v7, "/sdcard/sdcard"

    invoke-direct {v4, v7}, Ljava/io/File;-><init>(Ljava/lang/String;)V

    .line 235
    .restart local v4       #sampleDir:Ljava/io/File;
    :cond_1
    new-instance v5, Ljava/io/File;

    new-instance v7, Ljava/lang/StringBuilder;

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

    invoke-virtual {v4}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v8

    invoke-virtual {v7, v8}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v7

    const-string v8, "/PhoneRecord"

    invoke-virtual {v7, v8}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v7

    invoke-virtual {v7}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v7

    invoke-direct {v5, v7}, Ljava/io/File;-><init>(Ljava/lang/String;)V

    .line 236
    .end local v4           #sampleDir:Ljava/io/File;
    .local v5, sampleDir:Ljava/io/File;
    invoke-virtual {v5}, Ljava/io/File;->exists()Z

    move-result v7

    if-nez v7, :cond_2

    .line 237
    invoke-virtual {v5}, Ljava/io/File;->mkdirs()Z

    .line 241
    :cond_2
    :try_start_0
    invoke-static {v3, p2, v5}, Ljava/io/File;->createTempFile(Ljava/lang/String;Ljava/lang/String;Ljava/io/File;)Ljava/io/File;

    move-result-object v7

    iput-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;
    :try_end_0
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_1

    .line 248
    const-string v7, "finish creating temp file, start to record"

    invoke-virtual {p0, v7}, Lcom/mediatek/phone/recording/Recorder;->log(Ljava/lang/String;)V

    .line 250
    new-instance v7, Landroid/media/MediaRecorder;

    invoke-direct {v7}, Landroid/media/MediaRecorder;-><init>()V

    iput-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    .line 251
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v7, p0}, Landroid/media/MediaRecorder;->setOnErrorListener(Landroid/media/MediaRecorder$OnErrorListener;)V

    .line 252
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v7, v9}, Landroid/media/MediaRecorder;->setAudioSource(I)V

    .line 253
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v7, p1}, Landroid/media/MediaRecorder;->setOutputFormat(I)V

    .line 254
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v7, v9}, Landroid/media/MediaRecorder;->setAudioEncoder(I)V

    .line 255
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    iget-object v8, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleFile:Ljava/io/File;

    invoke-virtual {v8}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;

    move-result-object v8

    invoke-virtual {v7, v8}, Landroid/media/MediaRecorder;->setOutputFile(Ljava/lang/String;)V

    .line 258
    :try_start_1
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v7}, Landroid/media/MediaRecorder;->prepare()V

    .line 259
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v7}, Landroid/media/MediaRecorder;->start()V

    .line 260
    invoke-static {}, Ljava/lang/System;->currentTimeMillis()J

    move-result-wide v7

    iput-wide v7, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleStart:J

    .line 261
    const/4 v7, 0x1

    invoke-direct {p0, v7}, Lcom/mediatek/phone/recording/Recorder;->setState(I)V
    :try_end_1
    .catch Ljava/io/IOException; {:try_start_1 .. :try_end_1} :catch_0

    goto/16 :goto_0

    .line 262
    :catch_0
    move-exception v2

    .line 263
    .local v2, exception:Ljava/io/IOException;
    const-string v7, "startRecording, IOException"

    invoke-virtual {p0, v7}, Lcom/mediatek/phone/recording/Recorder;->log(Ljava/lang/String;)V

    .line 264
    const/4 v7, 0x2

    invoke-direct {p0, v7}, Lcom/mediatek/phone/recording/Recorder;->setError(I)V

    .line 265
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v7}, Landroid/media/MediaRecorder;->reset()V

    .line 266
    iget-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v7}, Landroid/media/MediaRecorder;->release()V

    .line 267
    const/4 v7, 0x0

    iput-object v7, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    .line 268
    throw v2

    .line 242
    .end local v2           #exception:Ljava/io/IOException;
    :catch_1
    move-exception v1

    .line 243
    .local v1, e:Ljava/io/IOException;
    invoke-direct {p0, v9}, Lcom/mediatek/phone/recording/Recorder;->setError(I)V

    .line 244
    const-string v7, "Recorder"

    const-string v8, "----***------- can\'t access sdcard !!"

    invoke-static {v7, v8}, Landroid/util/Log;->i(Ljava/lang/String;Ljava/lang/String;)I

    .line 245
    throw v1
.end method

.method public state()I
    .locals 1

    .prologue
    .line 152
    iget v0, p0, Lcom/mediatek/phone/recording/Recorder;->mState:I

    return v0
.end method

.method public stop()V
    .locals 1

    .prologue
    .line 286
    const-string v0, "stop"

    invoke-virtual {p0, v0}, Lcom/mediatek/phone/recording/Recorder;->log(Ljava/lang/String;)V

    .line 287
    invoke-virtual {p0}, Lcom/mediatek/phone/recording/Recorder;->stopRecording()V

    .line 288
    return-void
.end method

.method public stopRecording()V
    .locals 4

    .prologue
    .line 273
    const-string v0, "stopRecording"

    invoke-virtual {p0, v0}, Lcom/mediatek/phone/recording/Recorder;->log(Ljava/lang/String;)V

    .line 274
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    if-nez v0, :cond_0

    .line 283
    :goto_0
    return-void

    .line 277
    :cond_0
    invoke-static {}, Ljava/lang/System;->currentTimeMillis()J

    move-result-wide v0

    iget-wide v2, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleStart:J

    sub-long/2addr v0, v2

    iput-wide v0, p0, Lcom/mediatek/phone/recording/Recorder;->mSampleLength:J

    .line 278
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v0}, Landroid/media/MediaRecorder;->stop()V

    .line 279
    iget-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    invoke-virtual {v0}, Landroid/media/MediaRecorder;->release()V

    .line 280
    const/4 v0, 0x0

    iput-object v0, p0, Lcom/mediatek/phone/recording/Recorder;->mRecorder:Landroid/media/MediaRecorder;

    .line 282
    const/4 v0, 0x0

    invoke-direct {p0, v0}, Lcom/mediatek/phone/recording/Recorder;->setState(I)V

    goto :goto_0
.end method


text:
package com.rockson.rest;

import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface App extends Rest {

	void set(String name , String value);
	void get(String name);
	void enable(String name );
	boolean enabled(String name );
	void disable(String name );
	boolean disabled(String name );
	void use(Middle middle);
	void use(String path ,Middle middle);
	void use(Pattern pathPattern ,Middle middle);
	void use(String method,String path ,Middle middle);
	void use(String method,Pattern pathPattern ,Middle middle);
	Map<String, Map<String, Handle>> routes();
	void listen();
	void handle(HttpServletRequest request,HttpServletResponse response);

	static final String TrustProx = "trust proxy";

}


text:
layout: post
date:	2011-07-29 08:02:00
title:  The Dreamcatcher
tags: [archived-posts]
categories: archives
permalink: /:categories/:year/:month/:day/:title/
---
In my cousin's car, I found a decoration that I was curious about:

When I asked him about it, he told me that it was an Indian dreamcatcher. That intrigued me, and just now (to avoid the work of unpacking or sorting mail etc) I googled for it, and got

 The Wiki entry about the Dreamcatcher

How lovely is the thought that hanging one above the bed of a child will "catch" the nightmares and prevent the child from being distressed by them! Here's the quotation from American ethnographer

 Frances Densmore  :

"It was said that they "caught any harm that might be in the air as a spider's web catches and holds whatever comes in contact with it."

I wish I could have a Realitycatcher over my bed....I'd be spared a lot of harmful, not-nice reality that I don't want to face! The taxes that I must file, the death of a neighbour, bad health...oh, the Realitycatcher would be saturated soon, I suppose. :)


text:
'use strict';

const models = require('./index');

/**
 * @class
 * Initializes a new instance of the GalleryImage class.
 * @constructor
 * A gallery image.
 *
 * @member {string} [author] The author of the gallery image.
 *
 * @member {date} [createdDate] The creation date of the gallery image.
 *
 * @member {string} [description] The description of the gallery image.
 *
 * @member {object} [imageReference] The image reference of the gallery image.
 *
 * @member {string} [imageReference.offer] The offer of the gallery image.
 *
 * @member {string} [imageReference.publisher] The publisher of the gallery
 * image.
 *
 * @member {string} [imageReference.sku] The SKU of the gallery image.
 *
 * @member {string} [imageReference.osType] The OS type of the gallery image.
 *
 * @member {string} [imageReference.version] The version of the gallery image.
 *
 * @member {string} [icon] The icon of the gallery image.
 *
 * @member {boolean} [enabled] Indicates whether this gallery image is enabled.
 *
 * @member {string} [id] The identifier of the resource.
 *
 * @member {string} [name] The name of the resource.
 *
 * @member {string} [type] The type of the resource.
 *
 * @member {string} [location] The location of the resource.
 *
 * @member {object} [tags] The tags of the resource.
 *
 */
class GalleryImage extends models['BaseResource'] {
  constructor() {
    super();
  }

  /**
   * Defines the metadata of GalleryImage
   *
   * @returns {object} metadata of GalleryImage
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'GalleryImage',
      type: {
        name: 'Composite',
        className: 'GalleryImage',
        modelProperties: {
          author: {
            required: false,
            serializedName: 'properties.author',
            type: {
              name: 'String'
            }
          },
          createdDate: {
            required: false,
            serializedName: 'properties.createdDate',
            type: {
              name: 'DateTime'
            }
          },
          description: {
            required: false,
            serializedName: 'properties.description',
            type: {
              name: 'String'
            }
          },
          imageReference: {
            required: false,
            serializedName: 'properties.imageReference',
            type: {
              name: 'Composite',
              className: 'GalleryImageReference'
            }
          },
          icon: {
            required: false,
            serializedName: 'properties.icon',
            type: {
              name: 'String'
            }
          },
          enabled: {
            required: false,
            serializedName: 'properties.enabled',
            type: {
              name: 'Boolean'
            }
          },
          id: {
            required: false,
            serializedName: 'id',
            type: {
              name: 'String'
            }
          },
          name: {
            required: false,
            serializedName: 'name',
            type: {
              name: 'String'
            }
          },
          type: {
            required: false,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          location: {
            required: false,
            serializedName: 'location',
            type: {
              name: 'String'
            }
          },
          tags: {
            required: false,
            serializedName: 'tags',
            type: {
              name: 'Dictionary',
              value: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          }
        }
      }
    };
  }
}

module.exports = GalleryImage;


text:
package remoting.proxy;

import commons.Address;

public interface SkeletonInterface {
  public void stop();

  public Address getAddr();
}


text:
ACCEPTED

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

#### Published in
null

#### Original name
Rosa melina Greene

### Remarks
null


text:
SYNONYM

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

#### Published in
Mater. Mikol. Fitopat. Ross. 1(4): 72 (1915)

#### Original name
Septoria apii-graveolentis Dorogin, 1915

### Remarks
null


text:
// Copyright 2015 The Bazel Authors. All rights reserved.
//
// 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.google.devtools.build.lib.profiler.statistics;

import com.google.common.base.Predicate;
import com.google.devtools.build.lib.actions.MiddlemanAction;
import com.google.devtools.build.lib.profiler.ProfilerTask;
import com.google.devtools.build.lib.profiler.analysis.ProfileInfo;
import com.google.devtools.build.lib.profiler.analysis.ProfileInfo.CriticalPathEntry;
import com.google.devtools.build.lib.profiler.analysis.ProfileInfo.Task;
import com.google.devtools.build.lib.util.Pair;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Nullable;

/**
 * Keeps a predefined list of {@link CriticalPathEntry}'s cumulative durations and allows
 * iterating over pairs of their descriptions and relative durations.
 */
//TODO(bazel-team): Add remote vs build stats recorded by Logging.CriticalPathStats
public final class CriticalPathStatistics implements Iterable<Pair<String, Double>> {

  private static final EnumSet<ProfilerTask> FILTER_NONE = EnumSet.noneOf(ProfilerTask.class);
  /** Always filter out ACTION_LOCK and WAIT tasks to simulate unlimited resource critical path.
   * @see #optimalPath
   */
  private static final EnumSet<ProfilerTask> DEFAULT_FILTER =
      EnumSet.of(ProfilerTask.ACTION_LOCK, ProfilerTask.WAIT);

  private static final List<Pair<String, EnumSet<ProfilerTask>>> FILTERS =
      Arrays.asList(
          Pair.of("the builder overhead", EnumSet.allOf(ProfilerTask.class)),
          Pair.of(
              "the VFS calls",
              ProfilerTask.allSatisfying(
                  new Predicate<ProfilerTask>() {
                    @Override
                    public boolean apply(ProfilerTask task) {
                      return DEFAULT_FILTER.contains(task) || task.name().startsWith("VFS_");
                    }
                  })),
          typeFilter("the dependency checking", ProfilerTask.ACTION_CHECK),
          typeFilter("the execution setup", ProfilerTask.ACTION_EXECUTE),
          typeFilter("local execution", ProfilerTask.SPAWN, ProfilerTask.LOCAL_EXECUTION),
          typeFilter("the include scanner", ProfilerTask.SCANNER),
          typeFilter(
              "Remote execution (cumulative)",
              ProfilerTask.REMOTE_EXECUTION,
              ProfilerTask.PROCESS_TIME,
              ProfilerTask.LOCAL_PARSE,
              ProfilerTask.UPLOAD_TIME,
              ProfilerTask.REMOTE_QUEUE,
              ProfilerTask.REMOTE_SETUP,
              ProfilerTask.FETCH),
          typeFilter("  file uploads", ProfilerTask.UPLOAD_TIME, ProfilerTask.REMOTE_SETUP),
          typeFilter("  file fetching", ProfilerTask.FETCH),
          typeFilter("  process time", ProfilerTask.PROCESS_TIME),
          typeFilter("  remote queueing", ProfilerTask.REMOTE_QUEUE),
          typeFilter("  remote execution parse", ProfilerTask.LOCAL_PARSE),
          typeFilter("  other remote activities", ProfilerTask.REMOTE_EXECUTION));

  private final List<Long> criticalPathDurations;

  /**
   * The actual critical path.
   */
  private final CriticalPathEntry totalPath;

  /**
   * Unlimited resource critical path. Essentially, we assume that if we remove all scheduling
   * delays caused by resource semaphore contention, each action execution time would not change
   * (even though load now would be substantially higher - so this assumption might be incorrect
   * but it is the path excluding scheduling delays).
   */
  private final CriticalPathEntry optimalPath;

  private final long workerWaitTime;
  private final long mainThreadWaitTime;

  public CriticalPathStatistics(ProfileInfo info) {
    totalPath = info.getCriticalPath(FILTER_NONE);
    info.analyzeCriticalPath(FILTER_NONE, totalPath);

    optimalPath = info.getCriticalPath(DEFAULT_FILTER);
    info.analyzeCriticalPath(DEFAULT_FILTER, optimalPath);

    if (totalPath == null || totalPath.isComponent()) {
      this.workerWaitTime = 0;
      this.mainThreadWaitTime = 0;
      criticalPathDurations = Collections.emptyList();
      return;
    }
    // Worker thread pool scheduling delays for the actual critical path.
    long workerWaitTime = 0;
    long mainThreadWaitTime = 0;
    for (CriticalPathEntry entry = totalPath; entry != null; entry = entry.next) {
      workerWaitTime += info.getActionWaitTime(entry.task);
      mainThreadWaitTime += info.getActionQueueTime(entry.task);
    }
    this.workerWaitTime = workerWaitTime;
    this.mainThreadWaitTime = mainThreadWaitTime;

    criticalPathDurations = getCriticalPathDurations(info);
  }

  /**
   * @return the critical path obtained by not filtering out any {@link ProfilerTask}
   */
  public CriticalPathEntry getTotalPath() {
    return totalPath;
  }

  /**
   * @return the critical path obtained by filtering out any lock and wait tasks (see
   *    {@link #DEFAULT_FILTER})
   */
  public CriticalPathEntry getOptimalPath() {
    return optimalPath;
  }

  /**
   * @see ProfileInfo#getActionWaitTime(Task)
   * @return the sum of all action wait times on the total critical path
   */
  public long getWorkerWaitTime() {
    return workerWaitTime;
  }

  /**
   * @see ProfileInfo#getActionQueueTime(Task)
   * @return the mainThreadWaitTime
   */
  public long getMainThreadWaitTime() {
    return mainThreadWaitTime;
  }

  /**
   * Constructs a filtered Iterable from a critical path.
   *
   *  <p>Ignores all fake (task id < 0) path entries and
   *  {@link com.google.devtools.build.lib.actions.MiddlemanAction}-related entries.
   */
  public Iterable<CriticalPathEntry> getMiddlemanFilteredPath(final CriticalPathEntry path) {
    return new Iterable<CriticalPathEntry>() {
      @Override
      public Iterator<CriticalPathEntry> iterator() {
        return new Iterator<CriticalPathEntry>() {
          private CriticalPathEntry nextEntry = path;

          @Override
          public boolean hasNext() {
            return nextEntry != null;
          }

          @Override
          public CriticalPathEntry next() {
            CriticalPathEntry current = nextEntry;
            do {
              nextEntry = nextEntry.next;
            } while (nextEntry != null && (nextEntry.task.isFake() || isMiddleMan(nextEntry.task)));
            return current;
          }

          @Override
          public void remove() {
            throw new UnsupportedOperationException();
          }
        };
      }
    };
  }

  @Override
  public Iterator<Pair<String, Double>> iterator() {
    return new Iterator<Pair<String, Double>>() {

      Iterator<Long> durations = criticalPathDurations.iterator();
      Iterator<Pair<String, EnumSet<ProfilerTask>>> filters = FILTERS.iterator();
      boolean overheadFilter = true;

      @Override
      public boolean hasNext() {
        return durations.hasNext();
      }

      @Override
      public Pair<String, Double> next() {
        long duration = durations.next();
        String description = filters.next().first;
        double relativeDuration;
        if (overheadFilter) {
          overheadFilter = false;
          relativeDuration = (double) duration / totalPath.cumulativeDuration;
        } else {
          relativeDuration =
              (double) (optimalPath.cumulativeDuration - duration) / optimalPath.cumulativeDuration;
        }
        return Pair.of(description, relativeDuration);
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }
    };
  }

  /**
   * Extracts all {@link CriticalPathEntry} durations for the filters defined by {@link #FILTERS}.
   */
  private static List<Long> getCriticalPathDurations(ProfileInfo info) {
    List<Long> list = new ArrayList<>(FILTERS.size());

    for (Pair<String, EnumSet<ProfilerTask>> filter : FILTERS) {
      list.add(info.getCriticalPath(filter.second).cumulativeDuration);
    }
    return list;
  }

  /**
   * Returns set of profiler tasks to be filtered from critical path.
   * Also always filters out ACTION_LOCK and WAIT tasks to simulate
   * unlimited resource critical path (see comments inside formatExecutionPhaseStatistics()
   * method).
   */
  private static Pair<String, EnumSet<ProfilerTask>> typeFilter(
      String description, ProfilerTask... tasks) {
    EnumSet<ProfilerTask> filter = EnumSet.of(ProfilerTask.ACTION_LOCK, ProfilerTask.WAIT);
    Collections.addAll(filter, tasks);
    return Pair.of(description, filter);
  }

  /**
   * @return Whether the task is {@link MiddlemanAction}-related.
   */
  private static boolean isMiddleMan(Task task) {
    String description = task.getDescription();
    return description.startsWith(MiddlemanAction.MIDDLEMAN_MNEMONIC + " ")
        || description.startsWith("TargetCompletionMiddleman");
  }

  /**
   * Aggregates statistics related to {@link MiddlemanAction}s on the critical path.
   */
  public static final class MiddleManStatistics {
    public final int count;
    public final long duration;
    public final long criticalTime;

    private MiddleManStatistics(int count, long duration, long criticalTime) {
      this.count = count;
      this.duration = duration;
      this.criticalTime = criticalTime;
    }

    /**
     * Summarizes middleman actions on the critical path.
     * @return null if path is null, else the aggregate statistics
     */
    public static MiddleManStatistics create(@Nullable CriticalPathEntry path) {
      if (path == null) {
        return null;
      }
      int middleManCount = 0;
      long middleManDuration = 0;
      long middleManCritTime = 0;
      for (CriticalPathEntry entry = path; entry != null; entry = entry.next) {
        Task task = entry.task;
        if (!task.isFake() && isMiddleMan(task)) {
          // Aggregate middleman actions.
          middleManCount++;
          middleManDuration += entry.duration;
          middleManCritTime += entry.getCriticalTime();
        }
      }
      return new MiddleManStatistics(middleManCount, middleManDuration, middleManCritTime);
    }
  }
}


text:
package com.netflix.genie.agent.execution.statemachine;

import com.netflix.genie.agent.execution.services.KillService;

import java.util.List;

/**
 * Interface JobExecutionStateMachine hides the actual state machine details.
 *
 * @author mprimi
 * @since 4.0.0
 */
public interface JobExecutionStateMachine {

    /**
     * Runs the state machine until completion.
     */
    void run();

    /**
     * Get the list of execution stages.
     *
     * @return an immutable ordered list of execution stages
     */
    List<ExecutionStage> getExecutionStages();

    /**
     * Get the execution context.
     * This is meant for post-execution read-only access.
     *
     * @return the execution context used by the state machine.
     */
    ExecutionContext getExecutionContext();

    /**
     * Abort execution, if necessary by stopping the running job process.
     * The state machine still runs to termination, but may skip steps as appropriate.
     *
     * @param killSource a representation of who/what requested the kill
     */
    void kill(KillService.KillSource killSource);
}


text:
Article 1490
----
Les dispositions des articles précédents ne font point obstacle à ce que, sans
préjudicier aux droits des tiers, une clause du partage oblige l'un ou l'autre
des époux à payer une quotité de dettes autre que celle qui est fixée ci-dessus,
ou même à acquitter le passif entièrement.


text:
package test;

import java.util.function.Supplier;

import org.springframework.cloud.contract.spec.Contract;

class MyHttpContract implements Supplier<Contract> {
	@Override
	public Contract get() {
		return Contract.make(c -> {
			c.request(r -> {
				r.method(r.GET());
				r.url("/example");
			});
			c.response(r -> {
				r.status(r.OK());
			});
		});
	}
}


text:
package org.elasticsearch.mapping;

/**
 * Defaults to true for analyzed fields, and to false for not_analyzed fields.
 *
 * @author luc boutier
 */
public enum NormEnabled {
    TRUE, FALSE, DEFAULT;
}


text:
package io.pivotal.fe.sentiment;

import io.pivotal.fe.sentiment.engine.NLP;

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

import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class SentimentAnayticsServiceApplication {

	@RequestMapping("/env")
	public Map<String,Object> env(HttpServletRequest request) {
	    Map<String,Object> model = new HashMap<String,Object>();
	    model.put("ip", request.getLocalAddr());
	    model.put("port", request.getLocalPort());
		return model;
	}

	@RequestMapping("/sentiment/{text}")
	public Map<String,Object> sentiment(@PathVariable String text, HttpServletRequest request) {
		int sentiment = NLP.findSentiment(text);
	    Map<String,Object> model = new HashMap<String,Object>();
	    model.put("id", UUID.randomUUID().toString());
	    model.put("sentiment", new Integer(sentiment));

	    System.out.println("######### Remote IP: "+request.getRemoteHost());

		return model;
	}

	public static void main(String[] args) {
        SpringApplication.run(SentimentAnayticsServiceApplication.class, args);
        NLP.init();
    }
}


text:
import re
import markdown
from markdown.inlinepatterns import Pattern
from markdown.util import etree

class EmoticonExtension(markdown.Extension):
    def __init__ (self, configs):
        self.config = {
            'EMOTICONS': [{
                ":)" : "test.png",
                }, 'A mapping from emoticon symbols to image names.'],
            }

        for key, value in configs.iteritems() :
            self.config[key][0] = value

    def extendMarkdown(self, md, md_globals):
        self.md = md
        EMOTICON_RE = u'(^|(?<=\s))(?P<emoticon>{0})((?=\s)|$)'.format('|'.join(
            [re.escape(emoticon) for emoticon in self.getConfig('EMOTICONS').keys()]))
        md.inlinePatterns.add('emoticons', EmoticonPattern(EMOTICON_RE, self),"<linebreak")

class EmoticonPattern(Pattern):
    def __init__ (self, pattern, emoticons):
        Pattern.__init__(self, pattern)
        self.emoticons = emoticons

    def handleMatch(self, m):
        try:
            emoticon = m.group('emoticon')
        except IndexError:
            return None
        el = etree.Element('img')
        el.set('src', '%s' % (self.emoticons.getConfig('EMOTICONS')[emoticon],))
        el.set('alt', emoticon)
        return el

def makeExtension(configs=None) :
    return EmoticonExtension(configs=configs)


text:
package com.thinkbiganalytics.servicemonitor.check;

import com.thinkbiganalytics.servicemonitor.model.ServiceStatusResponse;

/**
 * Marker interface to perform Service Status verification in the Kylo Operations Manager.
 * Any classes with this interface will be automatically wired in and checked for Service Health in Kylo.
 *
 * This class is used to check a single services.  If you are checking a multiple services that are similar you should implement {@link ServicesStatusCheck}
 * Note:  The classes must be Spring Managed Beans
 *
 * @see ServicesStatusCheck
 */
public interface ServiceStatusCheck {

    /**
     * Check a given service and return its health information
     *
     * @return the health of a given service
     */
    ServiceStatusResponse healthCheck();
}


text:
"""Utility functions for features and targets manipulation."""

import numpy as np
from sklearn.decomposition import PCA
import tensorflow as tf

def pca_reduction(features, n_components=0.8, svd_solver='full'):
  """Apply PCA dimensionality reduction.

  Args:
    features: matrix of dimension [N, D], where N is the number of datapoints
      and D the feature dimensionality to reduce.
    n_components: if > 1 reduce the dimensionlity of the features to this value,
      if 0 < n_components < 1, select the number of components such that the
      percentage of variance explained is greater than (n_components * 100).
    svd_solver: SVD solver to use. As default we compute the exact full SVD.

  Returns:
    reduced_features: matrix [N, K] of features with reduced dimensionality K.

  """

  reduced_feature = PCA(
      n_components=n_components, svd_solver=svd_solver).fit_transform(features)
  return reduced_feature.astype(np.float32)

def shift_target_labels(target_labels):
  """Change target_labels values to be in the range [0, target classes number).

  Args:
    target_labels: ground truth target labels of dimension [N, 1].

  Returns:
    shifted_target_labels: target_labels in the range [0, target classes number)
  """

  target_labels = np.array(target_labels)
  dict_to_shift = {l: i for i, l in enumerate(set(target_labels))}
  shifted_target_labels = np.array([dict_to_shift[l] for l in target_labels])

  return shifted_target_labels.astype(np.int32)

def compute_class_frequencies(target_train_dataset):
  """Compute the classes frequencies of a semantic segmentation dataset."""
  class_counts = {}
  for _, labels in iter(target_train_dataset):
    labels = tf.reshape(labels, [-1])
    labels, counts = np.unique(labels, return_counts=True)
    for label, count in zip(labels, counts):
      if label not in class_counts:
        class_counts[int(label)] = count
      else:
        class_counts[int(label)] += count
  return class_counts

def get_sampling_indices(sampling_seed, class_counts, labels, num_samples):
  """Function to generates sampling indices of the given labels.

  Args:
    sampling_seed: seed used for the sampling process.
    class_counts: instances count of every class in the dataset. If None,
      uniform sampling is applied.
    labels: ground-truth labels from the target dataset.
    num_samples: number of labels to sample from the labels.

  Returns:
    indices: indices for sampling the labels.

  """
  np.random.seed(sampling_seed)
  num_samples = min(num_samples, labels.shape[0])  # To avoid sampling errors

  if not class_counts:  # Uniform sampling
    weights_labels = None
  else:  # Class balanced sampling
    weights_labels = [1/class_counts[int(x)] for x in labels]
    weights_labels = weights_labels / np.sum(weights_labels)

  indices = np.random.choice(
      np.arange(labels.shape[0]),
      num_samples,
      replace=False,
      p=weights_labels)
  return tf.cast(indices, tf.int32)

def sample_from_image(outputs, labels, sampling_seed, class_counts,
                      num_samples):
  """Function to sample images and labels for semantic segmentation.

  Args:
    outputs: either activations or predictions at the pixel level.
    labels: ground-truth labels from the target dataset.
    sampling_seed: seed used for the sampling process.
    class_counts: Instances count of every class in the dataset. If None, random
      sampling is applied.
    num_samples: number of labels to sample from the labels.

  Returns:
    sampled_outputs, sampled_labels

  """

  outputs = tf.reshape(outputs, [-1, outputs.shape[-1]])
  labels = tf.reshape(labels, [-1])

  # Remove background pixels located at label==0
  mask = tf.not_equal(labels, 0)
  labels = tf.gather_nd(labels, tf.where(mask))
  outputs = tf.gather_nd(outputs, tf.where(mask))
  if np.sum(mask) == 0:  # Just background pixels
    return  [], []

  if num_samples:  # Sample num_sample pixels per image.
    sampling_indices = get_sampling_indices(
        sampling_seed, class_counts, labels, num_samples)

    outputs = tf.gather(outputs, sampling_indices)
    labels = tf.gather(labels, sampling_indices)

  return outputs, labels


text:
<!DOCTYPE html>

	<title></title>

	<wicket:panel>

			<form>

									<wicket:message key="button.edit" />

						<wicket:message
								key="label.description" />:

						<wicket:message key="label.metric.source" />:

						<wicket:message key="label.metric.scale" />:

						<wicket:message
								key="label.metric.unit" />:

						<wicket:message key="label.metric.targetValue" />:
						<wicket:message key="label.metric.weight" />:

						<wicket:message key="label.qModelTagData" />

			</form>

	</wicket:panel>


text:
using HttpException = Saklient.Errors.HttpException;

namespace Saklient.Errors
{

	/// <summary>HTTPエラー。Unprocessable Entity.
	/// </summary>
	public class HttpUnprocessableEntityException : HttpException
	{

		/// <summary>
		/// <param name="status" />
		/// <param name="code" />
		/// <param name="message" />
		/// </summary>
		public HttpUnprocessableEntityException(long status, string code=null, string message="") : base(status, code, message == null || message == "" ? "HTTPエラー。Unprocessable Entity." : message)
		{
			/*!base!*/;
		}

	}

}


text:
package com.bunk3r.spanez.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

import com.bunk3r.spanez.SpanEZ;
import com.bunk3r.spanez.callbacks.OnSpanClickListener;
import com.bunk3r.spanez.locators.Paragraph;
import com.bunk3r.spanez.locators.Range;
import com.bunk3r.spanez.locators.Word;

import static com.bunk3r.spanez.api.EZ.BOLD;
import static com.bunk3r.spanez.api.EZ.ITALIC;
import static com.bunk3r.spanez.api.EZ.STRIKETHROUGH;
import static com.bunk3r.spanez.api.EZ.UNDERLINE;

public class MainActivity extends AppCompatActivity {
    private TextView sample;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        sample = (TextView) findViewById(R.id.sample_text);
    }

    @Override
    protected void onResume() {
        super.onResume();

        SpanEZ.withTextView(sample)
              .withContent(R.string.lorem_ipsum)
              .absoluteSize(Range.from(0, 5), 20)
              .absoluteSizeDP(Range.from(6, 10), 34)
              .exclusive()
              .backgroundColor(Word.findFirst("ipsum dolor"), R.color.colorPrimary)
              .backgroundColor(Range.from(30, 50), R.color.colorPrimaryDark)
              .foregroundColor(Range.from(45, 100), R.color.colorAccent)
              .inclusiveExclusive()
              .style(Word.findAll("ipsum"), BOLD | UNDERLINE)
              .style(Word.findFirst("ipsum"), ITALIC | STRIKETHROUGH)
              .link(Word.findFirst("ut ultricies dolor molestie eget"), "http://www.google.com")
              .clickable(Word.findFirst("Mauris in lacus at nulla"), new OnSpanClickListener() {
                  @Override
                  public void onSpanClick(String spanContent) {
                      Toast.makeText(MainActivity.this, spanContent, Toast.LENGTH_SHORT)
                           .show();
                  }
              })
              .inclusive()
              .quote(Paragraph.containing("Lorem"))
              .scaleX(Range.from(60, 80), 2)
              .apply();
    }
}


text:
package org.apache.jackrabbit.oak.management;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Lists.newArrayList;
import static java.util.Collections.singletonMap;
import static org.apache.jackrabbit.oak.commons.jmx.ManagementOperation.Status;
import static org.apache.jackrabbit.oak.commons.jmx.ManagementOperation.Status.failed;
import static org.apache.jackrabbit.oak.commons.jmx.ManagementOperation.Status.fromCompositeData;
import static org.apache.jackrabbit.oak.commons.jmx.ManagementOperation.Status.succeeded;
import static org.apache.jackrabbit.oak.commons.jmx.ManagementOperation.Status.toTabularData;
import static org.apache.jackrabbit.oak.commons.jmx.ManagementOperation.Status.unavailable;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.annotation.Nonnull;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.TabularData;

import com.google.common.base.Function;
import org.apache.jackrabbit.oak.api.jmx.FileStoreBackupRestoreMBean;
import org.apache.jackrabbit.oak.api.jmx.RepositoryManagementMBean;
import org.apache.jackrabbit.oak.api.jmx.SessionMBean;
import org.apache.jackrabbit.oak.commons.jmx.AnnotatedStandardMBean;
import org.apache.jackrabbit.oak.plugins.blob.BlobGCMBean;
import org.apache.jackrabbit.oak.plugins.index.property.jmx.PropertyIndexAsyncReindexMBean;
import org.apache.jackrabbit.oak.spi.state.RevisionGCMBean;
import org.apache.jackrabbit.oak.spi.whiteboard.Tracker;
import org.apache.jackrabbit.oak.spi.whiteboard.Whiteboard;

/**
 * Default implementation of the {@link RepositoryManagementMBean} based
 * on a {@link Whiteboard} instance, which is used to look up individual
 * service providers for backup ({@link FileStoreBackupRestoreMBean}), data store
 * garbage collections ({@link BlobGCMBean}) and revision store garbage
 * collections ({@link RevisionGCMBean}).
 */
public class RepositoryManager extends AnnotatedStandardMBean implements RepositoryManagementMBean {
    private final Whiteboard whiteboard;

    public RepositoryManager(@Nonnull Whiteboard whiteboard) {
        super(RepositoryManagementMBean.class);
        this.whiteboard = checkNotNull(whiteboard);
    }

    public String getName() {
        return "repository manager";
    }

    private <T> Status execute(Class<T> serviceType, Function<T, Status> operation) {
        return execute(serviceType, operation, Collections.emptyMap());
    }

    private <T> Status execute(Class<T> serviceType, Function<T, Status> operation, Map<String, String> filter) {
        Tracker<T> tracker;
        if (filter.isEmpty()) {
            tracker = whiteboard.track(serviceType);
        } else {
            tracker = whiteboard.track(serviceType, filter);
        }
        try {
            List<T> services = tracker.getServices();
            if (services.size() == 1) {
                return operation.apply(services.get(0));
            } else if (services.isEmpty()) {
                return unavailable("Cannot perform operation: no service of type " +
                        serviceType.getSimpleName() + " found."
                );
            } else {
                return failed("Cannot perform operation: multiple services of type " +
                        serviceType.getSimpleName() + " found."
                );
            }
        } finally {
            tracker.stop();
        }
    }

    private <T> Iterable<Status> executeAll(Class<T> serviceType, Function<T, Status> operation) {
        Tracker<T> tracker = whiteboard.track(serviceType);
        List<Status> statuses = newArrayList();
        try {
            for (T service : tracker.getServices()) {
                statuses.add(operation.apply(service));
            }
            return statuses;
        } finally {
            tracker.stop();
        }
    }

    @Override
    public CompositeData startBackup() {
        return execute(FileStoreBackupRestoreMBean.class, new Function<FileStoreBackupRestoreMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(FileStoreBackupRestoreMBean fileStoreBackupRestoreMBean) {
                return fromCompositeData(fileStoreBackupRestoreMBean.startBackup());
            }
        }).toCompositeData();
    }

    @Override
    public CompositeData getBackupStatus() {
        return execute(FileStoreBackupRestoreMBean.class, new Function<FileStoreBackupRestoreMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(FileStoreBackupRestoreMBean backupService) {
                return fromCompositeData(backupService.getBackupStatus());
            }
        }).toCompositeData();
    }

    @Override
    public CompositeData startRestore() {
        return execute(FileStoreBackupRestoreMBean.class, new Function<FileStoreBackupRestoreMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(FileStoreBackupRestoreMBean backupService) {
                return fromCompositeData(backupService.startRestore());
            }
        }).toCompositeData();
    }

    @Override
    public CompositeData getRestoreStatus() {
        return execute(FileStoreBackupRestoreMBean.class, new Function<FileStoreBackupRestoreMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(FileStoreBackupRestoreMBean backupService) {
                return fromCompositeData(backupService.getRestoreStatus());
            }
        }).toCompositeData();
    }

    @Override
    public CompositeData startDataStoreGC(final boolean markOnly) {
        return execute(BlobGCMBean.class, new Function<BlobGCMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(BlobGCMBean blobGCService) {
                return fromCompositeData(blobGCService.startBlobGC(markOnly));
            }
        }).toCompositeData();
    }

    @Override
    public CompositeData getDataStoreGCStatus() {
        return execute(BlobGCMBean.class, new Function<BlobGCMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(BlobGCMBean blobGCService) {
                return fromCompositeData(blobGCService.getBlobGCStatus());
            }
        }).toCompositeData();
    }

    @Override
    public CompositeData startRevisionGC() {
        return startRevisionGCForRole(null);
    }

    @Override
    public CompositeData startRevisionGCForRole(String role) {
        return execute(RevisionGCMBean.class, new Function<RevisionGCMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(RevisionGCMBean revisionGCService) {
                return fromCompositeData(revisionGCService.startRevisionGC());
            }
        }, singletonMap("role", role)).toCompositeData();
    }

    @Nonnull
    @Override
    public CompositeData cancelRevisionGC() {
        return cancelRevisionGCForRole(null);
    }

    @Nonnull
    @Override
    public CompositeData cancelRevisionGCForRole(String role) {
        return execute(RevisionGCMBean.class, new Function<RevisionGCMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(RevisionGCMBean revisionGCService) {
                return fromCompositeData(revisionGCService.cancelRevisionGC());
            }
        }, singletonMap("role", role)).toCompositeData();
    }

    @Override
    public CompositeData getRevisionGCStatus() {
        return getRevisionGCStatusForRole(null);
    }

    @Nonnull
    @Override
    public CompositeData getRevisionGCStatusForRole(String role) {
        return execute(RevisionGCMBean.class, new Function<RevisionGCMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(RevisionGCMBean revisionGCService) {
                return fromCompositeData(revisionGCService.getRevisionGCStatus());
            }
        }, singletonMap("role", role)).toCompositeData();
    }

    @Override
    public String checkpoint(final long lifetime) {
        Status status = execute(FileStoreBackupRestoreMBean.class, new Function<FileStoreBackupRestoreMBean, Status>() {
            @Nonnull
            @Override
            public Status apply(FileStoreBackupRestoreMBean backupService) {
                String checkpoint = backupService.checkpoint(lifetime);
                return succeeded(checkpoint);
            }
        });

        return status.isSuccess()
            ? status.getMessage()
            : null;
    }

    @Override
    public CompositeData startPropertyIndexAsyncReindex() {
        return execute(PropertyIndexAsyncReindexMBean.class,
                new Function<PropertyIndexAsyncReindexMBean, Status>() {
                    @Nonnull
                    @Override
                    public Status apply(PropertyIndexAsyncReindexMBean reindexer) {
                        return fromCompositeData(reindexer
                                .startPropertyIndexAsyncReindex());
                    }
                }).toCompositeData();
    }

    @Override
    public CompositeData getPropertyIndexAsyncReindexStatus() {
        return execute(PropertyIndexAsyncReindexMBean.class,
                new Function<PropertyIndexAsyncReindexMBean, Status>() {
                    @Nonnull
                    @Override
                    public Status apply(PropertyIndexAsyncReindexMBean reindexer) {
                        return fromCompositeData(reindexer
                                .getPropertyIndexAsyncReindexStatus());
                    }
                }).toCompositeData();
    }

    @Override
    public TabularData refreshAllSessions() {
        return toTabularData(executeAll(SessionMBean.class, new Function<SessionMBean, Status>() {
            @Override
            public Status apply(SessionMBean sessionMBean) {
                sessionMBean.refresh();
                return succeeded("OK");
            }
        }));
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
Bidr. Känn. Finl. Nat. Folk 37: v, 1 (1882)

#### Original name
Suillus P. Karst.

### Remarks
null


text:
std::vector<cmdline_option> rv_gen_fpu_test::get_cmdline_options()
{
	return std::vector<cmdline_option>{
		{ "-FH", "--print-fpu-test-h", cmdline_arg_type_none,
			"Print FPU test header",
			[&](std::string s) { return gen->set_option("print_fpu_test_h"); } },
		{ "-FC", "--print-fpu-test-c", cmdline_arg_type_none,
			"Print FPU test source",
			[&](std::string s) { return gen->set_option("print_fpu_test_c"); } },
	};
}

typedef std::pair<const rv_primitive_type*,std::string> rv_operand_desc;

static rv_operand_desc rv_fpu_operand_type(rv_opcode_ptr &opcode, rv_extension_ptr &ext, rv_operand_ptr &operand, size_t i)
{
	// create operand name
	std::string operand_name = operand->name;
	operand_name = replace(operand_name, "frd", "d");
	operand_name = replace(operand_name, "rd", "d");
	operand_name = replace(operand_name, "frs", "s");
	operand_name = replace(operand_name, "rs", "s");

	return rv_operand_desc(rv_meta_model::infer_operand_primitive(opcode, ext, operand, i), operand_name);
}

template <typename T> void typed_value_set(std::set<std::string> &values, const rv_primitive_type *primitive)
{
	char fmt[16];
	char buf[256];
	snprintf(fmt, sizeof(fmt), "%s%s", primitive->c_fmt, primitive->c_suffix);
	snprintf(buf, sizeof(buf), fmt, T(2)); values.insert(buf);
	if (std::numeric_limits<T>::is_signed) {
		snprintf(buf, sizeof(buf), fmt, T(-2)); values.insert(buf);
	}
	if (std::numeric_limits<T>::is_iec559) {
		values.insert("NAN");
		values.insert("INFINITY");
		snprintf(buf, sizeof(buf), fmt, T(0.5)); values.insert(buf);
		snprintf(buf, sizeof(buf), fmt, T(0.25)); values.insert(buf);
	}
}

static std::set<std::string> test_values(const rv_primitive_type *primitive)
{
	std::set<std::string> values;
	switch (primitive->enum_type) {
		case rvt_sx:  typed_value_set<int64_t>(values, primitive); break;
		case rvt_ux:  typed_value_set<uint64_t>(values, primitive); break;
		case rvt_s32: typed_value_set<int32_t>(values, primitive); break;
		case rvt_u32: typed_value_set<uint32_t>(values, primitive); break;
		case rvt_s64: typed_value_set<int64_t>(values, primitive); break;
		case rvt_u64: typed_value_set<uint64_t>(values, primitive); break;
		case rvt_f32: typed_value_set<float>(values, primitive); break;
		case rvt_f64: typed_value_set<double>(values, primitive); break;
		default: break;
	};
	return values;
}

static void print_fpu_test_h(rv_gen *gen)
{
	static const char* kFpuHeader =

R"C(
typedef signed int         s32;
typedef unsigned int       u32;
typedef signed long long   s64;
typedef unsigned long long u64;
typedef float              f32;
typedef double             f64;
typedef signed long        sx;
typedef unsigned long      ux;

#define nan NAN
#define nanf NAN
#define inf INFINITY
#define inff INFINITY

#define FPU_IDENTITY(fn, args...) printf("\tFPU_ASSERT(%s, " fmt_res_##fn ", " fmt_arg_##fn ");\n", #fn, test_##fn(args), args)
#define FPU_ASSERT(fn, result, args...) assert(isinf(result) ? isinf(test_##fn(args)) : isnan(result) ? isnan(test_##fn(args)) : test_##fn(args) == result)
)C";

	printf(kCHeader, "test-fpu-gen.h");
	printf("#ifndef test_fpu_gen_h\n");
	printf("#define test_fpu_gen_h\n");
	printf("%s\n", kFpuHeader);

	// loop through FPU instructions
	for (auto &opcode : gen->opcodes) {

		// find extension with minimum isa width
		auto ext_min_width_i = std::min_element(opcode->extensions.begin(), opcode->extensions.end(),
			[](rv_extension_ptr &a, rv_extension_ptr &b){ return a->isa_width < b->isa_width; });
		if (ext_min_width_i == opcode->extensions.end()) continue;
		auto ext = *ext_min_width_i;

		// skip non floating point instructions
		if (ext->alpha_code != 'f' && ext->alpha_code != 'd') continue;

		// infer C argument types for test function
		bool skip_imm = false;
		std::vector<rv_operand_desc> operand_list;
		for (size_t i = 0; i < opcode->codec->operands.size(); i++) {
			auto operand = opcode->codec->operands[i];
			// round mode operand not supported
			if (operand->name == "rm") continue;
			// instructions with immediates not supported (fld, fsw)
			if (operand->name.find("imm") != std::string::npos) skip_imm = true;
			// infer primitive type based on the opcode components and operand types
			operand_list.push_back(rv_fpu_operand_type(opcode, ext, operand, i));
		}
		if (skip_imm) continue;

		std::vector<std::string> fn_arity;
		std::transform(operand_list.begin() + 1, operand_list.end(),
			std::back_inserter(fn_arity), [](const rv_operand_desc& operand) {
				return format_string("%s %s", operand.first->meta_type, operand.second.c_str());
		});

		std::vector<std::string> operand_fmt;
		std::transform(operand_list.begin() + 1, operand_list.end(),
			std::back_inserter(operand_fmt), [](const rv_operand_desc& operand) {
				return format_string("%s%s", operand.first->c_fmt, operand.first->c_suffix);
		});

		std::vector<std::string> asm_arity;
		std::transform(operand_list.begin(), operand_list.end(),
			std::back_inserter(asm_arity), [](const rv_operand_desc& operand) {
				return format_string("%%[%s]", operand.second.c_str());
		});

		std::vector<std::string> asm_results;
		std::transform(operand_list.begin() + 1, operand_list.end(),
			std::back_inserter(asm_results), [](const rv_operand_desc& operand) {
				return format_string("[%s]\"%s\" (%s)",
					operand.second.c_str(), operand.first->asm_type, operand.second.c_str());
		});

		// output function
		if (ext->isa_width == 64) printf("#if _RISCV_SZPTR != _RISCV_SZINT\n");
		std::string opcode_dot = rv_meta_model::opcode_format("", opcode, ".");
		std::string opcode_name = rv_meta_model::opcode_format("", opcode, "_");
		printf(
			"#define fmt_res_%s \"%s%s\"\n"
			"#define fmt_arg_%s \"%s\"\n"
			"inline %s test_%s(%s)\n{\n\t%s %s;\n"
			"\tasm(\"%s %s\\n\"\n\t\t: [%s]\"=%s\" (%s)\n"
			"\t\t: %s\n\t\t:\n\t);\n\treturn %s;\n}\n",
			opcode_name.c_str(),
			operand_list[0].first->c_fmt,
			operand_list[0].first->c_suffix,
			opcode_name.c_str(),
			join(operand_fmt, ", ").c_str(),
			operand_list[0].first->meta_type,
			opcode_name.c_str(),
			join(fn_arity, ", ").c_str(),
			operand_list[0].first->meta_type,
			operand_list[0].second.c_str(),
			opcode_dot.c_str(),
			join(asm_arity, ", ").c_str(),
			operand_list[0].second.c_str(),
			operand_list[0].first->asm_type,
			operand_list[0].second.c_str(),
			join(asm_results, ", ").c_str(),
			operand_list[0].second.c_str()
		);
		if (ext->isa_width == 64) printf("#endif\n");
		printf("\n");
	}

	printf("#endif\n");
}

static void print_fpu_test_c(rv_gen *gen)
{
	static const char* kFpuSourceHeader =

R"C(#include <stdio.h>
#include <assert.h>
#include <math.h>

#include "test-fpu-gen.h"

int main()
{
	printf("#include <stdio.h>\n");
	printf("#include <assert.h>\n");
	printf("#include <math.h>\n");
	printf("\n");
	printf("#include \"test-fpu-gen.h\"\n");
	printf("\n");
	printf("int main()\n");
	printf("{\n");

)C";

	static const char* kFpuSourceFooter =

R"C(
	printf("\treturn 0;\n");
	printf("}\n");

	return 0;
}
)C";

	printf(kCHeader, "test-fpu-gen.c");
	printf("%s", kFpuSourceHeader);

	// loop through FPU instructions
	for (auto &opcode : gen->opcodes) {

		// skip pseudo opcodes
		if (opcode->is_pseudo()) continue;

		// find extension with minimum isa width
		auto ext_min_width_i = std::min_element(opcode->extensions.begin(), opcode->extensions.end(),
			[](rv_extension_ptr &a, rv_extension_ptr &b){ return a->isa_width < b->isa_width; });
		if (ext_min_width_i == opcode->extensions.end()) continue;
		auto ext = *ext_min_width_i;

		// skip non floating point instructions
		if (ext->alpha_code != 'f' && ext->alpha_code != 'd') continue;

		// infer C argument types for test function
		bool skip_imm = false;
		std::vector<rv_operand_desc> operand_list;
		for (size_t i = 0; i < opcode->codec->operands.size(); i++) {
			auto operand = opcode->codec->operands[i];
			// round mode operand not supported
			if (operand->name == "rm") continue;
			// instructions with immediates not supported (fld, fsw)
			if (operand->name.find("imm") != std::string::npos) skip_imm = true;
			// infer primitive type based on the opcode components and operand types
			operand_list.push_back(rv_fpu_operand_type(opcode, ext, operand, i));
		}
		if (skip_imm) continue;

		// generate test cases
		if (ext->isa_width == 64) printf("#if _RISCV_SZPTR != _RISCV_SZINT\n");
		switch (operand_list.size()) {
			case 2: {
				std::set<std::string> values1 = test_values(operand_list[1].first);
				for (auto &v1 : values1) {
					printf("\tFPU_IDENTITY(%s, %s);\n",
						rv_meta_model::opcode_format("", opcode, "_").c_str(),
						v1.c_str());
				}
				break;
			}
			case 3: {
				std::set<std::string> values1 = test_values(operand_list[1].first);
				std::set<std::string> values2 = test_values(operand_list[2].first);
				for (auto &v1 : values1) {
					for (auto &v2 : values2) {
						printf("\tFPU_IDENTITY(%s, %s, %s);\n",
							rv_meta_model::opcode_format("", opcode, "_").c_str(),
							v1.c_str(), v2.c_str());
					}
				}
				break;
			}
			case 4: {
				std::set<std::string> values1 = test_values(operand_list[1].first);
				std::set<std::string> values2 = test_values(operand_list[2].first);
				std::set<std::string> values3 = test_values(operand_list[3].first);
				for (auto &v1 : values1) {
					for (auto &v2 : values2) {
						for (auto &v3 : values3) {
							printf("\tFPU_IDENTITY(%s, %s, %s, %s);\n",
								rv_meta_model::opcode_format("", opcode, "_").c_str(),
								v1.c_str(), v2.c_str(), v3.c_str());
						}
					}
				}
				break;
			}
		}
		if (ext->isa_width == 64) printf("#endif\n");
	}

	printf("%s", kFpuSourceFooter);
}

void rv_gen_fpu_test::generate()
{
	if (gen->has_option("print_fpu_test_h")) print_fpu_test_h(gen);
	if (gen->has_option("print_fpu_test_c")) print_fpu_test_c(gen);
}


text:
const es6Compat = process.env.BABEL_ES_COMPAT === "6" || process.env.NODE_ENV === "test";

module.exports = {
  presets: [
    [
      "@babel/preset-env",
      {
        targets: es6Compat ? "maintained node versions" : "> 0.25%, not dead"
      },
    ],
    "@babel/react",
    "@babel/preset-flow"
  ],
  plugins: [
    "@babel/plugin-transform-flow-comments",
    "@babel/plugin-proposal-class-properties",
    "babel-plugin-preval"
  ]
};


text:
from keras.layers import Input, Dense
import keras.optimizers
from keras.models import Model
import sklearn.model_selection as mds
import numpy as np
import problem.load_data as load_data
import problem.train_MINST as train_MINST
import matplotlib.pyplot as plt
import hyperLearn.sample as sp

############################################
## function to learn the RSM of the model ##
############################################
def learn_RSM(x, y):
    # x_train, x_test, y_train, y_test = mds.train_test_split(x, y, test_size=0.10, random_state=0)
    # x_train, x_valid, y_train, y_valid = mds.train_test_split(x, y, test_size=0.10, random_state=0)
    # print('RSMdata',x_train,y_train)
    x_train = x
    y_train = y
    ## due to the size of the sets we use all data for training and validation, the RSM may overfit
    x_valid = x
    y_valid = y

    dim = x.shape[1]
    input = Input(shape=(dim,))
    # the network architecture : 2 hidden layers as indicated in the article
    network = Dense(20 * dim, activation="relu")(input)
    network = Dense(20 * dim, activation="relu")(network)
    network = Dense(1, activation="linear")(network)

    # print(x_train,y_train)
    model = Model(input=input, output=network)
    opt = keras.optimizers.SGD(lr=0.1)
    model.compile(optimizer=opt, loss="mse")
    loss = model.fit(x_train, y_train,
                     nb_epoch=100,
                     batch_size=20,
                     verbose=0,
                     shuffle=True,
                     validation_data=(x_valid, y_valid))
    return model.evaluate(x_valid, y_valid, verbose=0), model

## function to add a value to the training set for the RSM
def add_train(old, new):
    to_train = new[0]
    if old[0] == None:
        return np.matrix(to_train), [new[1]]
    else:
        # print(old[0].shape,np.matrix(to_train).shape)
        return np.append(old[0], np.matrix(to_train), axis=0), np.append(old[1], [new[1]], axis=0)

## main function
def learn_hyperparam():
    data = load_data.load_data()
    x = None
    y = None
    # initialisation : 5 random training
    for i in range(5):
        s = sp.sample()
        print(s.get_MNIST())
        res = train_MINST.train_model_s(s.get_MNIST(), data)
        (x, y) = add_train((x, y), (s.get_RSM(), res[0]))
    (acc, RSM_model) = learn_RSM(x, y)

    # initialisation of loops variables
    hist_acc = []
    hist_res = []
    macc = []
    alpha = 0.001
    max_acc = max(y)
    best_model = []
    k = 0
    # first sample is randomly chosen
    s = sp.sample()
    best_conf = s
    while k < 200:
        print('n° test', k)
        # with a little propability we come bach to the best configuration found yet
        if np.random.uniform(0, 1) < alpha * 0.001:
            s = best_conf
        # gaussion sampling of the next solution
        s = s.gaussian_samp()
        # prediction of its performance
        p = RSM_model.predict(np.matrix(s.get_RSM()))
        print('predict_loss ', p, 'acc', max_acc)
        # test conditions :
        if p > max_acc:
            r = np.random.uniform(0, 1)
            if r > alpha:
                RSM_model, best_conf, best_model, k, max_acc, x, y = test_mod(RSM_model, best_conf, best_model, data,
                                                                              hist_acc, hist_res, k, macc, max_acc, s,
                                                                              x, y)
        else:
            r = np.random.uniform(0, 1)
            if r < alpha:
                RSM_model, best_conf, best_model, k, max_acc, x, y = test_mod(RSM_model, best_conf, best_model, data,
                                                                              hist_acc, hist_res, k, macc, max_acc, s,
                                                                              x, y)
    # plot the results
    print('bestconf',best_conf)
    print('error of RSM',max_acc)
    plt.plot(range(len(macc)), macc)
    plt.plot(range(len(macc)), macc)
    plt.plot(range(len(hist_acc)), hist_acc)
    plt.show()
    return best_conf, best_model, max_acc

# function to test configuration and update paramters
# - train MNIST
# - compare the results
# - add solution to RSM dataset
# - train RSM
# - save configurations
def test_mod(RSM_model, best_conf, best_model, data, hist_acc, hist_res, k, macc, max_acc, s, x, y):
    res = train_MINST.train_model_s(s.get_MNIST(), data)
    if res[0] > max_acc:
        max_acc = res[0]
        best_model = res[1]
        best_conf = s
    (x, y) = add_train((x, y), (s.get_RSM(), res[0]))
    (acc, RSM_model) = learn_RSM(x, y)
    macc.append(max_acc)
    hist_res.append(res[0])
    hist_acc.append(acc)
    np.save('../hyperlearn/hist_macc',macc)
    np.save('../hyperlearn/hist_res',hist_res)
    np.save('../hyperlearn/hist_acc',hist_acc)
    print('RSM_acc', acc)
    k = k + 1
    return RSM_model, best_conf, best_model, k, max_acc, x, y

if __name__ == '__main__':
    res = learn_hyperparam()
    print('bestconf',res[0])
    print('error of RSM',res[3])
    # s=[0, np.array([], dtype='float64'), 0.14289055892459254, 0.0, 0.0, 0.64011881862533493, 0.66598721505367042, 1, 1]
    # print(train_MINST.train_model_s(s, data)[0])


text:
<?php

namespace App\Validations;

use App\Repositories\SubagentRepository;
use App\Validations\Validation;
use Illuminate\Validation\Validator;

class SubagentValidation extends Validation
{
	/**
     * Get rules for index request.
     *
     * @return array
     */
    public function rulesIndex()
    {
        return array_merge($this->basicIndexRules('subagents'), [
            'agent' => 'sometimes|exists:andila.agents,id',
            'contract_value' => 'sometimes',
            'active' => 'sometimes|boolean',
            'schedulable' => 'sometimes|boolean',
        ]);
    }

    /**
     * Get rules for store single request.
     *
     * @return array
     */
    public function rulesSingle()
    {
    	return [
            'agent_id' => 'required|exists:andila.agents,id',
            'name' => 'required|max:255',
            'email' => 'required|email|max:255',
            'phone' => 'required|string',
            'owner' => 'required|string',
            'location' => 'required|array',
            'location.*' => 'required|numeric',
            'contract_value' => 'required|numeric|between:'. SubagentRepository::CONTRACT_VALUE_MIN .','. SubagentRepository::CONTRACT_VALUE_MAX,
            'address.detail' => 'sometimes|string',
	        'address.subdistrict' => 'sometimes|string',
	        'address.district' => 'sometimes|string',
	        'address.regency' => 'sometimes|string',
	        'address.province' => 'sometimes|string',
	        'address.postal_code' => 'sometimes|numeric',
	        'user.email' => 'sometimes|required_with:user.password|email|max:255|unique:andila.users,email',
	        'user.password' => 'sometimes|required_with:user.email|string|min:5',
        ];
    }

    /**
     * Get rules for show request.
     *
     * @return array
     */
    public function rulesShow()
    {
        return [
            'agent' => 'sometimes|boolean',
            'subschedules' => 'sometimes|boolean',
        ];
    }

    /**
     * Get rules for activates request.
     *
     * @return array
     */
    public function rulesActivates()
    {
        return [
        	'ids' => 'required|array',
            'ids.*' => 'required_with:ids|exists:andila.subagents,id,active,0',
        ];
    }

    /**
     * Get rules for deactivates request.
     *
     * @return array
     */
    public function rulesDeactivates()
    {
        return [
        	'ids' => 'required|array',
            'ids.*' => 'required_with:ids|exists:andila.subagents,id,active,1',
        ];
    }

    /**
     * Get rules for update request.
     *
     * @return array
     */
    public function rulesUpdate()
    {
    	return [
            'name' => 'sometimes|max:255',
            'email' => 'sometimes|email|max:255',
            'phone' => 'sometimes|string',
            'owner' => 'sometimes|string',
            'location' => 'sometimes|array',
            'location.*' => 'required_with:location|numeric',
            'contract_value' => 'sometimes|numeric|between:'. SubagentRepository::CONTRACT_VALUE_MIN .','. SubagentRepository::CONTRACT_VALUE_MAX,
            'address.detail' => 'sometimes|string',
	        'address.subdistrict' => 'sometimes|string',
	        'address.district' => 'sometimes|string',
	        'address.regency' => 'sometimes|string',
	        'address.province' => 'sometimes|string',
	        'address.postal_code' => 'sometimes|numeric',
        ];
    }

    /**
     * Run extra validation of index request.
     *
     * @param  Validator  $validator
     * @param  array  $additional
     * @return Validator
     */
    public function afterIndex(Validator $validator, $additional)
    {
        if (is_null($additional['contract_value'])) {
            return $validator;
        }

        $validator->after(function ($v) use ($additional) {
            list($operator, $value) = explode(':', $additional['contract_value']);

            // If the operator is invalid, error will be inserted.
            // This step is hardcoded for some reason.
            if ($operator !== '=' && $operator !== '<' && $operator !== '>' && $operator !== '<=' && $operator !== '>=' && $operator !== '<>') {
            	$this->addContractValueError($v);
            }

            // If the value is a negative integer
            // Error will be inserted.
            if (! is_numeric($value) || (int)$value < 0) {
            	$this->addContractValueError($v);
            }

        });

        return $validator;
    }

    /**
     * Add "contract_value" field error to validator.
     * That's right! I separated this due to its multiple calls.
     *
     * @param  Validator  $validator
     * @return void
     */
    protected function addContractValueError(Validator $validator)
    {
        $validator->errors()->add('contract_value', 'The contract_value should be a pair of operator and value separated with colon (operator:value), where operator is valid according to documentation and value is not a negative integer');
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../../nemo/session_types/trait.Acceptor.html">

Redirecting to ../../../nemo/session_types/trait.Acceptor.html...


text:
% --- Executes on slider movement.
function slider_callback(index)
global Plant TestData
handles = guihandles;
if strcmp(Plant.optimoptions.solver,'NREL')
    building = Plant.Building;
    building.Tzone = 22;
    date = TestData.Timestamp(1) + get(handles.sliderStartDate,'Value');
    solution = single_optimization_NREL(Plant.Generator,building,Plant.optimoptions,TestData,date);
    Plant.Building.Tzone = solution.Buildings.Temperature(1);
    plot_project(Plant.Generator,Plant.Building,[],3,[],solution,[],handles,'Result')
else
    if ~isfield(Plant,'Dispatch') || isempty(Plant.Dispatch) || ~isfield(Plant.Dispatch,'Timestamp') || isempty(Plant.Dispatch.Timestamp) || min(abs(Plant.Dispatch.Timestamp-(TestData.Timestamp(1) + get(handles.sliderStartDate,'Value'))))>=Plant.optimoptions.Resolution/24
        date = TestData.Timestamp(1) + get(handles.sliderStartDate,'Value')+[0;build_time_vector(Plant.optimoptions)/24];
        if ~isfield(Plant,'Building')
            Plant.Building = [];
        end
        if ~isfield(Plant,'fluid_loop')
            Plant.fluid_loop = [];
        end
        if isfield(Plant,'Data')
            data = Plant.Data;
        else
            data = [];
        end
        if isfield(Plant,'Weather')
            weather = Plant.Weather;
        else
            weather = [];
        end
        TestData = update_test_data(TestData,data,weather,Plant.optimoptions);
        if ~isfield(Plant,'Dispatch') || ~isempty(Plant.Dispatch)
            [Plant.Generator,Plant.Building,Plant.fluid_loop,Plant.subNet,Plant.OpMatA,Plant.OpMatB,Plant.OneStep,~,~,Plant.Dispatch,Plant.Predicted,Plant.Design,~] = initialize_optimization(Plant.Generator,Plant.Building,Plant.fluid_loop,Plant.Network,Plant.optimoptions,TestData,date(1));
        end
        [wy_forecast,Plant.Generator] = water_year_forecast(Plant.Generator,Plant.Building,Plant.fluid_loop,Plant.subNet,Plant.optimoptions,date,[],TestData);%if october 1st,Run a yearly forecast for hydrology
        if strcmp(Plant.optimoptions.solver,'ANN')
            Plant.optimoptions.solver = 'quadprog';
            [solution,forecast,Plant.Generator,Plant.Building,Plant.fluid_loop] = single_optimization(date,[],Plant.Generator,Plant.Building,Plant.fluid_loop,Plant.optimoptions,Plant.Dispatch,Plant.subNet,Plant.OpMatA,Plant.OpMatB,Plant.OneStep,TestData,wy_forecast);
            Plant.optimoptions.solver = 'ANN';
        else
            [solution,forecast,Plant.Generator,Plant.Building,Plant.fluid_loop] = single_optimization(date,[],Plant.Generator,Plant.Building,Plant.fluid_loop,Plant.optimoptions,Plant.Dispatch,Plant.subNet,Plant.OpMatA,Plant.OpMatB,Plant.OneStep,TestData,wy_forecast);
        end
        Plant.current_solution = solution;
        history = [];
    else
        d = TestData.Timestamp(1) + get(handles.sliderStartDate,'Value');
        s_i = max((1:1:length(Plant.Dispatch.Timestamp))'.*(Plant.Dispatch.Timestamp<=d & Plant.Dispatch.Timestamp>0)); %index preceeding current step
        if (Plant.Dispatch.Timestamp(s_i+1)>0 && (Plant.Dispatch.Timestamp(s_i+1)-d)<(d-Plant.Dispatch.Timestamp(s_i)))
            s_i = s_i+1; %The next time step is actually closer
        elseif Plant.Predicted.Timestamp(1,s_i)==0
            s_i = s_i - 1;
        end
        if s_i ==0
            solution = Plant.current_solution;
            history = [];
            date = TestData.Timestamp(1) + get(handles.sliderStartDate,'Value')+[0;build_time_vector(Plant.optimoptions)/24];
        else
            date = [d;Plant.Predicted.Timestamp(:,s_i)];
            solution.Dispatch = [zeros(1,length(Plant.Predicted.GenDisp(1,:,s_i)));Plant.Predicted.GenDisp(:,:,s_i);];
            solution.LineFlows = Plant.Predicted.LineFlows(:,:,s_i);
            solution.Buildings.Temperature = Plant.Predicted.Buildings(:,:,s_i);
            solution.fluid_loop = Plant.Predicted.fluid_loop(:,:,s_i);
            solution.hydroSOC = Plant.Predicted.hydroSOC(:,:,s_i);
            backSteps = min(s_i-1,Plant.optimoptions.Horizon/Plant.optimoptions.Resolution);
            history.Dispatch = Plant.Dispatch.GeneratorState(s_i-backSteps:s_i,:);
            history.LineFlows = Plant.Dispatch.LineFlows(s_i-backSteps:s_i,:);
            history.Buildings = Plant.Dispatch.Buildings(s_i-backSteps:s_i,:);
            history.fluid_loop = Plant.Dispatch.fluid_loop(s_i-backSteps:s_i,:);
            history.hydroSOC = Plant.Dispatch.Hydro.SOC(s_i-backSteps:s_i,:);
            history.Timestamp = Plant.Dispatch.Timestamp(s_i-backSteps:s_i,:);
        end
    end
    solution.Timestamp = date;
    gen = Plant.Generator;
    mode = 'Result';
    if ~isempty(index)
        gen = gen(index);
        solution.Dispatch = solution.Dispatch(:,index);
        if ~isempty(history)
            history.Dispatch = history.Dispatch(:,index);
        end
        mode = 'Forecast';
    end
    n_plot = length(fieldnames(Plant.subNet));
    plot_project(gen,Plant.Building,Plant.fluid_loop,n_plot,history,solution,[],handles,mode)
end


text:
package org.jabref.gui.collab.entryadd;

import org.jabref.gui.DialogService;
import org.jabref.gui.StateManager;
import org.jabref.gui.collab.ExternalChangeDetailsView;
import org.jabref.gui.preview.PreviewViewer;
import org.jabref.gui.theme.ThemeManager;
import org.jabref.model.database.BibDatabaseContext;
import org.jabref.preferences.PreferencesService;

public final class EntryAddDetailsView extends ExternalChangeDetailsView {

    public EntryAddDetailsView(EntryAdd entryAdd, BibDatabaseContext bibDatabaseContext, DialogService dialogService, StateManager stateManager, ThemeManager themeManager, PreferencesService preferencesService) {
        PreviewViewer previewViewer = new PreviewViewer(bibDatabaseContext, dialogService, stateManager, themeManager);
        previewViewer.setLayout(preferencesService.getPreviewPreferences().getSelectedPreviewLayout());
        previewViewer.setEntry(entryAdd.getAddedEntry());

        setLeftAnchor(previewViewer, 8d);
        setTopAnchor(previewViewer, 8d);
        setRightAnchor(previewViewer, 8d);
        setBottomAnchor(previewViewer, 8d);

        getChildren().setAll(previewViewer);
    }
}


text:
Given(/^I visit the collection's edit page$/) do
  visit edit_collection_path(@collection)
end

Then(/^the collection is no longer visible$/) do
  visit gallery_collections_path(@collection.gallery_id)
  expect(page).not_to have_content(@collection.name)
end

When(/^I select a different gallery$/) do
  select(@new_gallery.name, :from => 'Gallery')
end

When(/^I click "([^"]*)"$/) do |link_name|
  click_link_or_button link_name
end

Then(/^I see success message "([^"]*)"$/) do |notice|
  expect(page).to have_content(notice)
end

Then(/^the collection now belong to a different gallery$/) do
  visit collection_path(@collection)
  expect(page).to have_content(@new_gallery.name)
end

When(/^I click to Destroy collection$/) do
  page.driver.submit :delete, "/collections/#{@collection.id}", {}
end

Given(/^collection has no items$/) do
  @collection.items = []
end

Then(/^I no longer see collection$/) do
  expect(page).not_to have_content(@collection.name)

end