text:
package com.google.javascript.refactoring;

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

import com.google.common.collect.ImmutableList;
import com.google.javascript.jscomp.AbstractCompiler;
import com.google.javascript.jscomp.JSError;
import com.google.javascript.jscomp.NodeTraversal;
import com.google.javascript.jscomp.NodeUtil;
import com.google.javascript.jscomp.lint.CheckProvidesSorted;
import com.google.javascript.jscomp.lint.CheckRequiresSorted;
import com.google.javascript.refactoring.SuggestedFix.ImportType;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Maps a {@code JSError} to a list of {@code SuggestedFix}es, if possible.
 * TODO(tbreisacher): Move this into the compiler itself (i.e. into the jscomp package). This will
 *     make it easier for people adding new warnings to also add fixes for them.
 */
public final class ErrorToFixMapper {

  private static final Pattern DID_YOU_MEAN = Pattern.compile(".*Did you mean (.*)\\?");
  private static final Pattern EARLY_REF =
      Pattern.compile("Variable referenced before declaration: (.*)");
  private static final Pattern MISSING_REQUIRE =
      Pattern.compile("'([^']+)' references a .*", Pattern.DOTALL);
  private static final Pattern FULLY_QUALIFIED_NAME =
      Pattern.compile("Reference to fully qualified import name '([^']+)'.*");
  private static final Pattern USE_SHORT_NAME =
      Pattern.compile(".*Please use the short name '(.*)' instead.");

  private final AbstractCompiler compiler;
  private final LinkedHashMap<Node, ScriptMetadata> metadataForEachScript = new LinkedHashMap<>();

  public ErrorToFixMapper(AbstractCompiler compiler) {
    this.compiler = compiler;
  }

  public ImmutableList<SuggestedFix> getFixesForJsError(JSError error) {
    SuggestedFix fix = getFixForJsError(error);
    if (fix != null) {
      return ImmutableList.of(fix);
    }
    switch (error.getType().key) {
      case "JSC_IMPLICITLY_NONNULL_JSDOC":
      case "JSC_IMPLICITLY_NULLABLE_JSDOC":
      case "JSC_MISSING_NULLABILITY_MODIFIER_JSDOC":
      case "JSC_NULL_MISSING_NULLABILITY_MODIFIER_JSDOC":
        return getFixesForImplicitNullabilityErrors(error);
      default:
        return ImmutableList.of();
    }
  }

  /**
   * Creates a SuggestedFix for the given error. Note that some errors have multiple fixes so
   * getFixesForJsError should often be used instead of this.
   */
  public SuggestedFix getFixForJsError(JSError error) {
    switch (error.getType().key) {
      case "JSC_REDECLARED_VARIABLE":
        return getFixForRedeclaration(error);
      case "JSC_REFERENCE_BEFORE_DECLARE":
        return getFixForEarlyReference(error);
      case "JSC_MISSING_SEMICOLON":
        return getFixForMissingSemicolon(error);
      case "JSC_REQUIRES_NOT_SORTED":
        return getFixForUnsortedRequires(error);
      case "JSC_PROVIDES_NOT_SORTED":
        return getFixForUnsortedProvides(error);
      case "JSC_DEBUGGER_STATEMENT_PRESENT":
        return new SuggestedFix.Builder()
            .attachMatchedNodeInfo(error.getNode(), compiler)
            .setDescription("Remove debugger statement")
            .delete(error.getNode())
            .build();
      case "JSC_USELESS_EMPTY_STATEMENT":
        return removeEmptyStatement(error);
      case "JSC_INEXISTENT_PROPERTY_WITH_SUGGESTION":
      case "JSC_STRICT_INEXISTENT_PROPERTY_WITH_SUGGESTION":
        return getFixForInexistentProperty(error);
      case "JSC_MISSING_CALL_TO_SUPER":
        return getFixForMissingSuper(error);
      case "JSC_INVALID_SUPER_CALL_WITH_SUGGESTION":
        return getFixForInvalidSuper(error);
      case "JSC_MISSING_REQUIRE":
      case "JSC_MISSING_REQUIRE_IN_PROVIDES_FILE":
        return getFixForMissingRequire(error, ImportType.REQUIRE);
      case "JSC_MISSING_REQUIRE_TYPE":
      case "JSC_MISSING_REQUIRE_TYPE_IN_PROVIDES_FILE":
        return getFixForMissingRequire(error, ImportType.REQUIRE_TYPE);
      case "JSC_EXTRA_REQUIRE_WARNING":
        return getFixForExtraRequire(error);
      case "JSC_REFERENCE_TO_SHORT_IMPORT_BY_LONG_NAME_INCLUDING_SHORT_NAME":
      case "JSC_REFERENCE_TO_FULLY_QUALIFIED_IMPORT_NAME":
        return getFixForReferenceToShortImportByLongName(error);
      case "JSC_REDUNDANT_NULLABILITY_MODIFIER_JSDOC":
        return getFixForRedundantNullabilityModifierJsDoc(error);
      case "JSC_MISSING_CONST_ON_CONSTANT_CASE":
        return getFixForConstantCaseErrors(error);
      default:
        return null;
    }
  }

  private SuggestedFix getFixForRedeclaration(JSError error) {
    Node name = error.getNode();
    checkState(name.isName(), name);
    Node parent = name.getParent();
    if (!NodeUtil.isNameDeclaration(parent)) {
      return null;
    }

    SuggestedFix.Builder fix = new SuggestedFix.Builder().attachMatchedNodeInfo(name, compiler);

    if (!name.hasChildren()) {
      Node nodeToDelete = parent.hasOneChild() ? parent : error.getNode();
      return fix.setDescription("Remove redundant declaration").delete(nodeToDelete).build();
    }

    fix.setDescription("Convert redundant declaration to assignment");

    Node assign = IR.exprResult(
        IR.assign(name.cloneNode(), name.getFirstChild().cloneTree()));
    if (parent.hasOneChild()) {
      return fix.replace(parent, assign, compiler).build();
    }

    // Split the var statement into an assignment and up to two var statements.
    // var a = 0,
    //     b = 1,  // This is the one we're removing.
    //     c = 2;
    //
    // becomes
    //
    // var a = 0;  // This is the "added" var statement.
    // b = 1;
    // var c = 2;  // This is the original var statement.
    List<Node> childrenOfAddedVarStatement = new ArrayList<>();
    for (Node n = parent.getFirstChild(); n != null; n = n.getNext()) {
      if (n == name) {
        break;
      }
      childrenOfAddedVarStatement.add(n);
    }

    if (!childrenOfAddedVarStatement.isEmpty()) {
      Node var = new Node(parent.getToken());
      for (Node n : childrenOfAddedVarStatement) {
        var.addChildToBack(n.cloneTree());
      }
      // Use a sortKey of "1" to make sure this is applied before the statement below.
      fix.insertBefore(parent, var, compiler, "1");
    }

    if (name.getNext() != null) {
      // Keep the original var statement, just remove the names that will be put in the added one.
      for (Node n : childrenOfAddedVarStatement) {
        fix.delete(n);
      }
      fix.delete(name);
      // Use a sortKey of "2" to make sure this is applied after the statement above.
      fix.insertBefore(parent, assign, compiler, "2");
    } else {
      // Remove the original var statement.
      fix.replace(parent, assign, compiler);
    }

    return fix.build();
  }

  /**
   * This fix is not ideal. It trades one warning (JSC_REFERENCE_BEFORE_DECLARE) for another
   * (JSC_REDECLARED_VARIABLE). But after running the fixer once, you can then run it again and
   * #getFixForRedeclaration will take care of the JSC_REDECLARED_VARIABLE warning.
   */
  private SuggestedFix getFixForEarlyReference(JSError error) {
    Matcher m = EARLY_REF.matcher(error.getDescription());
    if (m.matches()) {
      String name = m.group(1);
      Node stmt = NodeUtil.getEnclosingStatement(error.getNode());
      return new SuggestedFix.Builder()
          .attachMatchedNodeInfo(error.getNode(), compiler)
          .setDescription("Insert var declaration statement")
          .insertBefore(stmt, "var " + name + ";\n")
          .build();
    }
    return null;
  }

  private SuggestedFix getFixForReferenceToShortImportByLongName(JSError error) {
    SuggestedFix.Builder fix =
        new SuggestedFix.Builder().attachMatchedNodeInfo(error.getNode(), compiler);
    NodeMetadata metadata = new NodeMetadata(compiler);
    Match match = new Match(error.getNode(), metadata);

    Node script = compiler.getScriptNode(error.getSourceName());
    ScriptMetadata scriptMetadata = this.getMetadataForScript(script);

    Matcher fullNameMatcher = FULLY_QUALIFIED_NAME.matcher(error.getDescription());
    checkState(fullNameMatcher.matches(), error.getDescription());
    String fullName = fullNameMatcher.group(1);

    Matcher shortNameMatcher = USE_SHORT_NAME.matcher(error.getDescription());
    String shortName;
    if (shortNameMatcher.matches()) {
      shortName = shortNameMatcher.group(1);
    } else {
      fix.addGoogRequire(match, fullName, scriptMetadata);
      shortName = scriptMetadata.getAlias(fullName);
    }

    String oldName =
        error.getNode().isQualifiedName()
            ? error.getNode().getQualifiedName()
            : error.getNode().getString();

    return fix.replace(
            error.getNode(),
            NodeUtil.newQName(compiler, oldName.replace(fullName, shortName)),
            compiler)
        .build();
  }

  private ImmutableList<SuggestedFix> getFixesForImplicitNullabilityErrors(JSError error) {

    if (error.getNode().getSourceFileName() == null) {
      // If we don't have a source location we can't generate a valid fix.
      return ImmutableList.of();
    }

    SuggestedFix qmark =
        new SuggestedFix.Builder()
            .attachMatchedNodeInfo(error.getNode(), compiler)
            .insertBefore(error.getNode(), "?")
            .setDescription("Make nullability explicit")
            .build();
    SuggestedFix bang =
        new SuggestedFix.Builder()
            .attachMatchedNodeInfo(error.getNode(), compiler)
            .insertBefore(error.getNode(), "!")
            .setDescription("Make type non-nullable")
            .build();
    switch (error.getType().key) {
      case "JSC_NULL_MISSING_NULLABILITY_MODIFIER_JSDOC":
        // When initializer was null, we can be confident about nullability
        return ImmutableList.of(qmark);
      case "JSC_MISSING_NULLABILITY_MODIFIER_JSDOC":
        // Otherwise, the linter should assume ! is preferred over ?.
        return ImmutableList.of(bang, qmark);
      case "JSC_IMPLICITLY_NULLABLE_JSDOC":
        // The type-based check prefers ? over ! since it only warns for names that are nullable.
        return ImmutableList.of(qmark, bang);
      case "JSC_IMPLICITLY_NONNULL_JSDOC":
        // Using type-information, we can also be confident about ! for enums and typedefs.
        return ImmutableList.of(bang);
      default:
        throw new IllegalArgumentException("Unexpected JSError Type: " + error.getType().key);
    }
  }

  private SuggestedFix removeEmptyStatement(JSError error) {
    return new SuggestedFix.Builder()
        .attachMatchedNodeInfo(error.getNode(), compiler)
        .setDescription("Remove empty statement")
        .deleteWithoutRemovingWhitespace(error.getNode())
        .build();
  }

  private SuggestedFix getFixForMissingSemicolon(JSError error) {
    return new SuggestedFix.Builder()
        .attachMatchedNodeInfo(error.getNode(), compiler)
        .insertAfter(error.getNode(), ";")
        .build();
  }

  private SuggestedFix getFixForMissingSuper(JSError error) {
    Node constructorFunction = error.getNode().getFirstChild();
    Node body = NodeUtil.getFunctionBody(constructorFunction);
    return new SuggestedFix.Builder()
        .attachMatchedNodeInfo(error.getNode(), compiler)
        .addChildToFront(body, "super();")
        .build();
  }

  private SuggestedFix getFixForInvalidSuper(JSError error) {
    Matcher m = DID_YOU_MEAN.matcher(error.getDescription());
    if (m.matches()) {
      String superDotSuggestion = checkNotNull(m.group(1));
      return new SuggestedFix.Builder()
          .attachMatchedNodeInfo(error.getNode(), compiler)
          .setDescription("Call '" + superDotSuggestion + "' instead")
          .replace(error.getNode(), NodeUtil.newQName(compiler, superDotSuggestion), compiler)
          .build();
    }
    return null;
  }

  private SuggestedFix getFixForInexistentProperty(JSError error) {
    Matcher m = DID_YOU_MEAN.matcher(error.getDescription());
    if (m.matches()) {
      String suggestedPropName = m.group(1);
      return new SuggestedFix.Builder()
          .attachMatchedNodeInfo(error.getNode(), compiler)
          .setDescription("Change property name to '" + suggestedPropName + "'")
          .rename(error.getNode(), suggestedPropName)
          .build();
    }
    return null;
  }

  private SuggestedFix getFixForMissingRequire(JSError error, ImportType importType) {
    Matcher regexMatcher = MISSING_REQUIRE.matcher(error.getDescription());
    checkState(regexMatcher.matches(), "Unexpected error description: %s", error.getDescription());
    String namespaceToRequire = regexMatcher.group(1);

    String qName =
        error.getNode().isQualifiedName()
            ? error.getNode().getQualifiedName()
            : error.getNode().getString();

    checkState(
        qName.startsWith(namespaceToRequire),
        "Expected error location %s to start with namespace <%s>",
        error.getNode(),
        namespaceToRequire);

    Node script = compiler.getScriptNode(error.getSourceName());
    ScriptMetadata scriptMetadata = this.getMetadataForScript(script);

    NodeMetadata metadata = new NodeMetadata(compiler);
    Match match = new Match(error.getNode(), metadata);
    SuggestedFix.Builder fix =
        new SuggestedFix.Builder()
            .attachMatchedNodeInfo(error.getNode(), compiler)
            .addImport(match, namespaceToRequire, importType, scriptMetadata);

    String alias = scriptMetadata.getAlias(namespaceToRequire);
    if (alias != null) {
      fix.replace(
          error.getNode(),
          NodeUtil.newQName(compiler, qName.replace(namespaceToRequire, alias)),
          compiler);
    }

    return fix.build();
  }

  private SuggestedFix getFixForExtraRequire(JSError error) {
    Node node = error.getNode();

    SuggestedFix.Builder fix = new SuggestedFix.Builder().attachMatchedNodeInfo(node, compiler);
    boolean destructuring = NodeUtil.getEnclosingType(node, Token.OBJECT_PATTERN) != null;
    if (destructuring) {
      fix.setDescription("Delete unused symbol");
      if (node.isStringKey()) {
        fix.delete(node);
      } else {
        checkState(node.getParent().isStringKey(), node.getParent());
        fix.delete(node.getParent());
      }
    } else {
      fix.setDescription("Delete extra require");
      fix.deleteWithoutRemovingWhitespaceBefore(NodeUtil.getEnclosingStatement(node));
    }
    return fix.build();
  }

  private SuggestedFix getFixForUnsortedRequires(JSError error) {
    // TODO(tjgq): Encode enough information in the error to avoid the need to run a traversal in
    // order to produce the fix.
    Node script = NodeUtil.getEnclosingScript(error.getNode());
    CheckRequiresSorted callback = new CheckRequiresSorted(CheckRequiresSorted.Mode.COLLECT_ONLY);
    NodeTraversal.traverse(compiler, script, callback);

    if (!callback.needsFix()) {
      return null;
    }

    return new SuggestedFix.Builder()
        .attachMatchedNodeInfo(callback.getFirstNode(), compiler)
        .replaceRange(callback.getFirstNode(), callback.getLastNode(), callback.getReplacement())
        .build();
  }

  private SuggestedFix getFixForUnsortedProvides(JSError error) {
    // TODO(tjgq): Encode enough information in the error to avoid the need to run a traversal in
    // order to produce the fix.
    Node script = NodeUtil.getEnclosingScript(error.getNode());
    CheckProvidesSorted callback = new CheckProvidesSorted(CheckProvidesSorted.Mode.COLLECT_ONLY);
    NodeTraversal.traverse(compiler, script, callback);

    if (!callback.needsFix()) {
      return null;
    }

    return new SuggestedFix.Builder()
        .attachMatchedNodeInfo(callback.getFirstNode(), compiler)
        .replaceRange(callback.getFirstNode(), callback.getLastNode(), callback.getReplacement())
        .build();
  }

  private SuggestedFix getFixForRedundantNullabilityModifierJsDoc(JSError error) {
    return new SuggestedFix.Builder()
        .attachMatchedNodeInfo(error.getNode(), compiler)
        .replaceText(error.getNode(), 1, "")
        .build();
  }
  /**
   * Suggests a fix for a constant case error.
   *
   * <p>If the variable is in a let clause, suggest adding a const. If the variable is not, suggest
   * adding a @const annotation. Don't try to adjust the JSDoc, because that can produce invalid
   * output.
   */
  private SuggestedFix getFixForConstantCaseErrors(JSError error) {
    Node n = error.getNode();
    Node parent = n.getParent();
    if (!n.isName() || !NodeUtil.isNameDeclaration(parent)) {
      return null;
    }

    if (parent.isLet()) {
      // Convert to a `const` declaration
      return new SuggestedFix.Builder()
          .setDescription("Make explicitly constant")
          .attachMatchedNodeInfo(parent, compiler)
          .replaceText(parent, 3, "const")
          .build();
    }
    // Don't convert a `var` to a `const` to avoid breaking variable scoping.
    checkState(parent.isVar(), parent);
    JSDocInfo info = parent.getJSDocInfo();
    if (info == null) {
      return new SuggestedFix.Builder()
          .setDescription("Make explicitly constant")
          .attachMatchedNodeInfo(parent, compiler)
          .addOrReplaceJsDoc(parent, "/** @const */\n")
          .build();
    }
    return null;
  }

  private ScriptMetadata getMetadataForScript(Node script) {
    checkArgument(script.isScript());
    return this.metadataForEachScript.computeIfAbsent(
        script, (s) -> ScriptMetadata.create(s, this.compiler));
  }
}


text:
package org.jboss.weld.tests.proxy.synthetic;

import jakarta.enterprise.context.Dependent;
import jakarta.interceptor.Interceptors;

@Interceptors(BarInterceptor.class)
@Dependent
public class Bar {

    void bar() {
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef QJSENGINE_H
#define QJSENGINE_H

#include <QtCore/qmetatype.h>

#include <QtCore/qvariant.h>
#include <QtCore/qsharedpointer.h>
#include <QtCore/qobject.h>
#include <QtQml/qjsvalue.h>

QT_BEGIN_NAMESPACE

class QV8Engine;

template <typename T>
inline T qjsvalue_cast(const QJSValue &);

class QJSEnginePrivate;
class Q_QML_EXPORT QJSEngine
    : public QObject
{
    Q_OBJECT
public:
    QJSEngine();
    explicit QJSEngine(QObject *parent);
    virtual ~QJSEngine();

    QJSValue globalObject() const;

    QJSValue evaluate(const QString &program, const QString &fileName = QString(), int lineNumber = 1);

    QJSValue newObject();
    QJSValue newArray(uint length = 0);

    QJSValue newQObject(QObject *object);

    template <typename T>
    inline QJSValue toScriptValue(const T &value)
    {
        return create(qMetaTypeId<T>(), &value);
    }
    template <typename T>
    inline T fromScriptValue(const QJSValue &value)
    {
        return qjsvalue_cast<T>(value);
    }

    void collectGarbage();

    QV8Engine *handle() const { return d; }

private:
    QJSValue create(int type, const void *ptr);

    static bool convertV2(const QJSValue &value, int type, void *ptr);

    friend inline bool qjsvalue_cast_helper(const QJSValue &, int, void *);

protected:
    QJSEngine(QJSEnginePrivate &dd, QObject *parent = 0);

private:
    QV8Engine *d;
    Q_DISABLE_COPY(QJSEngine)
    Q_DECLARE_PRIVATE(QJSEngine)
    friend class QV8Engine;
};

inline bool qjsvalue_cast_helper(const QJSValue &value, int type, void *ptr)
{
    return QJSEngine::convertV2(value, type, ptr);
}

template<typename T>
T qjsvalue_cast(const QJSValue &value)
{
    T t;
    const int id = qMetaTypeId<T>();

    if (qjsvalue_cast_helper(value, id, &t))
        return t;
    else if (value.isVariant())
        return qvariant_cast<T>(value.toVariant());

    return T();
}

template <>
inline QVariant qjsvalue_cast<QVariant>(const QJSValue &value)
{
    return value.toVariant();
}

QT_END_NAMESPACE

#endif // QJSENGINE_H


text:
{:L('PUBLIC_GROUP_NAME')}:<input type="text" name='groupname' id='add_groupname' class="s-txt" onblur="this.className='s-txt'" onfocus="this.className='s-txt-focus'" >

{:L('PUBLIC_CONFIRM')}{:L('PUBLIC_CANCEL')}


text:
<?php

namespace frontend\assets;

use yii\web\AssetBundle;

class TouchPunchAsset extends AssetBundle
{
    public $sourcePath = '@bower/jquery-ui-touch-punch-improved';
    public $js = [
        'jquery.ui.touch-punch-improved.js',
    ];
}


text:
package com.angcyo.uiview.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.view.Choreographer;
import android.view.View;

import com.angcyo.uiview.R;

public class LoadingImageView extends AppCompatImageView implements Choreographer.FrameCallback {

    static Choreographer mChoreographer = Choreographer.getInstance();
    float degrees = 0;
    boolean isLoading = false;
    Runnable loadRunnable = new Runnable() {
        @Override
        public void run() {
            postInvalidate();
            postDelayed(loadRunnable, 40);//40 = 24 帧, 16 = 60 帧
        }
    };

    public LoadingImageView(Context context) {
        this(context, null);
    }

    public LoadingImageView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setImageResource(R.drawable.loading);
        setScaleType(ScaleType.CENTER_INSIDE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        final Drawable drawable = getDrawable();
        if (drawable != null) {
            canvas.save();
            canvas.translate(getMeasuredWidth() / 2, getMeasuredHeight() / 2);
            canvas.rotate(degrees);
            final int intrinsicWidth = drawable.getIntrinsicWidth();
            final int intrinsicHeight = drawable.getIntrinsicHeight();
            drawable.setBounds(-intrinsicWidth / 2, -intrinsicHeight / 2, intrinsicWidth / 2, intrinsicHeight / 2);
            drawable.draw(canvas);
            canvas.restore();
        }

        degrees += 10;

        if (isLoading) {
            mChoreographer.postFrameCallback(this);
        }
    }

    @Override
    public void setVisibility(int visibility) {
        super.setVisibility(visibility);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        endLoad();
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == VISIBLE) {
            if (isLoading) {
                return;
            }
            startLoad();
        } else {
            endLoad();
        }
    }

    private void startLoad() {
        //post(loadRunnable);
        removeCallbacks(loadRunnable);
        mChoreographer.removeFrameCallback(this);
        mChoreographer.postFrameCallback(this);
        isLoading = true;
    }

    public void endLoad() {
        removeCallbacks(loadRunnable);
        mChoreographer.removeFrameCallback(this);
        isLoading = false;
    }

    @Override
    public void doFrame(long frameTimeNanos) {
        postInvalidate();
    }
}


text:
#ifndef FLIP_BIT_MUTATOR_H_
#define FLIP_BIT_MUTATOR_H_

#include <k52/common/disallow_copy_and_assign.h>
#include <k52/optimization/i_mutator.h>
#include <k52/optimization/gen_mutator_base.h>

namespace k52
{
namespace optimization
{

class FlipBitMutator : public GenMutatorBase
{
public:
    FlipBitMutator(double gen_mutation_probability);

protected:
    bool ShouldMutateCurrentGen();
    void AfterGenProcessed(bool wasMutated);

private:
    void SetGensToSkipNow();

    double mutation_probability_;
    int max_number_of_skipped_gens_;
    int currently_skipped_gens_;
    int gens_to_skip_now_;

    DISALLOW_COPY_AND_ASSIGN(FlipBitMutator);
};

}/* namespace optimization */
}/* namespace k52 */

#endif /* FLIP_BIT_MUTATOR_H_ */


text:
package de.mikeherwig.LRWebdriverBridge;

public class ActionResult {

	private long responseTime = 0;

	private boolean isSuccess = false;

	public ActionResult() {
	}

	public ActionResult(long responseTime, boolean isSuccess) {
		this.responseTime = responseTime;
		this.isSuccess = isSuccess;
	}

	public long getResponseTime() {
		return responseTime;
	}

	public void setResponseTime(long responseTime) {
		this.responseTime = responseTime;
	}

	public boolean isSuccess() {
		return isSuccess;
	}

	public void setSuccess(boolean isSuccess) {
		this.isSuccess = isSuccess;
	}
}


text:
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable

  attr_accessor :login

  devise :database_authenticatable, :registerable,
    :recoverable, :confirmable, :rememberable, :trackable, :validatable

  devise :omniauthable, :omniauth_providers => [:facebook, :google_oauth2]

  validates :first_name, presence: true, length: { maximum: 100 }
  validates :last_name, presence: true, length: { maximum: 100 }
  validates :username, length: { maximum: 20 }, :uniqueness => { case_sensitive: false }

  mount_uploader :avatar, AvatarUploader

  def slug_candidates
    [
      [:first_name, :last_name]
    ]
  end

  extend FriendlyId
  friendly_id :slug_candidates, use: [:slugged, :finders]

  has_many :posts
  has_many :authentications
  has_many :upvotes
  has_many :downvotes
  has_many :favorites
  has_many :comments
  has_many :categories

  def self.find_for_oauth(auth)
    registered_user = User.where(:email => auth.info.email).first
    if registered_user
      registered_user.update_attribute(:remote_avatar_url, auth.info.image.gsub('http://','https://'))
      return registered_user
    else
      user = User.new(first_name: auth.info.first_name, last_name: auth.info.last_name, email: auth.info.email,
                      password: Devise.friendly_token[0,20], remote_avatar_url: auth.info.image.gsub('http://','https://'),
                      has_random_password: true)
      user.skip_confirmation!
      user.save
      return user
    end
  end

  def self.find_for_database_authentication(warden_conditions)
    conditions = warden_conditions.dup
    if login = conditions.delete(:login)
      where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
    else
      where(conditions).first
    end
  end

end


text:
namespace impeller {
namespace egl {

Context::Context(EGLDisplay display, EGLContext context)
    : display_(display), context_(context) {}

Context::~Context() {
  if (context_ != EGL_NO_CONTEXT) {
    if (::eglDestroyContext(display_, context_) != EGL_TRUE) {
      IMPELLER_LOG_EGL_ERROR;
    }
  }
}

bool Context::IsValid() const {
  return context_ != EGL_NO_CONTEXT;
}

const EGLContext& Context::GetHandle() const {
  return context_;
}

static EGLBoolean EGLMakeCurrentIfNecessary(EGLDisplay display,
                                            EGLSurface draw,
                                            EGLSurface read,
                                            EGLContext context) {
  if (display != ::eglGetCurrentDisplay() ||
      draw != ::eglGetCurrentSurface(EGL_DRAW) ||
      read != ::eglGetCurrentSurface(EGL_READ) ||
      context != ::eglGetCurrentContext()) {
    return ::eglMakeCurrent(display, draw, read, context);
  }
  // The specified context configuration is already current.
  return EGL_TRUE;
}

bool Context::MakeCurrent(const Surface& surface) const {
  if (context_ == EGL_NO_CONTEXT) {
    return false;
  }
  const auto result = EGLMakeCurrentIfNecessary(display_,             //
                                                surface.GetHandle(),  //
                                                surface.GetHandle(),  //
                                                context_              //
                                                ) == EGL_TRUE;
  if (!result) {
    IMPELLER_LOG_EGL_ERROR;
  }
  return result;
}

bool Context::ClearCurrent() const {
  const auto result = EGLMakeCurrentIfNecessary(display_,        //
                                                EGL_NO_SURFACE,  //
                                                EGL_NO_SURFACE,  //
                                                EGL_NO_CONTEXT   //
                                                ) == EGL_TRUE;
  if (!result) {
    IMPELLER_LOG_EGL_ERROR;
  }
  return result;
}

}  // namespace egl
}  // namespace impeller


text:
var _x = /*#__PURE__*/babelHelpers.classPrivateFieldLooseKey("x");

var _y = /*#__PURE__*/babelHelpers.classPrivateFieldLooseKey("y");

var Point = /*#__PURE__*/function () {
  "use strict";

  function Point(x = 0, y = 0) {
    babelHelpers.classCallCheck(this, Point);
    Object.defineProperty(this, _x, {
      writable: true,
      value: void 0
    });
    Object.defineProperty(this, _y, {
      writable: true,
      value: void 0
    });
    babelHelpers.classPrivateFieldLooseBase(this, _x)[_x] = +x;
    babelHelpers.classPrivateFieldLooseBase(this, _y)[_y] = +y;
  }

  babelHelpers.createClass(Point, [{
    key: "x",
    get: function () {
      return babelHelpers.classPrivateFieldLooseBase(this, _x)[_x];
    },
    set: function (value) {
      babelHelpers.classPrivateFieldLooseBase(this, _x)[_x] = +value;
    }
  }, {
    key: "y",
    get: function () {
      return babelHelpers.classPrivateFieldLooseBase(this, _y)[_y];
    },
    set: function (value) {
      babelHelpers.classPrivateFieldLooseBase(this, _y)[_y] = +value;
    }
  }, {
    key: "equals",
    value: function equals(p) {
      return babelHelpers.classPrivateFieldLooseBase(this, _x)[_x] === babelHelpers.classPrivateFieldLooseBase(p, _x)[_x] && babelHelpers.classPrivateFieldLooseBase(this, _y)[_y] === babelHelpers.classPrivateFieldLooseBase(p, _y)[_y];
    }
  }, {
    key: "toString",
    value: function toString() {
      return `Point<${babelHelpers.classPrivateFieldLooseBase(this, _x)[_x]},${babelHelpers.classPrivateFieldLooseBase(this, _y)[_y]}>`;
    }
  }]);
  return Point;
}();


text:
package com.impetus.client.es;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;

import org.eclipse.persistence.jpa.jpql.parser.AdditionExpression;
import org.eclipse.persistence.jpa.jpql.parser.AndExpression;
import org.eclipse.persistence.jpa.jpql.parser.BetweenExpression;
import org.eclipse.persistence.jpa.jpql.parser.CollectionExpression;
import org.eclipse.persistence.jpa.jpql.parser.ComparisonExpression;
import org.eclipse.persistence.jpa.jpql.parser.DivisionExpression;
import org.eclipse.persistence.jpa.jpql.parser.Expression;
import org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable;
import org.eclipse.persistence.jpa.jpql.parser.InExpression;
import org.eclipse.persistence.jpa.jpql.parser.InputParameter;
import org.eclipse.persistence.jpa.jpql.parser.LikeExpression;
import org.eclipse.persistence.jpa.jpql.parser.LogicalExpression;
import org.eclipse.persistence.jpa.jpql.parser.MultiplicationExpression;
import org.eclipse.persistence.jpa.jpql.parser.NullExpression;
import org.eclipse.persistence.jpa.jpql.parser.NumericLiteral;
import org.eclipse.persistence.jpa.jpql.parser.OrExpression;
import org.eclipse.persistence.jpa.jpql.parser.StateFieldPathExpression;
import org.eclipse.persistence.jpa.jpql.parser.SubExpression;
import org.eclipse.persistence.jpa.jpql.parser.SubtractionExpression;
import org.elasticsearch.index.query.AndQueryBuilder;
import org.elasticsearch.index.query.NotQueryBuilder;
import org.elasticsearch.index.query.OrQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.impetus.kundera.KunderaException;
import com.impetus.kundera.metadata.model.EntityMetadata;
import com.impetus.kundera.metadata.model.MetamodelImpl;
import com.impetus.kundera.metadata.model.attributes.AbstractAttribute;
import com.impetus.kundera.persistence.EntityManagerFactoryImpl.KunderaMetadata;
import com.impetus.kundera.query.KunderaQuery;
import com.impetus.kundera.query.KunderaQuery.FilterClause;

/**
 * The Class ESFilterBuilder.
 *
 * @author Amit Kumar
 */
public class ESFilterBuilder
{
    /** The Kundera query. */
    private KunderaQuery kunderaQuery;

    /** The Kundera metadata. */
    private KunderaMetadata kunderaMetadata;

    /** log for this class. */
    private static Logger log = LoggerFactory.getLogger(ESFilterBuilder.class);

    /**
     * Instantiates a new ES filter builder.
     *
     * @param kunderaQuery
     *            the kundera query
     * @param kunderaMetadata
     *            the kundera metadata
     */
    public ESFilterBuilder(KunderaQuery kunderaQuery, KunderaMetadata kunderaMetadata)
    {
        this.kunderaQuery = kunderaQuery;
        this.kunderaMetadata = kunderaMetadata;
    }

    /**
     * Populate filter builder.
     *
     * @param condtionalExp
     *            the condtional exp
     * @param m
     *            the m
     * @param entity
     *            the entity
     * @return the filter builder
     */
    public QueryBuilder populateFilterBuilder(Expression condtionalExp, EntityMetadata m)
    {
        log.info("Populating filter for expression: " + condtionalExp);
        QueryBuilder filter = null;

        if (condtionalExp instanceof SubExpression)
        {
            filter = populateFilterBuilder(((SubExpression) condtionalExp).getExpression(), m);
        }
        else if (condtionalExp instanceof ComparisonExpression)
        {
            filter = getFilter(populateFilterClause((ComparisonExpression) condtionalExp), m);
        }
        else if (condtionalExp instanceof BetweenExpression)
        {
            filter = populateBetweenFilter((BetweenExpression) condtionalExp, m);
        }
        else if (condtionalExp instanceof LogicalExpression)
        {
            filter = populateLogicalFilterBuilder(condtionalExp, m);
        }
        else if (condtionalExp instanceof LikeExpression)
        {
            filter = populateLikeQuery((LikeExpression) condtionalExp, m);
        }
        else if (condtionalExp instanceof InExpression)
        {
            filter = populateInQuery((InExpression) condtionalExp, m);
        }
        else
        {
            log.error(condtionalExp.toParsedText() + "found in where clause. Not supported in elasticsearch.");
            throw new KunderaException(condtionalExp.toParsedText() + " not supported in ElasticSearch");
        }

        log.debug("Following is the populated filter for required query: " + filter);
        return filter;
    }

    /**
     * Populate like query.
     *
     * @param likeExpression
     *            the like expression
     * @param metadata
     *            the metadata
     * @return the filter builder
     */
    private QueryBuilder populateLikeQuery(LikeExpression likeExpression, EntityMetadata metadata)
    {
        Expression patternValue = likeExpression.getPatternValue();
        String field = likeExpression.getStringExpression().toString();

        String likePattern = (patternValue instanceof InputParameter) ? kunderaQuery.getParametersMap()
                .get((patternValue).toParsedText()).toString() : patternValue.toParsedText().toString();
        String jpaField = getField(field);

        log.debug("Pattern value for field " + field + " is: " + patternValue);
        QueryBuilder filterBuilder = getQueryBuilder(kunderaQuery.new FilterClause(jpaField, Expression.LIKE,
                likePattern, field), metadata);

        return filterBuilder;
    }

    /**
     * Populate IN query filter.
     *
     * @param inExpression
     *            the in expression
     * @param metadata
     *            the metadata
     * @return the filter builder
     */
    private QueryBuilder populateInQuery(InExpression inExpression, EntityMetadata metadata)
    {
        String property = getField(inExpression.getExpression().toParsedText());
        Expression inItemsParameter = inExpression.getInItems();

        log.debug("IN query parameters for field " + property + " is: " + inItemsParameter);
        Iterable inItemsIterable = getInValuesCollection(inItemsParameter);

        return getFilter(kunderaQuery.new FilterClause(property, Expression.IN, inItemsIterable, property), metadata);
    }

    /**
     * Returns the collection of IN clause values.
     *
     * @param inClauseValues
     *            the in clause values
     * @return the in values collection
     */
    private Collection getInValuesCollection(Expression inClauseValues)
    {
        Collection inParameterCollection = new ArrayList<>();
        if (inClauseValues instanceof NullExpression)
        {
            log.debug("No items passed in IN clause values, returning blank IN values list");
            return inParameterCollection;
        }

        if (inClauseValues instanceof InputParameter)
        {
            Object inValues = kunderaQuery.getParametersMap().get(inClauseValues.toParsedText());
            log.debug(inClauseValues.toParsedText() + "named parameter found in query, Replacing parameter with "
                    + inValues);

            inParameterCollection = inValues.getClass().isArray() ? Arrays.asList((Object[]) inValues)
                    : (Collection) kunderaQuery.getParametersMap().get(inClauseValues.toParsedText());

            return inParameterCollection;
        }

        if (inClauseValues instanceof CollectionExpression)
        {
            Iterator inValueIterator = ((CollectionExpression) inClauseValues).children().iterator();

            log.debug("Collection object found for IN clause values");
            while (inValueIterator.hasNext())
            {
                Expression value = (Expression) inValueIterator.next();
                inParameterCollection.add(value.toParsedText());
            }
            return inParameterCollection;
        }

        throw new KunderaException(inClauseValues.toParsedText() + " not supported for IN clause");
    }

    /**
     * Gets the field.
     *
     * @param fieldValue
     *            the field value
     * @return the field
     */
    private String getField(String fieldValue)
    {
        return fieldValue.substring(fieldValue.indexOf(ESConstants.DOT) + 1, fieldValue.length());
    }

    /**
     * Populate between filter.
     *
     * @param betweenExpression
     *            the between expression
     * @param m
     *            the m
     * @param entity
     *            the entity
     * @return the filter builder
     */
    private QueryBuilder populateBetweenFilter(BetweenExpression betweenExpression, EntityMetadata m)
    {
        String lowerBoundExpression = getBetweenBoundaryValues(betweenExpression.getLowerBoundExpression());
        String upperBoundExpression = getBetweenBoundaryValues(betweenExpression.getUpperBoundExpression());
        String field = getField(betweenExpression.getExpression().toParsedText());

        log.debug("Between clause for field " + field + "with lower bound " + lowerBoundExpression + "and upper bound "
                + upperBoundExpression);

        return new AndQueryBuilder(getFilter(kunderaQuery.new FilterClause(field, Expression.GREATER_THAN_OR_EQUAL,
                lowerBoundExpression, field), m), getFilter(kunderaQuery.new FilterClause(field,
                Expression.LOWER_THAN_OR_EQUAL, upperBoundExpression,field), m));
    }

    /**
     * Gets the between boundary values.
     *
     * @param boundExpression
     *            the bound expression
     * @return the between boundry values
     */
    private String getBetweenBoundaryValues(Expression boundExpression)
    {
        if (boundExpression instanceof IdentificationVariable || boundExpression instanceof NumericLiteral
                || boundExpression instanceof InputParameter)
        {
            Object value = (boundExpression instanceof InputParameter) ? kunderaQuery.getParametersMap().get(
                    (boundExpression).toParsedText()) : boundExpression.toParsedText();
            return value.toString();
        }
        else if (boundExpression instanceof AdditionExpression)
        {
            String leftValue = checkInputParameter(((AdditionExpression) boundExpression).getLeftExpression());
            String rightValue = checkInputParameter(((AdditionExpression) boundExpression).getRightExpression());

            return new Integer(Integer.parseInt(leftValue) + Integer.parseInt(rightValue)).toString();
        }
        else if (boundExpression instanceof SubtractionExpression)
        {
            String leftValue = checkInputParameter(((SubtractionExpression) boundExpression).getLeftExpression());
            String rightValue = checkInputParameter(((SubtractionExpression) boundExpression).getRightExpression());

            return new Integer(Integer.parseInt(leftValue) - Integer.parseInt(rightValue)).toString();
        }
        else if (boundExpression instanceof MultiplicationExpression)
        {
            String leftValue = checkInputParameter(((MultiplicationExpression) boundExpression).getLeftExpression());
            String rightValue = checkInputParameter(((MultiplicationExpression) boundExpression).getRightExpression());

            return new Integer(Integer.parseInt(leftValue) * Integer.parseInt(rightValue)).toString();
        }

        else if (boundExpression instanceof DivisionExpression)
        {
            String leftValue = checkInputParameter(((DivisionExpression) boundExpression).getLeftExpression());
            String rightValue = checkInputParameter(((DivisionExpression) boundExpression).getRightExpression());
            return new Integer(Integer.parseInt(leftValue) / Integer.parseInt(rightValue)).toString();
        }

        return null;
    }

    /**
     * Check input parameter.
     *
     * @param expression
     *            the expression
     * @return the string
     */
    private String checkInputParameter(Expression expression)
    {
        return (expression instanceof InputParameter) ? kunderaQuery.getParametersMap()
                .get((expression).toParsedText()).toString() : expression.toParsedText().toString();
    }

    /**
     * Populate logical filter builder.
     *
     * @param logicalExp
     *            the logical exp
     * @param m
     *            the m
     * @param entity
     *            the entity
     * @return the filter builder
     */
    private QueryBuilder populateLogicalFilterBuilder(Expression logicalExp, EntityMetadata m)
    {
        String identifier = ((LogicalExpression) logicalExp).getIdentifier();

        return (identifier.equalsIgnoreCase(LogicalExpression.AND)) ? getAndFilterBuilder(logicalExp, m) : (identifier
                .equalsIgnoreCase(LogicalExpression.OR)) ? getOrFilterBuilder(logicalExp, m) : null;
    }

    /**
     * Gets the and filter builder.
     *
     * @param logicalExp
     *            the logical exp
     * @param m
     *            the m
     * @param entity
     *            the entity
     * @return the and filter builder
     */
    private AndQueryBuilder getAndFilterBuilder(Expression logicalExp, EntityMetadata m)
    {
        AndExpression andExp = (AndExpression) logicalExp;
        Expression leftExpression = andExp.getLeftExpression();
        Expression rightExpression = andExp.getRightExpression();

        return new AndQueryBuilder(populateFilterBuilder(leftExpression, m), populateFilterBuilder(rightExpression, m));
    }

    /**
     * Gets the or filter builder.
     *
     * @param logicalExp
     *            the logical exp
     * @param m
     *            the m
     * @param entity
     *            the entity
     * @return the or filter builder
     */
    private OrQueryBuilder getOrFilterBuilder(Expression logicalExp, EntityMetadata m)
    {
        OrExpression orExp = (OrExpression) logicalExp;
        Expression leftExpression = orExp.getLeftExpression();
        Expression rightExpression = orExp.getRightExpression();

        return new OrQueryBuilder(populateFilterBuilder(leftExpression, m), populateFilterBuilder(rightExpression, m));
    }

    /**
     * Populate filter clause.
     *
     * @param conditionalExpression
     *            the conditional expression
     * @return the filter clause
     */
    private FilterClause populateFilterClause(ComparisonExpression conditionalExpression)
    {
        String property = ((StateFieldPathExpression) conditionalExpression.getLeftExpression()).getPath(1);
        String condition = conditionalExpression.getComparisonOperator();
        Expression rightExpression = conditionalExpression.getRightExpression();
        Object value = (rightExpression instanceof InputParameter) ? kunderaQuery.getParametersMap().get(
                (rightExpression).toParsedText()) : rightExpression.toParsedText();

        return (condition != null && property != null) ? kunderaQuery.new FilterClause(property, condition, value, property)
                : null;
    }

    /**
     * Gets the filter.
     *
     * @param clause
     *            the clause
     * @param metadata
     *            the metadata
     * @param entityType
     *            the entity type
     * @return the filter
     */
    private QueryBuilder getFilter(FilterClause clause, final EntityMetadata metadata)
    {
        String condition = clause.getCondition();
        Object value = condition.equals(Expression.IN) ? clause.getValue() : clause.getValue().get(0);
        String name = ((AbstractAttribute) ((MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                metadata.getPersistenceUnit())).entity(metadata.getEntityClazz()).getAttribute(clause.getProperty()))
                .getJPAColumnName();

        QueryBuilder filterBuilder = null;

        if (condition.equals(Expression.EQUAL))
        {
            filterBuilder = new TermQueryBuilder(name, value);
        }
        else if (condition.equals(Expression.GREATER_THAN))
        {
            filterBuilder = new RangeQueryBuilder(name).gt(value);
        }
        else if (condition.equals(Expression.LOWER_THAN))
        {
            filterBuilder = new RangeQueryBuilder(name).lt(value);
        }
        else if (condition.equals(Expression.GREATER_THAN_OR_EQUAL))
        {
            filterBuilder = new RangeQueryBuilder(name).gte(value);
        }
        else if (condition.equals(Expression.LOWER_THAN_OR_EQUAL))
        {
            filterBuilder = new RangeQueryBuilder(name).lte(value);
        }
        else if (condition.equals(Expression.DIFFERENT))
        {
            filterBuilder = new NotQueryBuilder(new TermQueryBuilder(name, value));
        }
        else if (condition.equals(Expression.IN))
        {
            filterBuilder = new TermsQueryBuilder(name, clause.getValue());
        }

        return filterBuilder;
    }

    /**
     * Gets the query.
     *
     * @param clause
     *            the clause
     * @param metadata
     *            the metadata
     * @return the query
     */
    private QueryBuilder getQueryBuilder(FilterClause clause, final EntityMetadata metadata)
    {
        String condition = clause.getCondition();
        String value = clause.getValue().get(0).toString();
        String name = ((AbstractAttribute) ((MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                metadata.getPersistenceUnit())).entity(metadata.getEntityClazz()).getAttribute(clause.getProperty()))
                .getJPAColumnName();

        String likePattern = value.contains(ESConstants.PERCENTAGE) ? value.replaceAll(ESConstants.PERCENTAGE,
                ESConstants.ASTERISK) : ESConstants.ASTERISK + value + ESConstants.ASTERISK;

        QueryBuilder queryBuilder = null;
        if (condition.equals(Expression.LIKE))
        {
            queryBuilder = QueryBuilders.wildcardQuery(name, likePattern);
        }

        return QueryBuilders.queryFilter(queryBuilder);
    }
}


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

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Avocado-And-Scallop Ceviche</title>
      <categories>
        <cat>Appetizers</cat>
        <cat>Seafood</cat></categories>
      <yield>8</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1/2</qty>
          <unit>cups</unit></amt>
        <item>Fresh lime juice</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>tablespoons</unit></amt>
        <item>Peanut oil or vegetable oil</item></ing>
      <ing>
        <amt>
          <qty>24</qty>
          <unit/></amt>
        <item>Green peppercorns; crushed</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Salt</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Freshly ground black pepper</item></ing>
      <ing>
        <amt>
          <qty>3/4</qty>
          <unit>pounds</unit></amt>
        <item>Sea or bay scallops finely chopped</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>large</unit></amt>
        <item>Ripe avocado; peeled</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Fresh chives, chopped or scallions, chopped</item></ing>
      <ing>
        <amt>
          <qty>40</qty>
          <unit>small</unit></amt>
        <item>White mushrooms</item></ing>
      <ing>
        <amt>
          <qty>1/4</qty>
          <unit>cups</unit></amt>
        <item>Vegetable oil</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Fresh lemon juice</item></ing>
      <ing>
        <amt>
          <qty>1</qty>
          <unit>medium</unit></amt>
        <item>Garlic clove peeled and crushed</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Salt and pepper to taste</item></ing>
      <ing>
        <amt>
          <qty/>
          <unit/></amt>
        <item>Additional chives, optional (or scallions), for  garnish</item></ing></ingredients>
    <directions>
      <step>  COMBINE THE LIME JUICE, oil, peppercorns, salt and pepper together in a
  glass or ceramic bowl. Stir in the scallops, cover and refrigerate for at
  least 4 hours while they marinate. They should become opaque in this time.
  Mash the avocado until almost smooth, then add it along with the chives or
  scallions to the marinating scallops (do not drain them) and mix well. Set
  aside for at least 1/2 hour, refrigerated. About half an hour before
  serving the scallops, remove the stems from the mushrooms and wipe them to
  remove any dirt. Combine the vegetable oil, lemon juice, garlic, salt and
  pepper in a small bowl, and brush the insides of the mushrooms liberally
  with the mixture. Just before serving, drain the caps and fill with the
  scallop mixture. Garnish with additional chives, if desired.

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>


text:
//*@public
/**
	_enyo.DataList_ is an [enyo.DataRepeater](#enyo.DataRepeater) that employs a
	paginated scrolling scheme to enhance performance with larger datasets. The
	data is provided to the DataList by an [enyo.Collection](#enyo.Collection) set
	as the value of its _collection_ property.

	Note that care should be taken when deciding how to lay out the list's
	children. When there are a large number of child elements, the layout process
	can be taxing and non-performant for the browser. Avoid	dynamically-updated
	layouts that require lots of calculations each time the data in a view is
	updated. Try to use CSS whenever possible.
*/
enyo.kind({
	name: "enyo.DataList",
	kind: enyo.DataRepeater,
	/**
		The _enyo.DataList_ kind will emit a registered event when paging, `paging`,
		so that for per-page updates can be made when necessary. You can register for
		this event by calling _addListener()_ for the `paging` event with a callback.
		The callback method will be passed a reference to the _enyo.DataList_ that is
		paging, the name of the event (`paging`), and hash with the properties `start`,
		`end` and `action` that refer to the lowest active index in the dataset through
		the highest active index and the action that triggered the paging respectively.
		The `action` value can be either 'scroll' or 'reset'.
	*/
	/**
		The _enyo.DataList_ kind places its rows inside of a scroller. Any
		configurable options associated with _enyo.Scroller_ may be placed in this
		hash and will be set accordingly on this list's scroller. If no options are
		specified, the default _enyo.Scroller_ settings are used.
	*/
	scrollerOptions: null,
	/**
		The paging orientation. Valid values are _"vertical"_ and _"horizontal"_.
		This property will be mapped to a particular strategy governing how the list
		will flow.
	*/
	orientation: "vertical",
	/**
		This is typically handled automatically but some platforms may benefit from
		having a larger or smaller value here. If there is a number here it will be
		multiplied by the available viewport size (depending on orientation) to determine
		the minimum page size. The page size is directly related to the number of controls
		that will be generated at any given time (and subsequently needing update)
		whenever paging occurs. This number can be any rational number greater than _1.2_.
	*/
	pageSizeMultiplier: null,
	/**
		To disable the default smoothing-transitions (for supported platforms) set
		this flag to `false`.
	*/
	allowTransitions: true,
	/**
		Because some systems perform poorly on initialization there is a delay when
		attempting to actually draw the contents of a _enyo.DataList_. Usually you
		will not need to adjust this value (ms). If _renderDelay_ is null there will
		be no delay and it will be executed synchronously. Note that if set to 0 it
		will be executed asynchronously.
	*/
	renderDelay: 250,
	/**
		Completely resets the current list such that it scrolls to the top of the
		scrollable region and regenerates all of its children. This is typically
		necessary only on initialization, or if the entire dataset has been swapped
		out.
	*/
	reset: function () {
		// we can only reset if we've already rendered
		if (this.generated && this.$.scroller.generated) {
			this.delegate.reset(this);
		}
	},
	/**
		Unlike _reset()_, which tears down and regenerates the entire list, this
		method attempts to refresh the pages as they are against the current
		dataset. This is much cheaper to call than _reset()_, but is primarily used
		internally.
	*/
	refresh: function () {
		if (this.hasRendered) {
			this.delegate.refresh(this);
		}
	},
	/**
		Pass in an integer within the bounds of the lists's collection to have it
		scroll to the position of that index in the list.
	*/
	scrollToIndex: function (idx) {
		if (idx >= 0 && idx < this.length) {
			this.delegate.scrollToIndex(this, idx);
		}
	},
	//*@protected
	constructor: enyo.inherit(function (sup) {
		return function () {
			sup.apply(this, arguments);
			this.metrics       = {};
			this.metrics.pages = {};
			if (this.pageSizeMultiplier !== null && !isNaN(this.pageSizeMultiplier)) {
				this.pageSizeMultiplier = Math.max(1.2, this.pageSizeMultiplier);
			}
		};
	}),
	create: enyo.inherit(function (sup) {
		return function () {
			// if we can, we use transitions
			this.allowTransitionsChanged();
			// map the selected strategy to the correct delegate for operations
			// on the list, default to _vertical_ if none is provided or if it
			// could not be found
			this.delegate = this.ctor.delegates[this.orientation] || this.base.delegates.vertical;
			// if the delegate has an initialization routine execute it now before the
			// container and children are rendered
			if (this.delegate.initList) {
				this.delegate.initList(this);
			}
			sup.apply(this, arguments);
			// initialize the _pages_ array and add the pages to it
			this.pages = [this.$.page1, this.$.page2];
		};
	}),
	render: enyo.inherit(function (sup) {
		return function () {
			this.$.scroller.canGenerate = false;
			this.$.scroller.teardownRender();
			sup.apply(this, arguments);
		};
	}),
	/**
		Attempts to do initialization. There are only a few basic startup paths, but
		we need to be aware of what they are:

		* The view is rendered, it has a collection, and the collection has data.
		* The view is rendered, it has a collection with no data, and data is added
			later.
		* The view is rendered, but has no collection.

		Once the list itself is rendered, we check to see if we have a collection;
		if so, do we have any data to start rendering the rest of the list?
		Ultimately, the implementation decisions are decided by the delegate
		strategy.
	*/
	rendered: function () {
		// actually rendering a datalist can be taxing for some systems so
		// we arbitrarily delay showing for a fixed amount of time unless delay is
		// null in which case it will be executed immediately
		var startup = function () {
			// now that the base list is rendered, we can safely generate our scroller
			this.$.scroller.canGenerate = true;
			this.$.scroller.render();
			// and now we hand over the action to our strategy to let it initialize the
			// way it needs to
			this.delegate.rendered(this);
			this.hasRendered = true;
			// now add our class to adjust visibility (if no overridden)
			this.addClass("rendered");
			if (this.didRender) {
				this.didRender();
			}
		};
		if (this.renderDelay === null) {
			startup.call(this);
		} else {
			this.startJob("rendering", startup, this.renderDelay);
			// this delay will allow slower systems to keep going and get everything else
			// on screen before worrying about setting up the list
		}
	},
	/**
		Overloaded to call a method of the delegate strategy.
	*/
	modelsAdded: function (c, e, props) {
		if (c === this.collection && this.$.scroller.canGenerate) {
			this.delegate.modelsAdded(this, props);
		}
	},
	/**
		Overloaded to call a method of the delegate strategy.
	*/
	modelsRemoved: function (c, e, props) {
		if (c === this.collection && this.$.scroller.canGenerate) {
			this.delegate.modelsRemoved(this, props);
		}
	},
	destroy: enyo.inherit(function (sup) {
		return function () {
			if (this.delegate && this.delegate.destroyList) {
				this.delegate.destroyList(this);
			}
			sup.apply(this, arguments);
		};
	}),
	/**
		Overloaded from base kind to ensure that the container options correctly apply
		the scroller options before instantiating it.
	*/
	initContainer: enyo.inherit(function (sup) {
		return function () {
			var o = enyo.clone(this.get("containerOptions")),
				s = this.get("scrollerOptions");
			if (s) { enyo.mixin(o, s, {exists: true}); }
			this.set("containerOptions", o);
			sup.apply(this, arguments);
		};
	}),
	/**
		We let the delegate strategy manage the event, but we arbitrarily return
		true Because we don't want the event to propagate beyond this kind.
	*/
	didScroll: function (sender, event) {
		if (this.hasRendered) {
			this.delegate.didScroll(this, event);
		}
		return true;
	},
	/**
		Special override to handle resizing in an attempt to minimize the amount of
		work we're doing. We don't want to waterfall the event to all children, so
		we hijack the normal handler.
	*/
	didResize: function (sender, event) {
		if (this.hasRendered) {
			this.delegate.didResize(this, event);
		}
	},
	/**
		Overload to adjust the root method to be able to find the nested child
		based on the requested index if its page is currently active. Will return
		undefined if the index is out of bounds or if the control is not currently
		available.

		Also see [getChildForIndex](#getChildForIndex) which calls this method.
	*/
	childForIndex: function (i) {
		return this.delegate.childForIndex(this, i);
	},
	//*@protected
	allowTransitionsChanged: function () {
		this.addRemoveClass("transitions", this.allowTransitions);
	},
	/**
		The _enyo.DataList_ kind uses an overloaded container from its base kind. We
		set the container to a scroller and provide a way to modify the scroller
		options (via the _scrollerOptions_ hash). All children will reside in one of
		the two pages owned by the scroller.
	*/
	containerOptions: {name: "scroller", kind: "enyo.Scroller", components: [
		{name: "active", classes: "active", components: [
			{name: "page1", classes: "page page1"},
			{name: "page2", classes: "page page2"},
			{name: "buffer", classes: "buffer"}
		]}
	], canGenerate: false, classes: "enyo-fit enyo-data-list-scroller"},
	//* We access this kind's constructor and need it to be undeferred at that time.
	noDefer: true,
	//* All of the CSS is relative to this class.
	classes: "enyo-data-list",
	//* Our initial _controlParent_ is us for the _flyweighter_ child.
	controlParentName: "",
	//* Of course we set our container to _scroller_ as needed by the base kind.
	containerName: "scroller",
	/**
		We have to trap the Enyo-generated _onScroll_ event and let the delegate
		handle it. We also need to catch the _onresize_ events so we know when to
		update our cached sizing. We overload the default handler so that we don't
		waterfall the resizing; we arbitrarily handle it to minimize the amount of
		work we do.
	*/
	handlers: {onScroll: "didScroll", onresize: "didResize"},
	//* Add the RegisteredEventSupport mixin for the paging event
	mixins: [enyo.RegisteredEventSupport],
	//* All delegates are named elsewhere but are stored in these statics.
	statics: {delegates: {}},
	//* An array of the actual _page_ references for easier access.
	pages: null
});
//*@protected
/**
	All subclasses of _enyo.DataList_ will have their own _delegates_ static hash.
	This is per _kind_, not per _instance_.
*/
enyo.DataList.subclass = function (ctor) {
	ctor.delegates = enyo.clone(ctor.prototype.base.delegates || this.delegates);
};


text:
[![Join the chat at https://gitter.im/Daplie/letsencrypt-express](https://badges.gitter.im/Daplie/letsencrypt-express.svg)](https://gitter.im/Daplie/letsencrypt-express?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

| [letsencrypt](https://github.com/Daplie/node-letsencrypt) (library)
| [letsencrypt-cli](https://github.com/Daplie/letsencrypt-cli)
| [letsencrypt-express](https://github.com/Daplie/letsencrypt-express)
| [letsencrypt-cluster](https://github.com/Daplie/letsencrypt-cluster)
| [letsencrypt-koa](https://github.com/Daplie/letsencrypt-koa)
| [letsencrypt-hapi](https://github.com/Daplie/letsencrypt-hapi)
|

# le-challenge-webroot

An fs-based strategy for node-letsencrypt for setting, retrieving,
and clearing ACME challenges issued by the ACME server

This places the acme challenge in an appropriate directory in the specified `webrootPath`
and removes it once the challenge has either completed or failed.

* Safe to use with node cluster
* Safe to use with ephemeral services (Heroku, Joyent, etc)

Install
-------

```bash
npm install --save le-challenge-fs@2.x
```

Usage
-----

```bash
var leChallenge = require('le-challenge-fs').create({
  webrootPath: '~/letsencrypt/srv/www/:hostname/.well-known/acme-challenge'   // defaults to os.tmpdir()
, loopbackPort: 5001                                                          // defaults to 80
, loopbackTimeout: 3000                                                       // defaults to 3000ms
, debug: false
});

var LE = require('letsencrypt');

LE.create({
  server: LE.stagingServerUrl                               // Change to LE.productionServerUrl in production
, challenge: leChallenge
});
```

NOTE: If you request a certificate with 6 domains listed,
it will require 6 individual challenges.

Exposed Methods
---------------

For ACME Challenge:

* `set(opts, domain, key, val, done)`
* `get(defaults, domain, key, done)`
* `remove(defaults, domain, key, done)`

For node-letsencrypt internals:

* `getOptions()` returns the internal defaults merged with the user-supplied options
* `loopback(defaults, domain, key, value, done)` test, by external means, that the ACME server's challenge server will succeed


text:
package goryachev.common.test;
import goryachev.common.util.CJob;
import goryachev.common.util.CKit;
import goryachev.common.util.CList;
import goryachev.common.util.CSorter;
import goryachev.common.util.Log;
import goryachev.common.util.log.ConsoleLogWriter;
import goryachev.common.util.log.LogWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.List;
import java.util.Vector;

public class TestRunner
{
	private final CList<Class> classes = new CList<>();
	private int failed;
	protected final Vector<TestCase> cases = new Vector<>();
	protected long started;
	protected long ended;

	public TestRunner()
	{
	}

	public static void run(List<Class> tests)
	{
		initLog();

		TestRunner r = new TestRunner();
		r.print("Testing started " + (new Date()) + ".\n");

		for(Class c: tests)
		{
			r.add(c);
		}

		r.executeTests();
		r.printResults();

		System.out.flush();
		System.err.flush();

		CKit.sleep(10);

		// command returns the number of failed tests (or 0 if all passed)
		System.exit(-r.failed);
	}

	public static void initLog()
	{
		LogWriter wr = new ConsoleLogWriter("console");
		wr.setAsync(false);
//		Log.addWriter(wr);
		Log.addErrorWriter(wr);
	}

	public void add(Class c)
	{
		checkConstructor(c);

		classes.add(c);
	}

	@SuppressWarnings("unchecked")
	protected void checkConstructor(Class c)
	{
		try
		{
			if(c.getConstructor() != null)
			{
				if(c.getConstructors().length == 1)
				{
					return;
				}
			}
		}
		catch(Exception e)
		{
			throw new TestException("Test class must define a single no-arg constructor: " + CKit.getSimpleName(c), e);
		}
	}

	protected void extract(Class c, CList<RunEntry> list, Class<? extends Annotation> type, boolean needsStatic)
	{
		for(Method m: c.getDeclaredMethods())
		{
			int mods = m.getModifiers();
			if(Modifier.isPublic(mods))
			{
				Annotation a = m.getAnnotation(type);
				if(a != null)
				{
					if(Modifier.isStatic(mods) != needsStatic)
					{
						if(needsStatic)
						{
							throw new TestException("method " + CKit.getSimpleName(c) + "." + m.getName() + "() must be static");
						}
						else
						{
							throw new TestException("method " + CKit.getSimpleName(c) + "." + m.getName() + "() must not be static");
						}
					}

					list.add(new RunEntry(m, a));
				}
			}
		}

		CSorter.sort(list);
	}

	protected void print(String s)
	{
		System.out.print(s);
	}

	protected void executeTests()
	{
		CList<CJob> jobs = new CList<>();

		started = System.currentTimeMillis();

		for(final Class c: classes)
		{
			CJob job = new CJob("test " + CKit.getSimpleName(c))
			{
				protected void process() throws Exception
				{
					try
					{
						executeTestClass(this, c);
					}
					catch(Throwable e)
					{
						e.printStackTrace();
					}
				}
			};
			jobs.add(job);
			job.submit();
		}

		CJob.waitForAll(jobs);

		ended = System.currentTimeMillis();
	}

	protected void executeTestClass(CJob parent, final Class c) throws Exception
	{
		final CList<RunEntry> beforeAll = new CList<>();
		final CList<RunEntry> before = new CList<>();
		final CList<RunEntry> tests = new CList<>();
		final CList<RunEntry> after = new CList<>();
		final CList<RunEntry> afterAll = new CList<>();

		extract(c, beforeAll, BeforeClass.class, true);
		extract(c, before, Before.class, false);
		extract(c, tests, Test.class, false);
		extract(c, after, After.class, false);
		extract(c, afterAll, AfterClass.class, true);

		if(tests.size() == 0)
		{
			System.out.println("No tests in " + CKit.getSimpleName(c));
			return;
		}

		for(RunEntry m: beforeAll)
		{
			m.invoke(null);
		}

		CList<CJob> jobs = new CList<>();

		// individual tests
		for(final RunEntry m: tests)
		{
			CJob job = new CJob(parent, "test " + CKit.getSimpleName(c) + "." + m)
			{
				protected void process() throws Exception
				{
					executeInstance(c, m, before, after);
				}
			};
			jobs.add(job);
			job.submit();
		}

		CJob.waitForAll(jobs);

		for(RunEntry m: afterAll)
		{
			m.invoke(null);
		}
	}

	protected void executeInstance(Class c, RunEntry testMethod, CList<RunEntry> before, CList<RunEntry> after)
	{
		String name = CKit.getSimpleName(c) + "." + testMethod;
		final TestCase tc = new TestCase(name);
		cases.add(tc);
		tc.started();

		try
		{
			Object instance = c.newInstance();
			tc.setTestInstance(instance);

			for(RunEntry m: before)
			{
				m.invoke(instance);
			}

			try
			{
				testMethod.invoke(instance);
				testMethod.checkNoException();
			}
			catch(InvocationTargetException e)
			{
				Throwable err = e.getTargetException();
				if(testMethod.isUnexpected(err))
				{
					if(err instanceof Exception)
					{
						throw (Exception)err;
					}
					else
					{
						throw new Exception(err);
					}
				}
			}
			catch(Exception e)
			{
				throw e;
			}

			for(RunEntry m: after)
			{
				m.invoke(instance);
			}

			tc.stopped();
			testSuccess(tc);
		}
		catch(Throwable e)
		{
			tc.stopped();
			tc.setFailed(e);
			testFailed(tc);
		}
	}

	protected void testSuccess(TestCase tc)
	{
		print(".");
	}

	protected void testFailed(TestCase tc)
	{
		print("E");
	}

	public void printResults()
	{
		int count = cases.size();

		for(TestCase c: cases)
		{
			if(c.isFailed())
			{
				failed++;
			}
		}

		print("\n\n");

		String elapsed = CKit.formatTimePeriod(ended - started);

		if(failed == 0)
		{
			print("OK");
		}
		else
		{
			print("FAILED " + failed);
		}
		print(" (" + count + " tests) " + elapsed + "\n");

		if(failed > 0)
		{
			for(TestCase c: cases)
			{
				if(c.isFailed())
				{
					print("\n");

					print(c.getName() + "\n");
					print(c.getText());
					print("\n");
					print(CKit.stackTrace(c.getFailure()));

					print("\n");
				}
			}
		}
	}

	//

	public static class RunEntry
		implements Comparable<RunEntry>
	{
		private final Method method;
		private final Annotation annotation;

		public RunEntry(Method method, Annotation annotation)
		{
			this.method = method;
			this.annotation = annotation;
		}

		public String toString()
		{
			return getName();
		}

		public String getName()
		{
			return method.getName();
		}

		public boolean isUnexpected(Throwable e)
		{
			Class<? extends Throwable> expected = ((Test)annotation).expected();
			if(expected == null)
			{
				return true;
			}

			return !expected.isAssignableFrom(e.getClass());
		}

		public void checkNoException() throws Exception
		{
			Class<? extends Throwable> expected = ((Test)annotation).expected();
			if(expected == Test.NoThrowable.class)
			{
				return;
			}
			else if(expected != null)
			{
				throw new Exception("This test case is expected to throw an " + CKit.getSimpleName(expected));
			}
		}

		public void invoke(Object x) throws Exception
		{
			method.invoke(x);
		}

		public int compareTo(RunEntry x)
		{
			return getName().compareTo(x.getName());
		}
	}
}


text:
exports.merge = require('utils-merge');

/**
 * Reconstructs the original URL of the request.
 *
 * This function builds a URL that corresponds the original URL requested by the
 * client, including the protocol (http or https) and host.
 *
 * If the request passed through any proxies that terminate SSL, the
 * `X-Forwarded-Proto` header is used to detect if the request was encrypted to
 * the proxy, assuming that the proxy has been flagged as trusted.
 *
 * @param {http.IncomingMessage} req
 * @param {Object} [options]
 * @return {String}
 * @api private
 */
exports.originalURL = function(req, options) {
  options = options || {};
  var app = req.app;
  if (app && app.get && app.get('trust proxy')) {
    options.proxy = true;
  }
  var trustProxy = options.proxy;

  var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
    , tls = req.connection.encrypted || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0])
    , host = (trustProxy && req.headers['x-forwarded-host']) || req.headers.host
    , protocol = tls ? 'https' : 'http'
    , path = req.url || '';
  return protocol + '://' + host + path;
};


text:
`tldextract` accurately separates the gTLD or ccTLD (generic or country code
top-level domain) from the registered domain and subdomains of a URL. For
example, say you want just the 'google' part of 'http://www.google.com'.

*Everybody gets this wrong.* Splitting on the '.' and taking the last 2
elements goes a long way only if you're thinking of simple e.g. .com
domains. Think parsing
[http://forums.bbc.co.uk](http://forums.bbc.co.uk) for example: the naive
splitting method above will give you 'co' as the domain and 'uk' as the TLD,
instead of 'bbc' and 'co.uk' respectively.

`tldextract` on the other hand knows what all gTLDs and ccTLDs look like by
looking up the currently living ones according to
[the Public Suffix List](http://www.publicsuffix.org). So,
given a URL, it knows its subdomain from its domain, and its domain from its
country code.

    >>> import tldextract
    >>> tldextract.extract('http://forums.news.cnn.com/')
    ExtractResult(subdomain='forums.news', domain='cnn', suffix='com')
    >>> tldextract.extract('http://forums.bbc.co.uk/') # United Kingdom
    ExtractResult(subdomain='forums', domain='bbc', suffix='co.uk')
    >>> tldextract.extract('http://www.worldbank.org.kg/') # Kyrgyzstan
    ExtractResult(subdomain='www', domain='worldbank', suffix='org.kg')

`ExtractResult` is a namedtuple, so it's simple to access the parts you want.

    >>> ext = tldextract.extract('http://forums.bbc.co.uk')
    >>> (ext.subdomain, ext.domain, ext.suffix)
    ('forums', 'bbc', 'co.uk')
    >>> # rejoin subdomain and domain
    >>> '.'.join(ext[:2])
    'forums.bbc'
    >>> # a common alias
    >>> ext.registered_domain
    'bbc.co.uk'

This module started by implementing the chosen answer from [this StackOverflow question on
getting the "domain name" from a URL](http://stackoverflow.com/questions/569137/how-to-get-domain-name-from-url/569219#569219).
However, the proposed regex solution doesn't address many country codes like
com.au, or the exceptions to country codes like the registered domain
parliament.uk. The Public Suffix List does, and so does this module.

## Installation

Latest release on PyPI:

    $ pip install tldextract

Or the latest dev version:

    $ pip install -e git://github.com/john-kurkowski/tldextract.git#egg=tldextract

Command-line usage, splits the url components by space:

    $ tldextract http://forums.bbc.co.uk
    forums bbc co.uk

## Tests

    $ python -m tldextract.tests.all

or run against all supported Python versions:

    $ tox

## Note About Caching & Advanced Usage

Beware when first running the module, it updates its TLD list with a live HTTP
request. This updated TLD set is cached indefinitely in
`/path/to/tldextract/.tld_set`.

(Arguably runtime bootstrapping like that shouldn't be the default behavior,
like for production systems. But I want you to have the latest TLDs, especially
when I haven't kept this code up to date.)

To avoid this fetch or control the cache's location, use your own extract
callable by setting TLDEXTRACT_CACHE environment variable or by setting the
cache_file path in TLDExtract initialization.

    # extract callable that falls back to the included TLD snapshot, no live HTTP fetching
    no_fetch_extract = tldextract.TLDExtract(suffix_list_url=False)
    no_fetch_extract('http://www.google.com')

    # extract callable that reads/writes the updated TLD set to a different path
    custom_cache_extract = tldextract.TLDExtract(cache_file='/path/to/your/cache/file')
    custom_cache_extract('http://www.google.com')

    # extract callable that doesn't use caching
    no_cache_extract = tldextract.TLDExtract(cache_file=False)
    no_cache_extract('http://www.google.com')

If you want to stay fresh with the TLD definitions--though they don't change
often--delete the cache file occasionally, or run

    tldextract --update

or:

    env TLDEXTRACT_CACHE="~/tldextract.cache" tldextract --update

It is also recommended to delete the file after upgrading this lib.

### Specifying your own URL or file for the Suffix List data

You can specify your own input data in place of the default Mozilla Public Suffix List:

    extract = tldextract.TLDExtract(
        suffix_list_url="http://foo.bar.baz",
        # Recommended: Specify your own cache file, to minimize ambiguities about where
        # tldextract is getting its data, or cached data, from.
        cache_file='/path/to/your/cache/file')

The above snippet will fetch from the URL *you* specified, upon first need to download the
suffix list (i.e. if the cache_file doesn't exist).

If you want to use input data from your local filesystem, just use the `file://` protocol:

    extract = tldextract.TLDExtract(
        suffix_list_url="file://absolute/path/to/your/local/suffix/list/file",
        cache_file='/path/to/your/cache/file')

Use an absolute path when specifying the `suffix_list_url` keyword argument. `os.path` is your
friend.

## FAQ

### If I pass an invalid URL, I still get a result, no error. What gives?

To keep `tldextract` light in LoC & overhead, and because there are plenty of
URL validators out there, this library is very lenient with input. If valid
URLs are important to you, validate them before calling `tldextract`.

This lenient stance lowers the learning curve of using the library, at the cost
of desensitizing users to the nuances of URLs. Who knows how much. But in the
future, I would consider an overhaul. For example, users could opt into
validation, either receiving exceptions or error metadata on results.

# Public API

I know it's just one method, but I've needed this functionality in a few
projects and programming languages, so I've uploaded
[`tldextract` to App Engine](http://tldextract.appspot.com/). It's there on
GAE's free pricing plan until Google cuts it off. Just hit it with
your favorite HTTP client with the URL you want parsed like so:

    $ curl "http://tldextract.appspot.com/api/extract?url=http://www.bbc.co.uk/foo/bar/baz.html"
    {"domain": "bbc", "subdomain": "www", "suffix": "co.uk"}


text:
package com.amazonaws.services.auditmanager.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum EvidenceFinderBackfillStatus {

    NOT_STARTED("NOT_STARTED"),
    IN_PROGRESS("IN_PROGRESS"),
    COMPLETED("COMPLETED");

    private String value;

    private EvidenceFinderBackfillStatus(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return EvidenceFinderBackfillStatus corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static EvidenceFinderBackfillStatus fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (EvidenceFinderBackfillStatus enumEntry : EvidenceFinderBackfillStatus.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
from alembic import op
import sqlalchemy as sa

"""Add VPC alloc table

Revision ID: f3765e42de23
Revises: 9148d96f9b39
Create Date: 2017-06-07 17:10:09.597016

"""

# revision identifiers, used by Alembic.
revision = 'f3765e42de23'
down_revision = '9148d96f9b39'

def upgrade():
    op.create_table('cisco_ml2_nexus_vpc_alloc',
        sa.Column('switch_ip', sa.String(length=64), nullable=False,
                  index=True),
        sa.Column('vpc_id', sa.Integer(), nullable=False),
        sa.Column('learned', sa.Boolean(), nullable=False),
        sa.Column('active', sa.Boolean(), nullable=False),
        sa.PrimaryKeyConstraint('switch_ip', 'vpc_id')
    )


text:
Outages is an application
meant to help IT departments and users
communicate planned outages of services.

Most organizations communicate planned service outages
in two ways:

* E-mails to everyone for every outage,
leading to a full inbox, and messages that are ignored
* Posting them on a web site that no one remembers to look at

Outages aims to solve the problem
by giving the recipient control
over the type of notifications they receive
and the services for which they receive notifications.
Typically, you're only interested in certain services:

* An end user only cares about production systems
* An end user may only care about certain prodution systems,
because their job is focussed on that application
* A developer may not care about production systems,
and only cares about the development environments
that they directly work on
* An operational support person will care about their
particular piece of the infrastructure,
across all development, test, and production environments

Here's what has to happen to get the benefits of Outages:

* Technical staff enter services,
and identify the relationships between the services.
A service can be anything from a single piece of IT equipment,
all the way up to a complete application.
The relationships show dependencies
between the services.
For example, an application is made up of other hardware and software services,
each of which may be made up of other services,
and so on.
<%= link_to "Services", documentation_services_path %>
* Technical staff (typically) enter outages -- times when
they're going to be working on a service,
and the service will be unavailable.
<%= link_to "Outages", documentation_outages_path %>
* Everyone who wants to be notified of outages
has to set up their preferences
to indicate how and when they want to be notified of outages.
They also have to indicate what they're watching.
Most of the time users watch a service,
and get notified about outages of that service.
You can also watch an outage.
<%= link_to "Watches", documentation_watches_path %>

However, the very first thing someone has to do
is
<%= link_to "set up an account", documentation_set_up_account_path %>
for your organization


text:
namespace Volt {

DataAsset::DataAsset () {
}

DataAsset::~DataAsset () {
    Unload();
}

bool DataAsset::Load (const DataItem& item) {
    m_path = item.path;

    Json::Reader reader;
    bool success = reader.parse(item.data, item.data + item.size, m_root);
    if (!success) {
        LOG(ERROR) << "Failed to parse " << item.path << ":\n" << reader.getFormatedErrorMessages();
    }
    return success;
}

void DataAsset::Reload () {
    Unload();
    DataItem item;
    m_manager->ReloadPath(this, &item);
    Load(item);
}

void DataAsset::Unload () {
    m_root.clear();
}

void DataAsset::Save (const Json::Value& root, const string& filename) {
    string path = G_AssetManager->sourcePath() + "/" + filename;
    ofstream out(path.c_str());
    if (!out.is_open()) {
        LOG(ERROR) << "Failed to open file " << path;
    }

    out << root;
    out.close();
}

}


text:
from botstory import matchers, utils
from botstory.ast import callable, forking, loop
from botstory.ast.story_context import reducers
from botstory.utils import advanced_json_encoder
import numbers

import logging
import uuid

logger = logging.getLogger(__name__)

class MissedStoryPart(Exception):
    pass

class StoryContext:
    def __init__(self, message, library, matched=False, waiting_for=None, parent_uid=None):
        self.uid = str(uuid.uuid4())
        self.parent_uid = parent_uid
        self.library = library
        # whether message was passed validation and was matched one story
        self.matched = matched
        self.message = message
        self.waiting_for = waiting_for

    def clone(self):
        return StoryContext(library=self.library,
                            matched=self.matched,
                            message=self.message,
                            parent_uid=self.uid,
                            waiting_for=self.waiting_for,
                            )

    def compiled_story(self):
        if self.is_empty_stack():
            return self.library.get_global_story(self.message)
        else:
            return self.library.get_story_by_topic(self.stack_tail()['topic'], stack=self.stack()[:-1])

    def could_scope_out(self):
        """
        could bubble up from current scope

        :return:
        """
        return not self.waiting_for or \
               isinstance(self.waiting_for, callable.EndOfStory) or \
               self.is_breaking_a_loop()

    def current_step(self):
        return self.stack_tail()['step']

    def does_it_match_any_story(self):
        return self.compiled_story() is not None and not self.matched

    def get_child_story(self):
        logger.debug('# get_child_story')
        """
        try child story that match message and get scope of it
        :return:
        """
        story_loop = self.compiled_story()
        if hasattr(story_loop, 'children_matcher') and not self.matched:
            return self.get_story_scope_child(story_loop)

        story_part = self.get_current_story_part()

        if not hasattr(story_part, 'get_child_by_validation_result'):
            logger.debug('# does not have get_child_by_validation_result')
            return None

        if isinstance(self.waiting_for, forking.SwitchOnValue):
            logger.debug('# switch on value')
            return story_part.get_child_by_validation_result(self.waiting_for.value)

        # for some base classes we could try validate result direct
        child_story = story_part.get_child_by_validation_result(self.waiting_for)
        if child_story:
            logger.debug('# child_story')
            logger.debug(child_story)
            return child_story

        stack_tail = self.stack_tail()
        if stack_tail['data'] is not None and not self.matched:
            validator = matchers.deserialize(stack_tail['data'])
            logger.debug('# validator')
            logger.debug(validator)
            logger.debug('# self.message')
            logger.debug(self.message)
            validation_result = validator.validate(self.message)
            logger.debug('# validation_result')
            logger.debug(validation_result)
            res = story_part.get_child_by_validation_result(validation_result)
            logger.debug('# res')
            logger.debug(res)
            # or we validate message
            # but can't find right child story
            # maybe we should use independent validators for each story here
            if res is None:
                return self.get_story_scope_child(story_part)
            else:
                return res

        return None

    def get_story_scope_child(self, story_part):
        logger.debug('# get_story_scope_child')
        validator = story_part.children_matcher()
        logger.debug('# validator')
        logger.debug(validator)
        logger.debug('# self.message')
        logger.debug(self.message)
        topic = validator.validate(self.message)
        # if topic == None:
        # we inside story loop scope
        # but got message that doesn't match
        # any local stories
        logger.debug('# topic {}'.format(topic))
        return story_part.by_topic(topic)

    def get_current_story_part(self):
        compiled_story = self.compiled_story()
        if not compiled_story:
            return None
        try:
            return compiled_story.story_line[self.current_step()]
        except IndexError:
            return None

    def get_user_data(self):
        return get_user_data(self.message)

    def has_child_story(self):
        return self.get_child_story() is not None

    def is_breaking_a_loop(self):
        return isinstance(self.waiting_for, loop.BreakLoop)

    def is_empty_stack(self):
        return len(self.stack()) == 0

    def is_end_of_story(self):
        compiled_story = self.compiled_story()
        if not compiled_story:
            return True
        return self.current_step() >= len(compiled_story.story_line)

    def is_scope_level(self):
        return isinstance(self.compiled_story(), loop.StoriesLoopNode)

    def is_scope_level_part(self):
        return isinstance(self.get_current_story_part(), loop.StoriesLoopNode)

    def is_tail_of_story(self):
        compiled_story = self.compiled_story()
        if not compiled_story:
            return True
        return self.current_step() >= len(compiled_story.story_line) - 1

    def is_waiting_for_input(self):
        """
        could make one step further
        :return:
        """
        return self.waiting_for and \
               not isinstance(self.waiting_for, forking.SwitchOnValue) and \
               not is_base_type(self.waiting_for)

    def stack(self):
        return self.message['session']['stack']

    def stack_tail(self):
        stack = self.stack()
        if len(stack) == 0:
            raise MissedStoryPart()
        return stack[-1]

    def to_json(self):
        return {
            'uid': self.uid,
            'parent_uid': self.parent_uid,
            'matched': self.matched,
            'message': self.message,
            'waiting_for': str(self.waiting_for),
        }

    def user(self):
        return self.message['user']

    def __repr__(self):
        try:
            return advanced_json_encoder.AdvancedJSONEncoder().encode(self.to_json())
        except Exception as err:
            logger.warn(err)
            logger.warn('fail to dump json of message {} '
                        'waiting for {}'.format(str(self.message), str(self.waiting_for)))

def is_base_type(value):
    return isinstance(value, str) or isinstance(value, numbers.Number)

def clean_message_data(ctx):
    return utils.safe_set(ctx, 'session', 'data', 'message', {})

def get_user_data(ctx):
    return ctx['session']['data']

def get_message_data(ctx, *args, **kwargs):
    return utils.safe_get(get_user_data(ctx)['message'], *args, **kwargs)

def get_message_attachment(ctx, attachment_type):
    logger.debug('# get_message_data(ctx)')
    logger.debug(get_message_data(ctx))
    attachment_list = get_message_data(ctx, 'attachments')
    if attachment_list is None or len(attachment_list) == 0:
        return None
    attachment_list_of_type = [a for a in attachment_list if a['type'] == attachment_type]
    if attachment_list_of_type is None or len(attachment_list_of_type) == 0:
        return None
    return attachment_list_of_type[0]

def set_user_data(ctx, data):
    ctx['session']['data'] = {
        **get_user_data(ctx),
        **data,
    }
    return ctx

def set_message_data(ctx, *args):
    return utils.safe_set(ctx, 'session', 'data', 'message', *args)

__all__ = [get_user_data, reducers, set_user_data, StoryContext]


text:
import os
import re
import sys
import threading

import openmdao.main
from openmdao.gui.session import TornadoSession
from openmdao.main.plugin import find_docs_url
from openmdao.main.rbac import Credentials
from openmdao.util.fileutil import get_ancestor_dir
from tornado.web import RequestHandler, StaticFileHandler

class ReqHandler(RequestHandler):
    ''' Override the get_current_user() method in request handlers to
        determine the current user based on the value of a cookie.
    '''

    def initialize(self):
        self.session = TornadoSession(self.application.session_manager, self)

    def get_sessionid(self):
        return self.session.session_id

    def get_current_user(self):
        return self.get_secure_cookie('user')

    def get_server(self):
        return self.application.server_manager.server(self.get_sessionid())

    def delete_server(self):
        self.application.server_manager.delete_server(self.get_sessionid())

    def get_project_dir(self):
        return self.application.project_dir

class LoginHandler(ReqHandler):
    ''' Currently we support a single user, the current user.
        This hook is for potential future development using Credentials.
    '''

    def get(self):
        # single user scenario, auto-login based on username
        server_creds = Credentials()
        print "server_creds:\n", server_creds
        self.set_secure_cookie('user', server_creds.user)
        self.redirect('/')

    def post(self):
        server_creds = Credentials()
        print 'server creds:\n', server_creds

        # single user... only allow same user@host as the server to log in
        allowed_users = {server_creds.user: server_creds.public_key}
        encoded = self.get_argument('encoded')
        client_creds = Credentials.verify(encoded, allowed_users)
        print 'client creds:\n', client_creds

        if client_creds:
            self.set_secure_cookie('user', client_creds.user)
        self.redirect('/')

class LogoutHandler(ReqHandler):
    ''' Lets users log out of the application simply by deleting the
        nickname cookie.
    '''

    def get(self):
        self.clear_cookie('user')
        self.redirect('/')

    def post(self):
        self.clear_cookie('user')
        self.redirect('/')

class ExitHandler(ReqHandler):
    ''' Shut it down; try to close the browser window.
    '''

    def get(self):
        self.application.exit()
        self.render('closewindow.html')

class PluginDocsHandler(StaticFileHandler):
    ''' Retrieve docs for a plugin. '''
    _plugin_map = {}
    _plugin_lock = threading.Lock()
    regex = re.compile("site-packages/openmdao.main.+\.egg")

    def _cname_valid(self, name):
        # TODO: use regex to check form of cname (must be dotted module path)
        return True

    def initialize(self, route):
        rpath = self.request.path[len(route):].strip('/')
        parts = rpath.split('/', 1)
        self.cname = parts[0] + os.sep
        self.added = ''
        if len(parts) == 1:
            with self._plugin_lock:
                if self._cname_valid(parts[0]) and parts[0] not in self._plugin_map:
                    url = find_docs_url(parts[0], build_if_needed=False)
                    # Remove "file://" from URL
                    url = url[7:]
                    if self.cname.startswith('openmdao.'):
                        if (self.regex.search(url)):
                            # url points to docs in a release version, so use docs packaged with openmdao.main
                            root = os.path.join(os.path.dirname(openmdao.main.__file__), "docs")
                        else:  # url points to docs in a developer version, so use locally built docs
                            root = os.path.join(get_ancestor_dir(sys.executable, 3), 'docs',
                                                '_build', 'html')
                        self.added = os.path.dirname(url)[len(root) + 1:]
                    else:
                        root = os.path.dirname(url)

                    default = os.path.basename(url)
                    self._plugin_map[parts[0]] = (root, default, self.added)

        root, default, self.added = self._plugin_map[parts[0]]

        super(PluginDocsHandler, self).initialize(root, default)

    def get(self, path, include_body=True):

        # Note, don't want to lower-case our URL
        # However, we do want to replace any MS-DOS slashes.
        if os.path.sep != "/":
            path = path.replace("/", os.path.sep)

        if path + os.sep == self.cname:
            self.redirect(os.path.join('/docs',
                                       'plugins',
                                       self.cname, self.default_filename))

        elif path.startswith(self.cname):
            super(PluginDocsHandler, self).get(os.path.join(self.added, path[len(self.cname):]),
                                               include_body)
        else:
            super(PluginDocsHandler, self).get(path, include_body)


text:
<?php namespace App;

use Illuminate\Database\Eloquent\Model;
use Session, View;

class Flash extends Model {

	public static function message() {
		// Do we have any messages?
		$hasMessage =  ( Session::has('errors') || Session::has('message') || Session::has('success') ) ? true : false;

		if ( $hasMessage ) {
			if ( Session::has('message-type') ) {
				// if there is a message type, use it
				$messageType = Session::get('message-type');
			} elseif ( Session::has('errors') ) {
				// if there are errors, set the type to danger
				$messageType = 'danger';
			}

			switch ( $messageType ) {
				case 'success':
					$class = 'alert alert-success alert-dismissible';  // green
					$icon = 'fa fa-check-circle';
					$preText = 'Success! ' . (Session::get('message') ? Session::get('message'):'');
					break;
				case 'warning':
					$class = 'alert alert-warning alert-dismissible';  // yellow
					$icon = 'fa fa-question-circle';
					$preText = 'Warning! ' . (Session::get('message') ? Session::get('message'):'Looks like something went wrong');
					break;
				case 'danger':
					$class = 'alert alert-danger alert-dismissible';  // red
					$icon = 'fa fa-exclamation-circle';
					$preText = 'Error!  ' . (Session::get('message') ? Session::get('message'):'Something has gone horribly wrong');
					break;
				case 'info':
					$class = 'alert alert-info alert-dismissible';  // blue
					$icon = 'fa fa-info-circle';
					$preText = 'Information! ' . (Session::get('message') ? Session::get('message'):'');
					break;
				default:
					$class = 'alert alert-info alert-dismissible';  // blue
					$icon = 'fa fa-info-circle';
					$preText = Session::get('message') ? Session::get('message'):'';
					break;
			}
			return View::make('components.flash', compact('class', 'icon', 'preText'));
		}
	}
}


text:
package apps.mathpadapp.networkmanager.messages.fromcontroller.broadcast;

import synergynetframework.appsystem.services.net.tablecomms.messages.application.BroadcastApplicationMessage;

/**
 * The Class BroadcastSearchProjectorMessage.
 */
public class BroadcastSearchProjectorMessage extends
		BroadcastApplicationMessage {

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

	/**
	 * Instantiates a new broadcast search projector message.
	 *
	 * @param targetClass
	 *            the target class
	 */
	public BroadcastSearchProjectorMessage(Class<?> targetClass) {
		super(targetClass);
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		return "Search Projector";
	}

}