text:
layout: page
title: "Interpreter in Apache Zeppelin"
description: "This document explains the role of interpreters, interpreter groups and interpreter settings in Apache Zeppelin. The concept of Zeppelin interpreters allows any language or data-processing backend to be plugged into Zeppelin."
group: usage/interpreter
---

{% include JB/setup %}

# Interpreter in Apache Zeppelin

## Overview

In this section, we will explain the role of interpreters, interpreter groups and interpreter settings in Zeppelin.
The concept of Zeppelin interpreters allows any language or data-processing backend to be plugged into Zeppelin.
Currently, Zeppelin supports many interpreters such as Scala (with Apache Spark), Python (with Apache Spark), Spark SQL, JDBC, Markdown, Shell and so on.

## What are Zeppelin interpreters?
A Zeppelin interpreter is a plug-in which enables Zeppelin users to use a specific language/data-processing-backend. For example, to use Scala code in Zeppelin, you would use the `%spark` interpreter.

When you click the ```+Create``` button on the interpreter page, the interpreter drop-down list box will show all the available interpreters on your server.

## What are the interpreter settings?
The interpreter settings are the configuration of a given interpreter on the Zeppelin server. For example, certain properties need to be set for the Apache Hive JDBC interpreter to connect to the Hive server.

Properties are exported as environment variables on the system if the property name consists of upper-case characters, numbers or underscores ([A-Z_0-9]). Otherwise, the property is set as a JVM property.

You may use parameters from the context of the interpreter by adding #{contextParameterName} in the value. The parameter can be of the following types: string, number, boolean.

###### Context parameters

    Name
    Type

    user
    string

    noteId
    string

    replName
    string

    className
    string

If the context parameter is null, then it is replaced by an empty string.

Each notebook can be bound to multiple Interpreter Settings using the setting icon in the upper right corner of the notebook.

## What are interpreter groups?
Every interpreter belongs to an **Interpreter Group**. Interpreter Groups are units of interpreters that can be started/stopped together.
By default, every interpreter belongs to a separate group, but the group might contain more interpreters. For example, the Spark interpreter group includes Spark support, pySpark, Spark SQL and the dependency loader.

Technically, Zeppelin interpreters from the same group run within the same JVM. For more information about this, please consult [the documentation on writing interpreters](../development/writing_zeppelin_interpreter.html).

Each interpreter belongs to a single group and is registered together. All relevant properties are listed in the interpreter setting as in the below example.

## Interpreter binding mode

In the Interpreter Settings, one can choose one of the 'shared', 'scoped', or 'isolated' interpreter binding modes.
In 'shared' mode, every notebook bound to the Interpreter Setting will share a single Interpreter instance. In 'scoped' mode, each notebook will create a new interpreter instance in the same interpreter process. In 'isolated' mode, each notebook will create new a interpreter process.

For more information, please consult [Interpreter Binding Mode](./interpreter_binding_mode.html).

## Connecting to the existing remote interpreter

Zeppelin users can start interpreter threads embedded in their service. This provides users with the flexibility of starting interpreters on a remote host. To start an interpreter along with your service you have to create an instance of ``RemoteInterpreterServer`` and start it as follows:

```java
RemoteInterpreterServer interpreter=new RemoteInterpreterServer(3678);
// Here, 3678 is the port on which interpreter will listen.
interpreter.start();

```

The above code will start an interpreter thread inside your process. Once the interpreter has started, you can configure Zeppelin to connect to RemoteInterpreter by checking the **Connect to existing process** checkbox and then provide the **Host** and **Port** on which interpreter process is listening, as shown in the image below:

## Precode

Snippet of code (language of interpreter) that executes after initialization of the interpreter depends on [Binding mode](#interpreter-binding-mode). To configure, add a parameter with the class of the interpreter (`zeppelin.<ClassName>.precode`) except JDBCInterpreter ([JDBC precode](../../interpreter/jdbc.html#usage-precode)).

## Interpreter Lifecycle Management

Before 0.8.0, Zeppelin didn't have lifecycle management for interpreters. Users had to shut down interpreters explicitly via the UI. Starting from 0.8.0, Zeppelin provides a new interface
`LifecycleManager` to control the lifecycle of interpreters. For now, there are two implementations: `NullLifecycleManager` and `TimeoutLifecycleManager`, which is the default.

`NullLifecycleManager` will do nothing, i.e., the user needs to control the lifecycle of interpreter by themselves as before. `TimeoutLifecycleManager` will shut down interpreters after an interpreter remains idle for a while. By default, the idle threshold is 1 hour.
Users can change this threshold via the `zeppelin.interpreter.lifecyclemanager.timeout.threshold` setting. `TimeoutLifecycleManager` is the default lifecycle manager, and users can change it via `zeppelin.interpreter.lifecyclemanager.class`.

## Generic ConfInterpreter

Zeppelin's interpreter setting is shared by all users and notes, if you want to have different settings, you have to create a new interpreter, e.g. you can create `spark_jar1` for running Spark with dependency jar1 and `spark_jar2` for running Spark with dependency jar2.
This approach works, but is not particularly convenient. `ConfInterpreter` can provide more fine-grained control on interpreter settings and more flexibility.

`ConfInterpreter` is a generic interpreter that can be used by any interpreter. The input format should be the property file format.
It can be used to make custom settings for any interpreter. However, `ConfInterpreter` needs to be run before that interpreter process is launched. When that interpreter process is launched is determined by the interpreter mode setting.
So users need to understand the [interpreter mode setting](../usage/interpreter/interpreter_bindings_mode.html) of Zeppelin and be aware of when the interpreter process is launched. E.g., if we set the Spark interpreter setting as isolated per note, then, under this setting, each note will launch one interpreter process.
In this scenario, users need to put `ConfInterpreter` as the first paragraph as in the below example. Otherwise, the customized setting cannot be applied (actually it would report ERROR).

## Interpreter Process Recovery

Before 0.8.0, shutting down Zeppelin also meant to shutdown all the running interpreter processes. Usually, an administrator will shutdown the Zeppelin server for maintenance or upgrades, but would not want to shut down the running interpreter processes.
In such cases, interpreter process recovery is necessary. Starting from 0.8.0, users can enable interpreter process recovery via the setting `zeppelin.recovery.storage.class` as
`org.apache.zeppelin.interpreter.recovery.FileSystemRecoveryStorage` or other implementations if available in the future. By default it is `org.apache.zeppelin.interpreter.recovery.NullRecoveryStorage`,
 which means recovery is not enabled. Enabling recovery means shutting down Zeppelin would not terminate interpreter processes, and when Zeppelin is restarted, it would try to reconnect to the existing running interpreter processes. If you want to kill all the interpreter processes after terminating Zeppelin even when recovery is enabled, you can run `bin/stop-interpreter.sh`

## Credential Injection

Credentials from the credential manager can be injected into Notebooks. Credential injection works by replacing the following patterns in Notebooks with matching credentials for the Credential Manager: `{user.CREDENTIAL_ENTITY}` and `{password.CREDENTIAL_ENTITY}`. However, credential injection must be enabled per Interpreter, by adding a boolean `injectCredentials` setting in the Interpreters configuration. Injected passwords are removed from Notebook output to prevent accidentally leaking passwords.

**Credential Injection Setting**

**Credential Entry Example**

**Credential Injection Example**
```
val password = "{password.SOME_CREDENTIAL_ENTITY}"
val username = "{user.SOME_CREDENTIAL_ENTITY}"
```


text:
package org.dhira.core.optimize.listeners

import lombok.Builder
import org.dhira.core.nnet.api.Model
import org.dhira.core.optimize.api.IterationListener
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.linalg.ops.transforms.Transforms
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardOpenOption

/**
 * An iteration listener that provides details on parameters and gradients at each iteration during traning.
 * Attempts to provide much of the same information as the UI histogram iteration listener, but in a text-based
 * format (for example, when learning on a system accessed via SSH etc).
 * i.e., is intended to aid network tuning and debugging

 * This iteration listener is set up to calculate mean, min, max, and mean absolute value
 * of each type of parameter and gradient in the network at each iteration.

 * These
 *
 *
 * @author Alex Black
 */
object ParamAndGradientIterationListener {
  private val MAX_WRITE_FAILURE_MESSAGES: Int = 10
  private val logger: Logger = LoggerFactory.getLogger(classOf[ParamAndGradientIterationListener])
}

class ParamAndGradientIterationListener extends IterationListener {
  private var isInvoked: Boolean = false
  private var iterations: Int = 1
  private var totalIterationCount: Long = 0
  private var printMean: Boolean = true
  private var printHeader: Boolean = true
  private var printMinMax: Boolean = true
  private var printMeanAbsValue: Boolean = true
  private var file: File = null
  private var filePath: Path = null
  private var outputToConsole: Boolean = false
  private var outputToFile: Boolean = false
  private var outputToLogger: Boolean = false
  private var delimiter: String = "\t"
  private var writeFailureCount: Int = 0

  /** Default constructor for output to console only every iteration, tab delimited */
//  def this() {
//   // this(1, true, true, true, true, true, false, false, null, "\t")
//  }

  /** Full constructor with all options.
    * Note also: ParamAndGradientIterationListener.builder() can be used instead of this constructor.
    * @param iterations calculate and report values every 'iterations' iterations
    * @param printHeader Whether to output a header row (i.e., names for each column)
    * @param printMean Calculate and display the mean of parameters and gradients
    * @param printMinMax Calculate and display the min/max of the parameters and gradients
    * @param printMeanAbsValue Calculate and display the mean absolute value
    * @param outputToConsole If true, display the values to the console (System.out.println())
    * @param outputToFile If true, write the values to a file, one per line
    * @param outputToLogger If true, log the values
    * @param file File to write values to. May be null, not used if outputToFile == false
    * @param delimiter delimiter (for example, "\t" or "," etc)
    */
  @Builder def this(iterations: Int, printHeader: Boolean, printMean: Boolean, printMinMax: Boolean,
                    printMeanAbsValue: Boolean, outputToConsole: Boolean, outputToFile: Boolean,
                    outputToLogger: Boolean, file: File, delimiter: String) {
    this()
    this.printHeader = printHeader
    this.printMean = printMean
    this.printMinMax = printMinMax
    this.printMeanAbsValue = printMeanAbsValue
    this.iterations = iterations
    this.file = file
    if (this.file != null) {
      this.filePath = file.toPath
    }
    this.outputToConsole = outputToConsole
    this.outputToFile = outputToFile
    this.outputToLogger = outputToLogger
    this.delimiter = delimiter
  }

  def invoked: Boolean = {
    return isInvoked
  }

  def invoke {
    isInvoked = true
  }

  def iterationDone(model: Model, iteration: Int) {
    totalIterationCount += 1
    if (totalIterationCount == 1 && printHeader) {
      val params: Map[String, INDArray] = model.paramTable
      model.conf.getVariables
      val sb: StringBuilder = new StringBuilder
      sb.append("n")
      sb.append(delimiter)
      sb.append("score")
      import scala.collection.JavaConversions._
      for (s <- params.keySet) {
        if (printMean) sb.append(delimiter).append(s).append("_mean")
        if (printMinMax) {
          sb.append(delimiter).append(s).append("_min").append(delimiter).append(s).append("_max")
        }
        if (printMeanAbsValue) sb.append(delimiter).append(s).append("_meanAbsValue")
        if (printMean) sb.append(delimiter).append(s).append("_meanG")
        if (printMinMax) {
          sb.append(delimiter).append(s).append("_minG").append(delimiter).append(s).append("_maxG")
        }
        if (printMeanAbsValue) sb.append(delimiter).append(s).append("_meanAbsValueG")
      }
      sb.append("\n")
      if (outputToFile) {
        try {
          Files.write(filePath, sb.toString.getBytes, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)
        }
        catch {
          case e: IOException => {
            if (({
              writeFailureCount += 1; writeFailureCount - 1
            }) < ParamAndGradientIterationListener.MAX_WRITE_FAILURE_MESSAGES) {
              ParamAndGradientIterationListener.logger.warn("Error writing to file: {}", e)
            }
            if (writeFailureCount == ParamAndGradientIterationListener.MAX_WRITE_FAILURE_MESSAGES) {
              ParamAndGradientIterationListener.logger.warn("Max file write messages displayed. No more failure messages will be printed")
            }
          }
        }
      }
      if (outputToLogger) ParamAndGradientIterationListener.logger.info(sb.toString)
      if (outputToConsole) System.out.println(sb.toString)
    }
    if (totalIterationCount % iterations != 0) return
    val params: Map[String, INDArray] = model.paramTable
    val grads: Map[String, INDArray] = model.gradient.gradientForVariable
    val sb: StringBuilder = new StringBuilder
    sb.append(totalIterationCount)
    sb.append(delimiter)
    sb.append(model.score)
    import scala.collection.JavaConversions._
    for (entry <- params.entrySet) {
      val currParams: INDArray = entry.getValue
      val currGrad: INDArray = grads.get(entry.getKey)
      if (printMean) {
        sb.append(delimiter)
        sb.append(currParams.meanNumber.doubleValue)
      }
      if (printMinMax) {
        sb.append(delimiter)
        sb.append(currParams.minNumber.doubleValue)
        sb.append(delimiter)
        sb.append(currParams.maxNumber.doubleValue)
      }
      if (printMeanAbsValue) {
        sb.append(delimiter)
        val abs: INDArray = Transforms.abs(currParams.dup)
        sb.append(abs.meanNumber.doubleValue)
      }
      if (printMean) {
        sb.append(delimiter)
        sb.append(currGrad.meanNumber.doubleValue)
      }
      if (printMinMax) {
        sb.append(delimiter)
        sb.append(currGrad.minNumber.doubleValue)
        sb.append(delimiter)
        sb.append(currGrad.maxNumber.doubleValue)
      }
      if (printMeanAbsValue) {
        sb.append(delimiter)
        val abs: INDArray = Transforms.abs(currGrad.dup)
        sb.append(abs.meanNumber.doubleValue)
      }
    }
    sb.append("\n")
    val out: String = sb.toString
    if (outputToLogger) ParamAndGradientIterationListener.logger.info(out)
    if (outputToConsole) System.out.print(out)
    if (outputToFile) {
      try {
        Files.write(filePath, out.getBytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND)
      }
      catch {
        case e: IOException => {
          if (({
            writeFailureCount += 1; writeFailureCount - 1
          }) < ParamAndGradientIterationListener.MAX_WRITE_FAILURE_MESSAGES) {
            ParamAndGradientIterationListener.logger.warn("Error writing to file: {}", e)
          }
          if (writeFailureCount == ParamAndGradientIterationListener.MAX_WRITE_FAILURE_MESSAGES) {
            ParamAndGradientIterationListener.logger.warn("Max file write messages displayed. No more failure messages will be printed")
          }
        }
      }
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
package patchtmpl

import (
	"testing"

	"github.com/GoogleCloudPlatform/k8s-cluster-bundle/pkg/converter"
	"github.com/GoogleCloudPlatform/k8s-cluster-bundle/pkg/filter"
)

func BenchmarkPatchTemplateApplier(t *testing.B) {
	component := `kind: Component
spec:
  objects:
  - apiVersion: v1
    kind: Pod
    metadata:
      namespace: derp
  - kind: PatchTemplate
    template: |
      kind: Pod
      metadata:
        namespace: {{.Name}}
  - kind: PatchTemplate
    template: |
      kind: Pod
      metadata:
        annotations:
          fooAnnot: {{.Annot}}
`
	patchOptions := map[string]interface{}{
		"Name":  "doom",
		"Annot": "slayer",
	}
	customFilter := &filter.Options{
		Annotations: map[string]string{
			"phase": "build",
		},
	}

	for i := 0; i < t.N; i++ {
		patcher := NewApplierWithConfig(WithFilterOpts(customFilter), WithIncludeTemplates(true))
		compObj, err := converter.FromYAMLString(component).ToComponent()
		if err != nil {
			t.Fatal(err)
		}
		_, err = patcher.ApplyOptions(compObj, patchOptions)
		if err != nil {
			t.Fatal(err)
		}
	}
}


text:
import os
import shutil
import subprocess
import sys

URL_TEMPLATE = ('https://commondatastorage.googleapis.com/chromeos-localmirror/'
                'distfiles/%(name)s-%(version)s.tar.bz2')

# Taken from the media-fonts/<name> ebuilds in chromiumos-overlay.
SOURCES = [
  {
    'name': 'notofonts',
    'version': '20150706'
  }, {
    'name': 'robotofonts',
    'version': '20150625'
  }
]

URLS = sorted([URL_TEMPLATE % d for d in SOURCES])
FONTS_DIR = '/usr/local/share/fonts'

def main(args):
  if not sys.platform.startswith('linux'):
    print "Error: %s must be run on Linux." % __file__
    return 1

  if os.getuid() != 0:
    print "Error: %s must be run as root." % __file__
    return 1

  if not os.path.isdir(FONTS_DIR):
    print "Error: Destination directory does not exist: %s" % FONTS_DIR
    return 1

  dest_dir = os.path.join(FONTS_DIR, 'chromeos')

  stamp = os.path.join(dest_dir, ".stamp02")
  if os.path.exists(stamp):
    with open(stamp) as s:
      if s.read() == '\n'.join(URLS):
        print "Chrome OS fonts already up-to-date in %s." % dest_dir
        return 0

  if os.path.isdir(dest_dir):
    shutil.rmtree(dest_dir)
  os.mkdir(dest_dir)
  os.chmod(dest_dir, 0755)

  print "Installing Chrome OS fonts to %s." % dest_dir
  for url in URLS:
    tarball = os.path.join(dest_dir, os.path.basename(url))
    subprocess.check_call(['curl', '-L', url, '-o', tarball])
    subprocess.check_call(['tar', '--no-same-owner', '--no-same-permissions',
                           '-xf', tarball, '-C', dest_dir])
    os.remove(tarball)

  readme = os.path.join(dest_dir, "README")
  with open(readme, 'w') as s:
    s.write("This directory and its contents are auto-generated.\n")
    s.write("It may be deleted and recreated. Do not modify.\n")
    s.write("Script: %s\n" % __file__)

  with open(stamp, 'w') as s:
    s.write('\n'.join(URLS))

  for base, dirs, files in os.walk(dest_dir):
    for dir in dirs:
      os.chmod(os.path.join(base, dir), 0755)
    for file in files:
      os.chmod(os.path.join(base, file), 0644)

  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))


text:
package top.limitart.concurrent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.limitart.base.Conditions;
import top.limitart.base.Func;
import top.limitart.base.Proc;

import java.util.concurrent.*;

/**
 * 消息队列占用者
 *
 * @param <R> 消息队列资源域
 */
public class TaskQueueActor<R extends Actor.Place<TaskQueue>> extends AbstractThreadActor<TaskQueue, R> {
    private static final Logger LOGGER = LoggerFactory.getLogger(TaskQueueActor.class);
    //同步执行最大阻塞时间
    private static final long SYNC_OVER_TIME = 2000;

    @Override
    public boolean sameThread(TaskQueue taskQueue) {
        return taskQueue.thread() == Thread.currentThread();
    }

    /**
     * 与其他消息队列协作任务(异步)
     * 当前线程不会等待指定线程执行完毕
     *
     * @param another   其他消息队列
     * @param process  其他消息队里执行的任务
     * @param onSuccess 在本队列执行的成功回调
     * @param onFail    在本队列执行的失败回调
     */
    public void onAnotherAsync(R another, Func<Boolean> process, Proc onSuccess, Proc onFail) {
        Conditions.notNull(another, "another");
        Conditions.notNull(process, "proccess");
        Conditions.notNull(onSuccess, "onSuccess");
        Conditions.notNull(onFail, "onFail");
        R where = where();
        Conditions.notNull(where, "no place to hold!");
        where.res().execute(() -> another.res().execute(() -> {
            if (process.run()) {
                where.res().execute(onSuccess::run);
            } else {
                where.res().execute(onFail::run);
            }
        }));
    }

    /**
     * 与其他消息队列协作任务(同步)
     * 保证在响应速度要求低的调用响应线程要求高的线程,阻塞前者以确保运行在前者线程的数据正确性
     *
     * @param another
     * @param process
     * @param onSuccess
     */
    public void onAnotherSync(R another, Func<Boolean> process, Proc onSuccess) {
        onAnotherSync(another, process, onSuccess, null);
    }

    public void onAnotherSync(R another, Func<Boolean> process, Proc onSuccess, Proc onFail) {
        Conditions.notNull(another, "another");
        Conditions.notNull(process, "process");
        Conditions.notNull(onSuccess, "onSuccess");
        R where = where();
        Conditions.notNull(where, "no place to hold!");
        where.res().execute(() -> {
            Future<Boolean> submit = another.res().submit(process::run);
            Boolean result = null;
            try {
                result = submit.get(SYNC_OVER_TIME, TimeUnit.MILLISECONDS);
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                LOGGER.error("task queue " + another.res().thread().getName(), e);
            }
            if (result == null || !result) {
                if (onFail != null) {
                    onFail.run();
                }
            } else {
                onSuccess.run();
            }
        });
    }
}


text:
#ifndef IDBDatabase_h
#define IDBDatabase_h

#include "bindings/v8/Dictionary.h"
#include "bindings/v8/ScriptWrappable.h"
#include "core/dom/ActiveDOMObject.h"
#include "core/dom/DOMStringList.h"
#include "core/events/Event.h"
#include "core/events/EventTarget.h"
#include "modules/indexeddb/IDBDatabaseCallbacks.h"
#include "modules/indexeddb/IDBMetadata.h"
#include "modules/indexeddb/IDBObjectStore.h"
#include "modules/indexeddb/IDBTransaction.h"
#include "modules/indexeddb/IndexedDB.h"
#include "public/platform/WebIDBDatabase.h"
#include "wtf/OwnPtr.h"
#include "wtf/PassOwnPtr.h"
#include "wtf/PassRefPtr.h"
#include "wtf/RefCounted.h"
#include "wtf/RefPtr.h"

namespace WebCore {

class DOMError;
class ExceptionState;
class ExecutionContext;

class IDBDatabase : public RefCounted<IDBDatabase>, public ScriptWrappable, public EventTargetWithInlineData, public ActiveDOMObject {
    REFCOUNTED_EVENT_TARGET(IDBDatabase);

public:
    static PassRefPtr<IDBDatabase> create(ExecutionContext*, PassOwnPtr<blink::WebIDBDatabase>, PassRefPtr<IDBDatabaseCallbacks>);
    ~IDBDatabase();

    void setMetadata(const IDBDatabaseMetadata& metadata) { m_metadata = metadata; }
    void indexCreated(int64_t objectStoreId, const IDBIndexMetadata&);
    void indexDeleted(int64_t objectStoreId, int64_t indexId);
    void transactionCreated(IDBTransaction*);
    void transactionFinished(const IDBTransaction*);

    // Implement the IDL
    const String& name() const { return m_metadata.name; }
    ScriptValue version(ExecutionContext*) const;
    PassRefPtr<DOMStringList> objectStoreNames() const;

    PassRefPtr<IDBObjectStore> createObjectStore(const String& name, const Dictionary&, ExceptionState&);
    PassRefPtr<IDBObjectStore> createObjectStore(const String& name, const IDBKeyPath&, bool autoIncrement, ExceptionState&);
    PassRefPtr<IDBTransaction> transaction(ExecutionContext* context, PassRefPtr<DOMStringList> scope, const String& mode, ExceptionState& exceptionState) { return transaction(context, *scope, mode, exceptionState); }
    PassRefPtr<IDBTransaction> transaction(ExecutionContext*, const Vector<String>&, const String& mode, ExceptionState&);
    PassRefPtr<IDBTransaction> transaction(ExecutionContext*, const String&, const String& mode, ExceptionState&);
    void deleteObjectStore(const String& name, ExceptionState&);
    void close();

    DEFINE_ATTRIBUTE_EVENT_LISTENER(abort);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(close);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
    DEFINE_ATTRIBUTE_EVENT_LISTENER(versionchange);

    // IDBDatabaseCallbacks
    virtual void onVersionChange(int64_t oldVersion, int64_t newVersion);
    virtual void onAbort(int64_t, PassRefPtr<DOMError>);
    virtual void onComplete(int64_t);

    // ActiveDOMObject
    virtual bool hasPendingActivity() const OVERRIDE;
    virtual void stop() OVERRIDE;

    // EventTarget
    virtual const AtomicString& interfaceName() const OVERRIDE;
    virtual ExecutionContext* executionContext() const OVERRIDE;

    bool isClosePending() const { return m_closePending; }
    void forceClose();
    const IDBDatabaseMetadata& metadata() const { return m_metadata; }
    void enqueueEvent(PassRefPtr<Event>);

    using EventTarget::dispatchEvent;
    virtual bool dispatchEvent(PassRefPtr<Event>) OVERRIDE;

    int64_t findObjectStoreId(const String& name) const;
    bool containsObjectStore(const String& name) const
    {
        return findObjectStoreId(name) != IDBObjectStoreMetadata::InvalidId;
    }

    blink::WebIDBDatabase* backend() const { return m_backend.get(); }

    static int64_t nextTransactionId();

    static const char indexDeletedErrorMessage[];
    static const char isKeyCursorErrorMessage[];
    static const char noKeyOrKeyRangeErrorMessage[];
    static const char noSuchIndexErrorMessage[];
    static const char noSuchObjectStoreErrorMessage[];
    static const char noValueErrorMessage[];
    static const char notValidKeyErrorMessage[];
    static const char notVersionChangeTransactionErrorMessage[];
    static const char objectStoreDeletedErrorMessage[];
    static const char requestNotFinishedErrorMessage[];
    static const char sourceDeletedErrorMessage[];
    static const char transactionFinishedErrorMessage[];
    static const char transactionInactiveErrorMessage[];

private:
    IDBDatabase(ExecutionContext*, PassOwnPtr<blink::WebIDBDatabase>, PassRefPtr<IDBDatabaseCallbacks>);

    void closeConnection();

    IDBDatabaseMetadata m_metadata;
    OwnPtr<blink::WebIDBDatabase> m_backend;
    RefPtr<IDBTransaction> m_versionChangeTransaction;
    typedef HashMap<int64_t, RefPtr<IDBTransaction> > TransactionMap;
    TransactionMap m_transactions;

    bool m_closePending;
    bool m_contextStopped;

    // Keep track of the versionchange events waiting to be fired on this
    // database so that we can cancel them if the database closes.
    Vector<RefPtr<Event> > m_enqueuedEvents;

    RefPtr<IDBDatabaseCallbacks> m_databaseCallbacks;
};

} // namespace WebCore

#endif // IDBDatabase_h


text:
<?php
/**
 * Created by PhpStorm.
 * User: marco.bunge
 * Date: 02.11.2016
 * Time: 17:27
 */

namespace Hawkbit\Application\Services;

use Hawkbit\Application;
use Hawkbit\Application\ApplicationInterface;
use Whoops\Run;

class WhoopsService
{
    private $service;
    /**
     * @var Run
     */
    private $runner;
    /**
     * @var Application\AbstractApplication
     */
    private $application;

    /**
     * ErrorHandler constructor.
     * @param Run $runner
     * @param Application\AbstractApplication $application
     */
    public function __construct(Run $runner, Application\AbstractApplication $application)
    {
        $this->runner = $runner;
        $this->application = $application;
    }

    /**
     * Determine error message by error configuration
     *
     * @param \Throwable|\Exception $exception
     *
     * @return string
     *
     */
    public function getErrorMessage($exception)
    {
        $application = $this->application;
        $errorHandler = $this->runner;

        // quit if error occured
        $shouldQuit = $application->isError();

        //
        if($application instanceof Application){
            // if request type ist not strict e.g. xml or json consider error config
            if (!$application->isXmlRequest() && !$application->isJsonRequest()) {
                $shouldQuit = $shouldQuit && $application->getConfig(ApplicationInterface::KEY_ERROR, ApplicationInterface::DEFAULT_ERROR);
            }
        }

        $errorHandler->allowQuit($shouldQuit);

        $method = $errorHandler::EXCEPTION_HANDLER;
        ob_start();
        $errorHandler->$method($exception);
        $message = ob_get_clean();

        return $message;
    }

    /**
     * Convert any type into an exception
     *
     * @param $error
     * @return \Exception|string
     */
    public function decorateException($error)
    {
        $application = $this->application;

        if (is_callable($error)) {
            $error = $application->getContainer()->call($error, [$application]);
        }

        if (is_object($error) && !($error instanceof \Exception)) {
            $error = method_exists($error,
                '__toString') ? $error->__toString() : 'Error with object ' . get_class($error);
        }

        if (is_resource($error)) {
            $error = 'Error with resource type ' . get_resource_type($error);
        }

        if (is_array($error)) {
            $error = implode("\n", $error);
        }

        if (!($error instanceof \Exception)) {
            $error = new \Exception(is_scalar($error) ? $error : 'Error with ' . gettype($error));
        }

        return $error;
    }
}


text:
<?php
namespace ZfcDatagrid\Column\Formatter;

use ZfcDatagrid\Column\AbstractColumn;

class Link extends AbstractFormatter
{
    protected $validRenderers = [
        'jqGrid',
        'bootstrapTable',
    ];

    public function getFormattedValue(AbstractColumn $column)
    {
        $row   = $this->getRowData();
        $value = $row[$column->getUniqueId()];

        return '' . $value . '';
    }
}


text:
#ifndef H_derivedLinkedStack
#define H_derivedLinkedStack

#include <iostream>
#include "unorderedLinkedList.h"

using namespace std;

template<class Type>
class linkedStackType: public unorderedLinkedList<Type>
{
public:
    void initializeStack();
    bool isEmptyStack() const;
    bool isFullStack() const;
    void push(const Type& newItem);
    Type top() const;
    void pop();
};

template<class Type>
void linkedStackType<Type>::initializeStack()
{
    unorderedLinkedList<Type>::initializeList();
}

template<class Type>
bool linkedStackType<Type>::isEmptyStack() const
{
    return unorderedLinkedList<Type>::isEmptyList();
}

template<class Type>
bool linkedStackType<Type>::isFullStack() const
{
    return false;
}

template<class Type>
void linkedStackType<Type>::push(const Type& newElement)
{
    unorderedLinkedList<Type>::insertFirst(newElement);
}

template<class Type>
Type linkedStackType<Type>::top() const
{
    return unorderedLinkedList<Type>::front();
}

template<class Type>
void linkedStackType<Type>::pop()
{
    nodeType<Type> *temp;

    temp = first;
    first = first->link;
    delete temp;
}

#endif


text:
//          Copyright Oliver Kowalke 2009.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_COROUTINES_STACK_ALLOCATOR_H
#define BOOST_COROUTINES_STACK_ALLOCATOR_H

#include <cstddef>

#include <boost/config.hpp>

#include <boost/context/detail/config.hpp>
#include <boost/coroutine/segmented_stack_allocator.hpp>
#include <boost/coroutine/standard_stack_allocator.hpp>

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

namespace boost {
namespace coroutines {

#if defined(BOOST_USE_SEGMENTED_STACKS)
typedef segmented_stack_allocator   stack_allocator;
#else
typedef standard_stack_allocator    stack_allocator;
#endif

}}

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

#endif // BOOST_COROUTINES_STACK_ALLOCATOR_H


text:
<!-- Basic mapping using the Dom4JListMapper to handle arbitrary content
 -->
<binding>
  <mapping name="contact" class="extras.Dom4JContact2">
    <value name="first-name" field="m_firstName"/>
    <value name="last-name" field="m_lastName"/>
    <value name="phone" field="m_phone"/>
    <structure field="m_information" usage="optional"
        marshaller="org.jibx.extras.Dom4JListMapper"
        unmarshaller="org.jibx.extras.Dom4JListMapper"/>
  </mapping>
</binding>


text:
<?php

namespace PB\Bundle\SuluStorageBundle\Tests\Provider\Filesystem\Exception;

use PB\Bundle\SuluStorageBundle\Provider\Filesystem\Exception\FilesystemProviderInternalException;
use PHPUnit\Framework\TestCase;

/**
 * @author Paweł Brzeziński <pawel.brzezinski@smartint.pl>
 */
class FilesystemProviderInternalExceptionTest extends TestCase
{
    public function exceptionDataProvider()
    {
        return [
            'default code parameter' => [0, null],
            'custom code parameter' => [123, 123],
        ];
    }

    /**
     * @dataProvider exceptionDataProvider
     *
     * @param $expectedCode
     * @param $code
     *
     * @throws FilesystemProviderInternalException
     */
    public function testException($expectedCode, $code)
    {
        // Expect
        $msg = 'Test exception message';
        $exceptionMsg = sprintf('Filesystem provider error occurred (%d): %s', $expectedCode, $msg);

        $this->expectException(FilesystemProviderInternalException::class);
        $this->expectExceptionCode(FilesystemProviderInternalException::INTERNAL_EXCEPTION_CODE);
        $this->expectExceptionMessage($exceptionMsg);

        // When
        if (null === $code) {
            throw new FilesystemProviderInternalException($msg);
        } else {
            throw new FilesystemProviderInternalException($msg, $code);
        }
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\Console\Command\Database\DatabaseLogBase.
 */

namespace Drupal\Console\Command\Database;

use Drupal\Core\Database\Connection;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\user\UserStorageInterface;
use Drupal\Console\Core\Command\Command;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\user\Entity\User;
use Drupal\Component\Utility\Unicode;
use Drupal\Component\Utility\Html;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;

/**
 * Class DatabaseLogBase
 *
 * @package Drupal\Console\Command\Database
 */
abstract class DatabaseLogBase extends Command
{
    /**
     * @var Connection
     */
    protected $database;

    /**
     * @var DateFormatterInterface
     */
    protected $dateFormatter;

    /**
     * @var EntityTypeManagerInterface
     */
    protected $entityTypeManager;

    /**
     * @var TranslationInterface
     */
    protected $stringTranslation;

    /**
     * @var UserStorageInterface
     */
    protected $userStorage;

    /**
     * @var TranslatableMarkup[]
     */
    protected $severityList;

    /**
     * @var null|string
     */
    protected $eventType;

    /**
     * @var null|string
     */
    protected $eventSeverity;

    /**
     * @var null|string
     */
    protected $userId;

    /**
     * LogDebugCommand constructor.
     *
     * @param Connection                 $database
     * @param DateFormatterInterface     $dateFormatter
     * @param EntityTypeManagerInterface $entityTypeManager
     * @param TranslationInterface       $stringTranslation
     */
    public function __construct(
        Connection $database,
        DateFormatterInterface $dateFormatter,
        EntityTypeManagerInterface $entityTypeManager,
        TranslationInterface $stringTranslation
    ) {
        $this->database = $database;
        $this->dateFormatter = $dateFormatter;
        $this->entityTypeManager = $entityTypeManager;
        $this->stringTranslation = $stringTranslation;
        $this->userStorage = $this->entityTypeManager->getStorage('user');
        $this->severityList = RfcLogLevel::getLevels();
        parent::__construct();
    }

    /**
     * addDefaultLoggingOptions.
     */
    protected function addDefaultLoggingOptions()
    {
        $this
            ->addOption(
                'type',
                null,
                InputOption::VALUE_OPTIONAL,
                $this->trans('commands.database.log.common.options.type')
            )
            ->addOption(
                'severity',
                null,
                InputOption::VALUE_OPTIONAL,
                $this->trans('commands.database.log.common.options.severity')
            )
            ->addOption(
                'user-id',
                null,
                InputOption::VALUE_OPTIONAL,
                $this->trans('commands.database.log.common.options.user-id')
            );
    }

    /**
     * @param InputInterface $input
     */
    protected function getDefaultOptions(InputInterface $input)
    {
        $this->eventType = $input->getOption('type');
        $this->eventSeverity = $input->getOption('severity');
        $this->userId = $input->getOption('user-id');
    }

    /**
     * @param null        $offset
     * @param int         $range
     * @return bool|\Drupal\Core\Database\Query\SelectInterface
     */
    protected function makeQuery($offset = null, $range = 1000)
    {
        $query = $this->database->select('watchdog', 'w');
        $query->fields(
            'w',
            [
                'wid',
                'uid',
                'severity',
                'type',
                'timestamp',
                'message',
                'variables',
            ]
        );

        if ($this->eventType) {
            $query->condition('type', $this->eventType);
        }

        if ($this->eventSeverity) {
            if (!in_array($this->eventSeverity, $this->severityList)) {
                $this->getIo()->error(
                    sprintf(
                        $this->trans('database.log.common.messages.invalid-severity'),
                        $this->eventSeverity
                    )
                );
                return false;
            }
            $query->condition(
                'severity',
                array_search(
                    $this->eventSeverity,
                    $this->severityList
                )
            );
        }

        if ($this->userId) {
            $query->condition('uid', $this->userId);
        }

        $query->orderBy('wid', 'ASC');

        if ($offset) {
            $query->range($offset, $range);
        }

        return $query;
    }

    /**
     * Generic logging table header
     *
     * @return array
     */
    protected function createTableHeader()
    {
        return [
            $this->trans('commands.database.log.common.messages.event-id'),
            $this->trans('commands.database.log.common.messages.type'),
            $this->trans('commands.database.log.common.messages.date'),
            $this->trans('commands.database.log.common.messages.message'),
            $this->trans('commands.database.log.common.messages.user'),
            $this->trans('commands.database.log.common.messages.severity'),
        ];
    }

    /**
     * @param \stdClass $dblog
     * @return array
     */
    protected function createTableRow(\stdClass $dblog)
    {

        /**
         * @var User $user
         */
        if ($user = $this->userStorage->load($dblog->uid)) {
            $user_id = $user->id();
            $user_name = $user->getAccountName();
        } else {
            $user_id = $dblog->uid;
            $user_name = $this->trans('commands.database.log.common.messages.user-deleted');
        }

        return [
            $dblog->wid,
            $dblog->type,
            $this->dateFormatter->format($dblog->timestamp, 'short'),
            Unicode::truncate(
                Html::decodeEntities(strip_tags($this->formatMessage($dblog))),
                500,
                true,
                true
            ),
            $user_name . ' (' . $user_id . ')',
            $this->severityList[$dblog->severity]->render(),
        ];
    }

    /**
     * Formats a database log message.
     *
     * @param $event
     *   The record from the watchdog table. The object properties are: wid, uid,
     *   severity, type, timestamp, message, variables, link, name.
     *
     * @return string|false
     *   The formatted log message or FALSE if the message or variables properties
     *   are not set.
     */
    protected function formatMessage(\stdClass $event)
    {
        $message = false;

        // Check for required properties.
        if (isset($event->message, $event->variables)) {
            // Messages without variables or user specified text.
            if ($event->variables === 'N;') {
                return $event->message;
            }

            return $this->stringTranslation->translate(
                $event->message,
                unserialize($event->variables)
            );
        }

        return $message;
    }

    /**
     * @param $dblog
     * @return array
     */
    protected function formatSingle($dblog)
    {
        return array_combine(
            $this->createTableHeader(),
            $this->createTableRow($dblog)
        );
    }
}


text:
<?php get_header(); ?>

	<?php if (have_posts()): while (have_posts()) : the_post(); ?>

		<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

			<?php if(function_exists('rdfa_breadcrumb')){ rdfa_breadcrumb(); } ?>

				<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?>

<?php echo mostrar_adsense_1(); ?>

<a href="http://www.facebook.com/sharer/sharer.php?s=100&p[url]=<?php the_permalink();?>&p[title]=<?php the_title();?>" class="facebook">

<a href="http://twitter.com/home?status=Interesante:%20<?php the_title();?>%20%3E%3E%20<?php the_permalink();?>" class="twitter">

<a href="https://plus.google.com/share?url=<?php the_permalink();?>" class="plusone">

			<?php the_content(); // Dynamic Content ?>

<?php echo mostrar_adsense_2(); ?>

Articulos relacionados

			<?php relacionados(5); ?>

				 <?php _e( 'Escrito por', 'html5blank' ); ?> <?php the_author_posts_link(); ?>

					<?php the_tags( __( 'Tags: ', 'html5blank' ), ', ', ''); // Separated by commas with a line break at the end ?>

				<?php the_time('F j, Y'); ?>

					<?php _e( 'Categorias: ', 'html5blank' ); the_category(', '); // Separated by commas ?>

			<?php edit_post_link(); // Always handy to have Edit Post Links available ?>

			<?php comments_template(); ?>

	<?php endwhile; ?>

	<?php else: ?>

<?php _e( 'Sorry, nothing to display.', 'html5blank' ); ?>

	<?php endif; ?>

<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

	<link href='http://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>

	<title>Road Trip Calculator</title>

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

Road Trip Calculator

Car

					Car depreciation per mile

$

						<input type="number" class="form-control" id="car-deprec" placeholder="0.30" value="0.30">

Tires

					Value of each tire

$

						<input type="number" class="form-control" id="tire-value" placeholder="250.00" value="250.00">

					Tire warranty

						<input type="number" class="form-control" id="tire-warranty" placeholder="50000" value="50000">

miles

Gas

					Car gas mileage

						<input type="number" class="form-control" id="gas-mileage" placeholder="30" value="30">

miles per gallon

					Price of gas

$

						<input type="number" class="form-control" id="gas-price" placeholder="3.00" value="3.00">

Oil

					Oil change frequency

						<input type="number" class="form-control" id="oil-change" placeholder="5000" value="5000">

miles

					Price of an oil change

$

						<input type="number" class="form-control" id="oil-price" placeholder="32.00" value="32.00">

Brakes

					Brake lifespan

						<input type="number" class="form-control" id="brake-change" placeholder="30000" value="30000">

miles

					Price for new brakes for one wheel

$

						<input type="number" class="form-control" id="brake-price" placeholder="200.00" value="200.00">

Trip

					Distance (one way)

						<input type="number" class="form-control" id="distance" placeholder="215" value="215">

miles

					Tolls (one way)

$

						<input type="number" class="form-control" id="tolls" placeholder="5.54" value="5.54">

					Parking

$

						<input type="number" class="form-control" id="parking" placeholder="0.00" value="0.00">

Fixed Ownership Costs

					Car insurance (monthly)

$

						<input type="number" class="form-control" id="insurance" placeholder="150.00" value="150.00">

					Parking (monthly)

$

						<input type="number" class="form-control" id="mparking" placeholder="0.00" value="0.00">

					Excise tax (yearly)

$

						<input type="number" class="form-control" id="excise" placeholder="625.00" value="625.00">

Result

click calculate

				<button class="btn btn-lg btn-primary" id="calculate-button">Calculate</button>

		Road Trip Calculator | tlextrait.com | jackfru.it

		Find this on GitHub

		© Copyright 2015-2016, Thomas Lextrait, All Rights Reserved

		Attributions:

Icon made by Freepik from www.flaticon.com is licensed under CC BY 3.0

Icon made by OCHA from www.flaticon.com is licensed under CC BY 3.0

Icon made by Puppets from www.flaticon.com is licensed under CC BY 3.0


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Web.Validators
{
    using System.ComponentModel.DataAnnotations;
    using System.Reflection;

    public class DataAnnotationsObjectValidator : AttributeBasedObjectValidator<ValidationAttribute>
    {
        /// <inheritdoc/>
        protected override ValidationResult ValidateAttribute(object target, PropertyInfo targetProperty, ValidationAttribute attribute)
        {
            return !attribute.IsValid(targetProperty.GetValue(target, new object[] { })) ? new ValidationResult(new[] { this.CreateError(targetProperty.Name, attribute) }) : ValidationResult.Successful;
        }

        protected virtual ValidationError CreateError(string propertyName, ValidationAttribute attribute)
        {
            return new ValidationError { ErrorMessage = attribute.FormatErrorMessage(propertyName), PropertyName = propertyName, Validator = attribute };
        }
    }
}


text:
'use strict'

let Formatter = require('../formatter')

class JSONFormat extends Formatter {
  static get defaults () {
    return {
      fileExtension: '.json',
      pretty: false
    }
  }

  // Convert given data into object
  toObject (data) {
    return JSON.parse(data)
  }

  // Convert given data into storable string
  toString (data) {
    if (this.options.pretty) {
      return JSON.stringify(data, null, 4)
    }

    return JSON.stringify(data)
  }
}

module.exports = JSONFormat


text:
"""Verifies that Google Test warns the user when not initialized properly."""

import gtest_test_utils

binary_name = 'googletest-param-test-invalid-name2-test_'
COMMAND = gtest_test_utils.GetTestExecutablePath(binary_name)

def Assert(condition):
  if not condition:
    raise AssertionError

def TestExitCodeAndOutput(command):
  """Runs the given command and verifies its exit code and output."""

  err = ('Duplicate parameterized test name \'a\'')

  p = gtest_test_utils.Subprocess(command)
  Assert(p.terminated_by_signal)

  # Check for appropriate output
  Assert(err in p.output)

class GTestParamTestInvalidName2Test(gtest_test_utils.TestCase):

  def testExitCodeAndOutput(self):
    TestExitCodeAndOutput(COMMAND)

if __name__ == '__main__':
  gtest_test_utils.Main()


text:
<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * WeaponClass
 *
 * @ORM\Table(name="weapon_class")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\WeaponClassRepository")
 */
class WeaponClass
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, unique=true)
     */
    private $name;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return WeaponClass
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    public function __toString() {
        return $this->name;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using ApiPeek.Core.Extensions;

namespace ApiPeek.Core.Model;

[DataContract]
public class ApiEvent : ApiBaseItem, IDetail
{
    [DataMember]
    public string Type { get; set; }
    [DataMember]
    public bool IsStatic { get; set; }

    [IgnoreDataMember]
    public override string SortName => ShortString;

    [IgnoreDataMember]
    public override string ShortString => string.Format("{1}{0} : {2}", PrefixString, Name, Type);

    [IgnoreDataMember]
    private string PrefixString => IsStatic ? " static event" : " event";

    public static IEqualityComparer<ApiEvent> DetailComparer =
        ProjectionEqualityComparer<ApiEvent>.Create(x => x.Detail);

    [IgnoreDataMember]
    public string Detail => InDetail();

    private string detail;
    public string InDetail(string indent = "")
    {
        if (detail == null)
        {
            StringBuilder sb = new StringBuilder("public ");
            if (IsStatic) sb.Append("static ");
            sb.AppendFormat("event {0} {1};", Type, Name);
            detail = sb.ToString();
        }
        return indent + detail;
    }
}


text:
import h2o

class FeatureInteraction:

    def _feature_interaction(self, max_interaction_depth=100, max_tree_depth=100, max_deepening=-1, path=None):
        """
        Feature interactions and importance, leaf statistics and split value histograms in a tabular form.
        Available for XGBoost and GBM.

        Metrics:
        Gain - Total gain of each feature or feature interaction.
        FScore - Amount of possible splits taken on a feature or feature interaction.
        wFScore - Amount of possible splits taken on a feature or feature interaction weighed by
        the probability of the splits to take place.
        Average wFScore - wFScore divided by FScore.
        Average Gain - Gain divided by FScore.
        Expected Gain - Total gain of each feature or feature interaction weighed by the probability to gather the gain.
        Average Tree Index
        Average Tree Depth

        :param max_interaction_depth: Upper bound for extracted feature interactions depth. Defaults to 100.
        :param max_tree_depth: Upper bound for tree depth. Defaults to 100.
        :param max_deepening: Upper bound for interaction start deepening (zero deepening => interactions
            starting at root only). Defaults to -1.
        :param path: (Optional) Path where to save the output in .xlsx format (e.g. ``/mypath/file.xlsx``).
            Please note that Pandas and XlsxWriter need to be installed for using this option. Defaults to None.

        :examples:
        >>> boston = h2o.import_file("https://s3.amazonaws.com/h2o-public-test-data/smalldata/gbm_test/BostonHousing.csv")
        >>> predictors = boston.columns[:-1]
        >>> response = "medv"
        >>> boston['chas'] = boston['chas'].asfactor()
        >>> train, valid = boston.split_frame(ratios=[.8])
        >>> boston_xgb = H2OXGBoostEstimator(seed=1234)
        >>> boston_xgb.train(y=response, x=predictors, training_frame=train)
        >>> feature_interactions = boston_xgb.feature_interaction()
        """
        kwargs = {}
        kwargs["model_id"] = self.model_id
        kwargs["max_interaction_depth"] = max_interaction_depth
        kwargs["max_tree_depth"] = max_tree_depth
        kwargs["max_deepening"] = max_deepening

        json = h2o.api("POST /3/FeatureInteraction", data=kwargs)
        if path is not None:
            import pandas as pd
            writer = pd.ExcelWriter(path, engine='xlsxwriter')
            for fi in json['feature_interaction']:
                fi.as_data_frame().to_excel(writer, sheet_name=fi._table_header)
            writer.save()

        return json['feature_interaction']


text:
Handy plugin that automate joining/unjoining chain calls. Especially handy when
usign with jquery call-chains.

### Demo

![Demo](https://github.com/shagabutdinov/sublime-enhanced-demos/raw/master/join_chain_call.gif "Demo")

### Installation

This plugin is part of [sublime-enhanced](http://github.com/shagabutdinov/sublime-enhanced)
plugin set. You can install sublime-enhanced and this plugin will be installed
automatically.

If you would like to install this package separately check "Installing packages
separately" section of [sublime-enhanced](http://github.com/shagabutdinov/sublime-enhanced)
package.

### Usage

1. Join chain call

  ```
  # before
  $('.class1'). # cursor should be outside of brackets
    find('.class2').
    find('.class3')

  # after
  $('.class1').find('.class2').find('.class3')
  ```

2. Unjoin chain call

  ```
  # before
  $('.class1').find('.class2').find('.class3') # cursor should be outside of brackets

  # after
  $('.class1').
    find('.class2').
    find('.class3')
  ```

### Commands

| Description               | Keyboard shortcut | Command palette        |
|---------------------------|-------------------|------------------------|
| Toggle chain call joining | ctrl+alt+v        | JoinChainCall: toggle  |
| Join chain call           | ctrl+m, j         | JoinChainCall: join    |
| Unjoin chain call         | ctrl+m, ctrl+j    | JoinChainCall: unjoin  |

### Dependencies

* [Statement](https://github.com/shagabutdinov/sublime-statement)
* [Expression](https://github.com/shagabutdinov/sublime-expression)


text:
<?php

namespace OpenConext\EngineBlock\Exception;

final class InvalidJsonException extends RuntimeException
{
}


text:
package manifest_test

import (
	. "github.com/cloudfoundry/bosh-init/installation/manifest"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	birelmanifest "github.com/cloudfoundry/bosh-init/release/manifest"
	birelsetmanifest "github.com/cloudfoundry/bosh-init/release/set/manifest"
	boshlog "github.com/cloudfoundry/bosh-utils/logger"
	biproperty "github.com/cloudfoundry/bosh-utils/property"
)

var _ = Describe("Validator", func() {
	var (
		logger             boshlog.Logger
		releaseSetManifest birelsetmanifest.Manifest
		validator          Validator

		releases      []birelmanifest.ReleaseRef
		validManifest Manifest
	)

	BeforeEach(func() {
		logger = boshlog.NewLogger(boshlog.LevelNone)

		releases = []birelmanifest.ReleaseRef{
			{Name: "provided-valid-release-name"},
		}

		validManifest = Manifest{
			Name: "fake-installation-name",
			Template: ReleaseJobRef{
				Name:    "cpi",
				Release: "provided-valid-release-name",
			},
			Properties: biproperty.Map{
				"fake-prop-key": "fake-prop-value",
				"fake-prop-map-key": biproperty.Map{
					"fake-prop-key": "fake-prop-value",
				},
			},
		}

		releaseSetManifest = birelsetmanifest.Manifest{
			Releases: releases,
		}

		validator = NewValidator(logger)
	})

	Describe("Validate", func() {
		It("does not error if deployment is valid", func() {
			manifest := validManifest

			err := validator.Validate(manifest, releaseSetManifest)
			Expect(err).ToNot(HaveOccurred())
		})

		It("validates template must be fully specified", func() {
			manifest := Manifest{}

			err := validator.Validate(manifest, releaseSetManifest)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("cloud_provider.template.name must be provided"))
			Expect(err.Error()).To(ContainSubstring("cloud_provider.template.release must be provided"))
		})

		It("validates template.name is not blank", func() {
			manifest := Manifest{
				Template: ReleaseJobRef{
					Name: " ",
				},
			}

			err := validator.Validate(manifest, releaseSetManifest)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("cloud_provider.template.name must be provided"))
		})

		It("validates template.release is not blank", func() {
			manifest := Manifest{
				Template: ReleaseJobRef{
					Release: " ",
				},
			}

			err := validator.Validate(manifest, releaseSetManifest)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("cloud_provider.template.release must be provided"))
		})

		It("validates the release is available", func() {
			manifest := Manifest{
				Template: ReleaseJobRef{
					Release: "not-provided-valid-release-name",
				},
			}

			err := validator.Validate(manifest, releaseSetManifest)
			Expect(err).To(HaveOccurred())
			Expect(err.Error()).To(ContainSubstring("cloud_provider.template.release 'not-provided-valid-release-name' must refer to a release in releases"))
		})
	})
})


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactDom = require('react-dom');

var _reactDom2 = _interopRequireDefault(_reactDom);

var _domAlign = require('dom-align');

var _domAlign2 = _interopRequireDefault(_domAlign);

var _addEventListener = require('rc-util/lib/Dom/addEventListener');

var _addEventListener2 = _interopRequireDefault(_addEventListener);

var _isWindow = require('./isWindow');

var _isWindow2 = _interopRequireDefault(_isWindow);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function buffer(fn, ms) {
  var timer = void 0;

  function clear() {
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }
  }

  function bufferFn() {
    clear();
    timer = setTimeout(fn, ms);
  }

  bufferFn.clear = clear;

  return bufferFn;
}

var Align = _react2["default"].createClass({
  displayName: 'Align',

  propTypes: {
    childrenProps: _react.PropTypes.object,
    align: _react.PropTypes.object.isRequired,
    target: _react.PropTypes.func,
    onAlign: _react.PropTypes.func,
    monitorBufferTime: _react.PropTypes.number,
    monitorWindowResize: _react.PropTypes.bool,
    disabled: _react.PropTypes.bool,
    children: _react.PropTypes.any
  },

  getDefaultProps: function getDefaultProps() {
    return {
      target: function target() {
        return window;
      },
      onAlign: function onAlign() {},

      monitorBufferTime: 50,
      monitorWindowResize: false,
      disabled: false
    };
  },
  componentDidMount: function componentDidMount() {
    var props = this.props;
    // if parent ref not attached .... use document.getElementById
    this.forceAlign();
    if (!props.disabled && props.monitorWindowResize) {
      this.startMonitorWindowResize();
    }
  },
  componentDidUpdate: function componentDidUpdate(prevProps) {
    var reAlign = false;
    var props = this.props;

    if (!props.disabled) {
      if (prevProps.disabled || prevProps.align !== props.align) {
        reAlign = true;
      } else {
        var lastTarget = prevProps.target();
        var currentTarget = props.target();
        if ((0, _isWindow2["default"])(lastTarget) && (0, _isWindow2["default"])(currentTarget)) {
          reAlign = false;
        } else if (lastTarget !== currentTarget) {
          reAlign = true;
        }
      }
    }

    if (reAlign) {
      this.forceAlign();
    }

    if (props.monitorWindowResize && !props.disabled) {
      this.startMonitorWindowResize();
    } else {
      this.stopMonitorWindowResize();
    }
  },
  componentWillUnmount: function componentWillUnmount() {
    this.stopMonitorWindowResize();
  },
  startMonitorWindowResize: function startMonitorWindowResize() {
    if (!this.resizeHandler) {
      this.bufferMonitor = buffer(this.forceAlign, this.props.monitorBufferTime);
      this.resizeHandler = (0, _addEventListener2["default"])(window, 'resize', this.bufferMonitor);
    }
  },
  stopMonitorWindowResize: function stopMonitorWindowResize() {
    if (this.resizeHandler) {
      this.bufferMonitor.clear();
      this.resizeHandler.remove();
      this.resizeHandler = null;
    }
  },
  forceAlign: function forceAlign() {
    var props = this.props;
    if (!props.disabled) {
      var source = _reactDom2["default"].findDOMNode(this);
      props.onAlign(source, (0, _domAlign2["default"])(source, props.target(), props.align));
    }
  },
  render: function render() {
    var _props = this.props,
        childrenProps = _props.childrenProps,
        children = _props.children;

    var child = _react2["default"].Children.only(children);
    if (childrenProps) {
      var newProps = {};
      for (var prop in childrenProps) {
        if (childrenProps.hasOwnProperty(prop)) {
          newProps[prop] = this.props[childrenProps[prop]];
        }
      }
      return _react2["default"].cloneElement(child, newProps);
    }
    return child;
  }
});

exports["default"] = Align;
module.exports = exports['default'];


text:
<?xml version="1.0" encoding="UTF-8" ?>

<NaaccrDictionary dictionaryUri="http://mycompany.org/my-very-own-naaccr-dictionary.xml" naaccrVersion="140">
    <ItemDefs>
        <ItemDef naaccrId="myVariable1" naaccrNum="10001" naaccrName="My Variable 1" startColumn="2340" length="1" recordTypes="A,M,C,I" parentXmlElement="Tumor"/>
        <ItemDef naaccrId="myVariable2" naaccrNum="10002" naaccrName="My Variable 2" startColumn="2341" length="1" recordTypes="A,M,C,I" parentXmlElement="Patient"/>
        <ItemDef naaccrId="myVariable3" naaccrNum="10003" naaccrName="My Variable 3" startColumn="2342" length="1" recordTypes="A,M,C,I" parentXmlElement="NaaccrData"/>

        <!-- following was added to test an issue reported in the user dictionary validation -->
        <ItemDef naaccrId="npcrSpecificField" naaccrNum="3720" naaccrName="NPCR Specific Field" startColumn="1306" length="75" recordTypes="A,M,C,I" parentXmlElement="Tumor" trim="none"/>
    </ItemDefs>
</NaaccrDictionary>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>A xref</title>
<link type="text/css" rel="stylesheet" href="../../stylesheet.css" />

View Javadoc

1   package badNaming.package2;
2
3   public class A {
4
5   }

Copyright © 2015. All rights reserved.


text:
require 'socket'
require 'zlib'

require File.join(File.dirname(__FILE__), "kafka", "io")
require File.join(File.dirname(__FILE__), "kafka", "request_type")
require File.join(File.dirname(__FILE__), "kafka", "error_codes")
require File.join(File.dirname(__FILE__), "kafka", "batch")
require File.join(File.dirname(__FILE__), "kafka", "message")
require File.join(File.dirname(__FILE__), "kafka", "producer")
require File.join(File.dirname(__FILE__), "kafka", "consumer")

module Kafka
end


text:
package F5

import (
	"encoding/json"
	"log"
	"strings"
	//	"github.com/kr/pretty"
)

type LBVirtualPolicy struct {
	Name      string `json:"name"`
	Partition string `json:"partition"`
	FullPath  string `json:"fullPath"`
}

type LBVirtualPoliciesRef struct {
	Items []LBVirtualPolicy `json":items"`
}

type LBVirtualProfile struct {
	Name      string `json:"name"`
	Partition string `json:"partition"`
	FullPath  string `json:"fullPath"`
	Context   string `json:"context"`
}

type LBVirtualPersistProfile struct {
	Name      string `json:"name"`
	Partition string `json:"partition"`
	TmDefault string `json:"tmDefault"`
}

type LBVirtualProfileRef struct {
	Items []LBVirtualProfile `json":items"`
}

type LBVirtual struct {
	Name             string                    `json:"name"`
	FullPath         string                    `json:"fullPath"`
	Partition        string                    `json:"partition"`
	Destination      string                    `json:"destination"`
	Pool             string                    `json:"pool"`
	AddressStatus    string                    `json:"addressStatus"`
	AutoLastHop      string                    `json:"autoLasthop"`
	CmpEnabled       string                    `json:"cmpEnabled"`
	ConnectionLimit  int                       `json:"connectionLimit"`
	Enabled          bool                      `json:"enabled"`
	IpProtocol       string                    `json:"ipProtocol"`
	Source           string                    `json:"source"`
	SourcePort       string                    `json:"sourcePort"`
	SynCookieStatus  string                    `json:"synCookieStatus"`
	TranslateAddress string                    `json:"translateAddress"`
	TranslatePort    string                    `json:"translatePort"`
	Profiles         LBVirtualProfileRef       `json:"profilesReference"`
	Policies         LBVirtualPoliciesRef      `json:"policiesReference"`
	Rules            []string                  `json:"rules"`
	Persist          []LBVirtualPersistProfile `json:"persist"`
}

type LBVirtuals struct {
	Items []LBVirtual
}

func (f *Device) ShowVirtual(vname string) {

	vname = strings.Replace(vname, "/", "~", -1)
	u := "https://" + f.Hostname + "/mgmt/tm/ltm/virtual/" + vname + "?expandSubcollections=true"
	res := LBVirtual{}

	err, resp := f.SendRequest(u, GET, nil, &res)
	if err != nil {
		log.Fatalf("%s : %s\n", resp.Status, err)
	}
	f.PrintResponse(&res)

}

func (f *Device) UpdateVirtual(vname string) {

	vname = strings.Replace(vname, "/", "~", -1)
	u := "https://" + f.Hostname + "/mgmt/tm/ltm/virtual/" + vname
	res := LBVirtual{}
	body := json.RawMessage{}

	// read in json file
	/*
		dat, err := ioutil.ReadFile(f5Input)
		if err != nil {
			log.Fatal(err)
		}

		// convert json to a virtual struct
		err := json.Unmarshal(dat, &body)
		if err != nil {
			log.Fatal(err)
		}
	*/

	// put the request
	err, resp := f.SendRequest(u, PUT, &body, &res)
	if err != nil {
		log.Fatalf("%s : %s\n", resp.Status, err)
	}
	f.PrintResponse(&res)
}


text:
<?php if ($currentSession['user']['userid'] != $settings->get('nonauthenticated_userid')): ?>
   -
<?php echo $currentSession['user']['username']; ?>
(uitloggen)
<?php endif; ?>


text:
@font-face {
	font-family: 'Roboto';
	font-style: normal;
	font-weight: 400;
	src: local('Roboto'), local('Roboto-Regular'),
	url(roboto-regular.woff2) format('woff2');
}

@font-face {
	font-family: 'Roboto';
	font-style: normal;
	font-weight: 500;
	src: local('Roboto Medium'), local('Roboto-Medium'),
	url(roboto-medium.woff2) format('woff2');
}

@font-face {
	font-family: 'Roboto';
	font-style: normal;
	font-weight: 700;
	src: local('Roboto Bold'), local('Roboto-Bold'),
	url(roboto-bold.woff2) format('woff2');
}


text:
layout: post
date: 2018-03-21
title: "JLM Couture-Tara Keely Tara Keely Style tk2509 Long Sleeves Chapel Train Mermaid/Trumpet"
category: JLM Couture-Tara Keely
tags: [JLM Couture-Tara Keely ,Mermaid/Trumpet,Sweetheart,Chapel Train,Long Sleeves]
---
### JLM Couture-Tara Keely Tara Keely Style tk2509
Just **$369.99**
###   Long Sleeves Chapel Train Mermaid/Trumpet

BRANDS	JLM Couture-Tara Keely

Silhouette	Mermaid/Trumpet

Neckline	Sweetheart

Hemline/Train	Chapel Train

Sleeve	Long Sleeves

Buy it: [https://www.readybrides.com/en/jlm-couture-tara-keely-/47708-tara-keely-style-tk2509.html](https://www.readybrides.com/en/jlm-couture-tara-keely-/47708-tara-keely-style-tk2509.html)


text:
import socket

import supybot.conf as conf
import supybot.utils as utils
from supybot.commands import *
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks

try:
    dictclient = utils.python.universalImport('dictclient', 'local.dictclient')
except ImportError:
    raise callbacks.Error, \
            'You need to have dictclient installed to use this plugin.  ' \
            'Download it at <http://quux.org:70/devel/dictclient>'

class Dict(callbacks.Plugin):
    threaded = True
    def dictionaries(self, irc, msg, args):
        """takes no arguments

        Returns the dictionaries valid for the dict command.
        """
        try:
            server = conf.supybot.plugins.Dict.server()
            conn = dictclient.Connection(server)
            dbs = list(conn.getdbdescs().keys())
            dbs.sort()
            irc.reply(format('%L', dbs))
        except socket.error, e:
            irc.error(utils.web.strError(e))
    dictionaries = wrap(dictionaries)

    def random(self, irc, msg, args):
        """takes no arguments

        Returns a random valid dictionary.
        """
        try:
            server = conf.supybot.plugins.Dict.server()
            conn = dictclient.Connection(server)
            dbs = conn.getdbdescs().keys()
            irc.reply(utils.iter.choice(dbs))
        except socket.error, e:
            irc.error(utils.web.strError(e))
    random = wrap(random)

    def dict(self, irc, msg, args, words):
        """[<dictionary>] <word>

        Looks up the definition of <word> on dict.org's dictd server.
        """
        try:
            server = conf.supybot.plugins.Dict.server()
            conn = dictclient.Connection(server)
        except socket.error, e:
            irc.error(utils.web.strError(e), Raise=True)
        dbs = set(conn.getdbdescs())
        if words[0] in dbs:
            dictionary = words.pop(0)
        else:
            default = self.registryValue('default', msg.args[0])
            if default in dbs:
                dictionary = default
            else:
                if default:
                    self.log.info('Default dict for %s is not a supported '
                                  'dictionary: %s.', msg.args[0], default)
                dictionary = '*'
        if not words:
            irc.error('You must give a word to define.', Raise=True)
        word = ' '.join(words)
        definitions = conn.define(dictionary, word)
        dbs = set()
        if not definitions:
            if dictionary == '*':
                irc.reply(format('No definition for %q could be found.', word))
            else:
                irc.reply(format('No definition for %q could be found in %s',
                                 word, ircutils.bold(dictionary)))
            return
        L = []
        for d in definitions:
            dbs.add(ircutils.bold(d.getdb().getname()))
            (db, s) = (d.getdb().getname(), d.getdefstr())
            db = ircutils.bold(db)
            s = utils.str.normalizeWhitespace(s).rstrip(';.,')
            L.append('%s: %s' % (db, s))
        utils.sortBy(len, L)
        if dictionary == '*' and len(dbs) > 1:
            s = format('%L responded: %s', list(dbs), '; '.join(L))
        else:
            s = '; '.join(L)
        irc.reply(s)
    dict = wrap(dict, [many('something')])

Class = Dict

# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:


text:
package org.apache.mina.filter.codec.textline;

import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

import org.apache.mina.core.buffer.BufferDataException;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.AttributeKey;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderException;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;
import org.apache.mina.filter.codec.RecoverableProtocolDecoderException;

/**
 * A {@link ProtocolDecoder} which decodes a text line into a string.
 *
 * @author Apache MINA Project
 */
public class TextLineDecoder implements ProtocolDecoder {
    private final AttributeKey CONTEXT = new AttributeKey(getClass(), "context");

    private final Charset charset;

    private final LineDelimiter delimiter;

    private IoBuffer delimBuf;

    private int maxLineLength = 1024;

    /**
     * Creates a new instance with the current default {@link Charset}
     * and {@link LineDelimiter#AUTO} delimiter.
     */
    public TextLineDecoder() {
        this(LineDelimiter.AUTO);
    }

    /**
     * Creates a new instance with the current default {@link Charset}
     * and the specified <tt>delimiter</tt>.
     */
    public TextLineDecoder(String delimiter) {
        this(new LineDelimiter(delimiter));
    }

    /**
     * Creates a new instance with the current default {@link Charset}
     * and the specified <tt>delimiter</tt>.
     */
    public TextLineDecoder(LineDelimiter delimiter) {
        this(Charset.defaultCharset(), delimiter);
    }

    /**
     * Creates a new instance with the spcified <tt>charset</tt>
     * and {@link LineDelimiter#AUTO} delimiter.
     */
    public TextLineDecoder(Charset charset) {
        this(charset, LineDelimiter.AUTO);
    }

    /**
     * Creates a new instance with the spcified <tt>charset</tt>
     * and the specified <tt>delimiter</tt>.
     */
    public TextLineDecoder(Charset charset, String delimiter) {
        this(charset, new LineDelimiter(delimiter));
    }

    /**
     * Creates a new instance with the specified <tt>charset</tt>
     * and the specified <tt>delimiter</tt>.
     */
    public TextLineDecoder(Charset charset, LineDelimiter delimiter) {
        if (charset == null) {
            throw new NullPointerException("charset");
        }
        if (delimiter == null) {
            throw new NullPointerException("delimiter");
        }

        this.charset = charset;
        this.delimiter = delimiter;
    }

    /**
     * Returns the allowed maximum size of the line to be decoded.
     * If the size of the line to be decoded exceeds this value, the
     * decoder will throw a {@link BufferDataException}.  The default
     * value is <tt>1024</tt> (1KB).
     */
    public int getMaxLineLength() {
        return maxLineLength;
    }

    /**
     * Sets the allowed maximum size of the line to be decoded.
     * If the size of the line to be decoded exceeds this value, the
     * decoder will throw a {@link BufferDataException}.  The default
     * value is <tt>1024</tt> (1KB).
     */
    public void setMaxLineLength(int maxLineLength) {
        if (maxLineLength <= 0) {
            throw new IllegalArgumentException("maxLineLength: "
                    + maxLineLength);
        }

        this.maxLineLength = maxLineLength;
    }

    public void decode(IoSession session, IoBuffer in,
            ProtocolDecoderOutput out) throws Exception {
        Context ctx = getContext(session);

        if (LineDelimiter.AUTO.equals(delimiter)) {
            decodeAuto(ctx, session, in, out);
        } else {
            decodeNormal(ctx, session, in, out);
        }
    }

    private Context getContext(IoSession session) {
        Context ctx;
        ctx = (Context) session.getAttribute(CONTEXT);
        if (ctx == null) {
            ctx = new Context();
            session.setAttribute(CONTEXT, ctx);
        }
        return ctx;
    }

    public void finishDecode(IoSession session, ProtocolDecoderOutput out)
            throws Exception {
        // Do nothing
    }

    public void dispose(IoSession session) throws Exception {
        Context ctx = (Context) session.getAttribute(CONTEXT);
        if (ctx != null) {
            session.removeAttribute(CONTEXT);
        }
    }

    private void decodeAuto(Context ctx, IoSession session, IoBuffer in, ProtocolDecoderOutput out)
            throws CharacterCodingException, ProtocolDecoderException {

        int matchCount = ctx.getMatchCount();

        // Try to find a match
        int oldPos = in.position();
        int oldLimit = in.limit();
        while (in.hasRemaining()) {
            byte b = in.get();
            boolean matched = false;
            switch (b) {
            case '\r':
                // Might be Mac, but we don't auto-detect Mac EOL
                // to avoid confusion.
                matchCount++;
                break;
            case '\n':
                // UNIX
                matchCount++;
                matched = true;
                break;
            default:
                matchCount = 0;
            }

            if (matched) {
                // Found a match.
                int pos = in.position();
                in.limit(pos);
                in.position(oldPos);

                ctx.append(in);

                in.limit(oldLimit);
                in.position(pos);

                if (ctx.getOverflowPosition() == 0) {
                    IoBuffer buf = ctx.getBuffer();
                    buf.flip();
                    buf.limit(buf.limit() - matchCount);
                    try {
                        writeText(session, buf.getString(ctx.getDecoder()), out);
                    } finally {
                        buf.clear();
                    }
                } else {
                    int overflowPosition = ctx.getOverflowPosition();
                    ctx.reset();
                    throw new RecoverableProtocolDecoderException(
                            "Line is too long: " + overflowPosition);
                }

                oldPos = pos;
                matchCount = 0;
            }
        }

        // Put remainder to buf.
        in.position(oldPos);
        ctx.append(in);

        ctx.setMatchCount(matchCount);
    }

    private void decodeNormal(Context ctx, IoSession session, IoBuffer in, ProtocolDecoderOutput out)
            throws CharacterCodingException, ProtocolDecoderException {

        int matchCount = ctx.getMatchCount();

        // Convert delimiter to ByteBuffer if not done yet.
        if (delimBuf == null) {
            IoBuffer tmp = IoBuffer.allocate(2).setAutoExpand(true);
            tmp.putString(delimiter.getValue(), charset.newEncoder());
            tmp.flip();
            delimBuf = tmp;
        }

        // Try to find a match
        int oldPos = in.position();
        int oldLimit = in.limit();
        while (in.hasRemaining()) {
            byte b = in.get();
            if (delimBuf.get(matchCount) == b) {
                matchCount++;
                if (matchCount == delimBuf.limit()) {
                    // Found a match.
                    int pos = in.position();
                    in.limit(pos);
                    in.position(oldPos);

                    ctx.append(in);

                    in.limit(oldLimit);
                    in.position(pos);
                    if (ctx.getOverflowPosition() == 0) {
                        IoBuffer buf = ctx.getBuffer();
                        buf.flip();
                        buf.limit(buf.limit() - matchCount);
                        try {
                            writeText(session, buf.getString(ctx.getDecoder()), out);
                        } finally {
                            buf.clear();
                        }
                    } else {
                        int overflowPosition = ctx.getOverflowPosition();
                        ctx.reset();
                        throw new RecoverableProtocolDecoderException(
                                "Line is too long: " + overflowPosition);
                    }

                    oldPos = pos;
                    matchCount = 0;
                }
            } else {
                // fix for DIRMINA-506 & DIRMINA-536
                in.position(Math.max(0, in.position() - matchCount));
                matchCount = 0;
            }
        }

        // Put remainder to buf.
        in.position(oldPos);
        ctx.append(in);

        ctx.setMatchCount(matchCount);
    }

    /**
     * By default, this method propagates the decoded line of text to
     * {@code ProtocolDecoderOutput#write(Object)}.  You may override this method to modify
     * the default behavior.
     *
     * @param session  the {@code IoSession} the received data.
     * @param text  the decoded text
     * @param out  the upstream {@code ProtocolDecoderOutput}.
     */
    protected void writeText(IoSession session, String text, ProtocolDecoderOutput out) {
        out.write(text);
    }

    private class Context {
        private final CharsetDecoder decoder;
        private final IoBuffer buf;
        private int matchCount = 0;
        private int overflowPosition = 0;

        private Context() {
            decoder = charset.newDecoder();
            buf = IoBuffer.allocate(80).setAutoExpand(true);
        }

        public CharsetDecoder getDecoder() {
            return decoder;
        }

        public IoBuffer getBuffer() {
            return buf;
        }

        public int getOverflowPosition() {
            return overflowPosition;
        }

        public int getMatchCount() {
            return matchCount;
        }

        public void setMatchCount(int matchCount) {
            this.matchCount = matchCount;
        }

        public void reset() {
            overflowPosition = 0;
            matchCount = 0;
            decoder.reset();
        }

        public void append(IoBuffer in) {
            if (overflowPosition != 0) {
                discard(in);
            } else if (buf.position() > maxLineLength - in.remaining()) {
                    overflowPosition = buf.position();
                    buf.clear();
                    discard(in);
            } else {
                getBuffer().put(in);
            }
        }

        private void discard(IoBuffer in) {
            if (Integer.MAX_VALUE - in.remaining() < overflowPosition) {
                overflowPosition = Integer.MAX_VALUE;
            } else {
                overflowPosition += in.remaining();
            }
            in.position(in.limit());
        }
    }
}


text:
import unittest

from publication import controller

class TestController(unittest.TestCase):

    def test_construct_aggs(self):
        aggs = controller.construct_aggs(['subject_areas'])

        expected = {
            "aggs": {
                "subject_areas": {
                    "terms": {
                        "field": "subject_areas",
                        "size": 0
                    }
                }
            }
        }

        self.assertEqual(expected, aggs)

    def test_construct_aggs_multi_aggs(self):
        aggs = controller.construct_aggs(['collection', 'subject_areas'])

        expected = {
            "aggs": {
                "collection": {
                    "terms": {
                        "field": "collection",
                        "size": 0
                    },
                    "aggs": {
                        "subject_areas": {
                            "terms": {
                                "field": "subject_areas",
                                "size": 0
                            }
                        }
                    }
                }
            }
        }

        self.assertEqual(expected, aggs)


text:
#pragma once

#include <nuttx/compiler.h>

__BEGIN_DECLS

/* Define the signature for the Application descriptor as 'APDesc' and a
 * revision number of 00 used in app_descriptor_t
 */

#define APP_DESCRIPTOR_SIGNATURE_ID 'A','P','D','e','s','c'
#define APP_DESCRIPTOR_SIGNATURE_REV '0','0'
#define APP_DESCRIPTOR_SIGNATURE APP_DESCRIPTOR_SIGNATURE_ID, APP_DESCRIPTOR_SIGNATURE_REV

/* N.B. the .ld file must emit this sections */
# define boot_app_shared_section __attribute__((section(".app_descriptor")))

/* eRole defines the role of the bootloader_app_shared_t structure */

typedef enum eRole  {
	Invalid,
	App,
	BootLoader
} eRole_t;

/****************************************************************************
 *
 * Bootloader and Application shared structure.
 *
 * The data in this structure is passed in SRAM or the the CAN filter
 * registers from bootloader to application and application to bootloader.
 *
 * Do not assume any mapping or location for the passing of this data
 * that is done in the read and write routines and is abstracted by design.
 *
 * For reference, the following is performed based on eRole in API calls
 * defined below:
 *
 *      The application must write BOOTLOADER_COMMON_APP_SIGNATURE to the
 *      signature field when passing data to the bootloader; when the
 *      bootloader passes data to the application, it must write
 *      BOOTLOADER_COMMON_BOOTLOADER_SIGNATURE to the signature field.
 *
 *      The CRC is calculated over the structure from signature to the
 *      last byte. The resulting values are then copied to the CAN filter
 *      registers by bootloader_app_shared_read and
 *      bootloader_app_shared_write.
 *
****************************************************************************/

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wattributes"
typedef begin_packed_struct struct bootloader_app_shared_t {
	union {
		uint64_t ull;
		uint32_t ul[2];
		uint8_t  valid;
	} crc;
	uint32_t signature;
	uint32_t bus_speed;
	uint32_t node_id;
} end_packed_struct bootloader_app_shared_t;
#pragma GCC diagnostic pop

/****************************************************************************
 *
 * Application firmware descriptor.
 *
 * This structure located by the linker script somewhere after the vector table.
 * (within the first several kilobytes of the beginning address of the
 * application);
 *
 * This structure must be aligned on an 8-byte boundary.
 *
 * The bootloader will scan through the application FLASH image until it
 * finds the signature.
 *
 * The image_crc is calculated as follows:
 *      1) All fields of this structure must be initialized with the correct
 *         information about the firmware image bin file
 *         (Here after refereed to as image)
 *      2) image_crc set to 0;
 *      3) The CRC 64 is calculated over the image from offset 0 up to and including the
 *         last byte of the image file.
 *      4) The calculated CRC 64 is stored in image_crc
 *      5) The new image file is then written to a file a ".img" extension.
 *
****************************************************************************/

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wattributes"
#pragma GCC diagnostic ignored "-Wpacked"
typedef begin_packed_struct struct app_descriptor_t {
	uint8_t signature[sizeof(uint64_t)];
	uint64_t image_crc;
	uint32_t image_size;
	uint32_t vcs_commit;
	uint8_t major_version;
	uint8_t minor_version;
	uint8_t reserved[6];
} end_packed_struct app_descriptor_t;
#pragma GCC diagnostic pop

/****************************************************************************
 * Name: bootloader_app_shared_read
 *
 * Description:
 *   Based on the role requested, this function will conditionally populate
 *   a bootloader_app_shared_t structure from the physical locations used
 *   to transfer the shared data to/from an application (internal data) .
 *
 *   The functions will only populate the structure and return a status
 *   indicating success, if the internal data has the correct signature as
 *   requested by the Role AND has a valid crc.
 *
 * Input Parameters:
 *   shared - A pointer to a bootloader_app_shared_t return the data in if
 *   the internal data is valid for the requested Role
 *   role   - An eRole_t of App or BootLoader to validate the internal data
 *            against. For a Bootloader this would be the value of App to
 *            read the application passed data.
 *
 * Returned value:
 *   OK     - Indicates that the internal data has been copied to callers
 *            bootloader_app_shared_t structure.
 *
 *  -EBADR  - The Role or crc of the internal data was not valid. The copy
 *            did not occur.
 *
 ****************************************************************************/

int bootloader_app_shared_read(bootloader_app_shared_t *shared, eRole_t role);

/****************************************************************************
 * Name: bootloader_app_shared_write
 *
 * Description:
 *   Based on the role, this function will commit the data passed
 *   into the physical locations used to transfer the shared data to/from
 *   an application (internal data) .
 *
 *   The functions will populate the signature and crc the data
 *   based on the provided Role.
 *
 * Input Parameters:
 *   shared - A pointer to a bootloader_app_shared_t data to commit to
 *   the internal data for passing to/from an application.
 *   role   - An eRole_t of App or BootLoader to use in the internal data
 *            to be passed to/from an application. For a Bootloader this
 *            would be the value of Bootloader to write to the passed data.
 *            to the application via the internal data.
 *
 * Returned value:
 *   None.
 *
 ****************************************************************************/

void bootloader_app_shared_write(bootloader_app_shared_t *shared, eRole_t role);

/****************************************************************************
 * Name: bootloader_app_shared_invalidate
 *
 * Description:
 *   Invalidates the data passed the physical locations used to transfer
 *   the shared data to/from an application (internal data) .
 *
 *   The functions will invalidate the signature and crc and should be used
 *   to prevent deja vu.
 *
 * Input Parameters:
 *   None.
 *
 * Returned value:
 *   None.
 *
 ****************************************************************************/

void bootloader_app_shared_invalidate(void);

__END_DECLS


text:
// Copyright (c) Mohamed Hassan & Contributors. All rights reserved. See License.md in the project root for license information.

using CommandLine;
using OData2Poco.Extensions;
using OData2Poco.InfraStructure.Logging;

namespace OData2Poco.CommandLine;

public class ArgumentParser
{
    public static bool ShowVersionOrHelp { get; set; }
    public static StringWriter HelpWriter { get; private set; }
    public static string Help => HelpWriter.ToString();
    private static readonly ILog Logger = PocoLogger.Default;
    public static string OutPut => Logger.Output.ToString();

    public void ClearLogger() => Logger.Clear();

    public void SetLoggerSilent(bool flag = true) => Logger.Silent = flag;

    public async Task<int> RunOptionsAsync(string[] args, Func<Options, Task> func)
    {
        Logger.Clear();
        var result = GetParserResult(args);

        var retCode = await result.MapResult(
            async x =>
            {
                await func.Invoke(x);
                return 0;
            },
            errs =>
            {
                var retValue = GetHelp(errs);
                return Task.FromResult(retValue);
            });

        return retCode;
    }

    public async Task<int> RunOptionsAsync(string[] args)
    {
        return await RunOptionsAsync(args, RunCommandAsync);
    }

    private async Task RunCommandAsync(Options options)
    {
        Logger.Info(ApplicationInfo.HeadingInfo);
        Logger.Normal(ApplicationInfo.Copyright);
        await new CsCommand(options, StartUp.FileSystem).Execute().ConfigureAwait(false);
    }

    private int GetHelp(IEnumerable<Error> errors)
    {
        if (errors == null)
            return 0;
        ShowVersionOrHelp = true;
        var enumerable = errors.ToList();
        if (enumerable.Any(e => e.Tag == ErrorType.VersionRequestedError))
        {
            Logger.Info(HelpWriter.ToString());
            return 0;
        }

        if (enumerable.Any(e => e.Tag == ErrorType.HelpRequestedError))
        {
            Logger.Normal(HelpWriter.ToString().RemoveEmptyLines());
            return 0;
        }

        Logger.Normal(HelpWriter.ToString().RemoveEmptyLines());
        return (int)ExitCodes.ArgumentsInvalid;
    }

    internal ParserResult<Options> GetParserResult(string[] args)
    {
        HelpWriter = new StringWriter();
        var parser = new Parser(config =>
        {
            config.HelpWriter = HelpWriter;
            config.CaseSensitive = true;
            config.MaximumDisplayWidth = 4000;
            config.IgnoreUnknownArguments = false;
            config.CaseInsensitiveEnumValues = true;
        });

        var result = parser.ParseArguments<Options>(args);
        return result;
    }
}