text:
package org.apache.derby.iapi.store.raw.xact;

import org.apache.derby.iapi.services.context.ContextManager;
import org.apache.derby.iapi.services.daemon.Serviceable;
import org.apache.derby.iapi.services.io.Formatable;
import org.apache.derby.iapi.services.locks.CompatibilitySpace;
import org.apache.derby.iapi.services.locks.LockFactory;

import org.apache.derby.iapi.store.access.TransactionInfo;

import org.apache.derby.iapi.store.raw.RawStoreFactory;
import org.apache.derby.iapi.store.raw.Transaction;
import org.apache.derby.iapi.store.raw.Corruptable;

import org.apache.derby.iapi.store.raw.log.LogInstant;

import org.apache.derby.shared.common.error.StandardException;

/**
	This module is intended to be used only within the RawStore. RawStore functionality
	is accessed only through the RawStoreFactory interface.
	The transaction manager is responsible for:

Generating unique transaction identifiers.

Keeping a list of all open transactions within the raw store.

	@see RawStoreFactory
	@see Transaction
*/

public interface TransactionFactory extends Corruptable {

	public static String MODULE =
        "org.apache.derby.iapi.store.raw.xact.TransactionFactory";

	/**
		Get the LockFactory to use with this store.
	*/
	public LockFactory getLockFactory();

	/**
	 * Return the module providing XAresource interface to the transaction
     * table.
     *
	 * @exception StandardException Standard Derby exception policy.
	 */
	public /* XAResourceManager */ Object getXAResourceManager()
        throws StandardException;

	/**
		Start a new transaction within the given raw store. This method will
        push a transaction context as described in
        RawStoreFactory.startTransaction

        @param contextMgr is the context manager to use.  It must be the current
                          context manager.
        @param transName is the transaction name. It will be displayed in the
            transactiontable VTI.

		@see RawStoreFactory#startTransaction

		@exception StandardException Standard Derby error policy.
	*/
	public RawTransaction startTransaction(
    RawStoreFactory rsf,
    ContextManager  contextMgr,
    String transName)
        throws StandardException;

	/**
		Start a new read only transaction within the given raw store. This
        method will push a transaction context as described in
        RawStoreFactory.startNestedTransaction

		@param rsf                      the RawStoreFactory
		@param parentTransaction   the parent transaction
		@param compatibilitySpace   compatibility space to use for locks.
        @param contextMgr           is the context manager to use.  It must be
                                    the current context manager.
        @param transName            is the transaction name. It will be
                                    displayed in the transactiontable VTI.

		@see RawStoreFactory#startNestedReadOnlyUserTransaction

		@exception StandardException Standard Derby error policy.
	*/
	public RawTransaction startNestedReadOnlyUserTransaction(
    RawStoreFactory rsf,
    RawTransaction parentTransaction,
    CompatibilitySpace compatibilitySpace,
    ContextManager  contextMgr,
    String          transName)
        throws StandardException;

	/**
		Start a new update transaction within the given raw store. This method
        will push a transaction context as described in
        RawStoreFactory.startNestedTransaction

		@param rsf                      the RawStoreFactory
		@param parentTransaction   the parent transaction
        @param contextMgr               is the context manager to use.  It must
                                        be the current context manager.
        @param transName                is the transaction name. It will be
                                        displayed in the transactiontable VTI.
        @param flush_log_on_xact_end    By default should the transaction commit
                                        and abort be synced to the log.  Normal
                                        usage should pick true, unless there
                                        is specific performance need and usage
                                        works correctly if a commit can be
                                        lost on system crash.

		@see RawStoreFactory#startNestedUpdateUserTransaction

		@exception StandardException Standard Derby error policy.
	*/
	public RawTransaction startNestedUpdateUserTransaction(
    RawStoreFactory rsf,
    RawTransaction parentTransaction,
    ContextManager  contextMgr,
    String          transName,
    boolean         flush_log_on_xact_end)
        throws StandardException;

	/**
		Start a new transaction within the given raw store. This method will
        push a transaction context as described in
        RawStoreFactory.startTransaction

        @param format_id  the format id part of the Xid - ie. Xid.getFormatId().
        @param global_id  the global transaction identifier part of XID - ie.
                          Xid.getGlobalTransactionId().
        @param branch_id  The branch qualifier of the Xid - ie.
                          Xid.getBranchQaulifier()
        @param contextMgr is the context manager to use.  It must be the current
                          context manager.

		@see RawStoreFactory#startGlobalTransaction

		@exception StandardException Standard Derby error policy.
	*/
	public RawTransaction startGlobalTransaction(
    RawStoreFactory rsf,
    ContextManager  contextMgr,
    int             format_id,
    byte[]          global_id,
    byte[]          branch_id)
        throws StandardException;

	/**
		Find a user transaction within the given raw store and the given
		contextMgr.  If no user transaction exist, then start one with name
        transName. This method will push a transaction context as described in
		RawStoreFactory.startTransaction

		@see RawStoreFactory#findUserTransaction
		@see RawStoreFactory#startTransaction

		@exception StandardException Standard Derby error policy.
	*/
	public RawTransaction findUserTransaction(
        RawStoreFactory rsf,
        ContextManager contextMgr,
        String transName) throws StandardException;

	/**
		Start a new nested top transaction within the given raw store. This
        method will push a transaction context as described in
        RawStoreFactory.startNestedTopTransaction

		@see RawStoreFactory#startTransaction(ContextManager, String)

		@exception StandardException Standard Derby error policy.
	*/
	public RawTransaction startNestedTopTransaction(RawStoreFactory rsf, ContextManager contextMgr) throws StandardException;

	/**
		Start a new internal transaction within the given raw store. This
        method will push a transaction context as described in
        RawStoreFactory.startInternalTransaction

		@see RawStoreFactory#startTransaction

		@exception StandardException Standard Derby error policy.
	*/
	public RawTransaction startInternalTransaction(RawStoreFactory rsf, ContextManager contextMgr) throws StandardException;

	/**
		Find a transaction using a transactionId and make the passed in
		transaction assume the identity and properties of that transaction.
		Used in recovery only.
	*/
	public boolean findTransaction(TransactionId id, RawTransaction tran);

	/**
		Reset any resettable transaction Id
		@exception StandardException Standard Derby error policy.
	*/
	public void resetTranId() throws StandardException;

	/**
		The first log instant that belongs to a transaction that is still
		active in the raw store. This is the first log record of the longest
		running transaction at this moment.
	*/
	public LogInstant firstUpdateInstant();

	/**
        Run through all prepared transactions known to this factory
        and restore their state such that they remain after recovery, and
        can be found and handled by a XA transaction manager.  This includes
        creating a context manager for each, pushing a xact context, and
        reclaiming update locks on all data changed by the transaction.

		Used only in recovery.

		@exception StandardException Derby Standard Error policy
	*/
	public void handlePreparedXacts(
    RawStoreFactory rsf)
		 throws StandardException;

	/**
		Rollback and close all transactions known to this factory using a
		passed in transaction.  Used only in recovery.

		@param recoveryTransaction the transaction used to rollback
		@exception StandardException Derby Standard Error policy
	*/
	public void rollbackAllTransactions(RawTransaction recoveryTransaction,
										RawStoreFactory rsf)
		 throws StandardException ;

	/**
		Submit a post commit work to the post commit daemon.
		The work is always added to the deamon, regardless of the
		state it returns.

		@return true if the daemon indicates it is being overloaded,
		false it's happy.

		<MT> must be MT-safe
	*/
	public boolean submitPostCommitWork(Serviceable work);

	/**
		make Transaction factory aware of which raw store factory it belongs to
	*/
	public void setRawStoreFactory(RawStoreFactory rsf) throws StandardException;

	/**
		Returns true if the transaction factory has no active updating
        transaction
	*/
	public boolean noActiveUpdateTransaction();

    /**
     * Check if there are any prepared transanctions.
     *
     *
MT - unsafe, called during boot, which is single threaded.
     *
     * @return   <tt>true</tt> if prepared transactions exist,
     *			 <tt>false</tt> otherwise.
     */
	public boolean hasPreparedXact();

	/**
		Database creation finished

		@exception StandardException Standard Derby exception policy.
	*/
	public void createFinished() throws StandardException;

	/**
		Return the transaction table so it can get logged with the checkpoint
		log record.
	 */
	public Formatable getTransactionTable();

	/**
		Use this transaction table, which is gotten from a checkpoint
		operation.  Use ONLY during recovery.

		@exception StandardException Standard Derby exception policy.
	 */
	public void useTransactionTable(Formatable transactionTable)
		 throws StandardException;

	/**
	  @see org.apache.derby.iapi.store.access.AccessFactory#getTransactionInfo
	 */
	public TransactionInfo[] getTransactionInfo();

	/**
	 * Checks if there any backup blocking operations are in progress and
	 * prevents new ones from starting until the backup is finished.
	 *
	 * @param wait if <tt>true</tt>, waits for the current backup blocking
	 *             operations in progress to finish.
	 * @return     <tt>true</tt> if there are no backup blocking
	 *             operations in progress.
	 *             <tt>false</tt> otherwise.
	 * @exception StandardException if interrupted or a runtime exception occurs.
	 */
	public boolean blockBackupBlockingOperations(boolean wait)
		throws StandardException ;

	/**
	 * Backup completed. Allow backup blocking operations.
	 */
	public void  unblockBackupBlockingOperations();

}


text:
package nl.utwente.viskell.ui.components;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.geometry.BoundingBox;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.*;
import nl.utwente.viskell.haskell.expr.*;
import nl.utwente.viskell.haskell.type.FunType;
import nl.utwente.viskell.haskell.type.Type;
import nl.utwente.viskell.haskell.type.TypeScope;
import nl.utwente.viskell.ui.DragContext;
import nl.utwente.viskell.ui.ToplevelPane;
import nl.utwente.viskell.ui.serialize.Bundleable;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

public class FunApplyBlock extends Block {

    /** Function input anchor that can be dragged down for currying. */
    private class FunInputAnchor extends Pane implements ConnectionAnchor.Target {

        /** The connection anchor for this input argument. */
        private final InputAnchor anchor;

        /** The input type label of this anchor. */
        private final Label inputType;

        /** Label with function arrow when in curried state. */
        private final Label curryArrow;

        /** The draggable pane combining both type label and curry arrow */
        private final Pane typePane;

        /** Whether this input argument is in curried state. */
        private boolean curried;

        /** The drag handler for this. */
        private final DragContext dragContext;

        public FunInputAnchor() {
            this.curried = false;
            this.inputType = new Label(".....");
            this.inputType.setMinWidth(USE_PREF_SIZE);
            this.inputType.getStyleClass().add("inputType");
            this.curryArrow = new Label("->");
            this.curryArrow.setMinWidth(USE_PREF_SIZE);
            this.curryArrow.getStyleClass().add("curryArrow");
            this.curryArrow.setVisible(false);
            this.curryArrow.setMouseTransparent(true);
            this.typePane = new HBox(this.inputType, this.curryArrow) {
                @Override
                public void relocate(double x, double y) {
                    super.relocate(x, y);
                    FunInputAnchor.this.dragShift(y);
                }
            };
            this.typePane.setMinWidth(USE_PREF_SIZE);
            this.typePane.setPickOnBounds(false);
            this.anchor = new InputAnchor(FunApplyBlock.this);
            this.anchor.layoutXProperty().bind(this.inputType.widthProperty().divide(2));
            this.getChildren().addAll(this.anchor, this.typePane);
            this.setTranslateY(-9);
            this.setPickOnBounds(false);

            dragContext = new DragContext(this.typePane);
            dragContext.setDragInitAction(c -> {this.curried = false;});
            dragContext.setDragFinishAction(c -> {
                double height = this.inputType.getHeight();
                boolean mostlyDown = (this.typePane.getLayoutY() > height) && !this.anchor.hasConnection();
                double newY = mostlyDown ? 1.5*height : 0;
                this.typePane.relocate(0, newY);
                this.curried = mostlyDown;
                FunApplyBlock.this.dragShiftOuput(newY - height);
                FunApplyBlock.this.initiateConnectionChanges();
                if (curried && this.anchor.getWireInProgress() != null) {
                    this.anchor.getWireInProgress().remove();
                }
            });
        }

        @Override
        public ConnectionAnchor getAssociatedAnchor() {
            return this.anchor;
        }

        @Override
        public double computePrefHeight(double width) {
            double height = this.inputType.prefHeight(width);
            this.dragContext.setDragLimits(new BoundingBox(0, 0, 0, height*1.5));
            return height;
        }

        /** Shift related things down to some distance. */
        private void dragShift(double y) {
            double height = this.inputType.getHeight();
            this.anchor.setLayoutY(y);
            this.anchor.setOpacity(1 - (y/(height)));
            this.anchor.setVisible(y < height);
            this.curryArrow.setManaged(y > height || Iterables.getLast(FunApplyBlock.this.inputs) != this);
            this.curryArrow.setVisible(y > height);
            FunApplyBlock.this.dragShiftOuput(y - height);
        }

        /** Refresh visual information such as types */
        public void invalidateVisualState() {
            this.anchor.invalidateVisualState();
            boolean validConnection = this.anchor.hasValidConnection();
            this.setTranslateY(validConnection ? 0 : -9);
            this.inputType.setText(validConnection ? "zyxwv" : this.anchor.getStringType());
            this.typePane.setVisible(!validConnection);
        }
    }

    /** The information about the function. */
    private FunctionReference funRef;

    private List<FunInputAnchor> inputs;

    /** Text label for the output type */
    private final Label resTypeLabel;

    /** The uncurried output type */
    private Type resType;

    /** The result anchor of this function. */
    private final OutputAnchor output;

    /** The background for curriedType labels */
    private final Pane curriedOutput;

    /** The space containing anchors and type labels. */
    @FXML private Pane bodySpace;

    private final Pane inputSpace;

    private static final Map<String, String> functionReferenceClassMap;
    static {
        Map<String, String> aMap = new HashMap<>();
        aMap.put(LocalDefUse.class.getSimpleName(), LocalDefUse.class.getName());
        aMap.put(LibraryFunUse.class.getSimpleName(), LibraryFunUse.class.getName());
        aMap.put(ApplyAnchor.class.getSimpleName(), ApplyAnchor.class.getName());
        functionReferenceClassMap = Collections.unmodifiableMap(aMap);
    }

    public FunApplyBlock(ToplevelPane pane, FunctionReference funRef) {
        super(pane);
        this.loadFXML("FunApplyBlock");

        this.funRef = funRef;
        this.funRef.initializeBlock(this);
        ((HBox)this.bodySpace.getParent()).getChildren().add(0, funRef.asRegion());

        this.inputs = new ArrayList<>();
        this.output = new OutputAnchor(this, new Binder("res"));

        this.resTypeLabel = new Label("");
        this.resTypeLabel.setMinWidth(USE_PREF_SIZE);
        this.resTypeLabel.getStyleClass().add("resultType");
        VBox outputSpace = new VBox(this.resTypeLabel, this.output);
        outputSpace.setAlignment(Pos.CENTER);
        outputSpace.setPickOnBounds(false);

        Type t = funRef.refreshedType(funRef.requiredArguments(), new TypeScope());
        while (t instanceof FunType) {
            FunType ft = (FunType) t;
            FunInputAnchor ia = new FunInputAnchor();
            this.inputs.add(ia);
            t = ft.getResult();
        }

        if (! this.inputs.isEmpty()) {
            Iterables.getLast(FunApplyBlock.this.inputs).curryArrow.setManaged(false);
        }

        this.inputSpace = new HBox(5, this.inputs.toArray(new Node[this.inputs.size()]));
        this.inputSpace.setPickOnBounds(false);

        this.curriedOutput = new Pane() {
                @Override
                public double computePrefWidth(double height) {
                    return Math.max(inputSpace.prefWidth(height), outputSpace.getLayoutX()+resTypeLabel.prefWidth(height));
                }
                @Override
                public double computePrefHeight(double width) {
                    return resTypeLabel.prefHeight(width)*2;
                }
            };
        this.curriedOutput.setVisible(false);
        this.curriedOutput.getStyleClass().add("curriedOutput");
        this.curriedOutput.setBorder(new Border(new BorderStroke(null, BorderStrokeStyle.SOLID, null, null, new Insets(-1))));

        this.bodySpace.getChildren().addAll(this.curriedOutput, this.inputSpace, outputSpace);
        outputSpace.layoutYProperty().bind(this.inputSpace.heightProperty());
        outputSpace.layoutXProperty().bind(Bindings.max(0, this.inputSpace.widthProperty().divide(2).subtract(resTypeLabel.widthProperty().divide(2))));
        outputSpace.setTranslateY(9);

        this.curriedOutput.translateYProperty().bind(outputSpace.translateYProperty());
    }

    /** @return a Map of class-specific properties of this Block. */
    @Override
    protected Map<String, Object> toBundleFragment() {
        Map<String, Object> bundleFragment = ImmutableMap.of(
                "curriedArgs", this.inputs.stream().map(i -> i.curried).toArray(),
                "funRef", this.funRef.toBundleFragment()
                );
        return bundleFragment;
    }

    /** return a new instance of this Block type deserializing class-specific properties used in constructor **/
    public static FunApplyBlock fromBundleFragment(ToplevelPane pane, Map<String,Object> bundleFragment) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Map<String, Object> funRefBundle = (Map<String, Object>)bundleFragment.get("funRef");

        String funcReferenceClassName = functionReferenceClassMap.get(funRefBundle.get(Bundleable.KIND));
        Class<?> clazz = Class.forName(funcReferenceClassName);

        // Find the static "fromBundleFragment" method for the named type and call it
        Method fromBundleMethod = clazz.getDeclaredMethod("fromBundleFragment", Map.class);
        FunctionReference functionReference = (FunctionReference)fromBundleMethod.invoke(null, funRefBundle);

        return new FunApplyBlock(pane, functionReference);
    }

    /** Shift the output type/anchor down to some distance. */
    private void dragShiftOuput(double y) {
        double shift = Math.max(0, y);
        if (this.inputs.stream().map(i -> i.curried).filter(c -> c).count() == 0) {
            this.output.getParent().setTranslateY(9 + shift);
            this.curriedOutput.setVisible(false);
            this.curriedOutput.setManaged(false);
        } else {
            this.curriedOutput.setManaged(true);
            this.curriedOutput.setVisible(true);
            this.curriedOutput.requestLayout();
        }
    }

    public FunctionReference getFunReference() {
        return this.funRef;
    }

    public void convertToOpenApply(ApplyAnchor apply) {
        this.funRef.deleteLinks();
        this.funRef = apply;
        apply.initializeBlock(this);
        ((HBox)this.bodySpace.getParent()).getChildren().set(0, funRef.asRegion());
        this.initiateConnectionChanges();
    }

    @Override
    public List<InputAnchor> getAllInputs() {
        List<InputAnchor> res = new ArrayList<>();
        this.inputs.stream().map(i -> i.anchor).collect(Collectors.toCollection(() -> res));
        this.funRef.getInputAnchor().ifPresent(fia -> res.add(0, fia));
        return res;
    }

    @Override
    public List<OutputAnchor> getAllOutputs() {
        return ImmutableList.of(this.output);
    }

    @Override
    public Optional<Block> getNewCopy() {
        if (this.inputs.stream().map(i -> i.curried).filter(c -> c).count() == 0) {
            return Optional.of(new FunApplyBlock(this.getToplevel(), this.funRef.getNewCopy()));
        }

        return Optional.empty();
    }

    @Override
    protected void refreshAnchorTypes() {
        TypeScope scope = new TypeScope();
        Type type = this.funRef.refreshedType(this.inputs.size(), scope);
        for (FunInputAnchor arg : this.inputs) {
            if (type instanceof FunType) {
                FunType ftype = (FunType)type;
                arg.anchor.setFreshRequiredType(ftype.getArgument(), scope);
                type = ftype.getResult();
            } else {
                new RuntimeException("too many arguments in this functionblock " + funRef.getName());
            }
        }
        this.resType = type.getFresh(scope);

        Type curriedType = this.resType;
        for (FunInputAnchor arg : Lists.reverse(this.inputs)) {
            if (arg.curried) {
                curriedType = new FunType (arg.anchor.getType(), curriedType);
            }
        }
        this.output.setExactRequiredType(curriedType);
    }

    @Override
    public Expression getLocalExpr(Set<OutputAnchor> outsideAnchors) {
        Expression expr = this.funRef.getLocalExpr(outsideAnchors);
        List<Binder> curriedArgs = new ArrayList<>();

        for (FunInputAnchor arg : this.inputs) {
            if (arg.curried) {
                Binder ca = new Binder("ca");
                curriedArgs.add(ca);
                expr = new Apply(expr, new LocalVar(ca));
            } else {
                expr = new Apply(expr, arg.anchor.getLocalExpr(outsideAnchors));
            }
        }

        if (curriedArgs.isEmpty()) {
            return expr;
        } else {
            return new Lambda(curriedArgs, expr);
        }
    }

    @Override
    public void invalidateVisualState() {
        this.funRef.invalidateVisualState();

        this.resTypeLabel.setText(this.resType.prettyPrint());
        this.output.invalidateVisualState();

        for (FunInputAnchor arg : this.inputs) {
        	arg.invalidateVisualState();
        }
    }

    @Override
    public boolean checkValidInCurrentContainer() {
        return this.funRef.isScopeCorrectIn(this.container) && super.checkValidInCurrentContainer();
    }

    @Override
    public void deleteAllLinks() {
        this.funRef.deleteLinks();
        super.deleteAllLinks();
    }

    @Override
    public boolean canAlterAnchors() {
        return this.funRef instanceof ApplyAnchor;
    }

    @Override
    public void alterAnchorCount(boolean isRemove) {
        if (this.funRef instanceof ApplyAnchor) {
            ApplyAnchor apply = (ApplyAnchor)this.funRef;
            if (apply.hasConnection()) {
                if (isRemove && apply.getType().countArguments() <= this.inputs.size()) {
                    return;
                }
                if (!isRemove && apply.getType().countArguments() >= this.inputs.size()) {
                    return;
                }
            }

            if (isRemove) {
                FunInputAnchor removed = this.inputs.remove(this.inputs.size()-1);
                this.inputSpace.getChildren().remove(removed);
            } else {
                FunInputAnchor extra = new FunInputAnchor();
                this.inputs.add(extra);
                this.inputSpace.getChildren().add(extra);
            }
            this.initiateConnectionChanges();
        }
    }

    @Override
    public String toString() {
        return funRef.getName();
    }
}

redpajama_set_name: RedPajamaGithub


text:
module EmarsysTestSuiteHelpers
  class TestCase

    def initialize(test_file)
      @test_data = ::JSON.parse(File.read(test_file), symbolize_names: true).to_snake_keys
      convert_naming
    end

    def [](arg)
      @test_data[arg]
    end

    def key
      {@test_data[:key_db].first[0] => @test_data[:key_db].first[1]}
    end

    def escher
      @test_data[:config][:current_time] = Time.parse(@test_data[:config].delete :date)
      @escher ||= ::Escher::Auth.new(@test_data[:config][:credential_scope], @test_data[:config])
    end

    def expected_request
      @test_data[:expected][:request].each { |_, v| v.sort! if v.class.method_defined? :sort! }
    end

    private
    def convert_naming
      @test_data[:request][:uri] = @test_data[:request].delete :url
      @test_data[:config][:api_key_id] = @test_data[:config].delete :access_key_id
    end

  end
end


text:
#pragma once
#include <aws/apprunner/AppRunner_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace AppRunner
{
namespace Model
{

  /**
   *
Provides summary information about an App Runner automatic scaling
   * configuration resource.

This type contains limited information about an
   * auto scaling configuration. It includes only identification information, without
   * configuration details. It's returned by the ListAutoScalingConfigurations
   * action. Complete configuration information is returned by the
   * CreateAutoScalingConfiguration, DescribeAutoScalingConfiguration,
   * and DeleteAutoScalingConfiguration actions using the
   * AutoScalingConfiguration type.

See Also:
   AWS
   * API Reference

   */
  class AWS_APPRUNNER_API AutoScalingConfigurationSummary
  {
  public:
    AutoScalingConfigurationSummary();
    AutoScalingConfigurationSummary(Aws::Utils::Json::JsonView jsonValue);
    AutoScalingConfigurationSummary& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The Amazon Resource Name (ARN) of this auto scaling configuration.

     */
    inline const Aws::String& GetAutoScalingConfigurationArn() const{ return m_autoScalingConfigurationArn; }

    /**
     *
The Amazon Resource Name (ARN) of this auto scaling configuration.

     */
    inline bool AutoScalingConfigurationArnHasBeenSet() const { return m_autoScalingConfigurationArnHasBeenSet; }

    /**
     *
The Amazon Resource Name (ARN) of this auto scaling configuration.

     */
    inline void SetAutoScalingConfigurationArn(const Aws::String& value) { m_autoScalingConfigurationArnHasBeenSet = true; m_autoScalingConfigurationArn = value; }

    /**
     *
The Amazon Resource Name (ARN) of this auto scaling configuration.

     */
    inline void SetAutoScalingConfigurationArn(Aws::String&& value) { m_autoScalingConfigurationArnHasBeenSet = true; m_autoScalingConfigurationArn = std::move(value); }

    /**
     *
The Amazon Resource Name (ARN) of this auto scaling configuration.

     */
    inline void SetAutoScalingConfigurationArn(const char* value) { m_autoScalingConfigurationArnHasBeenSet = true; m_autoScalingConfigurationArn.assign(value); }

    /**
     *
The Amazon Resource Name (ARN) of this auto scaling configuration.

     */
    inline AutoScalingConfigurationSummary& WithAutoScalingConfigurationArn(const Aws::String& value) { SetAutoScalingConfigurationArn(value); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of this auto scaling configuration.

     */
    inline AutoScalingConfigurationSummary& WithAutoScalingConfigurationArn(Aws::String&& value) { SetAutoScalingConfigurationArn(std::move(value)); return *this;}

    /**
     *
The Amazon Resource Name (ARN) of this auto scaling configuration.

     */
    inline AutoScalingConfigurationSummary& WithAutoScalingConfigurationArn(const char* value) { SetAutoScalingConfigurationArn(value); return *this;}

    /**
     *
The customer-provided auto scaling configuration name. It can be used in
     * multiple revisions of a configuration.

     */
    inline const Aws::String& GetAutoScalingConfigurationName() const{ return m_autoScalingConfigurationName; }

    /**
     *
The customer-provided auto scaling configuration name. It can be used in
     * multiple revisions of a configuration.

     */
    inline bool AutoScalingConfigurationNameHasBeenSet() const { return m_autoScalingConfigurationNameHasBeenSet; }

    /**
     *
The customer-provided auto scaling configuration name. It can be used in
     * multiple revisions of a configuration.

     */
    inline void SetAutoScalingConfigurationName(const Aws::String& value) { m_autoScalingConfigurationNameHasBeenSet = true; m_autoScalingConfigurationName = value; }

    /**
     *
The customer-provided auto scaling configuration name. It can be used in
     * multiple revisions of a configuration.

     */
    inline void SetAutoScalingConfigurationName(Aws::String&& value) { m_autoScalingConfigurationNameHasBeenSet = true; m_autoScalingConfigurationName = std::move(value); }

    /**
     *
The customer-provided auto scaling configuration name. It can be used in
     * multiple revisions of a configuration.

     */
    inline void SetAutoScalingConfigurationName(const char* value) { m_autoScalingConfigurationNameHasBeenSet = true; m_autoScalingConfigurationName.assign(value); }

    /**
     *
The customer-provided auto scaling configuration name. It can be used in
     * multiple revisions of a configuration.

     */
    inline AutoScalingConfigurationSummary& WithAutoScalingConfigurationName(const Aws::String& value) { SetAutoScalingConfigurationName(value); return *this;}

    /**
     *
The customer-provided auto scaling configuration name. It can be used in
     * multiple revisions of a configuration.

     */
    inline AutoScalingConfigurationSummary& WithAutoScalingConfigurationName(Aws::String&& value) { SetAutoScalingConfigurationName(std::move(value)); return *this;}

    /**
     *
The customer-provided auto scaling configuration name. It can be used in
     * multiple revisions of a configuration.

     */
    inline AutoScalingConfigurationSummary& WithAutoScalingConfigurationName(const char* value) { SetAutoScalingConfigurationName(value); return *this;}

    /**
     *
The revision of this auto scaling configuration. It's unique among all the
     * active configurations ("Status": "ACTIVE") with the same
     * AutoScalingConfigurationName.

     */
    inline int GetAutoScalingConfigurationRevision() const{ return m_autoScalingConfigurationRevision; }

    /**
     *
The revision of this auto scaling configuration. It's unique among all the
     * active configurations ("Status": "ACTIVE") with the same
     * AutoScalingConfigurationName.

     */
    inline bool AutoScalingConfigurationRevisionHasBeenSet() const { return m_autoScalingConfigurationRevisionHasBeenSet; }

    /**
     *
The revision of this auto scaling configuration. It's unique among all the
     * active configurations ("Status": "ACTIVE") with the same
     * AutoScalingConfigurationName.

     */
    inline void SetAutoScalingConfigurationRevision(int value) { m_autoScalingConfigurationRevisionHasBeenSet = true; m_autoScalingConfigurationRevision = value; }

    /**
     *
The revision of this auto scaling configuration. It's unique among all the
     * active configurations ("Status": "ACTIVE") with the same
     * AutoScalingConfigurationName.

     */
    inline AutoScalingConfigurationSummary& WithAutoScalingConfigurationRevision(int value) { SetAutoScalingConfigurationRevision(value); return *this;}

  private:

    Aws::String m_autoScalingConfigurationArn;
    bool m_autoScalingConfigurationArnHasBeenSet = false;

    Aws::String m_autoScalingConfigurationName;
    bool m_autoScalingConfigurationNameHasBeenSet = false;

    int m_autoScalingConfigurationRevision;
    bool m_autoScalingConfigurationRevisionHasBeenSet = false;
  };

} // namespace Model
} // namespace AppRunner
} // namespace Aws


text:
[![Build Status](https://travis-ci.org/sensu-plugins/sensu-plugins-postgres.svg?branch=master)](https://travis-ci.org/sensu-plugins/sensu-plugins-postgres)
[![Gem Version](https://badge.fury.io/rb/sensu-plugins-postgres.svg)](http://badge.fury.io/rb/sensu-plugins-postgres)
[![Code Climate](https://codeclimate.com/github/sensu-plugins/sensu-plugins-postgres/badges/gpa.svg)](https://codeclimate.com/github/sensu-plugins/sensu-plugins-postgres)
[![Test Coverage](https://codeclimate.com/github/sensu-plugins/sensu-plugins-postgres/badges/coverage.svg)](https://codeclimate.com/github/sensu-plugins/sensu-plugins-postgres)
[![Dependency Status](https://gemnasium.com/sensu-plugins/sensu-plugins-postgres.svg)](https://gemnasium.com/sensu-plugins/sensu-plugins-postgres)

## Functionality

## Files
 * bin/check-postgres-alive.rb
 * bin/check-postgres-connections.rb
 * bin/metric-postgres-dbsize.rb
 * bin/metric-postgres-statsbgwriter.rb
 * bin/metric-postgres-statstable.rb
 * bin/check-postgres-replication.rb
 * bin/metric-postgres-graphite.rb
 * bin/metric-postgres-statsdb.rb
 * bin/metric-postgres-connections.rb
 * bin/metric-postgres-locks.rb
 * bin/metric-postgres-statsio.rb
 * bin/check-postgres-query.rb
 * bin/metrics-postgres-query.rb
 * bin/metric-postgres-relation-size.rb

## Usage

Use `--help` to see command arguments.

### Sample usage

#### Check if PostgreSQL is alive
```
$ check-postgres-alive.rb -d template1 -f /var/lib/postgresql/.pgpass
CheckPostgres OK: Server version: {"version"=>"PostgreSQL 9.6.3 on x86_64-pc-linux-gnu, compiled by gcc (Debian 4.9.2-10) 4.9.2, 64-bit"}
```

### Check replication status
```
$ check-postgres-replication.rb -m psql1.local -s psql2.local -d template1 -w 5 -c 10
CheckPostgresReplicationStatus OK: replication delayed by 0.0MB :: master:B0/B4031000 slave:B0/B4031000 m_segbytes:16777216
```

### Check number of connections
```
$ export PGPASSWORD=this-is-secret-password
$ check-postgres-connections.rb -a -w 80 -c 90 -d template1 -u sensu
CheckPostgresConnections OK: PostgreSQL connections under threshold: 17%, 174 out of 997 connections
```

### Default values

| Argument       | Env variable | Value     |
|----------------|--------------|-----------|
| -f, --pgpass   | PGPASSFILE   | ~/.pgpass |
| -h, --hostname | PGHOST       | localhost |
| -P, --port     | PGPORT       | 5432      |
| -d, --database | PGDATABASE   | postgres  |
| -u, --user     | PGUSER       | postgres  |
| -p, --password | PGPASSWORD   |           |

Options precedence is following:
1. command line arguments
1. pgpass file
1. env variables
1. defaults

### Pgpass file

When file `~/.pgpass` is found it is used by default. You can also use `-f, --pgpass` command line argument or set `PGPASSFILE` env variable.

File format is:

```
hostname:port:database:username:password
```

Only first line is used. If database is set to `*` it is ommited.

You can ovveride `pgpass` values with command line arguments, e.g. `-h` for hostname.

## Installation

```
gem install sensu-plugins-postgres
```

## Centos installation

```
yum -y install gcc ruby-devel rubygems  postgresql-devel
sensu-install -p sensu-plugins-postgres

```

See [Installation and Setup](http://sensu-plugins.io/docs/installation_instructions.html) for details.

### Known issues

When using Sensu with `EMBEDDED_RUBY=true` and installing Postgres checks with `/usr/bin/sensu-install -p sensu-plugins-postgres` you might get following error:

```
ERROR:  Error installing sensu-plugins-postgres:
	ERROR: Failed to build gem native extension.
[...]
checking for PQconnectdb() in -lpq... no
checking for PQconnectdb() in -llibpq... no
checking for PQconnectdb() in -lms/libpq... no
Can't find the PostgreSQL client library (libpq)
*** extconf.rb failed ***
```

The reason is that **libssl** library which comes with Sensu is incompatible with **libpq** library installed on your system. There is no easy way to fix it. You might want to install sensu-plugins-postgres globally with `gem install sensu-plugins-postgres`.

Checks are in `/usr/local/bin` directory.

## Notes


text:
import hashlib
import time
import json
import sqlite3
from flask import Flask
from flask import request

DB_NAME = 'scores.db'
app = Flask(__name__)

try:
    with open('secret', 'rb') as f:
        SECRET = f.read()
except:
    raise

@app.route('/')
def index():
    return ''

@app.route('/score', methods=['GET'])
def get_user_score():
    db = sqlite3.connect(DB_NAME)
    db_c = db.cursor()
    scores = []
    for x in db_c.execute("SELECT * FROM scores"):
        scores.append("{date: '%s', username='%s', score=%d}" % (
            x[0], x[1], int(x[2])
        ))
    db.close()
    return json.dumps(scores)

@app.route('/submit', methods=['POST'])
def login():
    if request.method == 'POST':
        # HMAC check
        if request.form['check'] != hashlib.sha512(SECRET + hashlib.sha512(SECRET + request.form['score'].encode('utf-8').hexdigest())).hexdigest():
            return json.dumps("{state: 'KO'}")
        # Check passed, process to score save.
        try:
            db = sqlite3.connect(DB_NAME)
            db_c = db.cursor()
            try:
                db_c.execute('UPDATE scores SET date=?, score=? WHERE username=?', (
                    time.ctime(),
                    int(request.form['score']),
                    request.form['username']
                ))
            except sqlite3.OperationalError as e:
                db_c.execute("INSERT INTO scores VALUES (?, ?, ?)", (
                    time.ctime(),
                    request.form['username'],
                    int(request.form['score'])
                ))
            db.commit()
            db.close()
        except:
            raise
            return json.dumps("{state: 'KO'}")
    return json.dumps("{state: 'OK'}")

if __name__ == '__main__':
    try:
        db = sqlite3.connect(DB_NAME)
        db_c = db.cursor()
        db_c.execute('''CREATE TABLE scores (date text, username text, score int, PRIMARY KEY (username))''')
        db.commit()
        db.close()
    except:
        pass

    app.run(host='0.0.0.0', debug=True)


text:
<component name="ArtifactManager">
  <artifact type="exploded-war" name="admin:war exploded">
    <output-path>$PROJECT_DIR$/admin/target/admin</output-path>
    <root id="root">
      <element id="directory" name="WEB-INF">
        <element id="directory" name="classes">
          <element id="module-output" name="admin" />
        </element>
        <element id="directory" name="lib">
          <element id="archive" name="model-1.0-SNAPSHOT.jar">
            <element id="module-output" name="model" />
          </element>
          <element id="library" level="project" name="Maven: org.apache.logging.log4j:log4j-api:2.8.2" />
          <element id="library" level="project" name="Maven: org.apache.logging.log4j:log4j-core:2.8.2" />
          <element id="library" level="project" name="Maven: org.apache.logging.log4j:log4j-jcl:2.8.2" />
          <element id="library" level="project" name="Maven: org.apache.logging.log4j:log4j-slf4j-impl:2.8.2" />
          <element id="library" level="project" name="Maven: org.slf4j:slf4j-api:1.7.25" />
          <element id="library" level="project" name="Maven: com.google.code.gson:gson:2.8.1" />
          <element id="archive" name="dao-1.0-SNAPSHOT.jar">
            <element id="module-output" name="dao" />
          </element>
          <element id="library" level="project" name="Maven: org.mybatis:mybatis:3.4.2" />
          <element id="archive" name="service-1.0-SNAPSHOT.jar">
            <element id="module-output" name="service" />
          </element>
          <element id="library" level="project" name="Maven: org.springframework:spring-context:4.3.7.RELEASE" />
          <element id="archive" name="common-1.0-SNAPSHOT.jar">
            <element id="module-output" name="common" />
          </element>
          <element id="library" level="project" name="Maven: commons-dbutils:commons-dbutils:1.6" />
          <element id="library" level="project" name="Maven: gnu.getopt:java-getopt:1.0.13" />
          <element id="library" level="project" name="Maven: commons-codec:commons-codec:1.10" />
          <element id="library" level="project" name="Maven: org.springframework:spring-aop:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-beans:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-core:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-expression:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-context-support:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: commons-logging:commons-logging:1.2" />
          <element id="library" level="project" name="Maven: org.springframework:spring-web:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-webmvc:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-jdbc:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: org.springframework:spring-tx:4.3.7.RELEASE" />
          <element id="library" level="project" name="Maven: org.mybatis:mybatis-spring:1.3.1" />
          <element id="library" level="project" name="Maven: org.mybatis.generator:mybatis-generator-core:1.3.5" />
          <element id="library" level="project" name="Maven: org.apache.commons:commons-dbcp2:2.1.1" />
          <element id="library" level="project" name="Maven: org.apache.commons:commons-pool2:2.4.2" />
          <element id="library" level="project" name="Maven: mysql:mysql-connector-java:5.1.43" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.8.7" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-annotations:2.8.0" />
          <element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-core:2.8.7" />
          <element id="library" level="project" name="Maven: com.alibaba:druid:1.1.2" />
          <element id="library" level="project" name="Maven: org.freemarker:freemarker:2.3.26-incubating" />
        </element>
      </element>
      <element id="directory" name="META-INF">
        <element id="file-copy" path="$PROJECT_DIR$/admin/target/admin/META-INF/MANIFEST.MF" />
      </element>
      <element id="javaee-facet-resources" facet="admin/web/Web" />
    </root>
  </artifact>
</component>


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="main.css" charset="utf-8">
    <title>Prepared for Disaster</title>
  </head>
  <body>
    <main class="app"></main>
    <script src="bundle.js"></script>
  </body>
</html>


text:
package com.lafaspot.jmetrics.common;

import java.lang.reflect.Method;
import java.util.List;

import javax.annotation.Nonnull;
import javax.management.openmbean.CompositeType;
import javax.management.openmbean.OpenDataException;
import javax.management.openmbean.OpenType;

/**
 * CompositeType for monitor class.
 *
 * @author KevinL
 *
 */
public class MetricClassComposite {
    /** All the methods that has metric annotation. */
    @Nonnull
    private final String[] methodNames;
    /** Class CompositeType. */
    private final CompositeType metricClassCompositeType;
    /** Method description. */
    private static final String METHOD_DESCRIPTION = "Method: ";

    /**
     * Constructor.
     *
     * @param className used to Construct type
     * @param metricClassName MetricClass name store in CompositeData type Description
     * @param methods contains metric annotation
     * @param methodCompositeType method CompositeType
     * @throws OpenDataException Create class compositeType fail
     */
    public MetricClassComposite(@Nonnull final String className, @Nonnull final String metricClassName, @Nonnull final List<Method> methods,
            @Nonnull final MetricMethodComposite methodCompositeType) throws OpenDataException {
        final int size = methods.size();

        methodNames = new String[size];
        final String[] methodDescriptions = new String[size];
        @SuppressWarnings("rawtypes")
        final OpenType[] methodTypes = new OpenType[size];
        for (int i = 0; i < size; i++) {
            final Method method = methods.get(i);
            methodNames[i] = method.getName();
            methodDescriptions[i] = METHOD_DESCRIPTION + methodNames[i];
            methodTypes[i] = methodCompositeType.getCompositeType();
        }
        metricClassCompositeType = new CompositeType(className, metricClassName, methodNames, methodDescriptions, methodTypes);
    }

    /**
     * Get the method names as key.
     * @return method array of one monitor
     */
    protected String[] getMethodNames() {
        return methodNames;
    }

    /**
     * Get class compositeType.
     * @return the class CompositeType
     */
    protected CompositeType getCompositeType() {
        return metricClassCompositeType;
    }
}


text:
var gulp = require('gulp');
var gulpif = require('gulp-if');
var browserify = require('gulp-browserify');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
var plumber = require('gulp-plumber');

// set to false to remove source mapping for js files
// and minifcation for css files when used in production
var condition = {
	devMode: true
};

/***************************************************
 *
 *					TERMINAL
 *
 **************************************************/
 var terminal = {
	js: {
		main:		'src/terminal/js/main.js',
		src:		'src/terminal/js/*.js',
		dest:		'build/terminal/',
		destFile:	'terminal.js'
	},
	css: {
		src: 		'src/terminal/css/*.less',
		dest:		'build/terminal/',
		destFile:	'terminal.css'
	}
};

gulp.task('terminal_js', function() {
	gulp.src(terminal.js.main)
	.pipe(plumber())
	.pipe(browserify({
		insertGlobals : true,
		debug : condition.devMode
	}))
	.pipe(rename(terminal.js.destFile))
	.pipe(gulp.dest(terminal.js.dest));
});

gulp.task('terminal_less', function() {
	gulp.src(terminal.css.src)
		.pipe(plumber())
		.pipe(less())
		.pipe(gulpif(!condition.devMode, minifyCSS()))
		.pipe(rename(terminal.css.destFile))
		.pipe(gulp.dest(terminal.css.dest));
});

/***************************************************
 *
 *				PACKAGE Router
 *
 **************************************************/
 var packageRouter = {
	main:		'src/packageRouter/main.js',
	src:		'src/packageRouter/*.js',
	dest:		'build/packageRouter/',
	destFile:	'pkgRouter.js'
};

gulp.task('package_Router', function() {
	gulp.src(packageRouter.main)
	.pipe(plumber())
	.pipe(browserify({
		insertGlobals : true,
		debug : condition.devMode
	}))
	// .pipe(uglify())
	.pipe(rename(packageRouter.destFile))
	.pipe(gulp.dest(packageRouter.dest));
});

/***************************************************
 *
 *					PACKAGES
 *
 **************************************************/
var packages = {
	packageStats: {
		main:		'src/packages/stats/main.js',
		src:		'src/packages/stats/*.js',
		dest:		'build/packages/',
		destFile:	'pkg_stats.js'
	}
};

gulp.task('package_stats', function() {
	gulp.src(packages.packageStats.main)
	.pipe(plumber())
	.pipe(browserify({
		insertGlobals : true,
		debug : condition.devMode
	}))
	// .pipe(uglify())
	.pipe(rename(packages.packageStats.destFile))
	.pipe(gulp.dest(packages.packageStats.dest));
});

/***************************************************
 *
 *					WATCH
 *
 **************************************************/
gulp.task('watch', function() {
	//livereload.listen();
	gulp.watch(terminal.js.src, ['terminal_js']);
	gulp.watch(terminal.css.src, ['terminal_less']);

	gulp.watch(packageRouter.src, ['package_Router']);

	//When you add a new package, make sure to add a new task
	gulp.watch(packages.packageStats.src, ['package_stats']);
});

gulp.task('default', ['watch']);


text:
import os
import shutil
import tempfile

import pytest

from . import helpers
from . import run
from . import refactor

def pytest_addoption(parser):
    parser.addoption(
        "--integration-case-dir",
        default=os.path.join(helpers.test_dir, 'completion'),
        help="Directory in which integration test case files locate.")
    parser.addoption(
        "--refactor-case-dir",
        default=os.path.join(helpers.test_dir, 'refactor'),
        help="Directory in which refactoring test case files locate.")
    parser.addoption(
        "--test-files", "-T", default=[], action='append',
        help=(
            "Specify test files using FILE_NAME[:LINE[,LINE[,...]]]. "
            "For example: -T generators.py:10,13,19. "
            "Note that you can use -m to specify the test case by id."))
    parser.addoption(
        "--thirdparty", action='store_true',
        help="Include integration tests that requires third party modules.")

def parse_test_files_option(opt):
    """
    Parse option passed to --test-files into a key-value pair.

    >>> parse_test_files_option('generators.py:10,13,19')
    ('generators.py', [10, 13, 19])
    """
    opt = str(opt)
    if ':' in opt:
        (f_name, rest) = opt.split(':', 1)
        return (f_name, list(map(int, rest.split(','))))
    else:
        return (opt, [])

def pytest_generate_tests(metafunc):
    """
    :type metafunc: _pytest.python.Metafunc
    """
    test_files = dict(map(parse_test_files_option,
                          metafunc.config.option.test_files))
    if 'case' in metafunc.fixturenames:
        base_dir = metafunc.config.option.integration_case_dir
        thirdparty = metafunc.config.option.thirdparty
        cases = list(run.collect_dir_tests(base_dir, test_files))
        if thirdparty:
            cases.extend(run.collect_dir_tests(
                os.path.join(base_dir, 'thirdparty'), test_files, True))
        metafunc.parametrize('case', cases)
    if 'refactor_case' in metafunc.fixturenames:
        base_dir = metafunc.config.option.refactor_case_dir
        metafunc.parametrize(
            'refactor_case',
            refactor.collect_dir_tests(base_dir, test_files))

@pytest.fixture()
def isolated_jedi_cache(monkeypatch, tmpdir):
    """
    Set `jedi.settings.cache_directory` to a temporary directory during test.

    Same as `clean_jedi_cache`, but create the temporary directory for
    each test case (scope='function').
    """
    from jedi import settings
    monkeypatch.setattr(settings, 'cache_directory', str(tmpdir))

@pytest.fixture(scope='session')
def clean_jedi_cache(request):
    """
    Set `jedi.settings.cache_directory` to a temporary directory during test.

    Note that you can't use built-in `tmpdir` and `monkeypatch`
    fixture here because their scope is 'function', which is not used
    in 'session' scope fixture.

    This fixture is activated in ../pytest.ini.
    """
    from jedi import settings
    old = settings.cache_directory
    tmp = tempfile.mkdtemp(prefix='jedi-test-')
    settings.cache_directory = tmp

    @request.addfinalizer
    def restore():
        settings.cache_directory = old
        shutil.rmtree(tmp)