text:
package com.sleepycat.collections;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import com.sleepycat.compat.DbCompat;
import com.sleepycat.db.Cursor;
import com.sleepycat.db.CursorConfig;
import com.sleepycat.db.Database;
import com.sleepycat.db.DatabaseException;
import com.sleepycat.db.Environment;
import com.sleepycat.db.EnvironmentConfig;
import com.sleepycat.db.LockMode;
import com.sleepycat.db.Transaction;
import com.sleepycat.db.TransactionConfig;
import com.sleepycat.util.RuntimeExceptionWrapper;

/**
 * Provides access to the current transaction for the current thread within the
 * context of a Berkeley DB environment.  This class provides explicit
 * transaction control beyond that provided by the {@link TransactionRunner}
 * class.  However, both methods of transaction control manage per-thread
 * transactions.
 *
 * @author Mark Hayes
 */
public class CurrentTransaction {

    /* For internal use, this class doubles as an Environment wrapper. */

    private static WeakHashMap<Environment,CurrentTransaction> envMap =
        new WeakHashMap<Environment,CurrentTransaction>();

    private LockMode writeLockMode;
    private boolean cdbMode;
    private boolean txnMode;
    private boolean lockingMode;
    private ThreadLocal localTrans = new ThreadLocal();
    private ThreadLocal localCdbCursors;

    /*
     * Use a WeakReference to the Environment to avoid pinning the environment
     * in the envMap.  The WeakHashMap envMap uses the Environment as a weak
     * key, but this won't prevent GC of the Environment if the map's value has
     * a hard reference to the Environment.  [#15444]
     */
    private WeakReference<Environment> envRef;

    /**
     * Gets the CurrentTransaction accessor for a specified Berkeley DB
     * environment.  This method always returns the same reference when called
     * more than once with the same environment parameter.
     *
     * @param env is an open Berkeley DB environment.
     *
     * @return the CurrentTransaction accessor for the given environment, or
     * null if the environment is not transactional.
     */
    public static CurrentTransaction getInstance(Environment env) {

        CurrentTransaction currentTxn = getInstanceInternal(env);
        return currentTxn.isTxnMode() ? currentTxn : null;
    }

    /**
     * Gets the CurrentTransaction accessor for a specified Berkeley DB
     * environment.  Unlike getInstance(), this method never returns null.
     *
     * @param env is an open Berkeley DB environment.
     */
    static CurrentTransaction getInstanceInternal(Environment env) {
        synchronized (envMap) {
            CurrentTransaction ct = envMap.get(env);
            if (ct == null) {
                ct = new CurrentTransaction(env);
                envMap.put(env, ct);
            }
            return ct;
        }
    }

    private CurrentTransaction(Environment env) {
        envRef = new WeakReference<Environment>(env);
        try {
            EnvironmentConfig config = env.getConfig();
            txnMode = config.getTransactional();
            lockingMode = DbCompat.getInitializeLocking(config);
            if (txnMode || lockingMode) {
                writeLockMode = LockMode.RMW;
            } else {
                writeLockMode = LockMode.DEFAULT;
            }
            cdbMode = DbCompat.getInitializeCDB(config);
            if (cdbMode) {
                localCdbCursors = new ThreadLocal();
            }
        } catch (DatabaseException e) {
            throw new RuntimeExceptionWrapper(e);
        }
    }

    /**
     * Returns whether environment is configured for locking.
     */
    final boolean isLockingMode() {

        return lockingMode;
    }

    /**
     * Returns whether this is a transactional environment.
     */
    final boolean isTxnMode() {

        return txnMode;
    }

    /**
     * Returns whether this is a Concurrent Data Store environment.
     */
    final boolean isCdbMode() {

        return cdbMode;
    }

    /**
     * Return the LockMode.RMW or null, depending on whether locking is
     * enabled.  LockMode.RMW will cause an error if passed when locking
     * is not enabled.  Locking is enabled if locking or transactions were
     * specified for this environment.
     */
    final LockMode getWriteLockMode() {

        return writeLockMode;
    }

    /**
     * Returns the underlying Berkeley DB environment.
     */
    public final Environment getEnvironment() {

        return envRef.get();
    }

    /**
     * Returns the transaction associated with the current thread for this
     * environment, or null if no transaction is active.
     */
    public final Transaction getTransaction() {

        Trans trans = (Trans) localTrans.get();
        return (trans != null) ? trans.txn : null;
    }

    /**
     * Returns whether auto-commit may be performed by the collections API.
     * True is returned if no collections API transaction is currently active,
     * and no XA transaction is currently active.
     */
    boolean isAutoCommitAllowed()
	throws DatabaseException {

        return getTransaction() == null &&
               DbCompat.getThreadTransaction(getEnvironment()) == null;
    }

    /**
     * Begins a new transaction for this environment and associates it with
     * the current thread.  If a transaction is already active for this
     * environment and thread, a nested transaction will be created.
     *
     * @param config the transaction configuration used for calling
     * {@link Environment#beginTransaction}, or null to use the default
     * configuration.
     *
     * @return the new transaction.
     *
     * @throws DatabaseException if the transaction cannot be started, in which
     * case any existing transaction is not affected.
     *
     * @throws IllegalStateException if a transaction is already active and
     * nested transactions are not supported by the environment.
     */
    public final Transaction beginTransaction(TransactionConfig config)
        throws DatabaseException {

        Environment env = getEnvironment();
        Trans trans = (Trans) localTrans.get();
        if (trans != null) {
            if (trans.txn != null) {
                if (!DbCompat.NESTED_TRANSACTIONS) {
                    throw new IllegalStateException(
                            "Nested transactions are not supported");
                }
                Transaction parentTxn = trans.txn;
                trans = new Trans(trans, config);
                trans.txn = env.beginTransaction(parentTxn, config);
                localTrans.set(trans);
            } else {
                trans.txn = env.beginTransaction(null, config);
                trans.config = config;
            }
        } else {
            trans = new Trans(null, config);
            trans.txn = env.beginTransaction(null, config);
            localTrans.set(trans);
        }
        return trans.txn;
    }

    /**
     * Commits the transaction that is active for the current thread for this
     * environment and makes the parent transaction (if any) the current
     * transaction.
     *
     * @return the parent transaction or null if the committed transaction was
     * not nested.
     *
     * @throws DatabaseException if an error occurs committing the transaction.
     * The transaction will still be closed and the parent transaction will
     * become the current transaction.
     *
     * @throws IllegalStateException if no transaction is active for the
     * current thread for this environment.
     */
    public final Transaction commitTransaction()
        throws DatabaseException, IllegalStateException {

        Trans trans = (Trans) localTrans.get();
        if (trans != null && trans.txn != null) {
            Transaction parent = closeTxn(trans);
            trans.txn.commit();
            return parent;
        } else {
            throw new IllegalStateException("No transaction is active");
        }
    }

    /**
     * Aborts the transaction that is active for the current thread for this
     * environment and makes the parent transaction (if any) the current
     * transaction.
     *
     * @return the parent transaction or null if the aborted transaction was
     * not nested.
     *
     * @throws DatabaseException if an error occurs aborting the transaction.
     * The transaction will still be closed and the parent transaction will
     * become the current transaction.
     *
     * @throws IllegalStateException if no transaction is active for the
     * current thread for this environment.
     */
    public final Transaction abortTransaction()
        throws DatabaseException, IllegalStateException {

        Trans trans = (Trans) localTrans.get();
        if (trans != null && trans.txn != null) {
            Transaction parent = closeTxn(trans);
            trans.txn.abort();
            return parent;
        } else {
            throw new IllegalStateException("No transaction is active");
        }
    }

    /**
     * Returns whether the current transaction is a readUncommitted
     * transaction.
     */
    final boolean isReadUncommitted() {

        Trans trans = (Trans) localTrans.get();
        if (trans != null && trans.config != null) {
            return trans.config.getReadUncommitted();
        } else {
            return false;
        }
    }

    private Transaction closeTxn(Trans trans) {

        localTrans.set(trans.parent);
        return (trans.parent != null) ? trans.parent.txn : null;
    }

    private static class Trans {

        private Trans parent;
        private Transaction txn;
        private TransactionConfig config;

        private Trans(Trans parent, TransactionConfig config) {

            this.parent = parent;
            this.config = config;
        }
    }

    /**
     * Opens a cursor for a given database, dup'ing an existing CDB cursor if
     * one is open for the current thread.
     */
    Cursor openCursor(Database db,
                      CursorConfig cursorConfig,
                      boolean writeCursor,
                      Transaction txn)
        throws DatabaseException {

        if (cdbMode) {
            CdbCursors cdbCursors = null;
            WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
            if (cdbCursorsMap == null) {
                cdbCursorsMap = new WeakHashMap();
                localCdbCursors.set(cdbCursorsMap);
            } else {
                cdbCursors = (CdbCursors) cdbCursorsMap.get(db);
            }
            if (cdbCursors == null) {
                cdbCursors = new CdbCursors();
                cdbCursorsMap.put(db, cdbCursors);
            }

            /*
             * In CDB mode the cursorConfig specified by the user is ignored
             * and only the writeCursor parameter is honored.  This is the only
             * meaningful cursor attribute for CDB, and here we count on
             * writeCursor flag being set correctly by the caller.
             */
            List cursors;
            CursorConfig cdbConfig;
            if (writeCursor) {
                if (cdbCursors.readCursors.size() > 0) {

                    /*
                     * Although CDB allows opening a write cursor when a read
                     * cursor is open, a self-deadlock will occur if a write is
                     * attempted for a record that is read-locked; we should
                     * avoid self-deadlocks at all costs
                     */
                    throw new IllegalStateException(
                      "cannot open CDB write cursor when read cursor is open");
                }
                cursors = cdbCursors.writeCursors;
                cdbConfig = new CursorConfig();
                DbCompat.setWriteCursor(cdbConfig, true);
            } else {
                cursors = cdbCursors.readCursors;
                cdbConfig = null;
            }
            Cursor cursor;
            if (cursors.size() > 0) {
                Cursor other = ((Cursor) cursors.get(0));
                cursor = other.dup(false);
            } else {
                cursor = db.openCursor(null, cdbConfig);
            }
            cursors.add(cursor);
            return cursor;
        } else {
            return db.openCursor(txn, cursorConfig);
        }
    }

    /**
     * Duplicates a cursor for a given database.
     *
     * @param writeCursor true to open a write cursor in a CDB environment, and
     * ignored for other environments.
     *
     * @param samePosition is passed through to Cursor.dup().
     *
     * @return the open cursor.
     *
     * @throws DatabaseException if a database problem occurs.
     */
    Cursor dupCursor(Cursor cursor, boolean writeCursor, boolean samePosition)
        throws DatabaseException {

        if (cdbMode) {
            WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
            if (cdbCursorsMap != null) {
                Database db = cursor.getDatabase();
                CdbCursors cdbCursors = (CdbCursors) cdbCursorsMap.get(db);
                if (cdbCursors != null) {
                    List cursors = writeCursor ? cdbCursors.writeCursors
                                               : cdbCursors.readCursors;
                    if (cursors.contains(cursor)) {
                        Cursor newCursor = cursor.dup(samePosition);
                        cursors.add(newCursor);
                        return newCursor;
                    }
                }
            }
            throw new IllegalStateException("cursor to dup not tracked");
        } else {
            return cursor.dup(samePosition);
        }
    }

    /**
     * Closes a cursor.
     *
     * @param cursor the cursor to close.
     *
     * @throws DatabaseException if a database problem occurs.
     */
    void closeCursor(Cursor cursor)
        throws DatabaseException {

        if (cursor == null) {
            return;
        }
        if (cdbMode) {
            WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
            if (cdbCursorsMap != null) {
                Database db = cursor.getDatabase();
                CdbCursors cdbCursors = (CdbCursors) cdbCursorsMap.get(db);
                if (cdbCursors != null) {
                    if (cdbCursors.readCursors.remove(cursor) ||
                        cdbCursors.writeCursors.remove(cursor)) {
                        cursor.close();
                        return;
                    }
                }
            }
            throw new IllegalStateException(
              "closing CDB cursor that was not known to be open");
        } else {
            cursor.close();
        }
    }

    /**
     * Returns true if a CDB cursor is open and therefore a Database write
     * operation should not be attempted since a self-deadlock may result.
     */
    boolean isCDBCursorOpen(Database db) {
        if (cdbMode) {
            WeakHashMap cdbCursorsMap = (WeakHashMap) localCdbCursors.get();
            if (cdbCursorsMap != null) {
                CdbCursors cdbCursors = (CdbCursors) cdbCursorsMap.get(db);

                if (cdbCursors != null &&
                    (cdbCursors.readCursors.size() > 0 ||
                     cdbCursors.writeCursors.size() > 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    static final class CdbCursors {

        List writeCursors = new ArrayList();
        List readCursors = new ArrayList();
    }
}


text:
package cmd

import (
	"fmt"

	"github.com/bpicode/fritzctl/fritz"
	"github.com/bpicode/fritzctl/internal/console"
	"github.com/spf13/cobra"
)

var boxInfoCmd = &cobra.Command{
	Use:     "boxinfo",
	Short:   "Display information about the FRITZ!Box",
	Long:    "Show information about the FRITZ!Box like firmware version, uptime, etc.",
	Example: "fritzctl boxinfo",
	RunE:    boxInfo,
}

func init() {
	RootCmd.AddCommand(boxInfoCmd)
}

func boxInfo(_ *cobra.Command, _ []string) error {
	c := clientLogin()
	f := fritz.NewInternal(c)
	info, err := f.BoxInfo()
	assertNoErr(err, "cannot obtain FRITZ!Box data")
	printBoxInfo(info)
	return nil
}

func printBoxInfo(boxData *fritz.BoxData) {
	fmt.Printf("%s %s\n", console.Cyan("Model:    "), boxData.Model)
	fmt.Printf("%s %s\n", console.Cyan("Firmware: "), boxData.FirmwareVersion)
	fmt.Printf("%s %s\n", console.Cyan("Running:  "), boxData.Runtime)
}

redpajama_set_name: RedPajamaGithub


text:
@protocol TitleViewDelegate <NSObject>

- (void)clickButton:(UIButton *) button;

@end

@interface TitleView : UIView

@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, strong) NSMutableArray *btnArray;
@property (nonatomic, strong) UIView *lineView;

@property (nonatomic, weak) id<TitleViewDelegate> delegate;

- (instancetype)initWithFrame:(CGRect)frame titleArray:(NSMutableArray *)titleArray;

@end


text:
package scalainterpreter

import javax.swing.text.{BadLocationException, JTextComponent}
import tools.nsc.interpreter.Completion.ScalaCompleter
import java.awt.Dialog.ModalityType
import javax.swing.event.{DocumentListener, DocumentEvent}
import java.awt.Point
import javax.swing.{GroupLayout, JList, JScrollPane, JTextField, JDialog, SwingUtilities}
import java.awt.event.{ActionEvent, MouseEvent, MouseAdapter, KeyEvent, KeyAdapter}
import jsyntaxpane.actions.gui.EscapeListener
import jsyntaxpane.util.{StringUtils, SwingUtils}
import jsyntaxpane.SyntaxDocument
import jsyntaxpane.actions.DefaultSyntaxAction

object CompletionAction {
  private final val escapeChars = ";(= \t\n\r"
  private final val defPrefix = "def "

  // keep the location in line, of the start of the text for completion
  var locInLineStartCompletion = 0

  private class Dialog(target: JTextComponent)
    extends JDialog(SwingUtilities.getWindowAncestor(target), ModalityType.APPLICATION_MODAL) with EscapeListener {
    dlg =>

    private var items = List.empty[String]
    private var succeed = (_: Option[String]) => ()

    private val ggText = new JTextField
    private val ggScroll = new JScrollPane
    private val ggList = new JList[String]

    setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE)
    setResizable(false)
    setUndecorated(true)

    ggText.setBorder(null)
    ggText.addKeyListener(new KeyAdapter {
      override def keyPressed(e: KeyEvent): Unit = dlg.keyPressed(e)
    })

    ggList.addMouseListener(new MouseAdapter {
      override def mouseClicked(e: MouseEvent): Unit = dlg.mouseClicked(e)
    })
    ggList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION)
    ggList.setFocusable(false)

    ggScroll.setViewportView(ggList)
    private val lay = new GroupLayout(getContentPane)
    getContentPane.setLayout(lay)
    lay.setHorizontalGroup(lay.createParallelGroup(GroupLayout.Alignment.LEADING)
      .addComponent(ggText, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MaxValue)
      .addComponent(ggScroll, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MaxValue))
    lay.setVerticalGroup(lay.createParallelGroup(GroupLayout.Alignment.LEADING)
      .addGroup(lay.createSequentialGroup
      .addComponent(ggText, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
      .addGap(0, 0, 0)
      .addComponent(ggScroll, GroupLayout.DEFAULT_SIZE, 111, Short.MaxValue)
      )
    )
    pack()
    ggText.getDocument.addDocumentListener(new DocumentListener {
      // refilter the complerion
      def insertUpdate(e: DocumentEvent): Unit = refilterList()

      def removeUpdate(e: DocumentEvent): Unit = refilterList()

      def changedUpdate(e: DocumentEvent): Unit = refilterList()
    })
    ggText.setFocusTraversalKeysEnabled(false)
    SwingUtils.addEscapeListener(this)

    def show(abbrev: String, items: List[String])(succeed: Option[String] => Unit): Unit = try {
      this.items = items
      this.succeed = succeed

      val window = SwingUtilities.getWindowAncestor(target)
      val rt = target.modelToView(target.getSelectionStart) // coordinates of the selection start

      val loc = new Point(rt.x, rt.y)

      setLocationRelativeTo(window)
      val loc1 = SwingUtilities.convertPoint(target, loc, window)
      SwingUtilities.convertPointToScreen(loc1, window)
      setLocation(loc1)
    } catch {
      case ex: BadLocationException => // ignore for now
    } finally {
      val font = target.getFont
      ggText.setFont(font)
      ggList.setFont(font)
      doLayout()
      ggText.setText(abbrev)
      refilterList()
      setVisible(true)
    }

    private def refilterList(): Unit = {
      val prefix = ggText.getText
      val selected = ggList.getSelectedValue
      val filtered = items.filter(StringUtils.camelCaseMatch(_, prefix))
      var jvec = new java.util.Vector[String]
      for (x <- filtered)
        jvec.add(x)

      ggList.setListData(jvec)
      if (selected != null && filtered.contains(selected)) {
        ggList.setSelectedValue(selected, true)
      } else {
        ggList.setSelectedIndex(0)
      }
    }

    private def finish(result: Option[String]): Unit = {
      // target.replaceSelection(result)
      succeed(result)
      setVisible(false)
    }

    private def keyPressed(e: KeyEvent): Unit = {
      val i = ggList.getSelectedIndex
      val ch = e.getKeyChar
      e.getKeyCode match {
        case KeyEvent.VK_ESCAPE => finish(None)

        case KeyEvent.VK_DOWN if i < ggList.getModel.getSize - 1 =>
          val i1 = i + 1
          ggList.setSelectedIndex(i1)
          ggList.ensureIndexIsVisible(i1)

        case KeyEvent.VK_UP if i > 0 =>
          val i1 = i - 1
          ggList.setSelectedIndex(i1)
          ggList.ensureIndexIsVisible(i1)

        case _ if escapeChars.indexOf(ch) >= 0 =>
          val result0 = if (ggList.getSelectedIndex >= 0) {
            ggList.getSelectedValue.toString
          } else {
            ggText.getText
          }
          val result = if (ch == '\n') result0
          else {
            result0 + (if (ch == '\t') ' ' else ch)
          }
          finish(Some(result))

        case _ =>
      }
    }

    private def mouseClicked(e: MouseEvent): Unit = {
      if (e.getClickCount == 2) {
        val selected: String = ggList.getSelectedValue.toString
        target.replaceSelection(selected)
        setVisible(false)
      }
    }

    def escapePressed(): Unit = setVisible(false)
  }

}

class CompletionAction(completer: ScalaCompleter) extends DefaultSyntaxAction("COMPLETION") {

  import CompletionAction.defPrefix

  private var dlg: CompletionAction.Dialog = null

  override def actionPerformed(target: JTextComponent, sdoc: SyntaxDocument, dot: Int, e: ActionEvent): Unit = {

    // cw: the text from the start of line up to caret position
    // start: offset of line start in document
    var (cw, start) = {
      val sel = target.getSelectedText
      if (sel != null) {
        // if the user has selected text complete with that text
        (sel, target.getSelectionStart)
      } else {
        val line = sdoc.getLineAt(dot)
        val start = sdoc.getLineStartOffset(dot)

        (line.substring(0, dot - start), start)
      }
    }

    // extract text for completion, cw is sthe string from the start of line to the
    // location where the user tries to complete
    var origcw = cw.toString // keep a copy cw
    //   \s means a whitespace character: [ \t\n\x0B\f\r]
    var result = cw.split("\\s")
    cw = result(result.length - 1) // the text for completion

    // index of the last token in line is point of the completion start
    CompletionAction.locInLineStartCompletion = origcw.indexOf(cw)

    var cwlen = cw.length
    val m = completer.complete(cw, cwlen)
    val cand = m.candidates
    if (cand.isEmpty) return

    val off = start + CompletionAction.locInLineStartCompletion + m.cursor

    val hasDef = cand.exists(_.startsWith(defPrefix))

    val more1@(head :: tail) = if (!hasDef) cand
    else cand.map {
      case x if x.startsWith(defPrefix) => x.substring(4) // cheesy way of handling the 'def'
      case x => x
    }

    val common = if (!hasDef) 0
    else {
      val comh0 = head.indexOf('[')
      val comh1 = if (comh0 >= 0) comh0 else head.length
      val comh2 = head.indexOf('(')
      val comh3 = if (comh2 >= 0) math.min(comh1, comh2) else comh1
      val comh4 = head.indexOf(':')
      val comh = if (comh4 >= 0) math.min(comh4, comh3) else comh3

      (comh /: tail) { (len, s1) =>
        val m1 = math.min(len, s1.length)
        var m2 = 0
        while (m2 < m1 && s1.charAt(m2) == head.charAt(m2)) m2 += 1
        m2
      }
    }

    target.select(off - common, start + CompletionAction.locInLineStartCompletion + cwlen)

    def perform(replc: String): Unit = {
      val replc1 = removeTypes(replc, 0)
      val p0 = target.getSelectionStart + CompletionAction.locInLineStartCompletion
      target.replaceSelection(replc1)
      val i = replc1.indexOf('(') + 1
      if (i > 0) {
        val j = replc1.indexOf(',', i)
        val k = replc1.indexOf(')', i)
        val m = math.min(j, k)
        target.select(p0 + i, p0 + m)
      }
    }

    more1 match {
      case one :: Nil => perform(one) // the match performs directly the completion
      // replacement without popping a dialog

      case more =>
        if (dlg == null) dlg = new CompletionAction.Dialog(target)

        dlg.show(cw.substring(m.cursor), more1) {
          case Some(result) =>

            perform(result)
          case _ => // aborted
            // orig:             target.setSelectionStart(target.getSelectionEnd)

            target.setSelectionStart(target.getSelectionEnd + CompletionAction.locInLineStartCompletion)
        }
    }
  }

  private def removeTypes(s: String, i0: Int): String = {
    val i = s.indexOf('[', i0)
    val j = s.indexOf('(', i0)
    if (i >= 0 && i < j) {
      // type parameter
      val k = s.indexOf(']', i + 1)
      removeTypes(s.substring(0, i) + s.substring(k + 1), i0)
    } else if (j >= 0) {
      val k = s.indexOf(')', j + 1)
      val m = s.indexOf(':', j + 1)
      if (m >= 0 && m < k) {
        val n = s.indexOf(',', m + 1)
        val pre = s.substring(0, m)
        val post = s.substring(if (n >= 0 && n < k) n else k)
        removeTypes(pre + post, i0)
      } else if (m == k + 1) {
        s.substring(0, m)
      } else if (k >= 0 /* && k < s.length - 1 && s.charAt(k + 1) == '(' */ ) {
        // multiple argument lists
        removeTypes(s, k + 1)
      } else {
        s
      }
    } else {
      val m = s.indexOf(':', i0)
      if (m >= 0) s.substring(0, m) else s
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>GraphRuntimeContext.PropertyKey</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

org.jetel.graph.runtime

Enum GraphRuntimeContext.PropertyKey

java.lang.Object

java.lang.Enum<GraphRuntimeContext.PropertyKey>

org.jetel.graph.runtime.GraphRuntimeContext.PropertyKey

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<GraphRuntimeContext.PropertyKey>

Enclosing class:

GraphRuntimeContext

public static enum GraphRuntimeContext.PropertyKey
extends java.lang.Enum<GraphRuntimeContext.PropertyKey>

This enum is attempt to provide a more generic way to this runtime configuration.
 Should not be used by third-party applications, can be changed in the future.

Enum Constant Summary

Enum Constants

Enum Constant and Description

CLASSPATH

CLEAR_OBSOLETE_TEMP_FILES

COMPILE_CLASSPATH

DEBUG_MODE

LOCALE

LOG_LEVEL

SKIP_CHECK_CONFIG

TIME_ZONE

VALIDATE_REQUIRED_PARAMETERS

VERBOSE_MODE

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
getKey()

String used as parameter key of this property in various APIs.

java.lang.Class<?>
getValueType()

abstract java.lang.Object
parseValue(java.lang.String s)

use this method for validation of config values.

static GraphRuntimeContext.PropertyKey
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static GraphRuntimeContext.PropertyKey[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

SKIP_CHECK_CONFIG

public static final GraphRuntimeContext.PropertyKey SKIP_CHECK_CONFIG

LOG_LEVEL

public static final GraphRuntimeContext.PropertyKey LOG_LEVEL

CLEAR_OBSOLETE_TEMP_FILES

public static final GraphRuntimeContext.PropertyKey CLEAR_OBSOLETE_TEMP_FILES

DEBUG_MODE

public static final GraphRuntimeContext.PropertyKey DEBUG_MODE

LOCALE

public static final GraphRuntimeContext.PropertyKey LOCALE

TIME_ZONE

public static final GraphRuntimeContext.PropertyKey TIME_ZONE

CLASSPATH

public static final GraphRuntimeContext.PropertyKey CLASSPATH

COMPILE_CLASSPATH

public static final GraphRuntimeContext.PropertyKey COMPILE_CLASSPATH

VALIDATE_REQUIRED_PARAMETERS

public static final GraphRuntimeContext.PropertyKey VALIDATE_REQUIRED_PARAMETERS

VERBOSE_MODE

public static final GraphRuntimeContext.PropertyKey VERBOSE_MODE

Method Detail

values

public static GraphRuntimeContext.PropertyKey[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (GraphRuntimeContext.PropertyKey c : GraphRuntimeContext.PropertyKey.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in
the order they are declared

valueOf

public static GraphRuntimeContext.PropertyKey valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

parseValue

public abstract java.lang.Object parseValue(java.lang.String s)

use this method for validation of config values.

Parameters:

s -

Returns:

getKey

public java.lang.String getKey()

String used as parameter key of this property in various APIs.

getValueType

public java.lang.Class<?> getValueType()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
<?php
namespace Framework;

use Framework\ErrorResponse\ErrorDisplayResponse;
use Framework\Exception\FrameworkException;
use Framework\ErrorResponse\ErrorResponse;
use Exception;
use Framework\Processor\IgnoreProcessor;
use Framework\Processor\PostProcessor;
use Framework\Processor\Processor;

/**
 * Class Route
 *
 * @package Framework
 */
class Route
{

    static function otherwise( $function ) {
        self::action('otherwise', null, $function);
    }

    static function action($method, $path, $function) {
        $restInput =array();
        $me = self::getInstance();

        if ( Input::has('__request_method') ) $request_method = Input::get('__request_method');
        else $request_method = $_SERVER['REQUEST_METHOD'];
        if ($me->is_called == true) return IgnoreProcessor::getInstance();

        if ( $method != 'otherwise' ) {

            if ($method != $request_method )
                return IgnoreProcessor::getInstance();

            $path_array = preg_split("/\//", $path);
            foreach ($path_array as $key => $path_element) {
                if (strlen(trim($path_element)) == 0) {
                    unset($path_array[$key]);
                }
            }
            $path_array = array_values($path_array);

            if(count($path_array)!=count($me->path)) {
                return $me->getPostProcessor();
            }

            foreach ($path_array as $key => $path_element) {
                if (preg_match("/^\:(.*)$/", $path_element, $match)
                    || preg_match("/^\{(.*)\}$/", $path_element, $match)
                ) {
                    Input::set($match[1], $me->path[$key]);
                    $restInput[]=$me->path[$key];
                } else {
                    if (!isset($me->path[$key]) ||
                        $me->path[$key] != $path_element
                    ) {
                        return IgnoreProcessor::getInstance();
                    }
                }
            }
        }

        if ( $me->skip ) return $me->getPostProcessor();

        try {
            if ( is_callable( $function ) ) {
                $response = $function();
            } else {

                $function_array = preg_split("/@/", $function );
                if ( !isset($function_array[1]))
                    throw FrameworkException::internalError('Routing Error');

                $controller_namespace = Config::get("app.controller_namespace","App\\Controller\\");

                $class_name = $controller_namespace . $function_array[0];
                $method_name = $function_array[1];

                //$response = $class_name::$method_name();
                // Initialization controller object
                $controller = new $class_name;

                $response=call_user_func_array(array($controller,$method_name),$restInput);
                //$response = $controller->$method_name();
            }

            if ( $response instanceof Response ) {
                $response->display();
            } else {
                $rs = new Response();
                $rs->setContentType('text/html')
                    ->setContent($response)
                    ->display();
            }
            $me->is_called = true;
        } catch ( FrameworkException $e ) {
            $me->handleError( $e );
            $me->is_called = true;
            return IgnoreProcessor::getInstance();

        } catch ( Exception $e ) {
            $exception = FrameworkException::internalError('Internal Error: ' . $e->getMessage( ) );
            $me->handleError($exception);
            $me->is_called = true;
            return IgnoreProcessor::getInstance();
        }
        return $me->getPostProcessor();
    }

    static function get($path, $function) {
        return self::action('GET', $path, $function);
    }
    static function post($path, $function) {
        return self::action('POST', $path, $function);
    }
    static function put($path, $function) {
        return self::action('PUT', $path, $function);
    }
    static function patch($path, $function) {
        return self::action('PATCH', $path, $function);
    }
    static function delete($path, $function) {
        return self::action('DELETE', $path, $function);
    }

    public static function reset( ) {
        self::$me = null;
    }

    public static function setErrorResponse( ErrorResponse $e ) {
        $me = self::getInstance();
        $me->error_response = $e;
    }

    public static function setPostProcessor( Processor $p ) {
        $me = self::getInstance();
        $me->post_processor = $p;
    }

    private $skip = false;

    public static function setSkipMain( ) {
        self::getInstance()->skip = true;
    }

    private function getPostProcessor( ) {
        if ( $this->post_processor ) return $this->post_processor;

        if ( Config::has('app.post_processor') ) {
            $this->post_processor = Config::get('app.post_processor');
        } else {
            $this->post_processor = new PostProcessor();

        }
        return $this->post_processor;
    }

    private static $me;
    private $path;
    private $is_called;
    private $error_response;
    private $post_processor;

    private function __construct( ) {
        $this->is_called = false;
        $this->error_response = null;
        $this->post_processor = null;

        if ( Input::has('__request_uri') ) {
            $this->path = Input::get('__request_uri');
        } else {
            $request_uri = preg_split( "/\?/", $_SERVER['REQUEST_URI'], 2 );
            $requestUri = preg_split( "/\//", $request_uri[0] );
            $scriptName = preg_split( "/\//", $_SERVER['SCRIPT_NAME'] );

            foreach ($scriptName as $key => $value) {
                if ($value == $requestUri[$key]){
                    unset($requestUri[$key]) ;
                }
            }

            foreach($requestUri as $key => $path_element) {
                if (strlen(trim($path_element)) == 0) {
                    unset($requestUri[$key]);
                }
            }

            $this->path = array_values($requestUri);

            Input::set('__request_uri', $this->path);
            Input::set('__request_method', $_SERVER['REQUEST_METHOD']);
        }

    }

    private static function getInstance( ) {
        if ( self::$me == null ) {
            self::$me = new Route();
        }
        return self::$me;
    }

    private function handleError( FrameworkException $e ) {
        if ( $this->error_response == null ) {
            if ( Config::has('app.error_response') )
                $this->error_response = Config::get('app.error_response');
            else if ( Config::get('app.debug', true ) )
                $this->error_response = new ErrorDisplayResponse();
            else $this->error_response = new ErrorResponse();
        }
        $this->error_response->set( $e )->display();
        return true;
    }

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black2"
    tools:context="francis.kylintest.modules.BlueToothActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:id="@+id/bluetoothll1"
        android:layout_alignParentBottom="true" >

        <Button
            android:id="@+id/blueTooth_pass"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="blueToothClick"
            android:text="@string/pass" />

        <Button
            android:id="@+id/blueTooth_fail"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="blueToothClick"
            android:text="@string/fail" />

        <Button
            android:id="@+id/blueTooth_back"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="blueToothClick"
            android:text="@string/back" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bluetoothll1"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/bluetooth_scantip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:textColor="@color/white"
            android:text="@string/scaning" />

        <ListView
            android:id="@+id/listView"
            android:textSize="28sp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</RelativeLayout>


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>guys i really need some help plz help :)</title>
		<link>http://bvs.wikidot.com/forum/t-111958/guys-i-really-need-some-help-plz-help</link>
		<description>Posts in the discussion thread "guys i really need some help plz help :)"</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 05:47:34 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-111958#post-330866</guid>
				<title>Re: guys i really need some help plz help :)</title>
				<link>http://bvs.wikidot.com/forum/t-111958/guys-i-really-need-some-help-plz-help#post-330866</link>
				<description></description>
				<pubDate>Tue, 09 Dec 2008 19:21:47 +0000</pubDate>
				<wikidot:authorName>Yoshirou</wikidot:authorName>				<wikidot:authorUserId>138620</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

If you loop your dou level is the only thing that loops so you will stay a lv 4 when you loop. As for when i did BN starting out, seeing how you are jonin, fries are useless at this point for the most part. Just use 1 greassy nugget a day and all the rest be greassy burgers, burgers help the most. also you will want to use ichi special ramen if you can so you get a replenishing supply of greassy items and more likely to find the other allies. But overall you kinda just got to hope you pass the missions for the two allies when the time comes and hope you pass. Once you have cici and lulu or suchan and lulu, things become much easier. but i found this strategy to be the most effective. Also as a season 1 i recommend that you dont start outskirts till season 2 till you're stronger and plus even in season 2 all you can really do is collect items for making the original 4 items needed to unlock wasteland. At any point good luck with whatever you choose!

				 	]]>
				</content:encoded>							</item>
					<item>
				<guid>http://bvs.wikidot.com/forum/t-111958#post-330764</guid>
				<title>guys i really need some help plz help :)</title>
				<link>http://bvs.wikidot.com/forum/t-111958/guys-i-really-need-some-help-plz-help#post-330764</link>
				<description></description>
				<pubDate>Tue, 09 Dec 2008 16:52:22 +0000</pubDate>
				<wikidot:authorName>Mekkan</wikidot:authorName>				<wikidot:authorUserId>251188</wikidot:authorUserId>				<content:encoded>
					<![CDATA[

Im a Season 1 jounin and i have CICI but i cant get the allies and items from the missions i keep failing all the time, and i havent finnish the outskirt missions its to hard and i havent started with the trade, can someone give me some tips about THE BN and i have eaten alot of greassy stuff still it doesnt help and my doujutsu is level 4, but ill start get penalties soon, so if i just loop right now without gaining and finnishing the items and allies from theese missions what will i lose? should i just keep trying? will it be better if i complete evreything right now?

plz help me :)

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
.class public abstract Landroid/webkit/CookieManager;
.super Ljava/lang/Object;
.source "CookieManager.java"

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

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

    return-void
.end method

.method public static allowFileSchemeCookies()Z
    .locals 1

    .prologue
    .line 240
    invoke-static {}, Landroid/webkit/CookieManager;->getInstance()Landroid/webkit/CookieManager;

    move-result-object v0

    invoke-virtual {v0}, Landroid/webkit/CookieManager;->allowFileSchemeCookiesImpl()Z

    move-result v0

    return v0
.end method

.method public static declared-synchronized getInstance()Landroid/webkit/CookieManager;
    .locals 2

    .prologue
    const-class v1, Landroid/webkit/CookieManager;

    monitor-enter v1

    .line 39
    :try_start_0
    invoke-static {}, Landroid/webkit/WebViewFactory;->getProvider()Landroid/webkit/WebViewFactoryProvider;

    move-result-object v0

    invoke-interface {v0}, Landroid/webkit/WebViewFactoryProvider;->getCookieManager()Landroid/webkit/CookieManager;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v0

    monitor-exit v1

    return-object v0

    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public static setAcceptFileSchemeCookies(Z)V
    .locals 1
    .param p0, "accept"    # Z

    .prologue
    .line 264
    invoke-static {}, Landroid/webkit/CookieManager;->getInstance()Landroid/webkit/CookieManager;

    move-result-object v0

    invoke-virtual {v0, p0}, Landroid/webkit/CookieManager;->setAcceptFileSchemeCookiesImpl(Z)V

    .line 263
    return-void
.end method

# virtual methods
.method public abstract acceptCookie()Z
.end method

.method public abstract acceptThirdPartyCookies(Landroid/webkit/WebView;)Z
.end method

.method protected abstract allowFileSchemeCookiesImpl()Z
.end method

.method protected clone()Ljava/lang/Object;
    .locals 2
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/CloneNotSupportedException;
        }
    .end annotation

    .prologue
    .line 30
    new-instance v0, Ljava/lang/CloneNotSupportedException;

    const-string/jumbo v1, "doesn\'t implement Cloneable"

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

    throw v0
.end method

.method public abstract flush()V
.end method

.method public declared-synchronized getCookie(Landroid/net/WebAddress;)Ljava/lang/String;
    .locals 1
    .param p1, "uri"    # Landroid/net/WebAddress;

    .prologue
    monitor-enter p0

    .line 153
    :try_start_0
    invoke-virtual {p1}, Landroid/net/WebAddress;->toString()Ljava/lang/String;

    move-result-object v0

    invoke-virtual {p0, v0}, Landroid/webkit/CookieManager;->getCookie(Ljava/lang/String;)Ljava/lang/String;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v0

    monitor-exit p0

    return-object v0

    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method public abstract getCookie(Ljava/lang/String;)Ljava/lang/String;
.end method

.method public abstract getCookie(Ljava/lang/String;Z)Ljava/lang/String;
.end method

.method public abstract hasCookies()Z
.end method

.method public abstract hasCookies(Z)Z
.end method

.method public abstract removeAllCookie()V
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end method

.method public abstract removeAllCookies(Landroid/webkit/ValueCallback;)V
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/webkit/ValueCallback",
            "<",
            "Ljava/lang/Boolean;",
            ">;)V"
        }
    .end annotation
.end method

.method public abstract removeExpiredCookie()V
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end method

.method public abstract removeSessionCookie()V
.end method

.method public abstract removeSessionCookies(Landroid/webkit/ValueCallback;)V
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Landroid/webkit/ValueCallback",
            "<",
            "Ljava/lang/Boolean;",
            ">;)V"
        }
    .end annotation
.end method

.method public abstract setAcceptCookie(Z)V
.end method

.method protected abstract setAcceptFileSchemeCookiesImpl(Z)V
.end method

.method public abstract setAcceptThirdPartyCookies(Landroid/webkit/WebView;Z)V
.end method

.method public abstract setCookie(Ljava/lang/String;Ljava/lang/String;)V
.end method

.method public abstract setCookie(Ljava/lang/String;Ljava/lang/String;Landroid/webkit/ValueCallback;)V
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "Ljava/lang/String;",
            "Landroid/webkit/ValueCallback",
            "<",
            "Ljava/lang/Boolean;",
            ">;)V"
        }
    .end annotation
.end method


text:
package org.apache.spark.network.server;

import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

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

import org.apache.spark.network.buffer.ManagedBuffer;

/**
 * StreamManager which allows registration of an Iterator<ManagedBuffer>, which are individually
 * fetched as chunks by the client. Each registered buffer is one chunk.
 */
public class OneForOneStreamManager extends StreamManager {
  private final Logger logger = LoggerFactory.getLogger(OneForOneStreamManager.class);

  private final AtomicLong nextStreamId;
  private final Map<Long, StreamState> streams;

  /** State of a single stream. */
  private static class StreamState {
    final Iterator<ManagedBuffer> buffers;

    // Used to keep track of the index of the buffer that the user has retrieved, just to ensure
    // that the caller only requests each chunk one at a time, in order.
    int curChunk = 0;

    StreamState(Iterator<ManagedBuffer> buffers) {
      this.buffers = buffers;
    }
  }

  public OneForOneStreamManager() {
    // For debugging purposes, start with a random stream id to help identifying different streams.
    // This does not need to be globally unique, only unique to this class.
    nextStreamId = new AtomicLong((long) new Random().nextInt(Integer.MAX_VALUE) * 1000);
    streams = new ConcurrentHashMap<Long, StreamState>();
  }

  @Override
  public ManagedBuffer getChunk(long streamId, int chunkIndex) {
    StreamState state = streams.get(streamId);
    if (chunkIndex != state.curChunk) {
      throw new IllegalStateException(String.format(
        "Received out-of-order chunk index %s (expected %s)", chunkIndex, state.curChunk));
    } else if (!state.buffers.hasNext()) {
      throw new IllegalStateException(String.format(
        "Requested chunk index beyond end %s", chunkIndex));
    }
    state.curChunk += 1;
    ManagedBuffer nextChunk = state.buffers.next();

    if (!state.buffers.hasNext()) {
      logger.trace("Removing stream id {}", streamId);
      streams.remove(streamId);
    }

    return nextChunk;
  }

  @Override
  public void connectionTerminated(long streamId) {
    // Release all remaining buffers.
    StreamState state = streams.remove(streamId);
    if (state != null && state.buffers != null) {
      while (state.buffers.hasNext()) {
        state.buffers.next().release();
      }
    }
  }

  /**
   * Registers a stream of ManagedBuffers which are served as individual chunks one at a time to
   * callers. Each ManagedBuffer will be release()'d after it is transferred on the wire. If a
   * client connection is closed before the iterator is fully drained, then the remaining buffers
   * will all be release()'d.
   */
  public long registerStream(Iterator<ManagedBuffer> buffers) {
    long myStreamId = nextStreamId.getAndIncrement();
    streams.put(myStreamId, new StreamState(buffers));
    return myStreamId;
  }
}


text:
package main

import (
	"errors"
	"html/template"
	"log"
	"net/http"
	"os"
	"strconv"
	"sync"
	"time"

	"github.com/Reshurum/goriot"
	"github.com/gorilla/mux"
	"github.com/stickmanventures/lol-csv/controllers"
	"github.com/stickmanventures/lol-csv/helpers"
	"github.com/stickmanventures/lol-csv/middleware"
	"gopkg.in/redis.v3"
)

// All templates used by the site.
var templates map[string]*template.Template

// Setup controller routes by calling all the controllers setup functions.
func initRoutes() {
	if os.Getenv("LOLCSV_REDIS_DB") == "" || os.Getenv("LOLCSV_REDIS_ADDR") == "" || os.Getenv("LOLCSV_APIKEY") == "" {
		err := errors.New("The environment variables LOLCSV_REDIS_DB, LOLCSV_REDIS_ADDR, and LOLCSV_APIKEY must be set.")
		log.Println(err)
		os.Exit(1)
	}

	redisDB, err := strconv.ParseInt(os.Getenv("LOLCSV_REDIS_DB"), 10, 64)
	if err != nil {
		log.Println(err)
		os.Exit(255)
	}

	redisClient := redis.NewClient(&redis.Options{
		Addr:     os.Getenv("LOLCSV_REDIS_ADDR"),
		Password: os.Getenv("LOLCSV_REDIS_PASSWORD"),
		DB:       redisDB,
	})

	r := mux.NewRouter()
	controllers.NewHomeController(templates).Setup(r)
	controllers.NewApiController(templates, redisClient).Setup(r)

	http.Handle("/", middleware.LogAccess(r))
	http.Handle("/static/", middleware.LogAccess(http.StripPrefix("/static/", http.FileServer(http.Dir("static/")))))
}

func main() {
	// Load all site templates.
	templates = make(map[string]*template.Template)
	helpers.LoadTemplates(templates)

	// TODO: Make api key a config value or command line argument.
	goriot.SetAPIKey(os.Getenv("LOLCSV_APIKEY"))
	goriot.SetSmallRateLimit(10, 10*time.Second)
	goriot.SetLongRateLimit(500, 10*time.Minute)

	initRoutes()

	var wg sync.WaitGroup

	wg.Add(2)
	go func() {
		defer wg.Done()

		var port string

		if os.Getenv("LOLCSV_HTTP_PORT") != "" {
			port = ":" + os.Getenv("LOLCSV_HTTP_PORT")
		} else {
			port = ":8080"
		}

		log.Printf("Serving on port %s", port)
		err := http.ListenAndServe(port, nil)
		if err != nil {
			log.Fatal(err)
		}
	}()
	go func() {
		defer wg.Done()

		// If a certificate or key is not passed, do not serve over ssl.
		if os.Getenv("LOLCSV_CERT") == "" || os.Getenv("LOLCSV_KEY") == "" {
			log.Println("Cert or key is missing, not serving over https.")
			return
		}

		var port string

		if os.Getenv("LOLCSV_HTTPS_PORT") != "" {
			port = ":" + os.Getenv("LOLCSV_HTTPS_PORT")
		} else {
			port = ":4343"
		}

		log.Printf("Serving on port %s", port)
		err := http.ListenAndServeTLS(port, os.Getenv("LOLCSV_CERT"), os.Getenv("LOLCSV_KEY"), nil)
		if err != nil {
			log.Fatal(err)
		}
	}()

	wg.Wait()
}


text:
<tool id="stanford.tagger_2.1.0" name="Stanford Part-of-Speech Tagger" version="1.0.0">

 <command interpreter="lsd">
  ../common/invoke_vassar.lsd stanford.tagger_2.1.0-SNAPSHOT $input $output
 </command>
 <inputs>
  <param format="lif" label="input" name="input" type="data">
  </param>
 </inputs>
 <outputs>
  <data format="lif" name="output">
  </data>
 </outputs>
 <help>
  <![CDATA[

**What it does**

Adds Penn part-of-speech tags to tokens using the `Stanford Part of Speech Tagger <https://nlp.stanford.edu/software/tagger.shtml>`_.

**Required annotations**

* `Token <http://vocab.lappsgrid.org/Token.html>`_  (LIF)

**Generated Annotations**

* A LIF document with a new view containing `Token <http://vocab.lappsgrid.org/Token.html>`_ annotations, to which a "pos" feature has been added indicating the token's part of speech (`Penn tagset <https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html>`_)

.. class:: infomark

**NOTE**: This tool adds a new view that duplicates existing Token annotations, but with an added "pos" feature.

**License**

Stanford NLP tools are licensed under the `GNU General Public License <https://stanfordnlp.github.io/CoreNLP/#license>`_.

]]>
 </help>
</tool>


text:
package me.joeycumines.javapromises.v1.perf.mather;

import java.util.Map;

import static org.junit.Assert.*;

public class MathRequester {
    private final Map.Entry<String, Double> data;
    private volatile long time;
    private volatile boolean complete;

    public MathRequester(Map.Entry<String, Double> data) {
        this.data = data;
        this.complete = false;
        this.time = 0;
    }

    public String request() {
        if (0 != this.time) {
            fail("single request only");
        }
        this.time = System.currentTimeMillis();
        return this.data.getKey();
    }

    public void respond(double response) {
        if (this.complete) {
            fail("single response only");
        }
        assertEquals(this.data.getValue(), response, 0.001);
        this.time = System.currentTimeMillis() - this.time;
        this.complete = true;
    }

    public boolean isComplete() {
        return this.complete;
    }

    public long getTime() {
        if (!this.complete) {
            fail("incomplete request cannot get time");
        }

        return this.time;
    }

    public MathRequester redo() {
        return new MathRequester(this.data);
    }
}


text:
"""Support for Broadlink RM devices."""
from datetime import timedelta
from ipaddress import ip_address
import logging

import broadlink as blk
from broadlink.exceptions import BroadlinkException, CommandNotSupportedError
import voluptuous as vol

from homeassistant.components.switch import DOMAIN, PLATFORM_SCHEMA, SwitchEntity
from homeassistant.const import (
    CONF_COMMAND_OFF,
    CONF_COMMAND_ON,
    CONF_FRIENDLY_NAME,
    CONF_HOST,
    CONF_MAC,
    CONF_SWITCHES,
    CONF_TIMEOUT,
    CONF_TYPE,
    STATE_ON,
)
from homeassistant.exceptions import PlatformNotReady
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.util import Throttle, slugify

from . import async_setup_service, data_packet, hostname, mac_address
from .const import (
    DEFAULT_NAME,
    DEFAULT_PORT,
    DEFAULT_TIMEOUT,
    MP1_TYPES,
    RM4_TYPES,
    RM_TYPES,
    SP1_TYPES,
    SP2_TYPES,
)
from .device import BroadlinkDevice

_LOGGER = logging.getLogger(__name__)

TIME_BETWEEN_UPDATES = timedelta(seconds=5)

CONF_SLOTS = "slots"
CONF_RETRY = "retry"

DEVICE_TYPES = RM_TYPES + RM4_TYPES + SP1_TYPES + SP2_TYPES + MP1_TYPES

SWITCH_SCHEMA = vol.Schema(
    {
        vol.Optional(CONF_COMMAND_OFF): data_packet,
        vol.Optional(CONF_COMMAND_ON): data_packet,
        vol.Optional(CONF_FRIENDLY_NAME): cv.string,
    }
)

MP1_SWITCH_SLOT_SCHEMA = vol.Schema(
    {
        vol.Optional("slot_1"): cv.string,
        vol.Optional("slot_2"): cv.string,
        vol.Optional("slot_3"): cv.string,
        vol.Optional("slot_4"): cv.string,
    }
)

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
    {
        vol.Optional(CONF_SWITCHES, default={}): cv.schema_with_slug_keys(
            SWITCH_SCHEMA
        ),
        vol.Optional(CONF_SLOTS, default={}): MP1_SWITCH_SLOT_SCHEMA,
        vol.Required(CONF_HOST): vol.All(vol.Any(hostname, ip_address), cv.string),
        vol.Required(CONF_MAC): mac_address,
        vol.Optional(CONF_FRIENDLY_NAME, default=DEFAULT_NAME): cv.string,
        vol.Optional(CONF_TYPE, default=DEVICE_TYPES[0]): vol.In(DEVICE_TYPES),
        vol.Optional(CONF_TIMEOUT, default=DEFAULT_TIMEOUT): cv.positive_int,
    }
)

async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Set up the Broadlink switches."""

    host = config[CONF_HOST]
    mac_addr = config[CONF_MAC]
    friendly_name = config[CONF_FRIENDLY_NAME]
    model = config[CONF_TYPE]
    timeout = config[CONF_TIMEOUT]
    slots = config[CONF_SLOTS]
    devices = config[CONF_SWITCHES]

    def generate_rm_switches(switches, broadlink_device):
        """Generate RM switches."""
        return [
            BroadlinkRMSwitch(
                object_id,
                config.get(CONF_FRIENDLY_NAME, object_id),
                broadlink_device,
                config.get(CONF_COMMAND_ON),
                config.get(CONF_COMMAND_OFF),
            )
            for object_id, config in switches.items()
        ]

    def get_mp1_slot_name(switch_friendly_name, slot):
        """Get slot name."""
        if not slots[f"slot_{slot}"]:
            return f"{switch_friendly_name} slot {slot}"
        return slots[f"slot_{slot}"]

    if model in RM_TYPES:
        api = blk.rm((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        switches = generate_rm_switches(devices, broadlink_device)
    elif model in RM4_TYPES:
        api = blk.rm4((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        switches = generate_rm_switches(devices, broadlink_device)
    elif model in SP1_TYPES:
        api = blk.sp1((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        switches = [BroadlinkSP1Switch(friendly_name, broadlink_device)]
    elif model in SP2_TYPES:
        api = blk.sp2((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        switches = [BroadlinkSP2Switch(friendly_name, broadlink_device)]
    elif model in MP1_TYPES:
        api = blk.mp1((host, DEFAULT_PORT), mac_addr, None)
        broadlink_device = BroadlinkDevice(hass, api)
        parent_device = BroadlinkMP1Switch(broadlink_device)
        switches = [
            BroadlinkMP1Slot(
                get_mp1_slot_name(friendly_name, i), broadlink_device, i, parent_device,
            )
            for i in range(1, 5)
        ]

    api.timeout = timeout
    connected = await broadlink_device.async_connect()
    if not connected:
        raise PlatformNotReady

    if model in RM_TYPES or model in RM4_TYPES:
        hass.async_create_task(async_setup_service(hass, host, broadlink_device))

    async_add_entities(switches)

class BroadlinkRMSwitch(SwitchEntity, RestoreEntity):
    """Representation of an Broadlink switch."""

    def __init__(self, name, friendly_name, device, command_on, command_off):
        """Initialize the switch."""
        self.device = device
        self.entity_id = f"{DOMAIN}.{slugify(name)}"
        self._name = friendly_name
        self._state = False
        self._command_on = command_on
        self._command_off = command_off

    async def async_added_to_hass(self):
        """Call when entity about to be added to hass."""
        await super().async_added_to_hass()
        state = await self.async_get_last_state()
        if state:
            self._state = state.state == STATE_ON

    @property
    def name(self):
        """Return the name of the switch."""
        return self._name

    @property
    def assumed_state(self):
        """Return true if unable to access real state of entity."""
        return True

    @property
    def available(self):
        """Return True if entity is available."""
        return not self.should_poll or self.device.available

    @property
    def should_poll(self):
        """Return the polling state."""
        return False

    @property
    def is_on(self):
        """Return true if device is on."""
        return self._state

    async def async_update(self):
        """Update the state of the device."""
        if not self.available:
            await self.device.async_connect()

    async def async_turn_on(self, **kwargs):
        """Turn the device on."""
        if await self._async_send_packet(self._command_on):
            self._state = True
            self.async_write_ha_state()

    async def async_turn_off(self, **kwargs):
        """Turn the device off."""
        if await self._async_send_packet(self._command_off):
            self._state = False
            self.async_write_ha_state()

    async def _async_send_packet(self, packet):
        """Send packet to device."""
        if packet is None:
            _LOGGER.debug("Empty packet")
            return True
        try:
            await self.device.async_request(self.device.api.send_data, packet)
        except BroadlinkException as err_msg:
            _LOGGER.error("Failed to send packet: %s", err_msg)
            return False
        return True

class BroadlinkSP1Switch(BroadlinkRMSwitch):
    """Representation of an Broadlink switch."""

    def __init__(self, friendly_name, device):
        """Initialize the switch."""
        super().__init__(friendly_name, friendly_name, device, None, None)
        self._command_on = 1
        self._command_off = 0
        self._load_power = None

    async def _async_send_packet(self, packet):
        """Send packet to device."""
        try:
            await self.device.async_request(self.device.api.set_power, packet)
        except BroadlinkException as err_msg:
            _LOGGER.error("Failed to send packet: %s", err_msg)
            return False
        return True

class BroadlinkSP2Switch(BroadlinkSP1Switch):
    """Representation of an Broadlink switch."""

    @property
    def assumed_state(self):
        """Return true if unable to access real state of entity."""
        return False

    @property
    def should_poll(self):
        """Return the polling state."""
        return True

    @property
    def current_power_w(self):
        """Return the current power usage in Watt."""
        try:
            return round(self._load_power, 2)
        except (ValueError, TypeError):
            return None

    async def async_update(self):
        """Update the state of the device."""
        try:
            self._state = await self.device.async_request(self.device.api.check_power)
        except BroadlinkException as err_msg:
            _LOGGER.error("Failed to update state: %s", err_msg)
            return

        try:
            self._load_power = await self.device.async_request(
                self.device.api.get_energy
            )
        except CommandNotSupportedError:
            return
        except BroadlinkException as err_msg:
            _LOGGER.error("Failed to update load power: %s", err_msg)

class BroadlinkMP1Slot(BroadlinkRMSwitch):
    """Representation of a slot of Broadlink switch."""

    def __init__(self, friendly_name, device, slot, parent_device):
        """Initialize the slot of switch."""
        super().__init__(friendly_name, friendly_name, device, None, None)
        self._command_on = 1
        self._command_off = 0
        self._slot = slot
        self._parent_device = parent_device

    @property
    def assumed_state(self):
        """Return true if unable to access real state of entity."""
        return False

    @property
    def should_poll(self):
        """Return the polling state."""
        return True

    async def async_update(self):
        """Update the state of the device."""
        await self._parent_device.async_update()
        self._state = self._parent_device.get_outlet_status(self._slot)

    async def _async_send_packet(self, packet):
        """Send packet to device."""
        try:
            await self.device.async_request(
                self.device.api.set_power, self._slot, packet
            )
        except BroadlinkException as err_msg:
            _LOGGER.error("Failed to send packet: %s", err_msg)
            return False
        return True

class BroadlinkMP1Switch:
    """Representation of a Broadlink switch - To fetch states of all slots."""

    def __init__(self, device):
        """Initialize the switch."""
        self.device = device
        self._states = None

    def get_outlet_status(self, slot):
        """Get status of outlet from cached status list."""
        if self._states is None:
            return None
        return self._states[f"s{slot}"]

    @Throttle(TIME_BETWEEN_UPDATES)
    async def async_update(self):
        """Update the state of the device."""
        try:
            states = await self.device.async_request(self.device.api.check_power)
        except BroadlinkException as err_msg:
            _LOGGER.error("Failed to update state: %s", err_msg)
        self._states = states


text:
var blob = require('content-addressable-blob-store');
var wrap = require('level-option-wrap');
var fwdb = require('fwdb');
var exchange = require('hash-exchange');
var decode = require('bytewise').decode;

var defined = require('defined');
var has = require('has');
var isarray = require('isarray');
var stringify = require('json-stable-stringify');
var uniq = require('uniq');

var through = require('through2');
var Readable = require('readable-stream').Readable;
var readonly = require('read-only-stream');
var writeonly = require('write-only-stream');
var duplexer = require('duplexer2');

var inherits = require('inherits');
var EventEmitter = require('events').EventEmitter;

var collect = require('./lib/collect.js');
var dropFirst = require('./lib/drop_first.js');

inherits(ForkDB, EventEmitter);
module.exports = ForkDB;

function ForkDB (db, opts) {
    var self = this;
    if (!(this instanceof ForkDB)) return new ForkDB(db, opts);
    if (!opts) opts = {};

    this._db = db;
    this._fwdb = fwdb(db);
    this.db = this._fwdb.db;

    this.store = defined(
        opts.store,
        blob({ dir: defined(opts.dir, './forkdb.blob') })
    );
    this._seen = {};
    this._queue = [];

    this._id = opts.id;
    if (this._id === undefined) {
        this._queue.push(function (cb) {
            self._getId(function (err, id) {
                if (err) return cb(err);
                self._id = id;
                cb(null);
            });
        });
    }
    this._queue.push(function (cb) {
        self._getSeq(function (err, seq) {
            if (err) return cb(err);
            self._seq = seq;
            cb(null);
        });
    });
    this._runQueue();
}

ForkDB.prototype._runQueue = function () {
    var self = this;
    if (self._running) return;
    self._running = true;
    (function next () {
        if (self._queue.length === 0) {
            self._running = false;
            return;
        }
        self._queue.shift()(function (err) {
            if (err) self.emit('error', err)
            else next()
        });
    })();
};

ForkDB.prototype._getId = function (cb) {
    var self = this;
    self.db.get('_id', function (err, value) {
        if (err && err.type === 'NotFoundError') {
            value = generateId();
            self.db.put('_id', value, function (err) {
                if (err) return cb(err)
                cb(null, value);
            });
        }
        else if (err) return cb(err)
        else cb(null, value)
    });
};

ForkDB.prototype._getSeq = function (cb) {
    var r = this.db.createReadStream({
        gt: [ 'seq', null ],
        lt: [ 'seq', undefined ],
        reverse: true,
        limit: 1
    });
    r.on('error', cb);
    r.pipe(through.obj(write, end));

    function write (row, enc, next) { cb(null, row.key[1]) }
    function end () { cb(null, 0) }
};

ForkDB.prototype._getSeen = function (id, cb) {
    var self = this;
    if (has(self._seen, id)) {
        return process.nextTick(function () {
            cb(null, self._seen[id]);
        });
    }
    self.db.get([ '_seen', id ], function (err, seq) {
        if (err && err.type !== 'NotFoundError') return cb(err);
        var n = self._seen[id] = defined(seq, -1);
        cb(null, n);
    });
};

ForkDB.prototype._addSeen = function (id, aseq, cb) {
    var self = this;
    self._getSeen(id, function (err, seq) {
        if (err) return cb(err);
        var mseq = Math.max(seq, aseq) || 0;
        self._seen[id] = mseq;
        cb(null, {
            type: 'put',
            key: [ '_seen', id ],
            value: mseq
        });
    });
};

ForkDB.prototype.replicate = function (opts, cb) {
    var self = this;
    var input = through(), output = through();
    var dup = duplexer(input, output);
    self._queue.push(function (fn) {
        var r = self._replicate(opts, cb);
        r.on('available', dup.emit.bind(dup, 'available'));
        r.on('response', dup.emit.bind(dup, 'response'));
        r.on('since', dup.emit.bind(dup, 'since'));

        input.pipe(r).pipe(output);
        fn();
    });
    self._runQueue();
    return dup;
};

ForkDB.prototype._replicate = function (opts, cb) {
    var self = this;
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    if (!cb) cb = function () {};

    var mode = defined(opts.mode, 'sync');
    var errors = [], exchanged = [];
    var pending = 1;

    var ex = exchange(function (hash, fn) {
        if (mode === 'pull') {
            if (pending === 0) done();
            return;
        }
        pending ++;

        self.db.get([ 'seq-hash', hash ], function (err, seq) {
            if (err) return cb(err);
            var r = self.store.createReadStream({ key: hash });
            r.on('error', cb);
            r.on('end', function () { if (-- pending === 0) done() });
            fn(null, r, seq);
        });
    });
    ex.id(JSON.stringify([ self._id, mode ]));

    var other = {};
    ex.on('id', function (id) {
        pending --;
        try { var p = JSON.parse(id) }
        catch (err) { return ex.destroy() }
        other.id = p[0];
        other.mode = p[1];
        self._getSeen(other.id, function (err, seq) {
            if (err) return cb(err)
            else ex.since(seq)
        });
    });
    ex.on('since', function (seq) {
        provideSeq(seq);
    });
    ex.on('seen', function (seq) {
        self._addSeen(other.id, seq, function () {});
    });

    function provideSeq (seq) {
        var hashes = [];
        var r = self.db.createReadStream({
            gt: [ 'seq', defined(seq, null) ],
            lt: [ 'seq', undefined ]
        });
        var provided = 0;
        r.pipe(through.obj(write, flush));
        function write (row, enc, next) {
            hashes.push(row.value);
            provided ++;
            if (hashes.length >= 25) flush();
            next();
        }
        function flush () {
            if (hashes.length) ex.provide(hashes);
            hashes = [];
            if (provided === 0) done();
        }
    }

    ex.on('available', function (hashes) {
        if (mode === 'push') return;
        var p = hashes.length;
        var needed = [];
        if (mode === 'sync' && other.mode === 'pull') return;

        hashes.forEach(function (h) {
            self.get(h, function (err) {
                if (err) needed.push(h);
                if (-- p === 0) {
                    pending += needed.length;
                    ex.request(needed);
                }
            });
        });
    });

    ex.on('response', function (hash, stream, seq) {
        var opts = {
            expected: hash, // TODO: verify hash
            prebatch: function (rows, key, fn) {
                self._addSeen(other.id, seq, function (err, rows_) {
                    if (err) fn(null, rows)
                    else fn(null, rows.concat(rows_))
                });
            }
        };
        var df = dropFirst(function (err, dmeta) {
            df.pipe(self.createWriteStream(dmeta, opts, function (err) {
                if (err) {
                    errors.push(err);
                    if (-- pending === 0) done();
                }
                else {
                    exchanged.push(hash)
                    self._addSeen(other.id, seq, function (err) {
                        if (err) cb(err)
                        else if (-- pending === 0) done()
                        ex.seen(seq);
                    });
                }
            }));
        });
        stream.pipe(df)
    });

    if (opts.live) {
        self._db.on('batch', function (rows) {
            var hashes = [];
            rows.forEach(function (row) {
                try { var key = decode(decode(row.key)[1]) }
                catch (err) { return }
                if (key[0] === 'hash') {
                    hashes.push(key[1]);
                }
            });
            if (hashes.length) ex.provide(hashes);
        });
    }
    return ex;

    function done () {
        if (cb) cb(errors.length ? errors : null, exchanged);
        ex.emit('sync', exchanged);
    }
};

ForkDB.prototype.createWriteStream = function (meta, opts, cb) {
    var self = this;
    var input = through();
    self._queue.push(function (fn) {
        var w = self._createWriteStream(meta, opts, cb);
        w.on('error', function (err) { fn() });
        w.on('complete', function () { fn(null) });
        input.pipe(w);
    });
    self._runQueue();
    return writeonly(input);
};

ForkDB.prototype._createWriteStream = function (meta, opts, cb) {
    var self = this;
    if (typeof meta === 'function') {
        cb = meta;
        opts = {};
        meta = {};
    }
    if (!meta || typeof meta !== 'object') meta = {};
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    var prebatch = defined(
        opts.prebatch,
        function (rows, key, fn) { fn(null, rows) }
    );
    var w = this.store.createWriteStream();
    w.write(stringify(meta) + '\n');
    if (cb) w.on('error', cb);

    w.once('finish', function () {
        var prev = getPrev(meta);
        var doc = { hash: w.key, key: meta.key, prev: prev };

        var key = defined(meta.key, 'undefined');
        self._fwdb._create(doc, function (err, rows) {
            if (err) return w.emit('error', err);
            if (prev.length === 0) {
                rows.push({
                    type: 'put',
                    key: [ 'tail', meta.key, w.key ],
                    value: 0
                });
            }
            var skey = [ 'seq', ++ self._seq ];
            var shkey = [ 'seq-hash', w.key ];
            rows.push({ type: 'put', key: [ 'meta', w.key ], value: meta });
            rows.push({ type: 'put', key: shkey, value: self._seq });
            rows.push({ type: 'put', key: skey, value: w.key });
            prebatch(rows, w.key, commit);
        });
    });
    return w;

    function commit (err, rows) {
        if (err) return w.emit('error', err);
        if (!isarray(rows)) {
            return w.emit('error', new Error(
                'prebatch result is not an array'
            ));
        }
        self.db.batch(rows, function (err) {
            if (err) return w.emit('error', err);
            if (cb) cb(null, w.key);
            w.emit('complete', w.key);
            self.emit('create', w.key);
        });
    }
};

ForkDB.prototype.forks = function (key, opts, cb) {
    return this._fwdb.heads(key, opts, cb);
};
ForkDB.prototype.heads = ForkDB.prototype.forks;

ForkDB.prototype.keys = function (opts, cb) {
    return this._fwdb.keys(opts, cb);
};

ForkDB.prototype.tails = function (key, opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    var r = this._fwdb.db.createReadStream(wrap(opts, {
        gt: function (x) { return [ 'tail', key, null ] },
        lt: function (x) { return [ 'tail', key, undefined ] }
    }));
    var tr = through.obj(function (row, enc, next) {
        this.push({ hash: row.key[2] });
        next();
    });
    r.on('error', function (err) { tr.emit('error', err) });
    if (cb) tr.pipe(collect(cb));
    if (cb) tr.on('error', cb);
    return readonly(r.pipe(tr));
};

ForkDB.prototype.list = function (opts, cb) {
    if (typeof opts === 'function') {
        cb = opts;
        opts = {};
    }
    if (!opts) opts = {};
    var r = this._fwdb.db.createReadStream(wrap(opts, {
        gt: function (x) { return [ 'meta', defined(x, null) ] },
        lt: function (x) { return [ 'meta', defined(x, undefined) ] }
    }));
    var tr = through.obj(function (row, enc, next) {
        this.push({ meta: row.value, hash: row.key[1] });
        next();
    });
    r.on('error', function (err) { tr.emit('error', err) });
    if (cb) tr.pipe(collect(cb));
    if (cb) tr.on('error', cb);
    return readonly(r.pipe(tr));
};

ForkDB.prototype.createReadStream = function (hash) {
    var r = this.store.createReadStream({ key: hash });
    return readonly(r.pipe(dropFirst()));
};

ForkDB.prototype.get = function (hash, cb) {
    this._fwdb.db.get([ 'meta', hash ], function (err, meta) {
        if (err && cb) cb(err)
        else if (cb) cb(null, meta)
    });
};

ForkDB.prototype.links = function (hash, opts, cb) {
    return this._fwdb.links(hash, opts, cb);
};

ForkDB.prototype.history = function (hash) {
    var self = this;
    var r = new Readable({ objectMode: true });
    var next = hash;

    r._read = function () {
        if (!next) return r.push(null);
        self.get(next, onget);
    };
    return r;

    function onget (err, meta) {
        if (err) return r.emit('error', err)
        var hash = next;
        var prev = getPrev(meta);

        if (prev.length === 0) {
            next = null;
            r.push({ hash: hash, meta: meta });
        }
        else if (prev.length === 1) {
            next = hashOf(prev[0]);
            r.push({ hash: hash, meta: meta });
        }
        else {
            next = null;
            r.push({ hash: hash, meta: meta });
            prev.forEach(function (p) {
                r.emit('branch', self.history(hashOf(p)));
            });
        }
    }
};

ForkDB.prototype.future = function (hash) {
    var self = this;
    var r = new Readable({ objectMode: true });
    var next = hash;

    r._read = function () {
        if (!next) return r.push(null);

        var pending = 2, ref = {};
        self.get(next, function (err, meta) {
            if (err) return r.emit('error', err);
            ref.meta = meta;
            if (-- pending === 0) done();
        });

        self.links(next, function (err, crows) {
            if (err) return r.emit('error', err);
            ref.rows = crows;
            if (-- pending === 0) done();
        });

        function done () {
            var prev = next;
            if (ref.rows.length === 0) {
                next = null;
                r.push({ hash: prev, meta: ref.meta });
            }
            else if (ref.rows.length === 1) {
                next = hashOf(ref.rows[0]);
                r.push({ hash: prev, meta: ref.meta });
            }
            else {
                next = null;
                r.push({ hash: prev, meta: ref.meta });
                ref.rows.forEach(function (crow) {
                    r.emit('branch', self.future(hashOf(crow)));
                });
            }
        }
    };
    return r;
};

ForkDB.prototype.concestor = function (hashes, cb) {
    var self = this;
    var seen = {};
    var seenh = {};
    var hs = hashes.map(function (h) { return [h] });
    hashes.forEach(function (h, ix) {
        seenh[ix] = {};
    });

    (function next (hashes) {
        var results = null;
        for (var i = 0; i < hashes.length; i++) {
            var hs = hashes[i];
            for (var j = 0; j < hs.length; j++) {
                var hash = hs[j];
                if (!has(seenh[i], hash)) {
                    seenh[i][hash] = true;
                    seen[hash] = (seen[hash] || 0) + 1;
                }
                if (seen[hash] === hashes.length) {
                    if (!results) results = [];
                    results.push(hash);
                }
            }
        }
        if (results && results.length) return cb(null, uniq(results));

        var pending = 0;
        var prev = [];

        hashes.forEach(function (hs, ix) {
            pending += hs.length;
            prev[ix] = [];
            hs.forEach(function (hash) {
                self.get(hash, function (err, value) {
                    if (!value) {}
                    else if (isarray(value.prev)) {
                        prev[ix].push.apply(prev[ix], value.prev.map(hashOf));
                    }
                    else if (value.prev) {
                        prev[ix].push(value.prev);
                    }
                    if (-- pending === 0) next(prev);
                });
            });
        });
        if (pending === 0) return cb(null, []);
    })(hs);
};

function getPrev (meta) {
    if (!meta) return [];
    if (!has(meta, 'prev')) return [];
    var prev = meta.prev;
    if (!isarray(prev)) prev = [ prev ];
    return prev.map(function (p) {
        if (p && typeof p === 'object' && p.hash) return p.hash;
        return p;
    }).filter(Boolean);
}

function hashOf (p) {
    return p && typeof p === 'object' ? p.hash : p;
}

function generateId () {
    var s = '';
    for (var i = 0; i < 4; i++) {
        s += Math.floor(Math.random() * Math.pow(16,8)).toString(16);
    }
    return s;
}


text:
"""
.. module: lemur.plugins.lemur_csr.plugin

An export plugin that exports CSR from a private key and certificate.
"""
from io import open
import subprocess

from flask import current_app

from lemur.utils import mktempfile, mktemppath
from lemur.plugins.bases import ExportPlugin
from lemur.plugins import lemur_csr as csr

def run_process(command):
    """
    Runs a given command with pOpen and wraps some
    error handling around it.
    :param command:
    :return:
    """
    p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    current_app.logger.debug(command)
    stdout, stderr = p.communicate()

    if p.returncode != 0:
        current_app.logger.debug(" ".join(command))
        current_app.logger.error(stderr)
        raise Exception(stderr)

def create_csr(cert, chain, csr_tmp, key):
    """
    Creates a csr from key and cert file.
    :param cert:
    :param chain:
    :param csr_tmp:
    :param key:
    """
    assert isinstance(cert, str)
    assert isinstance(chain, str)
    assert isinstance(key, str)

    with mktempfile() as key_tmp:
        with open(key_tmp, "w") as f:
            f.write(key)

        with mktempfile() as cert_tmp:
            with open(cert_tmp, "w") as f:
                if chain:
                    f.writelines([cert.strip() + "\n", chain.strip() + "\n"])
                else:
                    f.writelines([cert.strip() + "\n"])

            output = subprocess.check_output(
                ["openssl", "x509", "-x509toreq", "-in", cert_tmp, "-signkey", key_tmp]
            )
            subprocess.run(["openssl", "req", "-out", csr_tmp], input=output)

class CSRExportPlugin(ExportPlugin):
    title = "CSR"
    slug = "openssl-csr"
    description = "Exports a CSR"
    version = csr.VERSION

    author = "jchuong"
    author_url = "https://github.com/jchuong"

    def export(self, body, chain, key, options, **kwargs):
        """
        Creates CSR from certificate

        :param key:
        :param chain:
        :param body:
        :param options:
        :param kwargs:
        """
        with mktemppath() as output_tmp:
            if not key:
                raise Exception("Private Key required by CSR")

            create_csr(body, chain, output_tmp, key)
            extension = "csr"

            with open(output_tmp, "rb") as f:
                raw = f.read()
        # passphrase is None
        return extension, None, raw