text:
var InetSocketAddress = Java.type('java.net.InetSocketAddress');

nuklei.echo.capture("ws")
  .thenCompose(function(v) { return nuklei.ws.capture("echo"); })
  .thenCompose(function(v) { return nuklei.ws.capture("http"); })
  .thenCompose(function(v) { return nuklei.http.capture("ws"); })
  .thenCompose(function(v) { return nuklei.http.capture("tcp"); })
  .thenCompose(function(v) { return nuklei.tcp.capture("http"); })
  .thenCompose(function(v) { return nuklei.echo.route("ws"); })
  .thenCompose(function(v) { return nuklei.ws.route("echo"); })
  .thenCompose(function(v) { return nuklei.ws.route("http"); })
  .thenCompose(function(v) { return nuklei.http.route("ws"); })
  .thenCompose(function(v) { return nuklei.http.route("tcp"); })
  .thenCompose(function(v) { return nuklei.tcp.route("http"); })
  .thenCompose(function(v) { return nuklei.echo.bind("ws"); })
  .thenCompose(function(echoRef) { return nuklei.ws.bind("echo", echoRef, "http", null); })
  .thenCompose(function(wsRef) { return nuklei.http.bind("ws", wsRef, "tcp", { ":path": "/" }); })
  .thenCompose(function(httpRef) { return nuklei.tcp.bind("http", httpRef, new InetSocketAddress("localhost", 8080)); })
  .thenAccept(function(tcpRef) { return print('echo bound to ws://localhost:8080/'); })
  .join();


text:
var button = require('./lib/button');
var dom = button.dom;
var asyncJsAdd = button.async;

// Initialize Google +1 component
dom.el.innerHTML = '

';

// If Google+ SDK already exists on page, reparse new components,
// Otherwise, load Google+ SDK
if ( 'gapi' in window ) {
	gapi.plusone.go(dom.bookmarkletComponentWrapEl);
} else {
	asyncJsAdd('https://apis.google.com/js/plusone.js', 'gplusSdk');
}

redpajama_set_name: RedPajamaGithub


text:
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(COMPONENT_EXPORT(UI_WM),
                                       wm::WindowVisibilityAnimationTransition)

DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(COMPONENT_EXPORT(UI_WM), float)

namespace wm {

DEFINE_UI_CLASS_PROPERTY_KEY(bool, kUsesScreenCoordinatesKey, false)
DEFINE_UI_CLASS_PROPERTY_KEY(base::TimeDelta,
                             kWindowVisibilityAnimationDurationKey,
                             base::TimeDelta())
DEFINE_UI_CLASS_PROPERTY_KEY(WindowVisibilityAnimationTransition,
                             kWindowVisibilityAnimationTransitionKey,
                             ANIMATE_BOTH)
DEFINE_UI_CLASS_PROPERTY_KEY(int,
                             kWindowVisibilityAnimationTypeKey,
                             WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT)
DEFINE_UI_CLASS_PROPERTY_KEY(float,
                             kWindowVisibilityAnimationVerticalPositionKey,
                             15.f)
DEFINE_UI_CLASS_PROPERTY_KEY(int32_t, kWindowHidingAnimationCountKey, 0)

}  // namespace wm


text:
package certificates

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/base64"
	"encoding/pem"

	"github.com/pkg/errors"
)

const (
	rsaKeySize = 4096
)

//go:generate mockery --name=CSRProvider
type CSRProvider interface {
	CreateCSR(subject pkix.Name) (string, *rsa.PrivateKey, error)
}

type csrProvider struct {
}

func NewCSRProvider() CSRProvider {
	return &csrProvider{}
}

// CreateCSR generates private key and returns it along with base 64 encoded CSR
func (cp *csrProvider) CreateCSR(subject pkix.Name) (string, *rsa.PrivateKey, error) {
	clusterPrivateKey, err := rsa.GenerateKey(rand.Reader, rsaKeySize)
	if err != nil {
		return "", nil, err
	}

	csr, err := createCSR(subject, clusterPrivateKey)
	if err != nil {
		return "", nil, err
	}

	return base64.StdEncoding.EncodeToString(csr), clusterPrivateKey, nil
}

func createCSR(subject pkix.Name, key *rsa.PrivateKey) ([]byte, error) {
	csrTemplate := x509.CertificateRequest{
		Subject: subject,
	}

	csr, err := x509.CreateCertificateRequest(rand.Reader, &csrTemplate, key)
	if err != nil {
		return nil, errors.Wrap(err, "Failed to create cluster CSR")
	}

	pemEncodedCSR := pem.EncodeToMemory(&pem.Block{
		Type: "CERTIFICATE REQUEST", Bytes: csr,
	})

	return pemEncodedCSR, nil
}


text:
package jme3test.niftygui;

import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.math.Vector3f;
import com.jme3.niftygui.NiftyJmeDisplay;
import com.jme3.scene.Geometry;
import com.jme3.scene.shape.Box;
import de.lessvoid.nifty.Nifty;
import de.lessvoid.nifty.screen.Screen;
import de.lessvoid.nifty.screen.ScreenController;
import java.net.URL;

public class TestNiftyGui extends SimpleApplication implements ScreenController {

    private Nifty nifty;

    public static void main(String[] args){
        TestNiftyGui app = new TestNiftyGui();
        app.setPauseOnLostFocus(false);
        app.start();
    }

    public void simpleInitApp() {
        Box b = new Box(Vector3f.ZERO, 1, 1, 1);
        Geometry geom = new Geometry("Box", b);
        Material mat = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
        mat.setTexture("ColorMap", assetManager.loadTexture("Interface/Logo/Monkey.jpg"));
        geom.setMaterial(mat);
        rootNode.attachChild(geom);

        NiftyJmeDisplay niftyDisplay = new NiftyJmeDisplay(assetManager,
                                                          inputManager,
                                                          audioRenderer,
                                                          guiViewPort);
        nifty = niftyDisplay.getNifty();
        nifty.fromXml("Interface/Nifty/HelloJme.xml", "start", this);

        // attach the nifty display to the gui view port as a processor
        guiViewPort.addProcessor(niftyDisplay);

        // disable the fly cam
//        flyCam.setEnabled(false);
//        flyCam.setDragToRotate(true);
        inputManager.setCursorVisible(true);
    }

    public void bind(Nifty nifty, Screen screen) {
        System.out.println("bind( " + screen.getScreenId() + ")");
    }

    public void onStartScreen() {
        System.out.println("onStartScreen");
    }

    public void onEndScreen() {
        System.out.println("onEndScreen");
    }

    public void quit(){
        nifty.gotoScreen("end");
    }

}


text:
package stanhebben.zenscript.annotations;

import java.lang.annotation.*;

/**
 * Indicates a simple iterable. Annotated class must implement the iterable
 * interface.
 *
 * @author Stan Hebben
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface IterableSimple {

    String value();
}


text:
Template.item.events({
	'click .checkbox': function(e,t) {
		if (Meteor.user()) {
					console.log("clicked");

			if (t.find(".checkbox").checked) {
				Meteor.users.update({_id:Meteor.user()._id}, {$addToSet:{tasks : this._id }});
			} else {
				Meteor.users.update({_id:Meteor.user()._id}, {$pull:{tasks : this._id }});
			}
		} else {
			if (t.find(".checkbox").checked) {
				Session.set(this._id, true);
			} else {
				Session.set(this._id, false);
			}
		}

	}
})

Template.item.helpers({
	getDate : function() {
		//return moment(this.submitted, 'MM-DD-YYYY');
		return (moment(this.submitted)).format("YYYY-MM-DD HH:mm");
		//var d = new Date(this.submitted);
		//return (d.toLocaleDateString() + ', ' + d.toLocaleTimeString());
	}
})

Template.item.index = function() {
	return Items.find().count() - Items.find({_id: {$lte: this._id}}).count() + 1
}

Template.item.viewed = function() {
	if (Meteor.user()) {
		return Meteor.user().tasks.indexOf(this._id) != -1;
	} else {
		return !!Session.get(this._id);
	}

}


text:
(clear)
(watch compilations)
(load global.clp)
(load func.clp)
(load main.clp)
(load urine.clp)
(load opt-daily.clp)
(load gender.clp)
(load weight.clp)
(load condition.clp)
(load exercise.clp)
(reset)
(run)


text:
package org.apache.velocity.runtime.parser.node;

import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;

import org.apache.velocity.context.InternalContextAdapter;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.TemplateInitException;
import org.apache.velocity.runtime.RuntimeServices;
import org.apache.velocity.runtime.log.Log;
import org.apache.velocity.runtime.parser.Parser;
import org.apache.velocity.runtime.parser.Token;

/**
 *
 */
public class SimpleNode implements Node
{
    /** */
    protected RuntimeServices rsvc = null;

    /** */
    protected Log log = null;

    /** */
    protected Node parent;

    /** */
    protected Node[] children;

    /** */
    protected int id;

    /** */
    // TODO - It seems that this field is only valid when parsing, and should not be kept around.
    protected Parser parser;

    /** */
    protected int info; // added

    /** */
    public boolean state;

    /** */
    protected boolean invalid = false;

    /** */
    protected Token first;

    /** */
    protected Token last;

    protected String templateName;

    public RuntimeServices getRuntimeServices()
    {
      return rsvc;
    }

    /**
     * @param i
     */
    public SimpleNode(int i)
    {
        id = i;
    }

    /**
     * @param p
     * @param i
     */
    public SimpleNode(Parser p, int i)
    {
        this(i);
        parser = p;
        templateName = parser.currentTemplateName;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#jjtOpen()
     */
    public void jjtOpen()
    {
        first = parser.getToken(1); // added
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#jjtClose()
     */
    public void jjtClose()
    {
        last = parser.getToken(0); // added
    }

    /**
     * @param t
     */
    public void setFirstToken(Token t)
    {
        this.first = t;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#getFirstToken()
     */
    public Token getFirstToken()
    {
        return first;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#getLastToken()
     */
    public Token getLastToken()
    {
        return last;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#jjtSetParent(org.apache.velocity.runtime.parser.node.Node)
     */
    public void jjtSetParent(Node n)
    {
        parent = n;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#jjtGetParent()
     */
    public Node jjtGetParent()
    {
        return parent;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#jjtAddChild(org.apache.velocity.runtime.parser.node.Node, int)
     */
    public void jjtAddChild(Node n, int i)
    {
        if (children == null)
        {
            children = new Node[i + 1];
        }
        else if (i >= children.length)
        {
            Node c[] = new Node[i + 1];
            System.arraycopy(children, 0, c, 0, children.length);
            children = c;
        }
        children[i] = n;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#jjtGetChild(int)
     */
    public Node jjtGetChild(int i)
    {
        return children[i];
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#jjtGetNumChildren()
     */
    public int jjtGetNumChildren()
    {
        return (children == null) ? 0 : children.length;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#jjtAccept(org.apache.velocity.runtime.parser.node.ParserVisitor, java.lang.Object)
     */
    public Object jjtAccept(ParserVisitor visitor, Object data)
    {
        return visitor.visit(this, data);
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#childrenAccept(org.apache.velocity.runtime.parser.node.ParserVisitor, java.lang.Object)
     */
    public Object childrenAccept(ParserVisitor visitor, Object data)
    {
        if (children != null)
        {
            for (int i = 0; i < children.length; ++i)
            {
                children[i].jjtAccept(visitor, data);
            }
        }
        return data;
    }

    /* You can override these two methods in subclasses of SimpleNode to
        customize the way the node appears when the tree is dumped.  If
        your output uses more than one line you should override
        toString(String), otherwise overriding toString() is probably all
        you need to do. */

    //    public String toString()
    // {
    //    return ParserTreeConstants.jjtNodeName[id];
    // }
    /**
     * @param prefix
     * @return String representation of this node.
     */
    public String toString(String prefix)
    {
        return prefix + toString();
    }

    /**
     * Override this method if you want to customize how the node dumps
     * out its children.
     *
     * @param prefix
     */
    public void dump(String prefix)
    {
        System.out.println(toString(prefix));
        if (children != null)
        {
            for (int i = 0; i < children.length; ++i)
            {
                SimpleNode n = (SimpleNode) children[i];
                if (n != null)
                {
                    n.dump(prefix + " ");
                }
            }
        }
    }

    /**
     * Return a string that tells the current location of this node.
     */
    protected String getLocation(InternalContextAdapter context)
    {
        return Log.formatFileString(this);
    }

    // All additional methods

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#literal()
     */
    public String literal()
    {
        // if we have only one string, just return it and avoid
        // buffer allocation. VELOCITY-606
        if (first == last)
        {
            return NodeUtils.tokenLiteral(first);
        }

        Token t = first;
        StringBuilder sb = new StringBuilder(NodeUtils.tokenLiteral(t));
        while (t != last)
        {
            t = t.next;
            sb.append(NodeUtils.tokenLiteral(t));
        }
        return sb.toString();
    }

    /**
     * @throws TemplateInitException
     * @see org.apache.velocity.runtime.parser.node.Node#init(org.apache.velocity.context.InternalContextAdapter, java.lang.Object)
     */
    public Object init( InternalContextAdapter context, Object data) throws TemplateInitException
    {
        /*
         * hold onto the RuntimeServices
         */

        rsvc = (RuntimeServices) data;
        log = rsvc.getLog();

        int i, k = jjtGetNumChildren();

        for (i = 0; i < k; i++)
        {
            jjtGetChild(i).init( context, data);
        }

        return data;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#evaluate(org.apache.velocity.context.InternalContextAdapter)
     */
    public boolean evaluate( InternalContextAdapter  context)
        throws MethodInvocationException
    {
        return false;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#value(org.apache.velocity.context.InternalContextAdapter)
     */
    public Object value( InternalContextAdapter context)
        throws MethodInvocationException
    {
        return null;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#render(org.apache.velocity.context.InternalContextAdapter, java.io.Writer)
     */
    public boolean render( InternalContextAdapter context, Writer writer)
        throws IOException, MethodInvocationException, ParseErrorException, ResourceNotFoundException
    {
        int i, k = jjtGetNumChildren();

        for (i = 0; i < k; i++)
            jjtGetChild(i).render(context, writer);

        return true;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#execute(java.lang.Object, org.apache.velocity.context.InternalContextAdapter)
     */
    public Object execute(Object o, InternalContextAdapter context)
      throws MethodInvocationException
    {
        return null;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#getType()
     */
    public int getType()
    {
        return id;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#setInfo(int)
     */
    public void setInfo(int info)
    {
        this.info = info;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#getInfo()
     */
    public int getInfo()
    {
        return info;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#setInvalid()
     */
    public void setInvalid()
    {
        invalid = true;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#isInvalid()
     */
    public boolean isInvalid()
    {
        return invalid;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#getLine()
     */
    public int getLine()
    {
        return first.beginLine;
    }

    /**
     * @see org.apache.velocity.runtime.parser.node.Node#getColumn()
     */
    public int getColumn()
    {
        return first.beginColumn;
    }

    /**
     * @since 1.5
     */
    public String toString()
    {
        StringBuilder tokens = new StringBuilder();

        for (Token t = getFirstToken(); t != null; )
        {
            tokens.append("[").append(t.image).append("]");
            if (t.next != null)
            {
                if (t.equals(getLastToken()))
                {
                    break;
                }
                else
                {
                    tokens.append(", ");
                }
            }
            t = t.next;
        }

		return "SimpleNode [id=" + id + ", info=" + info + ", invalid="
		        + invalid + ", children=" + Arrays.toString(children)
		        + ", tokens=" + tokens + "]";
    }

	public String getTemplateName()
    {
      return templateName;
    }
}


text:
package iface

import (
	"context"
	"errors"
	"io"
	"time"

	options "github.com/ipfs/go-ipfs/core/coreapi/interface/options"

	ipld "gx/ipfs/QmNwUEK7QbwSqyKBu3mMtToo8SUc6wQJ7gdZq4gGGJqfnf/go-ipld-format"
	cid "gx/ipfs/QmeSrf6pzut73u6zLQkRFQ3ygt3k6XFT2kjdYP8Tnkwwyg/go-cid"
)

// Path is a generic wrapper for paths used in the API. A path can be resolved
// to a CID using one of Resolve functions in the API.
type Path interface {
	String() string
	Cid() *cid.Cid
	Root() *cid.Cid
	Resolved() bool
}

// TODO: should we really copy these?
//       if we didn't, godoc would generate nice links straight to go-ipld-format
type Node ipld.Node
type Link ipld.Link

type Reader interface {
	io.ReadSeeker
	io.Closer
}

type IpnsEntry interface {
	Name() string
	Value() Path
}

type Key interface {
	Name() string
	Path() Path
}

// CoreAPI defines an unified interface to IPFS for Go programs.
type CoreAPI interface {
	// Unixfs returns an implementation of Unixfs API
	Unixfs() UnixfsAPI
	Dag() DagAPI
	Name() NameAPI
	Key() KeyAPI

	// ResolvePath resolves the path using Unixfs resolver
	ResolvePath(context.Context, Path) (Path, error)

	// ResolveNode resolves the path (if not resolved already) using Unixfs
	// resolver, gets and returns the resolved Node
	ResolveNode(context.Context, Path) (Node, error)
}

// UnixfsAPI is the basic interface to immutable files in IPFS
type UnixfsAPI interface {
	// Add imports the data from the reader into merkledag file
	Add(context.Context, io.Reader) (Path, error)

	// Cat returns a reader for the file
	Cat(context.Context, Path) (Reader, error)

	// Ls returns the list of links in a directory
	Ls(context.Context, Path) ([]*Link, error)
}

// DagAPI specifies the interface to IPLD
type DagAPI interface {
	// Put inserts data using specified format and input encoding.
	// Unless used with WithCodec or WithHash, the defaults "dag-cbor" and
	// "sha256" are used.
	Put(ctx context.Context, src io.Reader, opts ...options.DagPutOption) (Path, error)

	// WithInputEnc is an option for Put which specifies the input encoding of the
	// data. Default is "json", most formats/codecs support "raw"
	WithInputEnc(enc string) options.DagPutOption

	// WithCodec is an option for Put which specifies the multicodec to use to
	// serialize the object. Default is cid.DagCBOR (0x71)
	WithCodec(codec uint64) options.DagPutOption

	// WithHash is an option for Put which specifies the multihash settings to use
	// when hashing the object. Default is based on the codec used
	// (mh.SHA2_256 (0x12) for DagCBOR). If mhLen is set to -1, default length for
	// the hash will be used
	WithHash(mhType uint64, mhLen int) options.DagPutOption

	// Get attempts to resolve and get the node specified by the path
	Get(ctx context.Context, path Path) (Node, error)

	// Tree returns list of paths within a node specified by the path.
	Tree(ctx context.Context, path Path, opts ...options.DagTreeOption) ([]Path, error)

	// WithDepth is an option for Tree which specifies maximum depth of the
	// returned tree. Default is -1 (no depth limit)
	WithDepth(depth int) options.DagTreeOption
}

// NameAPI specifies the interface to IPNS.
//
// IPNS is a PKI namespace, where names are the hashes of public keys, and the
// private key enables publishing new (signed) values. In both publish and
// resolve, the default name used is the node's own PeerID, which is the hash of
// its public key.
//
// You can use .Key API to list and generate more names and their respective keys.
type NameAPI interface {
	// Publish announces new IPNS name
	Publish(ctx context.Context, path Path, opts ...options.NamePublishOption) (IpnsEntry, error)

	// WithValidTime is an option for Publish which specifies for how long the
	// entry will remain valid. Default value is 24h
	WithValidTime(validTime time.Duration) options.NamePublishOption

	// WithKey is an option for Publish which specifies the key to use for
	// publishing. Default value is "self" which is the node's own PeerID.
	// The key parameter must be either PeerID or keystore key alias.
	//
	// You can use KeyAPI to list and generate more names and their respective keys.
	WithKey(key string) options.NamePublishOption

	// Resolve attempts to resolve the newest version of the specified name
	Resolve(ctx context.Context, name string, opts ...options.NameResolveOption) (Path, error)

	// WithRecursive is an option for Resolve which specifies whether to perform a
	// recursive lookup. Default value is false
	WithRecursive(recursive bool) options.NameResolveOption

	// WithLocal is an option for Resolve which specifies if the lookup should be
	// offline. Default value is false
	WithLocal(local bool) options.NameResolveOption

	// WithCache is an option for Resolve which specifies if cache should be used.
	// Default value is true
	WithCache(cache bool) options.NameResolveOption
}

// KeyAPI specifies the interface to Keystore
type KeyAPI interface {
	// Generate generates new key, stores it in the keystore under the specified
	// name and returns a base58 encoded multihash of it's public key
	Generate(ctx context.Context, name string, opts ...options.KeyGenerateOption) (Key, error)

	// WithType is an option for Generate which specifies which algorithm
	// should be used for the key. Default is options.RSAKey
	//
	// Supported key types:
	// * options.RSAKey
	// * options.Ed25519Key
	WithType(algorithm string) options.KeyGenerateOption

	// WithSize is an option for Generate which specifies the size of the key to
	// generated. Default is -1
	//
	// value of -1 means 'use default size for key type':
	//  * 2048 for RSA
	WithSize(size int) options.KeyGenerateOption

	// Rename renames oldName key to newName. Returns the key and whether another
	// key was overwritten, or an error
	Rename(ctx context.Context, oldName string, newName string, opts ...options.KeyRenameOption) (Key, bool, error)

	// WithForce is an option for Rename which specifies whether to allow to
	// replace existing keys.
	WithForce(force bool) options.KeyRenameOption

	// List lists keys stored in keystore
	List(ctx context.Context) ([]Key, error)

	// Remove removes keys from keystore. Returns ipns path of the removed key
	Remove(ctx context.Context, name string) (Path, error)
}

// type ObjectAPI interface {
// 	New() (cid.Cid, Object)
// 	Get(string) (Object, error)
// 	Links(string) ([]*Link, error)
// 	Data(string) (Reader, error)
// 	Stat(string) (ObjectStat, error)
// 	Put(Object) (cid.Cid, error)
// 	SetData(string, Reader) (cid.Cid, error)
// 	AppendData(string, Data) (cid.Cid, error)
// 	AddLink(string, string, string) (cid.Cid, error)
// 	RmLink(string, string) (cid.Cid, error)
// }

// type ObjectStat struct {
// 	Cid            cid.Cid
// 	NumLinks       int
// 	BlockSize      int
// 	LinksSize      int
// 	DataSize       int
// 	CumulativeSize int
// }

var ErrIsDir = errors.New("object is a directory")
var ErrOffline = errors.New("can't resolve, ipfs node is offline")


text:
package model;

public class pointtransfer {
	private int PointTransfer_id;
	private String PointTransfer_Time;
	private int PointTransfer_Points;
	private int PointTransfer_Type;
	private int User_id;
	private int Seller_id;
	private String SellerPointSystem_Username;

	public int getPointTransfer_id() {
		return PointTransfer_id;
	}
	public void setPointTransfer_id(int PointTransfer_id) {
		this.PointTransfer_id = PointTransfer_id;
	}

	public String getPointTransfer_Time() {
		return PointTransfer_Time;
	}
	public void setPointTransfer_Time(String PointTransfer_Time) {
		this.PointTransfer_Time = PointTransfer_Time;
	}

	public int getPointTransfer_Points() {
		return PointTransfer_Points;
	}
	public void setPointTransfer_Points(int PointTransfer_Points) {
		this.PointTransfer_Points = PointTransfer_Points;
	}

	public int getPointTransfer_Type() {
		return PointTransfer_Type;
	}
	public void setPointTransfer_Type(int PointTransfer_Type) {
		this.PointTransfer_Type = PointTransfer_Type;
	}

	public int getUser_id() {
		return User_id;
	}
	public void setUser_id(int User_id) {
		this.User_id = User_id;
	}

	public int getSeller_id() {
		return Seller_id;
	}
	public void setSeller_id(int Seller_id) {
		this.Seller_id = Seller_id;
	}

	public String getSellerPointSystem_Username() {
		return SellerPointSystem_Username;
	}
	public void setSellerPointSystem_Username(String SellerPointSystem_Username) {
		this.SellerPointSystem_Username = SellerPointSystem_Username;
	}
}


text:
int WINAPI DllEntryPoint(HINSTANCE, DWORD, PVOID){
    return 1;
}
//---------------------------------------------------------------------------
extern "C" __declspec(dllexport) BOOL PASCAL TransferJPEG(
        PCSTR jpegFile,
        PCSTR bmpFile){
    // attempts to xfer jpegFile to destination as a BMP
    TJPEGImage *bmp1 = new TJPEGImage();
    Graphics::TBitmap *bmp2 = new Graphics::TBitmap();
    BOOL bRet = TRUE;
    try{
        bmp1->LoadFromFile(jpegFile);
        bmp2->Assign(bmp1);
        bmp2->SaveToFile(bmpFile);
    }
    catch(...){
        bRet = FALSE;
    }
    delete bmp2;
    delete bmp1;
    return bRet;
}
//---------------------------------------------------------------------------


text:
<?xml version="1.0"?>
<!--

-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
    <default>
        <dev>
            <translate_inline>
                <active>0</active>
                <active_admin>0</active_admin>
                <invalid_caches>
                    <block_html />
                </invalid_caches>
            </translate_inline>
            <js>
                <translate_strategy>dictionary</translate_strategy>
            </js>
        </dev>
    </default>
</config>


text:
/**
 * @class CssPreprocessorTasks
 * @param {Object} gulp The Gulp module
 * @param {Object} $ The gulp-load-plugins module
 * @param {Object} config Gulp configuration object
 * @param PRODUCTION
 * @returns {{scss: LessTasks.scss}}
 * @constructor
 */
function CssPreprocessorTasks(gulp, $, config, PRODUCTION) {
  'use strict';

  var util = require('./util')($);

  /**
   * Compile the LESS files into app.css and app.min.css,
   * applying autoprefixer, csscomb (https://github.com/csscomb/csscomb.js), sourcemaps
   * and copy them to the dist folder.
   * @method less
   * @memberof LessTasks
   * @param callback
   */
  function scss(callback) {
    gulp.src(config.paths.scss.app)
      .pipe($.plumber({
        errorHandler: function (error) {
          $.util.log($.util.colors.red('Error (' + error.plugin + '): ' + error.message));
          this.emit('end');
        }}))
      .pipe($.replace('###version###', util.getVersionDate()))
      .pipe($.if(PRODUCTION, $.rename({ suffix: '.min' })))
      .pipe($.sourcemaps.init())
      .pipe($.sass()) // .on('error', $.sass.logError))
      .pipe($.autoprefixer(config.autoprefixer))
      //   // .pipe($.csscomb('.csscomb.json'))
      .pipe($.if(PRODUCTION, $.cssnano()))
      .pipe($.sourcemaps.write('./'))
      .pipe(gulp.dest('./dist/assets/css'));

    callback();
  }

  return {
    scss: scss
  };

}

module.exports = CssPreprocessorTasks;


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Frankenia tetrapetala Labill.

### Remarks
null


text: assert_ok "$FLOW" status .


text:
package org.springframework.security.core.authority.mapping;

import org.springframework.security.core.GrantedAuthority;

import java.util.*;

/**
 * Mapping interface which can be injected into the authentication layer to convert the
 * authorities loaded from storage into those which will be used in the {@code Authentication} object.
 *
 * @author Luke Taylor
 */
public interface GrantedAuthoritiesMapper {
    Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <issue id="HardcodedDebugMode" severity="warning" />
</lint>


text:
module Scoring (scoreTypeBinder, scoreValueBinder) where

import Data.Maybe (fromJust)
import Env as E
import Obj
import qualified Set
import Types
import TypesToC

-- | Scoring of types.
-- | The score is used for sorting the bindings before emitting them.
-- | A lower score means appearing earlier in the emitted file.
scoreTypeBinder :: TypeEnv -> Env -> Binder -> (Int, Binder)
scoreTypeBinder typeEnv env b@(Binder _ (XObj (Lst (XObj x _ _ : XObj (Sym _ _) _ _ : _)) _ _)) =
  case x of
    Defalias aliasedType ->
      let selfName = ""
       in -- we add 1 here because deftypes generate aliases that
          -- will at least have the same score as the type, but
          -- need to come after. The increment represents this dependency
          (depthOfType typeEnv Set.empty selfName aliasedType + 1, b)
    Deftype s -> depthOfStruct s
    DefSumtype s -> depthOfStruct s
    ExternalType _ -> (0, b)
    _ -> (500, b)
  where
    depthOfStruct (StructTy (ConcreteNameTy path@(SymPath _ name)) varTys) =
      case E.getTypeBinder typeEnv name <> findTypeBinder env path of
        Right (Binder _ typedef) -> (depthOfDeftype typeEnv Set.empty typedef varTys + 1, b)
        -- TODO: This function should return (Either ScoringError (Int,
        -- Binder)) instead of calling error.
        Left e -> error (show e)
    depthOfStruct _ = error "depthofstruct"
scoreTypeBinder _ _ b@(Binder _ (XObj (Mod _ _) _ _)) =
  (1000, b)
scoreTypeBinder _ _ x = error ("Can't score: " ++ show x)

depthOfDeftype :: TypeEnv -> Set.Set Ty -> XObj -> [Ty] -> Int
depthOfDeftype typeEnv visited (XObj (Lst (_ : XObj (Sym (SymPath path selfName) _) _ _ : rest)) _ _) varTys =
  case concatMap expandCase rest of
    [] -> 100
    xs -> maximum xs
  where
    depthsFromVarTys = map (depthOfType typeEnv visited (concat (path ++ [selfName]))) varTys
    expandCase :: XObj -> [Int]
    expandCase (XObj (Arr arr) _ _) =
      let members = memberXObjsToPairs arr
          depthsFromMembers = map (depthOfType typeEnv visited (concat (path ++ [selfName])) . snd) members
       in depthsFromMembers ++ depthsFromVarTys
    expandCase (XObj (Lst [XObj {}, XObj (Arr sumtypeCaseTys) _ _]) _ _) =
      let depthsFromCaseTys = map (depthOfType typeEnv visited (concat (path ++ [selfName])) . fromJust . xobjToTy) sumtypeCaseTys
       in depthsFromCaseTys ++ depthsFromVarTys
    expandCase (XObj (Sym _ _) _ _) =
      []
    expandCase _ = error "Malformed case in typedef."
depthOfDeftype _ _ xobj _ =
  error ("Can't get dependency depth from " ++ show xobj)

depthOfType :: TypeEnv -> Set.Set Ty -> String -> Ty -> Int
depthOfType typeEnv visited selfName theType =
  if theType `elem` visited
    then 0
    else visitType theType + 1
  where
    visitType :: Ty -> Int
    visitType t@(StructTy _ varTys) = depthOfStructType t varTys
    visitType (FuncTy argTys retTy ltTy) =
      -- trace ("Depth of args of " ++ show argTys ++ ": " ++ show (map (visitType . Just) argTys))
      --
      -- The `+ 1` in the function clause below is an important band-aid.
      -- Here's the issue:
      --   When we resolve declarations, some types may reference other types
      --   that have not been scored yet. When that happens, we add 500 to the
      --   binder to ensure it appears later than the types we'll resolve later
      --   on.
      --
      --   However, this means that function types can be tied w/ such binders
      --   when this case holds since they only took the maximum of their type
      --   members. e.g. both a struct and its functions might be
      --   scored "504" and we might incorrectly emit the functions before the
      --   struct.
      --
      --   Since functions are *always* dependent on the types in their
      --   signature, add 1 to ensure they appear after those types in all
      --   possible scenarios.
      --
      --   TODO: Should we find a more robust solution that explicitly
      --   accounts for unresolved types and scores based on these rather than
      --   relying on our hardcoded adjustments being correct?
      maximum (visitType ltTy : visitType retTy : fmap visitType argTys) + 1
    visitType (PointerTy p) = visitType p
    visitType (RefTy r lt) = max (visitType r) (visitType lt)
    visitType _ = 1
    depthOfStructType :: Ty -> [Ty] -> Int
    depthOfStructType struct varTys =
      1
        + case getStructName struct of
          "Array" -> depthOfVarTys
          _
            | tyToC struct == selfName -> 1
            | otherwise ->
              case E.getTypeBinder typeEnv s of
                Right (Binder _ typedef) -> depthOfDeftype typeEnv (Set.insert theType visited) typedef varTys
                Left _ ->
                  --trace ("Unknown type: " ++ name) $
                  -- Two problems here:
                  --
                  -- 1. generic types don't generate their definition in time
                  -- so we get nothing for those. Instead, let's try the type
                  -- vars.
                  -- 2. If a type wasn't found type may also refer to a type defined in another
                  -- module that's not yet been scored. To be safe, add 500
                  500 + depthOfVarTys
      where
        s = getNameFromStructName (getStructName struct)
        depthOfVarTys =
          case fmap (depthOfType typeEnv visited (getStructName struct)) varTys of
            [] -> 1
            xs -> maximum xs + 1

-- | Scoring of value bindings ('def' and 'defn')
-- | The score is used for sorting the bindings before emitting them.
-- | A lower score means appearing earlier in the emitted file.
scoreValueBinder :: Env -> Set.Set SymPath -> Binder -> (Int, Binder)
scoreValueBinder _ _ binder@(Binder _ (XObj (Lst (XObj (External _) _ _ : _)) _ _)) =
  (0, binder)
scoreValueBinder globalEnv visited binder@(Binder _ (XObj (Lst [XObj Def _ _, XObj (Sym _ Symbol) _ _, body]) _ _)) =
  (scoreBody globalEnv visited body, binder)
scoreValueBinder globalEnv visited binder@(Binder _ (XObj (Lst [XObj (Defn _) _ _, XObj (Sym _ Symbol) _ _, _, body]) _ _)) =
  (scoreBody globalEnv visited body, binder)
scoreValueBinder _ _ binder =
  (0, binder)

scoreBody :: Env -> Set.Set SymPath -> XObj -> Int
scoreBody globalEnv visited = visit
  where
    visit xobj =
      case xobjObj xobj of
        (Lst _) ->
          visitList xobj
        (Arr _) ->
          visitArray xobj
        (Sym path (LookupGlobal _ _)) ->
          if Set.member path visited
            then 0
            else case E.searchValueBinder globalEnv path of
              Right foundBinder ->
                let (score, _) = scoreValueBinder globalEnv (Set.insert path visited) foundBinder
                 in score + 1
              Left e ->
                error (show e)
        _ -> 0
    visitList (XObj (Lst []) _ _) =
      0
    visitList (XObj (Lst xobjs) _ _) =
      maximum (fmap visit xobjs)
    visitList _ = error "visitlist"
    visitArray (XObj (Arr []) _ _) =
      0
    visitArray (XObj (Arr xobjs) _ _) =
      maximum (fmap visit xobjs)
    visitArray _ = error "visitarray"


text:
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "uvkc/vulkan/device.h"

#include <cstdint>
#include <memory>

#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "uvkc/base/status.h"
#include "uvkc/vulkan/image.h"
#include "uvkc/vulkan/status_util.h"
#include "uvkc/vulkan/timestamp_query_pool.h"

namespace uvkc {
namespace vulkan {

absl::StatusOr<std::unique_ptr<Device>> Device::Create(
    VkPhysicalDevice physical_device, uint32_t queue_family_index,
    uint32_t valid_timestamp_bits, uint32_t nanoseconds_per_timestamp_value,
    VkDevice device, const DynamicSymbols &symbols) {
  VkCommandPoolCreateInfo create_info = {};
  create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  create_info.pNext = nullptr;
  create_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  create_info.queueFamilyIndex = queue_family_index;

  VkCommandPool command_pool = VK_NULL_HANDLE;
  VK_RETURN_IF_ERROR(symbols.vkCreateCommandPool(
      device, &create_info, /*pAllocator=*/nullptr, &command_pool));

  return absl::WrapUnique(new Device(
      device, physical_device, queue_family_index, valid_timestamp_bits,
      nanoseconds_per_timestamp_value, command_pool, symbols));
}

Device::~Device() {
  symbols_.vkDeviceWaitIdle(device_);
  symbols_.vkDestroyCommandPool(device_, command_pool_, /*pAllocator=*/nullptr);
  symbols_.vkDestroyDevice(device_, /*pAllocator=*/nullptr);
}

absl::StatusOr<std::unique_ptr<Buffer>> Device::CreateBuffer(
    VkBufferUsageFlags usage_flags, VkMemoryPropertyFlags memory_flags,
    VkDeviceSize size_in_bytes) {
  VkBufferCreateInfo create_info = {};
  create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  create_info.pNext = nullptr;
  create_info.flags = 0;
  create_info.size = size_in_bytes;
  create_info.usage = usage_flags;
  create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;

  VkBuffer buffer = VK_NULL_HANDLE;
  VK_RETURN_IF_ERROR(symbols_.vkCreateBuffer(device_, &create_info,
                                             /*pAllocator=*/nullptr, &buffer));

  // Get memory requirements for the buffer
  VkMemoryRequirements memory_requirements;
  symbols_.vkGetBufferMemoryRequirements(device_, buffer, &memory_requirements);

  // Allocate memory for the buffer
  UVKC_ASSIGN_OR_RETURN(VkDeviceMemory memory,
                        AllocateMemory(memory_requirements, memory_flags));

  // Bind the memory to the buffer
  VK_RETURN_IF_ERROR(
      symbols_.vkBindBufferMemory(device_, buffer, memory, /*memoryOffset=*/0));

  return std::make_unique<Buffer>(device_, memory, buffer, symbols_);
}

absl::StatusOr<std::unique_ptr<Image>> Device::CreateImage(
    VkImageUsageFlags usage_flags, VkMemoryPropertyFlags memory_flags,
    VkImageType image_type, VkFormat image_format, VkExtent3D dimensions,
    VkImageTiling image_tiling, VkImageViewType view_type) {
  VkImageCreateInfo create_info = {};
  create_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  create_info.pNext = nullptr;
  create_info.flags = 0;
  create_info.imageType = image_type;
  create_info.format = image_format;
  create_info.extent = dimensions;
  create_info.mipLevels = 1;
  create_info.arrayLayers = 1;
  create_info.samples = VK_SAMPLE_COUNT_1_BIT;
  create_info.tiling = image_tiling;
  create_info.usage = usage_flags;
  create_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  create_info.queueFamilyIndexCount = 0;
  create_info.pQueueFamilyIndices = nullptr;
  create_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;

  VkImage image = VK_NULL_HANDLE;
  VK_RETURN_IF_ERROR(symbols_.vkCreateImage(device_, &create_info,
                                            /*allocator=*/nullptr, &image));

  // Get memory requirements for the image
  VkMemoryRequirements memory_requirements;
  symbols_.vkGetImageMemoryRequirements(device_, image, &memory_requirements);

  // Allocate memory for the image
  UVKC_ASSIGN_OR_RETURN(VkDeviceMemory memory,
                        AllocateMemory(memory_requirements, memory_flags));

  // Bind the memory to the image
  VK_RETURN_IF_ERROR(
      symbols_.vkBindImageMemory(device_, image, memory, /*memoryOffset=*/0));

  // Create image view for the image
  VkImageViewCreateInfo view_create_info = {};
  view_create_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  view_create_info.pNext = nullptr;
  view_create_info.flags = 0;
  view_create_info.image = image;
  view_create_info.viewType = view_type;
  view_create_info.format = image_format;
  view_create_info.components = {
      VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY,
      VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY};
  view_create_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  view_create_info.subresourceRange.baseMipLevel = 0;
  view_create_info.subresourceRange.levelCount = 1;
  view_create_info.subresourceRange.baseArrayLayer = 0;
  view_create_info.subresourceRange.layerCount = 1;

  VkImageView view = VK_NULL_HANDLE;
  VK_RETURN_IF_ERROR(symbols_.vkCreateImageView(device_, &view_create_info,
                                                /*allocator=*/nullptr, &view));

  return std::make_unique<Image>(device_, memory, image, view, symbols_);
}

absl::StatusOr<std::unique_ptr<Sampler>> Device::CreateSampler() {
  VkSamplerCreateInfo create_info = {};
  create_info.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  create_info.pNext = nullptr;
  create_info.flags = 0;
  create_info.magFilter = VK_FILTER_NEAREST;
  create_info.minFilter = VK_FILTER_NEAREST;
  create_info.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST;
  create_info.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
  create_info.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
  create_info.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE;
  create_info.mipLodBias = 0.0f;
  create_info.anisotropyEnable = VK_FALSE;
  create_info.maxAnisotropy = 0.0f;
  create_info.compareEnable = VK_FALSE;
  create_info.compareOp = VK_COMPARE_OP_NEVER;
  create_info.minLod = 0.0f;
  create_info.maxLod = 0.0f;
  create_info.borderColor = VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK;
  create_info.unnormalizedCoordinates = VK_TRUE;

  VkSampler sampler = VK_NULL_HANDLE;
  VK_RETURN_IF_ERROR(symbols_.vkCreateSampler(
      device_, &create_info, /*pAllocator=*/nullptr, &sampler));
  return std::make_unique<Sampler>(device_, sampler, symbols_);
}

absl::StatusOr<std::unique_ptr<ShaderModule>> Device::CreateShaderModule(
    const uint32_t *spirv_data, size_t spirv_size) {
  return ShaderModule::Create(device_, spirv_data, spirv_size, symbols_);
}

absl::StatusOr<std::unique_ptr<Pipeline>> Device::CreatePipeline(
    const ShaderModule &shader_module, const char *entry_point,
    absl::Span<Pipeline::SpecConstant> spec_constants) {
  return Pipeline::Create(device_, shader_module, entry_point, spec_constants,
                          symbols_);
}

absl::StatusOr<std::unique_ptr<DescriptorPool>> Device::CreateDescriptorPool(
    const ShaderModule &shader_module) {
  auto pool_sizes = shader_module.CalculateDescriptorPoolSize();
  return DescriptorPool::Create(device_, shader_module.num_sets(),
                                {pool_sizes.data(), pool_sizes.size()},
                                symbols_);
}

absl::Status Device::AttachBufferToDescriptor(
    const ShaderModule &shader_module,
    const std::unordered_map<VkDescriptorSetLayout, VkDescriptorSet>
        &layout_set_map,
    absl::Span<const Device::BoundBuffer> bound_buffers) {
  std::vector<VkDescriptorBufferInfo> buffer_infos(bound_buffers.size());
  std::vector<VkWriteDescriptorSet> write_sets(bound_buffers.size());
  for (int i = 0; i < bound_buffers.size(); ++i) {
    const auto &descriptor = bound_buffers[i];
    auto &info = buffer_infos[i];
    auto &write = write_sets[i];

    info.buffer = descriptor.buffer->buffer();
    info.offset = 0;
    info.range = VK_WHOLE_SIZE;

    UVKC_ASSIGN_OR_RETURN(VkDescriptorSetLayout set_layout,
                          shader_module.GetDescriptorSetLayout(descriptor.set));
    UVKC_ASSIGN_OR_RETURN(const auto *binding_info,
                          shader_module.GetDescriptorSetLayoutBinding(
                              descriptor.set, descriptor.binding));

    write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
    write.pNext = nullptr;
    write.dstSet = layout_set_map.at(set_layout);
    write.dstBinding = descriptor.binding;
    write.dstArrayElement = 0;
    write.descriptorCount = 1;
    write.descriptorType = binding_info->descriptorType;
    write.pImageInfo = nullptr;
    write.pBufferInfo = &info;
    write.pTexelBufferView = nullptr;
  }

  symbols_.vkUpdateDescriptorSets(device_, write_sets.size(), write_sets.data(),
                                  /*descriptorCopyCount=*/0,
                                  /*pDescriptorCopies=*/nullptr);
  return absl::OkStatus();
}

absl::Status Device::AttachImageToDescriptor(
    const ShaderModule &shader_module,
    const std::unordered_map<VkDescriptorSetLayout, VkDescriptorSet>
        &layout_set_map,
    absl::Span<const Device::BoundImage> bound_images) {
  std::vector<VkDescriptorImageInfo> image_infos(bound_images.size());
  std::vector<VkWriteDescriptorSet> write_sets(bound_images.size());
  for (int i = 0; i < bound_images.size(); ++i) {
    const auto &descriptor = bound_images[i];
    auto &info = image_infos[i];
    auto &write = write_sets[i];

    if (descriptor.sampler) info.sampler = descriptor.sampler->sampler();
    info.imageView = descriptor.image->image_view();
    info.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;

    UVKC_ASSIGN_OR_RETURN(VkDescriptorSetLayout set_layout,
                          shader_module.GetDescriptorSetLayout(descriptor.set));
    UVKC_ASSIGN_OR_RETURN(const auto *binding_info,
                          shader_module.GetDescriptorSetLayoutBinding(
                              descriptor.set, descriptor.binding));

    write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
    write.pNext = nullptr;
    write.dstSet = layout_set_map.at(set_layout);
    write.dstBinding = descriptor.binding;
    write.dstArrayElement = 0;
    write.descriptorCount = 1;
    write.descriptorType = binding_info->descriptorType;
    write.pImageInfo = &info;
    write.pBufferInfo = nullptr;
    write.pTexelBufferView = nullptr;
  }

  symbols_.vkUpdateDescriptorSets(device_, write_sets.size(), write_sets.data(),
                                  /*descriptorCopyCount=*/0,
                                  /*pDescriptorCopies=*/nullptr);
  return absl::OkStatus();
}

absl::StatusOr<std::unique_ptr<CommandBuffer>> Device::AllocateCommandBuffer() {
  VkCommandBufferAllocateInfo allocate_info = {};
  allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  allocate_info.pNext = nullptr;
  allocate_info.commandPool = command_pool_;
  allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  allocate_info.commandBufferCount = 1;

  VkCommandBuffer command_buffer = VK_NULL_HANDLE;
  VK_RETURN_IF_ERROR(symbols_.vkAllocateCommandBuffers(device_, &allocate_info,
                                                       &command_buffer));
  return std::make_unique<CommandBuffer>(device_, command_buffer, symbols_);
}

absl::Status Device::ResetCommandPool() {
  return VkResultToStatus(symbols_.vkResetCommandPool(
      device_, command_pool_, VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT));
}

absl::StatusOr<std::unique_ptr<TimestampQueryPool>>
Device::CreateTimestampQueryPool(uint32_t query_count) {
  return TimestampQueryPool::Create(device_, valid_timestamp_bits_,
                                    nanoseconds_per_timestamp_value_,
                                    query_count, symbols_);
}

absl::Status Device::QueueSubmitAndWait(const CommandBuffer &command_buffer) {
  VkFenceCreateInfo fence_create_info = {};
  fence_create_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  fence_create_info.pNext = nullptr;
  fence_create_info.flags = 0;

  VkFence fence = VK_NULL_HANDLE;
  VK_RETURN_IF_ERROR(symbols_.vkCreateFence(device_, &fence_create_info,
                                            /*pALlocator=*/nullptr, &fence));

  VkCommandBuffer cmdbuf = command_buffer.command_buffer();
  VkSubmitInfo submit_info = {};
  submit_info.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  submit_info.commandBufferCount = 1;
  submit_info.pCommandBuffers = &cmdbuf;

  VK_RETURN_IF_ERROR(symbols_.vkQueueSubmit(queue_, 1, &submit_info, fence));

  VK_RETURN_IF_ERROR(symbols_.vkWaitForFences(device_, /*fenceCount=*/1, &fence,
                                              /*waitAll=*/true,
                                              /*timeout=*/UINT64_MAX));

  symbols_.vkDestroyFence(device_, fence, /*pAllocator=*/nullptr);
  return absl::OkStatus();
}

Device::Device(VkDevice device, VkPhysicalDevice physical_device,
               uint32_t queue_family_index, uint32_t valid_timestamp_bits,
               uint32_t nanoseconds_per_timestamp_value,
               VkCommandPool command_pool, const DynamicSymbols &symbols)
    : device_(device),
      physical_device_(physical_device),
      memory_properties_(),
      queue_(VK_NULL_HANDLE),
      queue_family_index_(queue_family_index),
      valid_timestamp_bits_(valid_timestamp_bits),
      nanoseconds_per_timestamp_value_(nanoseconds_per_timestamp_value),
      command_pool_(command_pool),
      symbols_(symbols) {
  symbols_.vkGetPhysicalDeviceMemoryProperties(physical_device_,
                                               &memory_properties_);
  symbols_.vkGetDeviceQueue(device_, queue_family_index_, 0, &queue_);
}

absl::StatusOr<uint32_t> Device::SelectMemoryType(
    uint32_t supported_memory_types,
    VkMemoryPropertyFlags desired_memory_properties) {
  for (int i = 0; i < memory_properties_.memoryTypeCount; ++i) {
    if ((supported_memory_types & (1 << i)) &&
        ((memory_properties_.memoryTypes[i].propertyFlags &
          desired_memory_properties) == desired_memory_properties))
      return i;
  }
  return absl::UnavailableError("cannot find memory type with required bits");
}

absl::StatusOr<VkDeviceMemory> Device::AllocateMemory(
    VkMemoryRequirements memory_requirements,
    VkMemoryPropertyFlags memory_flags) {
  VkMemoryAllocateInfo allocate_info = {};
  allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
  allocate_info.pNext = nullptr;
  allocate_info.allocationSize = memory_requirements.size;
  UVKC_ASSIGN_OR_RETURN(
      allocate_info.memoryTypeIndex,
      SelectMemoryType(memory_requirements.memoryTypeBits, memory_flags));

  VkDeviceMemory memory = VK_NULL_HANDLE;
  VK_RETURN_IF_ERROR(symbols_.vkAllocateMemory(device_, &allocate_info,
                                               /*pAlloator=*/nullptr, &memory));
  return memory;
}

}  // namespace vulkan
}  // namespace uvkc


text:
package com.techshroom.unplanned.ap.ecs.plan;

import static com.google.common.collect.ImmutableList.toImmutableList;

import java.util.List;
import java.util.function.UnaryOperator;

import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.type.DeclaredType;

import com.google.auto.common.MoreTypes;
import com.google.common.collect.ImmutableMap;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import com.techshroom.unplanned.core.util.UDStrings;

public final class PCMSimple implements PlanCodeManager {

    private static String fieldName(String compName, String fieldName) {
        return compName + "_" + fieldName;
    }

    private static String setterName(String compName, String fieldName) {
        return compName + UDStrings.uppercaseFirstLetter(fieldName);
    }

    private final ProcessingEnvironment env;

    public PCMSimple(ProcessingEnvironment env) {
        this.env = env;
    }

    @Override
    public List<FieldSpec> generateFields(PlanComponent component) {
        return component.getFields().stream().map(compField -> {
            // compfield is like ComponentField<XYZ> nameOfField;
            DeclaredType declType = MoreTypes.asDeclared(compField.asType());
            // we pull out the XYZ and the nameOfField
            return FieldSpec.builder(
                    TypeName.get(declType.getTypeArguments().get(0)),
                    fieldName(component.getName(), compField.getSimpleName().toString()),
                    Modifier.PRIVATE).build();
        }).collect(toImmutableList());
    }

    @Override
    public List<MethodSpec> generateBuilderSetters(UnaryOperator<MethodSpec.Builder> config, PlanComponent component) {
        return component.getFields().stream().map(compField -> {
            // compfield is like ComponentField<XYZ> nameOfField;
            DeclaredType declType = MoreTypes.asDeclared(compField.asType());
            // we pull out the XYZ and the nameOfField
            // then we merge it to create a name like $COMP_NAME$NAME_OF_FIELD
            // ex: gridPositionX
            String nameOfField = compField.getSimpleName().toString();
            String name = setterName(component.getName(), nameOfField);
            return config.apply(MethodSpec.methodBuilder(name)
                    .addModifiers(Modifier.PUBLIC)
                    .addParameter(TypeName.get(declType.getTypeArguments().get(0)), nameOfField)
                    .addStatement("this.$L = $L", fieldName(component.getName(), nameOfField), nameOfField)).build();
        }).collect(toImmutableList());
    }

    @Override
    public CodeBlock generateAssignment(String entityArg, String assocArg, TypeName source, PlanComponent component) {
        CodeBlock.Builder cb = CodeBlock.builder();
        component.getFields().forEach(compField -> {
            String fieldName = fieldName(component.getName(), compField.getSimpleName().toString());
            cb.beginControlFlow("if ($L != null)", fieldName);
            cb.addNamed("$assoc:L.set($entity:L, $source:T.$comp:L().getField($name:S), this.$value:L);\n", new ImmutableMap.Builder<String, Object>()
                    .put("assoc", assocArg)
                    .put("entity", entityArg)
                    .put("source", source)
                    .put("comp", component.getName())
                    .put("name", compField.getSimpleName().toString())
                    .put("value", fieldName)
                    .build());
            cb.endControlFlow();
        });
        return cb.build();
    }
}


text:
package com.github.usc.dubbo.demo.generic.impl;

import com.github.usc.dubbo.demo.generic.api.IUserService;

/**
 * @author chao.liuc
 *
 */
public class UserServiceImpl implements IUserService {

    public User get(Params params) {
        return new User(1, "charles");
    }
}


text:
package org.hisp.dhis.android.testapp.settings;

import org.hisp.dhis.android.core.settings.DataSyncPeriod;
import org.hisp.dhis.android.core.settings.GeneralSettings;
import org.hisp.dhis.android.core.utils.integration.mock.BaseMockIntegrationTestFullDispatcher;
import org.hisp.dhis.android.core.utils.runner.D2JunitRunner;
import org.junit.Test;
import org.junit.runner.RunWith;

import static com.google.common.truth.Truth.assertThat;

@RunWith(D2JunitRunner.class)
public class GeneralSettingsObjectRepositoryMockIntegrationShould extends BaseMockIntegrationTestFullDispatcher {

    @Test
    public void find_android_setting() {
        GeneralSettings generalSettings = d2.settingModule().generalSetting().blockingGet();
        assertThat(generalSettings.dataSync()).isEqualTo(DataSyncPeriod.EVERY_24_HOURS);
    }
}


text:
namespace OrchardCore.ContentLocalization
{
    public interface ILocalizable
    {
        string LocalizationSet { get; }
        string Culture { get; }
    }
}


text:
print 'Odd number from 1 to 1000'
for count in range(1,1000,2):
    print count


text:
  Rochefort-en-Terre est
       un village
       situé dans le département de Morbihan en Bretagne. On dénombrait 733 habitants en 2008.

La commune propose quelques  équipements sportifs, elle propose entre autres un terrain de tennis et une boucle de randonnée.

Le nombre de logements, à Rochefort-en-Terre, était réparti en 2011 en 92 appartements et 287 maisons soit
 un marché plutôt équilibré.

À proximité de Rochefort-en-Terre sont positionnées géographiquement les villes de
Pluherlin située à 1 km, 1 224 habitants,
Molac située à 8 km, 1 197 habitants,
Quily à 6 km, 299 habitants,
Pleucadeuc à 7 km, 1 716 habitants,
Caden à 8 km, 1 541 habitants,
Saint-Congard localisée à 8 km, 702 habitants,
 entre autres. De plus, Rochefort-en-Terre est située à seulement 25 km de Sainte-Marie.

Si vous pensez venir habiter à Rochefort-en-Terre, vous pourrez facilement trouver une maison à vendre.

À Rochefort-en-Terre, la valorisation moyenne à la vente d'un appartement s'évalue à 1 458 € du m² en vente. la valorisation moyenne d'une maison à l'achat se situe à 1 780 € du m². À la location le prix moyen se situe à 6,47 € du m² par mois.


text:
<!DOCTYPE html>

	<meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
	<meta name="viewport"
		content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no"/>
	<meta name="apple-mobile-web-app-capable" content="yes"/>
	<title>Filtered List Tests</title>

Filtered EdgeToEdgeStoreList

Filtered EdgeToEdgeStoreList

		<input data-dojo-type="dojox/mobile/SearchBox" type="search" id="filterBox2"
			class="myCustomClass mblFilteredEdgeToEdgeListSearchBox">

Filtered EdgeToEdgeStoreList

		<input data-dojo-type="dojox/mobile/SearchBox" type="search" id="filterBox3"
			data-dojo-props="filterBoxRef: 'filterBox', placeHolder: 'CustomPlaceHolder', store: store"
			class="myCustomClass mblFilteredEdgeToEdgeListSearchBox">

Filtered EdgeToEdgeDataList

		<input data-dojo-type="dojox/mobile/SearchBox" type="search" id="filterBox4"
			class="myCustomClass mblFilteredEdgeToEdgeListSearchBox">

Filtered EdgeToEdgeStoreList

Filtered RoundRectList

Alabama

Alaska

American Samoa

Arizona

Arkansas

Armed Forces Europe

Armed Forces Pacific

Armed Forces the Americas

California

Colorado

Connecticut

Delaware

District of Columbia

Federated States of Micronesia

Florida

Georgia

Guam

Hawaii

Idaho

Illinois

Indiana

Iowa

Kansas

Kentucky

Louisiana

Maine

Marshall Islands

Maryland

Massachusetts

Michigan

Minnesota

Mississippi

Missouri

Montana

Nebraska

Nevada

New Hampshire

New Jersey

New Mexico

New York

North Carolina

North Dakota

Northern Mariana Islands

Ohio

Oklahoma

Oregon

Pennsylvania

Puerto Rico

Rhode Island

South Carolina

South Dakota

Tennessee

Texas

Utah

Vermont

Virgin Islands, U.S.

Virginia

Washington

West Virginia

Wisconsin

Wyoming


text:
"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = function(context) {

    return {

        "ThrowStatement": function(node) {

            if (node.argument.type === "Literal") {
                context.report(node, "Do not throw a literal.");
            } else if (node.argument.type === "Identifier") {
                if (node.argument.name === "undefined") {
                    context.report(node, "Do not throw undefined.");
                }
            }

        }

    };

};

module.exports.schema = [];


text:
package org.camunda.bpm.engine.impl.jobexecutor.historycleanup;

import java.util.Date;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.jobexecutor.JobHandler;
import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity;
import org.camunda.bpm.engine.impl.persistence.entity.JobEntity;
import org.camunda.bpm.engine.impl.persistence.entity.SuspensionState;
import org.camunda.bpm.engine.impl.util.ClockUtil;
import org.camunda.bpm.engine.impl.util.json.JSONObject;

/**
 * Job handler for history cleanup job.
 * @author Svetlana Dorokhova
 */
public class HistoryCleanupJobHandler implements JobHandler<HistoryCleanupJobHandlerConfiguration> {

  public static final String TYPE = "history-cleanup";

  @Override
  public String getType() {
    return TYPE;
  }

  @Override
  public void execute(HistoryCleanupJobHandlerConfiguration configuration, ExecutionEntity execution, CommandContext commandContext, String tenantId) {
    //find JobEntity
    JobEntity jobEntity = commandContext.getJobManager().findJobByHandlerType(getType());

    boolean rescheduled = false;

    if (configuration.isImmediatelyDue()
        || (HistoryCleanupHelper.isBatchWindowConfigured(commandContext)
            && HistoryCleanupHelper.isWithinBatchWindow(ClockUtil.getCurrentTime(), commandContext)) ) {
      //find data to delete
      final HistoryCleanupBatch nextBatch = HistoryCleanupHelper.getNextBatch(commandContext);
      if (nextBatch.size() >= getBatchSizeThreshold(commandContext)) {

        //delete bunch of data
        nextBatch.performCleanup();

        //reschedule now
        commandContext.getJobManager().reschedule(jobEntity, ClockUtil.getCurrentTime());
        rescheduled = true;
        cancelCountEmptyRuns(configuration, jobEntity);
      } else {
        //still have something to delete
        if (nextBatch.size() > 0) {
          nextBatch.performCleanup();
        }
        //not enough data for cleanup was found
        if (HistoryCleanupHelper.isWithinBatchWindow(ClockUtil.getCurrentTime(), commandContext)) {
          //reschedule after some delay
          Date nextRunDate = configuration.getNextRunWithDelay(ClockUtil.getCurrentTime());
          if (HistoryCleanupHelper.isWithinBatchWindow(nextRunDate, commandContext)) {
            commandContext.getJobManager().reschedule(jobEntity, nextRunDate);
            rescheduled = true;
            incrementCountEmptyRuns(configuration, jobEntity);
          }
        }
      }
    }
    if (!rescheduled) {
      if (HistoryCleanupHelper.isBatchWindowConfigured(commandContext)) {
        rescheduleRegularCall(commandContext, jobEntity);
      } else {
        //nothing more to do, suspend the job
        suspendJob(jobEntity);
      }
      cancelCountEmptyRuns(configuration, jobEntity);
    }
  }

  private void rescheduleRegularCall(CommandContext commandContext, JobEntity jobEntity) {
    commandContext.getJobManager().reschedule(jobEntity, HistoryCleanupHelper.getNextRunWithinBatchWindow(ClockUtil.getCurrentTime(), commandContext));
  }

  private void suspendJob(JobEntity jobEntity) {
    jobEntity.setSuspensionState(SuspensionState.SUSPENDED.getStateCode());
  }

  private void incrementCountEmptyRuns(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) {
    configuration.setCountEmptyRuns(configuration.getCountEmptyRuns() + 1);
    jobEntity.setJobHandlerConfiguration(configuration);
  }

  private void cancelCountEmptyRuns(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) {
    configuration.setCountEmptyRuns(0);
    jobEntity.setJobHandlerConfiguration(configuration);
  }

  @Override
  public HistoryCleanupJobHandlerConfiguration newConfiguration(String canonicalString) {
    JSONObject jsonObject = new JSONObject(canonicalString);
    return HistoryCleanupJobHandlerConfiguration.fromJson(jsonObject);
  }

  @Override
  public void onDelete(HistoryCleanupJobHandlerConfiguration configuration, JobEntity jobEntity) {
  }

  public Integer getBatchSizeThreshold(CommandContext commandContext) {
    return commandContext.getProcessEngineConfiguration().getHistoryCleanupBatchThreshold();
  }

}


text:
namespace pe {

using block_graph::BlockGraph;
using block_graph::BlockVector;
using block_graph::ConstTypedBlock;
using core::RelativeAddress;

typedef std::vector<const BlockGraph::Section*> Sections;
typedef std::map<BlockGraph::SectionId, BlockVector> SectionBlocks;

namespace {

// Generates a sorted list of sections. Uses the default block graph ordering,
// but ensures that rsrc and reloc are second-last and last, respectively.
// Also ensures that those two sections are unique.
bool GetOrderedSections(BlockGraph* block_graph,
                        Sections* sections) {
  DCHECK(block_graph != NULL);
  DCHECK(sections != NULL);

  sections->clear();
  sections->reserve(block_graph->sections().size());

  const BlockGraph::Section* rsrc = NULL;
  const BlockGraph::Section* reloc = NULL;
  BlockGraph::SectionMap::const_iterator section_it =
      block_graph->sections().begin();
  for (; section_it != block_graph->sections().end(); ++section_it) {
    const BlockGraph::Section* section = &section_it->second;
    if (section->name() == kResourceSectionName) {
      if (rsrc != NULL) {
        LOG(ERROR) << "Found more than one " << kResourceSectionName
                   << " section.";
        return false;
      }
      rsrc = section;
      continue;
    }
    if (section->name() == kRelocSectionName) {
      if (reloc != NULL) {
        LOG(ERROR) << "Found more than one reloc section.";
        return false;
      }
      reloc = section;
      continue;
    }
    sections->push_back(section);
  }

  sections->push_back(rsrc);
  sections->push_back(reloc);

  DCHECK_EQ(sections->size(), block_graph->sections().size());

  return true;
}

// Lays out a block in the given address space. Takes care of alignment
// and incrementing the insert_at pointer.
bool LayoutBlock(BlockGraph::Block* block,
                 BlockGraph::AddressSpace* address_space,
                 RelativeAddress* insert_at) {
  DCHECK(block != NULL);
  DCHECK(address_space != NULL);
  DCHECK(insert_at != NULL);

  RelativeAddress aligned = insert_at->AlignUp(block->alignment());
  if (!address_space->InsertBlock(aligned, block)) {
    LOG(ERROR) << "Failed to insert block \"" << block->name() << "\" at "
               << *insert_at << ".";
    return false;
  }

  *insert_at = aligned + block->size();
  return true;
}

// Returns true if the block contains only zeros, and may safely be left
// implicitly initialized.
bool BlockIsZeros(const BlockGraph::Block* block) {
  if (block->references().size() != 0)
    return false;
  const uint8_t* data = block->data();
  if (data == NULL)
    return true;
  for (size_t i = 0; i < block->data_size(); ++i, ++data) {
    if (*data != 0)
      return false;
  }
  return true;
}

// Compares two blocks. Uses the source address of the first byte of each block.
// If one or both of the blocks has no such address then we sort such that empty
// (blocks that are all zeros and may be safely initialized) are pushed to the
// end of the section. Finally, we break ties using the block id.
bool BlockCompare(const BlockGraph::Block* block1,
                  const BlockGraph::Block* block2) {
  const BlockGraph::Block::SourceRanges::RangePair* pair1 =
      block1->source_ranges().FindRangePair(0, 1);
  const BlockGraph::Block::SourceRanges::RangePair* pair2 =
      block2->source_ranges().FindRangePair(0, 1);

  // If we have addresses, sort using them first.
  if (pair1 != NULL && pair2 != NULL) {
    RelativeAddress addr1 = pair1->second.start();
    RelativeAddress addr2 = pair2->second.start();
    if (addr1 < addr2)
      return true;
    if (addr2 < addr1)
      return false;
  }

  // Next, sort based on the contents. Blocks containing all zeros get pushed
  // to the end of the section.
  bool is_zeros1 = BlockIsZeros(block1);
  bool is_zeros2 = BlockIsZeros(block2);
  if (is_zeros1 != is_zeros2)
    return is_zeros2;

  // Finally we break ties using the block ID.
  return block1->id() < block2->id();
}

// Returns the length of data in a block that must be explicitly specified.
// Any data after this length may be implicitly initialized as zeroes.
size_t GetExplicitLength(const BlockGraph::Block* block) {
  size_t length = 0;

  // Get the offset of the last byte of the last reference, if there are any.
  if (block->references().size() > 0) {
    BlockGraph::Block::ReferenceMap::const_reverse_iterator last_ref =
        block->references().rbegin();
    length = last_ref->first + last_ref->second.size();
  }

  // If there is any explicit data beyond the last reference we need to
  // manually check it.
  if (block->data_size() > length) {
    const uint8_t* data = block->data();
    DCHECK(data != NULL);

    // Walk the data backwards from the end looking for the first non-zero byte.
    size_t i = block->data_size();
    data += i - 1;
    while (i > length && *data == 0) {
      --i;
      --data;
    }
    length = i;
  }

  return length;
}

}  // namespace

void CopySectionHeadersToImageLayout(
    size_t num_sections,
    const IMAGE_SECTION_HEADER* section_headers,
    std::vector<ImageLayout::SectionInfo>* sections) {
  DCHECK(num_sections > 0);
  DCHECK(section_headers != NULL);
  DCHECK(sections != NULL);

  sections->clear();
  sections->reserve(num_sections);
  for (size_t i = 0; i < num_sections; ++i) {
    sections->push_back(pe::ImageLayout::SectionInfo());
    pe::ImageLayout::SectionInfo& section = sections->back();

    section.name = PEFile::GetSectionName(section_headers[i]);
    section.addr.set_value(section_headers[i].VirtualAddress);
    section.size = section_headers[i].Misc.VirtualSize;
    section.data_size = section_headers[i].SizeOfRawData;
    section.characteristics = section_headers[i].Characteristics;
  }
}

bool CopyHeaderToImageLayout(const BlockGraph::Block* nt_headers_block,
                             ImageLayout* layout) {
  ConstTypedBlock<IMAGE_NT_HEADERS> nt_headers;
  if (!nt_headers.Init(0, nt_headers_block)) {
    LOG(ERROR) << "NT Headers too short.";
    return false;
  }

  ConstTypedBlock<IMAGE_SECTION_HEADER> section_headers;
  size_t size = sizeof(IMAGE_SECTION_HEADER) *
      nt_headers->FileHeader.NumberOfSections;
  if (!section_headers.InitWithSize(sizeof(IMAGE_NT_HEADERS),
                                    size,
                                    nt_headers_block)) {
    LOG(ERROR) << "NT Headers too short to contain section headers.";
    return false;
  }

  CopySectionHeadersToImageLayout(nt_headers->FileHeader.NumberOfSections,
                                  section_headers.Get(),
                                  &layout->sections);
  return true;
}

ImageLayout::ImageLayout(BlockGraph* block_graph)
    : blocks(block_graph) {
}

bool BuildCanonicalImageLayout(ImageLayout* image_layout) {
  DCHECK(image_layout != NULL);

  BlockGraph* block_graph = image_layout->blocks.graph();

  // First, create an ordering for the sections. This will be the same as
  // the ordering in the underlying block graph, but we enforce that
  // .rsrc and .reloc come second last and last.
  Sections sections;
  if (!GetOrderedSections(block_graph, &sections))
    return false;

  // Get a list of all of the blocks for each section, and find the header
  // blocks.
  SectionBlocks section_blocks;
  BlockGraph::Block* dos_header_block = NULL;
  BlockGraph::Block* nt_headers_block = NULL;
  BlockGraph::BlockMap::iterator block_it =
      block_graph->blocks_mutable().begin();
  for (; block_it != block_graph->blocks_mutable().end(); ++block_it) {
    BlockGraph::Block* block = &block_it->second;

    // Block has no section? Identify it as a header block.
    if (block->section() == BlockGraph::kInvalidSectionId) {
      if (dos_header_block == NULL && IsValidDosHeaderBlock(block)) {
        dos_header_block = block;
      } else if (nt_headers_block == NULL && IsValidNtHeadersBlock(block)) {
        nt_headers_block = block;
      } else {
        LOG(ERROR) << "Found invalid header block.";
        return false;
      }
    } else {
      section_blocks[block->section()].push_back(block);
    }
  }

  // Ensure we found both header blocks.
  if (dos_header_block == NULL || nt_headers_block == NULL) {
    LOG(ERROR) << "Missing one or both header blocks.";
    return false;
  }

  // Output the header blocks.
  RelativeAddress insert_at(0);
  if (!LayoutBlock(dos_header_block, &image_layout->blocks, &insert_at) ||
      !LayoutBlock(nt_headers_block, &image_layout->blocks, &insert_at)) {
    return false;
  }

  // Get the section alignment from the headers.
  ConstTypedBlock<IMAGE_DOS_HEADER> dos_header;
  if (!dos_header.Init(0, dos_header_block)) {
    LOG(ERROR) << "Failed to cast dos_header_block to IMAGE_DOS_HEADER.";
    return false;
  }
  ConstTypedBlock<IMAGE_NT_HEADERS> nt_header;
  if (!dos_header.Dereference(dos_header->e_lfanew, &nt_header)) {
    LOG(ERROR) << "Failed to cast nt_headers_block to IMAGE_NT_HEADERS.";
    return false;
  }
  size_t section_alignment = nt_header->OptionalHeader.SectionAlignment;
  size_t file_alignment = nt_header->OptionalHeader.FileAlignment;

  image_layout->sections.clear();
  image_layout->sections.reserve(sections.size());

  // Output the sections one at a time.
  for (size_t i = 0; i < sections.size(); ++i) {
    BlockVector& blocks = section_blocks[sections[i]->id()];

    // NOTE: BlockCompare uses BlockIsZeros, which is a slightly simpler
    //     version of GetExplicitLength (checks for explicit length == 0).
    //     This called for both blocks in each block comparison while sorting,
    //     and then explicitly again during layout. It may be worthwhile to
    //     precalculate and cache the explicit length values.

    // Sort the blocks for the section. This sorts based on the source address
    // if the block has a single source, then based on content (empty blocks
    // pushed to the end of the section), and finally by block id.
    std::sort(blocks.begin(), blocks.end(), &BlockCompare);

    // Align up for the section.
    insert_at = insert_at.AlignUp(section_alignment);
    RelativeAddress section_start = insert_at;
    RelativeAddress section_data_end = insert_at;

    // Layout the blocks. Keep track of the end of any blocks that aren't
    // strictly full of zeroes, in order to determine the data size.
    for (size_t j = 0; j < blocks.size(); ++j) {
      BlockGraph::Block* block = blocks[j];
      if (!LayoutBlock(block, &image_layout->blocks, &insert_at))
        return false;

      // Get the explicit length of this block. If it is non-zero update the
      // end of the explicit data for this section.
      size_t explicit_length = GetExplicitLength(block);
      if (explicit_length > 0)
        section_data_end = insert_at - block->size() + explicit_length;
    }

    // Add this section to the image layout.
    ImageLayout::SectionInfo section_info;
    section_info.name = sections[i]->name();
    section_info.addr = section_start;
    section_info.size = insert_at - section_start;
    section_info.data_size = common::AlignUp(section_data_end - section_start,
                                             file_alignment);
    section_info.characteristics = sections[i]->characteristics();
    image_layout->sections.push_back(section_info);
  }

  return true;
}

bool CopyImageLayoutWithoutPadding(const ImageLayout& input_image_layout,
                                   ImageLayout* output_image_layout) {
  DCHECK(output_image_layout != NULL);
  DCHECK_EQ(input_image_layout.blocks.graph(),
            output_image_layout->blocks.graph());
  DCHECK_EQ(0u, output_image_layout->blocks.size());

  output_image_layout->sections = input_image_layout.sections;
  BlockGraph* block_graph = output_image_layout->blocks.graph();

  // Remove the padding blocks from the decomposition. We also need to create
  // a new version of the image layout not containing those blocks.
  BlockGraph::AddressSpace::RangeMapConstIter block_it =
      input_image_layout.blocks.begin();
  for (; block_it != input_image_layout.blocks.end(); ++block_it) {
    BlockGraph::Block* block = block_it->second;

    // If it's a padding block, remove it from the block-graph and leave it
    // out of the new image layout.
    if ((block->attributes() & BlockGraph::PADDING_BLOCK)) {
      if (!block_graph->RemoveBlock(block)) {
        return false;
      }
    } else {
      // If it's not a padding block, copy it over to the new image layout.
      if (!output_image_layout->blocks.InsertBlock(block_it->first.start(),
                                                   block)) {
        return false;
      }
    }
  }

  return true;
}

}  // namespace pe


text:
package org.kaazing.gateway.client.impl.bridge;

import org.kaazing.gateway.client.impl.bridge.XoaEvent.XoaEventKind;

public interface ProxyListener {

    void eventReceived(Proxy proxy, XoaEventKind name, Object[] params);

}


text:
 <?php esc_html_e( 'Available Apps', 'wordpress-popup' ); ?>

<?php esc_html_e( "Hustle integrates with your favorite email and data collection apps. Here's a list of all the available apps that you can connect to.", 'wordpress-popup' ); ?>


text:
class UsersController < UITableViewController
  def users
    @users ||= [User.new("Harry", 100, "Green"),
                User.new("Ron", 80, "Blue"),
                User.new("Hermione", 120, "Red")]
  end

  def viewDidLoad
    super
    self.title = "Scoreboard"
  end

  def viewDidAppear(animated)
    super
    self.users.sort_by! { |x| x.score }.reverse!
    self.tableView.reloadData
  end

  def tableView(tableView, numberOfRowsInSection:section)
    self.users.count
  end

  def tableView(tableView, cellForRowAtIndexPath:indexPath)
    @identifier ||= "IDENTIFIER"

    cell = tableView.dequeueReusableCellWithIdentifier(@indentifier) || begin
      UITableViewCell.alloc.initWithStyle(UITableViewCellStyleSubtitle, reuseIdentifier:@identifier)
    end

    user = self.users[indexPath.row]
    cell.textLabel.text = "##{indexPath.row + 1}: #{user.name}"
    cell.detailTextLabel.text = user.team
    cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton

    cell
  end

  def tableView(tableView, didSelectRowAtIndexPath:indexPath)
    tableView.deselectRowAtIndexPath(indexPath, animated:true)

    user = self.users[indexPath.row]
    alert = UIAlertView.alloc.initWithTitle(user.name, message:"Score: #{user.score}", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:nil)
    alert.show
  end

  def tableView(tableView, accessoryButtonTappedForRowWithIndexPath:indexPath)
    # WHERE THE MAGIC HAPPENS!
    user = self.users[indexPath.row]
    controller = Formotion::FormableController.alloc.initWithModel(user)
    self.navigationController.pushViewController(controller, animated:true)
  end
end


text:
require 'socket'
require 'ladder_drive/plc_device'

module Plc
module Raspberrypi

  class RaspberrypiPlcServer

    class << self

      def launch config={}
        @server ||= begin
          server = new config
          server.run
          server
        end
      end

    end

    def initialize config = {}
      @port = config[:port] || 5555
      @plc = RaspberrypiPlc.new config
    end

    def run
      puts "launching respberrypi plc ... "
      @plc.run
      puts "done launching"

      Thread.new do
        server = TCPServer.open @port
        loop do
          Thread.start(server.accept) do |socket|
            while line = socket.gets
              begin
                r = @plc.execute_console_commands line
                socket.puts r
              rescue => e
                socket.puts "E0 #{e}\r\n"
              end
            end
          end
        end
      end

    end

  end

end
end


text:
1. Add the hip.vim to ~/.vim/syntax/ directory
2. Add the following text to the end of ~/.vimrc

```
augroup filetypedetect
 au BufNewFile,BufRead *.cpp set filetype=cpp syntax=hip
augroup END
augroup filetypedetect
 au BufNewFile,BufRead *.c set filetype=c syntax=hip
augroup END
augroup filetypedetect
 au BufNewFile,BufRead *.cu set filetype=cu syntax=hip
augroup END
```


text:
namespace password_manager {
namespace features_util {
namespace {

base::Value CreateOptedInAccountPref() {
  base::Value global_pref(base::Value::Type::DICTIONARY);
  base::Value account_pref(base::Value::Type::DICTIONARY);
  account_pref.SetBoolKey("opted_in", true);
  global_pref.SetKey("some_gaia_hash", std::move(account_pref));
  return global_pref;
}
}  // namespace

TEST(PasswordFeatureManagerUtil,
     AccountStoragePerAccountSettings_FeatureDisabled) {
  base::test::ScopedFeatureList features;
  features.InitAndDisableFeature(features::kEnablePasswordsAccountStorage);

  TestingPrefServiceSimple pref_service;
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);

  CoreAccountInfo account;
  account.email = "first@account.com";
  account.gaia = "first";
  account.account_id = CoreAccountId::FromGaiaId(account.gaia);

  // SyncService is running in transport mode with |account|.
  syncer::TestSyncService sync_service;
  sync_service.SetIsAuthenticatedAccountPrimary(false);
  sync_service.SetAuthenticatedAccountInfo(account);
  ASSERT_EQ(sync_service.GetTransportState(),
            syncer::SyncService::TransportState::ACTIVE);
  ASSERT_FALSE(sync_service.IsSyncFeatureEnabled());

  // Since the account storage feature is disabled, the profile store should be
  // the default.
  EXPECT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kProfileStore);

  // Same if the user is signed out.
  sync_service.SetAuthenticatedAccountInfo(CoreAccountInfo());
  sync_service.SetTransportState(syncer::SyncService::TransportState::DISABLED);
  EXPECT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kProfileStore);
}

TEST(PasswordFeatureManagerUtil, ShowAccountStorageResignIn) {
  TestingPrefServiceSimple pref_service;
  syncer::TestSyncService sync_service;
  base::test::ScopedFeatureList features;
  features.InitAndEnableFeature(features::kEnablePasswordsAccountStorage);

  // Add an account to prefs which opted into using the account-storage.
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);
  pref_service.Set(prefs::kAccountStoragePerAccountSettings,
                   CreateOptedInAccountPref());

  // SyncService is not running (because no user is signed-in).
  sync_service.SetTransportState(syncer::SyncService::TransportState::DISABLED);
  sync_service.SetDisableReasons(
      {syncer::SyncService::DisableReason::DISABLE_REASON_NOT_SIGNED_IN});

  EXPECT_TRUE(ShouldShowAccountStorageReSignin(&pref_service, &sync_service));
}

TEST(PasswordFeatureManagerUtil, ShowAccountStorageResignIn_FeatureDisabled) {
  TestingPrefServiceSimple pref_service;
  syncer::TestSyncService sync_service;
  base::test::ScopedFeatureList features;
  features.InitAndDisableFeature(features::kEnablePasswordsAccountStorage);

  // Add an account to prefs which opted into using the account-storage.
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);
  pref_service.Set(prefs::kAccountStoragePerAccountSettings,
                   CreateOptedInAccountPref());

  // SyncService is not running (because no user is signed-in).
  sync_service.SetTransportState(syncer::SyncService::TransportState::DISABLED);
  sync_service.SetDisableReasons(
      {syncer::SyncService::DisableReason::DISABLE_REASON_NOT_SIGNED_IN});

  EXPECT_FALSE(ShouldShowAccountStorageReSignin(&pref_service, &sync_service));
}

TEST(PasswordFeatureManagerUtil, DontShowAccountStorageResignIn_SyncActive) {
  TestingPrefServiceSimple pref_service;
  syncer::TestSyncService sync_service;
  base::test::ScopedFeatureList features;
  features.InitAndEnableFeature(features::kEnablePasswordsAccountStorage);

  // Add an account to prefs which opted into using the account-storage.
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);
  pref_service.Set(prefs::kAccountStoragePerAccountSettings,
                   CreateOptedInAccountPref());

  // SyncService is running (e.g for a different signed-in user).
  sync_service.SetTransportState(syncer::SyncService::TransportState::ACTIVE);

  EXPECT_FALSE(ShouldShowAccountStorageReSignin(&pref_service, &sync_service));
}

TEST(PasswordFeatureManagerUtil, DontShowAccountStorageResignIn_NoPrefs) {
  TestingPrefServiceSimple pref_service;
  syncer::TestSyncService sync_service;
  base::test::ScopedFeatureList features;
  features.InitAndEnableFeature(features::kEnablePasswordsAccountStorage);

  // Pref is registered but not set for any account.
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);

  // SyncService is not running (because no user is signed-in).
  sync_service.SetTransportState(syncer::SyncService::TransportState::DISABLED);
  sync_service.SetDisableReasons(
      {syncer::SyncService::DisableReason::DISABLE_REASON_NOT_SIGNED_IN});

  EXPECT_FALSE(ShouldShowAccountStorageReSignin(&pref_service, &sync_service));
}

TEST(PasswordFeatureManagerUtil, AccountStoragePerAccountSettings) {
  base::test::ScopedFeatureList features;
  features.InitAndEnableFeature(features::kEnablePasswordsAccountStorage);

  TestingPrefServiceSimple pref_service;
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);

  CoreAccountInfo first_account;
  first_account.email = "first@account.com";
  first_account.gaia = "first";
  first_account.account_id = CoreAccountId::FromGaiaId(first_account.gaia);

  CoreAccountInfo second_account;
  second_account.email = "second@account.com";
  second_account.gaia = "second";
  second_account.account_id = CoreAccountId::FromGaiaId(second_account.gaia);

  syncer::TestSyncService sync_service;
  sync_service.SetDisableReasons(
      {syncer::SyncService::DISABLE_REASON_NOT_SIGNED_IN});
  sync_service.SetTransportState(syncer::SyncService::TransportState::DISABLED);
  sync_service.SetIsAuthenticatedAccountPrimary(false);

  // Initially the user is not signed in, so everything is off/local.
  EXPECT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowPasswordStorePicker(&pref_service, &sync_service));
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kProfileStore);

  // Now let SyncService run in transport mode with |first_account|.
  sync_service.SetAuthenticatedAccountInfo(first_account);
  sync_service.SetDisableReasons({});
  sync_service.SetTransportState(syncer::SyncService::TransportState::ACTIVE);
  ASSERT_FALSE(sync_service.IsSyncFeatureEnabled());

  // By default, the user is not opted in. But since they're eligible for
  // account storage, the default store should be the account one.
  EXPECT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_TRUE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kAccountStore);

  // Opt in!
  OptInToAccountStorage(&pref_service, &sync_service);
  EXPECT_TRUE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  // ...and change the default store to the profile one.
  SetDefaultPasswordStore(&pref_service, &sync_service,
                          autofill::PasswordForm::Store::kProfileStore);
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kProfileStore);

  // Change to |second_account|. The opt-in for |first_account| should not
  // apply, and similarly the default store should be back to "account".
  sync_service.SetAuthenticatedAccountInfo(second_account);
  EXPECT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_TRUE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kAccountStore);

  // Change back to |first_account|. The previous opt-in and chosen default
  // store should now apply again.
  sync_service.SetAuthenticatedAccountInfo(first_account);
  EXPECT_TRUE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kProfileStore);

  // Sign out. Now the settings should have reasonable default values (not opted
  // in, save to profile store).
  sync_service.SetAuthenticatedAccountInfo(CoreAccountInfo());
  sync_service.SetTransportState(syncer::SyncService::TransportState::DISABLED);
  EXPECT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kProfileStore);
}

TEST(PasswordFeatureManagerUtil, SyncSuppressesAccountStorageOptIn) {
  base::test::ScopedFeatureList features;
  features.InitAndEnableFeature(features::kEnablePasswordsAccountStorage);

  TestingPrefServiceSimple pref_service;
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);

  CoreAccountInfo account;
  account.email = "name@account.com";
  account.gaia = "name";
  account.account_id = CoreAccountId::FromGaiaId(account.gaia);

  // Initially, the user is signed in but doesn't have Sync-the-feature enabled,
  // so the SyncService is running in transport mode.
  syncer::TestSyncService sync_service;
  sync_service.SetIsAuthenticatedAccountPrimary(false);
  sync_service.SetAuthenticatedAccountInfo(account);
  ASSERT_EQ(sync_service.GetTransportState(),
            syncer::SyncService::TransportState::ACTIVE);
  ASSERT_FALSE(sync_service.IsSyncFeatureEnabled());

  // In this state, the user could opt in to the account storage.
  ASSERT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  ASSERT_TRUE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  ASSERT_TRUE(ShouldShowPasswordStorePicker(&pref_service, &sync_service));

  // Now the user enables Sync-the-feature.
  sync_service.SetIsAuthenticatedAccountPrimary(true);
  sync_service.SetFirstSetupComplete(true);
  ASSERT_TRUE(sync_service.IsSyncFeatureEnabled());

  // Now the account-storage opt-in should *not* be available anymore.
  EXPECT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowPasswordStorePicker(&pref_service, &sync_service));
}

TEST(PasswordFeatureManagerUtil, SyncDisablesAccountStorage) {
  base::test::ScopedFeatureList features;
  features.InitAndEnableFeature(features::kEnablePasswordsAccountStorage);

  TestingPrefServiceSimple pref_service;
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);

  CoreAccountInfo account;
  account.email = "name@account.com";
  account.gaia = "name";
  account.account_id = CoreAccountId::FromGaiaId(account.gaia);

  // The SyncService is running in transport mode.
  syncer::TestSyncService sync_service;
  sync_service.SetIsAuthenticatedAccountPrimary(false);
  sync_service.SetAuthenticatedAccountInfo(account);
  ASSERT_EQ(sync_service.GetTransportState(),
            syncer::SyncService::TransportState::ACTIVE);
  ASSERT_FALSE(sync_service.IsSyncFeatureEnabled());

  // The account storage is available in principle, so the opt-in will be shown,
  // and saving will default to the account store.
  ASSERT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  ASSERT_TRUE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  ASSERT_TRUE(ShouldShowPasswordStorePicker(&pref_service, &sync_service));
  ASSERT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kAccountStore);

  // Opt in.
  OptInToAccountStorage(&pref_service, &sync_service);
  ASSERT_TRUE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  ASSERT_FALSE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  ASSERT_TRUE(ShouldShowPasswordStorePicker(&pref_service, &sync_service));
  ASSERT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kAccountStore);

  // Now enable Sync-the-feature. This should effectively turn *off* the account
  // storage again (since with Sync, there's only a single combined storage),
  // even though the opt-in wasn't actually cleared.
  sync_service.SetIsAuthenticatedAccountPrimary(true);
  sync_service.SetFirstSetupComplete(true);
  ASSERT_TRUE(sync_service.IsSyncFeatureEnabled());
  EXPECT_TRUE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowAccountStorageOptIn(&pref_service, &sync_service));
  EXPECT_FALSE(ShouldShowPasswordStorePicker(&pref_service, &sync_service));
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kProfileStore);
}

TEST(PasswordFeatureManagerUtil, OptOutClearsStorePreference) {
  base::test::ScopedFeatureList features;
  features.InitAndEnableFeature(features::kEnablePasswordsAccountStorage);
  base::HistogramTester histogram_tester;

  TestingPrefServiceSimple pref_service;
  pref_service.registry()->RegisterDictionaryPref(
      prefs::kAccountStoragePerAccountSettings);

  CoreAccountInfo account;
  account.email = "name@account.com";
  account.gaia = "name";
  account.account_id = CoreAccountId::FromGaiaId(account.gaia);

  // The SyncService is running in transport mode.
  syncer::TestSyncService sync_service;
  sync_service.SetIsAuthenticatedAccountPrimary(false);
  sync_service.SetAuthenticatedAccountInfo(account);
  ASSERT_EQ(sync_service.GetTransportState(),
            syncer::SyncService::TransportState::ACTIVE);
  ASSERT_FALSE(sync_service.IsSyncFeatureEnabled());

  // Opt in and set default store to profile.
  OptInToAccountStorage(&pref_service, &sync_service);
  ASSERT_TRUE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  SetDefaultPasswordStore(&pref_service, &sync_service,
                          autofill::PasswordForm::Store::kProfileStore);

  // Opt out.
  OptOutOfAccountStorageAndClearSettings(&pref_service, &sync_service);

  // The default store pref should have been erased, so GetDefaultPasswordStore
  // should return kAccountStore again.
  EXPECT_EQ(GetDefaultPasswordStore(&pref_service, &sync_service),
            autofill::PasswordForm::Store::kAccountStore);
  EXPECT_FALSE(IsOptedInForAccountStorage(&pref_service, &sync_service));
  histogram_tester.ExpectUniqueSample(
      "PasswordManager.AccountStorage.SignedInAccountFoundDuringOptOut", true,
      1);
}

}  // namespace features_util
}  // namespace password_manager