text:
package com.lb.launcher;

import com.lb.launcher.R;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

public class DragView extends View {
    private static float sDragAlpha = 1f;

    private Bitmap mBitmap;
    private Bitmap mCrossFadeBitmap;
    private Paint mPaint;
    private int mRegistrationX;
    private int mRegistrationY;

    private Point mDragVisualizeOffset = null;
    private Rect mDragRegion = null;
    private DragLayer mDragLayer = null;
    private boolean mHasDrawn = false;
    private float mCrossFadeProgress = 0f;

    ValueAnimator mAnim;
    private float mOffsetX = 0.0f;
    private float mOffsetY = 0.0f;
    private float mInitialScale = 1f;
    // The intrinsic icon scale factor is the scale factor for a drag icon over the workspace
    // size.  This is ignored for non-icons.
    private float mIntrinsicIconScale = 1f;

    /**
     * Construct the drag view.
     * <p>
     * The registration point is the point inside our view that the touch events should
     * be centered upon.
     *
     * @param launcher The Launcher instance
     * @param bitmap The view that we're dragging around.  We scale it up when we draw it.
     * @param registrationX The x coordinate of the registration point.
     * @param registrationY The y coordinate of the registration point.
     */
    public DragView(Launcher launcher, Bitmap bitmap, int registrationX, int registrationY,
            int left, int top, int width, int height, final float initialScale) {
        super(launcher);
        mDragLayer = launcher.getDragLayer();
        mInitialScale = initialScale;

        final Resources res = getResources();
        final float offsetX = res.getDimensionPixelSize(R.dimen.dragViewOffsetX);
        final float offsetY = res.getDimensionPixelSize(R.dimen.dragViewOffsetY);
        final float scaleDps = res.getDimensionPixelSize(R.dimen.dragViewScale);
        final float scale = (width + scaleDps) / width;

        // Set the initial scale to avoid any jumps
        setScaleX(initialScale);
        setScaleY(initialScale);

        // Animate the view into the correct position
        mAnim = LauncherAnimUtils.ofFloat(this, 0f, 1f);
        mAnim.setDuration(150);
        mAnim.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                final float value = (Float) animation.getAnimatedValue();

                final int deltaX = (int) ((value * offsetX) - mOffsetX);
                final int deltaY = (int) ((value * offsetY) - mOffsetY);

                mOffsetX += deltaX;
                mOffsetY += deltaY;
                setScaleX(initialScale + (value * (scale - initialScale)));
                setScaleY(initialScale + (value * (scale - initialScale)));
                if (sDragAlpha != 1f) {
                    setAlpha(sDragAlpha * value + (1f - value));
                }

                if (getParent() == null) {
                    animation.cancel();
                } else {
                    setTranslationX(getTranslationX() + deltaX);
                    setTranslationY(getTranslationY() + deltaY);
                }
            }
        });

        mBitmap = Bitmap.createBitmap(bitmap, left, top, width, height);
        setDragRegion(new Rect(0, 0, width, height));

        // The point in our scaled bitmap that the touch events are located
        mRegistrationX = registrationX;
        mRegistrationY = registrationY;

        // Force a measure, because Workspace uses getMeasuredHeight() before the layout pass
        int ms = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        measure(ms, ms);
        mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
    }

    /** Sets the scale of the view over the normal workspace icon size. */
    public void setIntrinsicIconScaleFactor(float scale) {
        mIntrinsicIconScale = scale;
    }

    public float getIntrinsicIconScaleFactor() {
        return mIntrinsicIconScale;
    }

    public float getOffsetY() {
        return mOffsetY;
    }

    public int getDragRegionLeft() {
        return mDragRegion.left;
    }

    public int getDragRegionTop() {
        return mDragRegion.top;
    }

    public int getDragRegionWidth() {
        return mDragRegion.width();
    }

    public int getDragRegionHeight() {
        return mDragRegion.height();
    }

    public void setDragVisualizeOffset(Point p) {
        mDragVisualizeOffset = p;
    }

    public Point getDragVisualizeOffset() {
        return mDragVisualizeOffset;
    }

    public void setDragRegion(Rect r) {
        mDragRegion = r;
    }

    public Rect getDragRegion() {
        return mDragRegion;
    }

    public float getInitialScale() {
        return mInitialScale;
    }

    public void updateInitialScaleToCurrentScale() {
        mInitialScale = getScaleX();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(mBitmap.getWidth(), mBitmap.getHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {
        @SuppressWarnings("all") // suppress dead code warning
        final boolean debug = false;
        if (debug) {
            Paint p = new Paint();
            p.setStyle(Paint.Style.FILL);
            p.setColor(0x66ffffff);
            canvas.drawRect(0, 0, getWidth(), getHeight(), p);
        }

        mHasDrawn = true;
        boolean crossFade = mCrossFadeProgress > 0 && mCrossFadeBitmap != null;
        if (crossFade) {
            int alpha = crossFade ? (int) (255 * (1 - mCrossFadeProgress)) : 255;
            mPaint.setAlpha(alpha);
        }
        canvas.drawBitmap(mBitmap, 0.0f, 0.0f, mPaint);
        if (crossFade) {
            mPaint.setAlpha((int) (255 * mCrossFadeProgress));
            canvas.save();
            float sX = (mBitmap.getWidth() * 1.0f) / mCrossFadeBitmap.getWidth();
            float sY = (mBitmap.getHeight() * 1.0f) / mCrossFadeBitmap.getHeight();
            canvas.scale(sX, sY);
            canvas.drawBitmap(mCrossFadeBitmap, 0.0f, 0.0f, mPaint);
            canvas.restore();
        }
    }

    public void setCrossFadeBitmap(Bitmap crossFadeBitmap) {
        mCrossFadeBitmap = crossFadeBitmap;
    }

    public void crossFade(int duration) {
        ValueAnimator va = LauncherAnimUtils.ofFloat(this, 0f, 1f);
        va.setDuration(duration);
        va.setInterpolator(new DecelerateInterpolator(1.5f));
        va.addUpdateListener(new AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mCrossFadeProgress = animation.getAnimatedFraction();
            }
        });
        va.start();
    }

    public void setColor(int color) {
        if (mPaint == null) {
            mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);
        }
        if (color != 0) {
            mPaint.setColorFilter(new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP));
        } else {
            mPaint.setColorFilter(null);
        }
        invalidate();
    }

    public boolean hasDrawn() {
        return mHasDrawn;
    }

    @Override
    public void setAlpha(float alpha) {
        super.setAlpha(alpha);
        mPaint.setAlpha((int) (255 * alpha));
        invalidate();
    }

    /**
     * Create a window containing this view and show it.
     *
     * @param windowToken obtained from v.getWindowToken() from one of your views
     * @param touchX the x coordinate the user touched in DragLayer coordinates
     * @param touchY the y coordinate the user touched in DragLayer coordinates
     */
    public void show(int touchX, int touchY) {
        mDragLayer.addView(this);

        // Start the pick-up animation
        DragLayer.LayoutParams lp = new DragLayer.LayoutParams(0, 0);
        lp.width = mBitmap.getWidth();
        lp.height = mBitmap.getHeight();
        lp.customPosition = true;
        setLayoutParams(lp);
        setTranslationX(touchX - mRegistrationX);
        setTranslationY(touchY - mRegistrationY);
        // Post the animation to skip other expensive work happening on the first frame
        post(new Runnable() {
                public void run() {
                    mAnim.start();
                }
            });
    }

    public void cancelAnimation() {
        if (mAnim != null && mAnim.isRunning()) {
            mAnim.cancel();
        }
    }

    public void resetLayoutParams() {
        mOffsetX = mOffsetY = 0;
        requestLayout();
    }

    /**
     * Move the window containing this view.
     *
     * @param touchX the x coordinate the user touched in DragLayer coordinates
     * @param touchY the y coordinate the user touched in DragLayer coordinates
     */
    void move(int touchX, int touchY) {
        setTranslationX(touchX - mRegistrationX + (int) mOffsetX);
        setTranslationY(touchY - mRegistrationY + (int) mOffsetY);
    }

    void remove() {
        if (getParent() != null) {
            mDragLayer.removeView(DragView.this);
        }
    }
}


text:
// Type definitions for postcss-flexbugs-fixes 4.2
// Project: https://github.com/luisrudge/postcss-flexbugs-fixes#readme
// Definitions by: Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

import { Plugin } from 'postcss';

declare namespace postcssFlexbugsFixes {
    type PostcssFlexbugsFixesPlugin = Plugin<Options>;

    interface Options {
        /**
         * @default true
         */
        bug4?: boolean;
        /**
         * @default true
         */
        bug6?: boolean;
        /**
         * @default true
         */
        bug81a?: boolean;
    }
}

/**
 * PostCSS plugin This project tries to fix all of {@link https://github.com/philipwalton/flexbugs|flexbug's} issues.
 */
declare const postcssFlexbugsFixes: postcssFlexbugsFixes.PostcssFlexbugsFixesPlugin;

export = postcssFlexbugsFixes;

redpajama_set_name: RedPajamaGithub


text:
package latest

import (
	"encoding/json"
	"reflect"
	"strconv"
	"testing"

	internal "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	_ "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1beta1"
	_ "github.com/GoogleCloudPlatform/kubernetes/pkg/api/v1beta2"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"

	docker "github.com/fsouza/go-dockerclient"
	fuzz "github.com/google/gofuzz"
)

// apiObjectFuzzer can randomly populate api objects.
var apiObjectFuzzer = fuzz.New().NilChance(.5).NumElements(1, 1).Funcs(
	func(j *internal.TypeMeta, c fuzz.Continue) {
		// We have to customize the randomization of TypeMetas because their
		// APIVersion and Kind must remain blank in memory.
		j.APIVersion = ""
		j.Kind = ""
	},
	func(j *internal.ObjectMeta, c fuzz.Continue) {
		j.Name = c.RandString()
		j.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10)
		j.SelfLink = c.RandString()

		var sec, nsec int64
		c.Fuzz(&sec)
		c.Fuzz(&nsec)
		j.CreationTimestamp = util.Unix(sec, nsec).Rfc3339Copy()
	},
	func(j *internal.ListMeta, c fuzz.Continue) {
		j.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10)
		j.SelfLink = c.RandString()
	},
	func(j *internal.ObjectReference, c fuzz.Continue) {
		// We have to customize the randomization of TypeMetas because their
		// APIVersion and Kind must remain blank in memory.
		j.APIVersion = c.RandString()
		j.Kind = c.RandString()
		j.Namespace = c.RandString()
		j.Name = c.RandString()
		j.ResourceVersion = strconv.FormatUint(c.RandUint64(), 10)
		j.FieldPath = c.RandString()
	},
	func(j *internal.PodPhase, c fuzz.Continue) {
		statuses := []internal.PodPhase{internal.PodPending, internal.PodRunning, internal.PodFailed, internal.PodUnknown}
		*j = statuses[c.Rand.Intn(len(statuses))]
	},
	func(j *internal.ReplicationControllerSpec, c fuzz.Continue) {
		// TemplateRef must be nil for round trip
		c.Fuzz(&j.Template)
		if j.Template == nil {
			// TODO: v1beta1/2 can't round trip a nil template correctly, fix by having v1beta1/2
			// conversion compare converted object to nil via DeepEqual
			j.Template = &internal.PodTemplateSpec{}
		}
		j.Template.ObjectMeta = internal.ObjectMeta{Labels: j.Template.ObjectMeta.Labels}
		j.Template.Spec.NodeSelector = nil
		c.Fuzz(&j.Selector)
		j.Replicas = int(c.RandUint64())
	},
	func(j *internal.ReplicationControllerStatus, c fuzz.Continue) {
		// only replicas round trips
		j.Replicas = int(c.RandUint64())
	},
	func(j *internal.List, c fuzz.Continue) {
		c.Fuzz(&j.ListMeta)
		c.Fuzz(&j.Items)
		if j.Items == nil {
			j.Items = []runtime.Object{}
		}
	},
	func(j *runtime.Object, c fuzz.Continue) {
		if c.RandBool() {
			*j = &runtime.Unknown{
				TypeMeta: runtime.TypeMeta{Kind: "Something", APIVersion: "unknown"},
				RawJSON:  []byte(`{"apiVersion":"unknown","kind":"Something","someKey":"someValue"}`),
			}
		} else {
			types := []runtime.Object{&internal.Pod{}, &internal.ReplicationController{}}
			t := types[c.Rand.Intn(len(types))]
			c.Fuzz(t)
			*j = t
		}
	},
	func(intstr *util.IntOrString, c fuzz.Continue) {
		// util.IntOrString will panic if its kind is set wrong.
		if c.RandBool() {
			intstr.Kind = util.IntstrInt
			intstr.IntVal = int(c.RandUint64())
			intstr.StrVal = ""
		} else {
			intstr.Kind = util.IntstrString
			intstr.IntVal = 0
			intstr.StrVal = c.RandString()
		}
	},
	func(pb map[docker.Port][]docker.PortBinding, c fuzz.Continue) {
		// This is necessary because keys with nil values get omitted.
		// TODO: Is this a bug?
		pb[docker.Port(c.RandString())] = []docker.PortBinding{
			{c.RandString(), c.RandString()},
			{c.RandString(), c.RandString()},
		}
	},
	func(pm map[string]docker.PortMapping, c fuzz.Continue) {
		// This is necessary because keys with nil values get omitted.
		// TODO: Is this a bug?
		pm[c.RandString()] = docker.PortMapping{
			c.RandString(): c.RandString(),
		}
	},
)

func TestInternalRoundTrip(t *testing.T) {
	latest := "v1beta2"

	for k := range internal.Scheme.KnownTypes("") {
		obj, err := internal.Scheme.New("", k)
		if err != nil {
			t.Errorf("%s: unexpected error: %v", k, err)
			continue
		}
		apiObjectFuzzer.Fuzz(obj)

		newer, err := internal.Scheme.New(latest, k)
		if err != nil {
			t.Errorf("%s: unexpected error: %v", k, err)
			continue
		}

		if err := internal.Scheme.Convert(obj, newer); err != nil {
			t.Errorf("unable to convert %#v to %#v: %v", obj, newer, err)
			continue
		}

		actual, err := internal.Scheme.New("", k)
		if err != nil {
			t.Errorf("%s: unexpected error: %v", k, err)
			continue
		}

		if err := internal.Scheme.Convert(newer, actual); err != nil {
			t.Errorf("unable to convert %#v to %#v: %v", newer, actual, err)
			continue
		}

		if !reflect.DeepEqual(obj, actual) {
			t.Errorf("%s: diff %s", k, util.ObjectDiff(obj, actual))
		}
	}
}

func TestResourceVersioner(t *testing.T) {
	pod := internal.Pod{ObjectMeta: internal.ObjectMeta{ResourceVersion: "10"}}
	version, err := ResourceVersioner.ResourceVersion(&pod)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if version != "10" {
		t.Errorf("unexpected version %v", version)
	}

	podList := internal.PodList{ListMeta: internal.ListMeta{ResourceVersion: "10"}}
	version, err = ResourceVersioner.ResourceVersion(&podList)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if version != "10" {
		t.Errorf("unexpected version %v", version)
	}
}

func TestCodec(t *testing.T) {
	pod := internal.Pod{}
	data, err := Codec.Encode(&pod)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	other := internal.Pod{}
	if err := json.Unmarshal(data, &other); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if other.APIVersion != Version || other.Kind != "Pod" {
		t.Errorf("unexpected unmarshalled object %#v", other)
	}
}

func TestInterfacesFor(t *testing.T) {
	if _, err := InterfacesFor(""); err == nil {
		t.Fatalf("unexpected non-error: %v", err)
	}
	for i, version := range append([]string{Version, OldestVersion}, Versions...) {
		if vi, err := InterfacesFor(version); err != nil || vi == nil {
			t.Fatalf("%d: unexpected result: %v", i, err)
		}
	}
}

func TestRESTMapper(t *testing.T) {
	if v, k, err := RESTMapper.VersionAndKindForResource("replicationControllers"); err != nil || v != Version || k != "ReplicationController" {
		t.Errorf("unexpected version mapping: %s %s %v", v, k, err)
	}
	if v, k, err := RESTMapper.VersionAndKindForResource("replicationcontrollers"); err != nil || v != Version || k != "ReplicationController" {
		t.Errorf("unexpected version mapping: %s %s %v", v, k, err)
	}

	for _, version := range Versions {
		mapping, err := RESTMapper.RESTMapping(version, "ReplicationController")
		if err != nil {
			t.Errorf("unexpected error: %v", err)
		}

		if mapping.Resource != "replicationControllers" && mapping.Resource != "replicationcontrollers" {
			t.Errorf("incorrect resource name: %#v", mapping)
		}
		if mapping.APIVersion != version {
			t.Errorf("incorrect version: %v", mapping)
		}

		interfaces, _ := InterfacesFor(version)
		if mapping.Codec != interfaces.Codec {
			t.Errorf("unexpected codec: %#v", mapping)
		}

		rc := &internal.ReplicationController{ObjectMeta: internal.ObjectMeta{Name: "foo"}}
		name, err := mapping.MetadataAccessor.Name(rc)
		if err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if name != "foo" {
			t.Errorf("unable to retrieve object meta with: %v", mapping.MetadataAccessor)
		}
	}
}


text:
/**
 * @author Swagatam Mitra

 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, document, console, brackets, $, Mustache */

define(function (require, exports, module) {
    "use strict";

    var startOffset = null;
    var layout = null;

    $(document).on("mousedown","#middle-left-control",function(event){
        startOffset = {x:event.clientX,y:event.clientY};
        $("#element-resize-plane").show();
        event.stopPropagation();
        layout.open();
    });

    $(document).on("mousemove","#element-resize-plane",function(event){
        if(startOffset){
            var xMov = startOffset.x - event.clientX;
            if(layout.xAxisAlignment === 'left'){
                layout.changeX(xMov);
            }
            layout.changeWidth(xMov);
            layout.refresh();
            startOffset = {x:event.clientX,y:event.clientY};
            event.stopPropagation();
        }
    });

    $(document).on("mouseleave mouseout mouseup ","#element-resize-plane",function(event){
        if(startOffset){
            startOffset = null;
            $("#element-resize-plane").hide();
            event.stopPropagation();
            layout.close();
        }
    });

    $(document).on("layout.decision","#html-design-editor", function(event,layoutObj){
        layout = layoutObj;
     });

    $(document).on("grouplayout.decision","#html-design-editor", function(event,layoutObj){
        layout = layoutObj;
     });

});


text:
package com.amee.domain.auth;

import com.amee.domain.*;
import com.amee.domain.environment.Environment;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.persistence.*;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * A Permission represents the permissions (rights) that a 'principal' has over an 'entity'.
 * The entity can be any persistent entity within AMEE, such as a Profile or DataCategory. A
 * principal can be a User, Group or other entity that needs to own or access an entity.
 *

 * The principal and entity are represented by AMEEEntityReference instances, the
 * principalReference and entityReference properties, respectively.
 *

 * Permissions are made up of permission entries. These typically represent the 'view',
 * 'create', 'modify', 'delete' verbs (CRUD). Each permission entry is accompanied
 * by an allow or deny flag. Other types of entries are also possible, such as
 * 'own' or 'create.profile'.
 *

 * The permission entries are stored in the entries property. Internally this is
 * held and persisted as a JSON String. The entries are exposed externally as a
 * Set of PermissionEntry instances. The entries String is automatically managed
 * by Permission.
 *
 * @author Diggory Briercliffe
 */
@Entity
@Table(name = "permission")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Permission extends AMEEEntity implements Comparable {

    public final static int ENTRIES_MAX_SIZE = 1000;

    @Override
    public boolean isTrash() {
        return status.equals(AMEEStatus.TRASH) || getEntityReference().getEntity().isTrash();
    }

    /**
     * The entity that this permission is governing access to.
     */
    @Embedded
    private AMEEEntityReference entityReference = new AMEEEntityReference();

    /**
     * The principal that this permission is defining access permissions for.
     */
    @Embedded
    @AttributeOverrides({
            @AttributeOverride(name = "entityId", column = @Column(name = "principal_id")),
            @AttributeOverride(name = "entityUid", column = @Column(name = "principal_uid")),
            @AttributeOverride(name = "entityType", column = @Column(name = "principal_type"))})
    private AMEEEntityReference principalReference = new AMEEEntityReference();

    /**
     * A String containing permission entries structured as JSON. These entries
     * are private but exposed via a Set of PermissionEntry instances.
     */
    @Column(name = "entries", length = ENTRIES_MAX_SIZE, nullable = false)
    private String entries = "";

    /**
     * Set of PermissionEntry instances. This represents the materialised view of
     * the entries JSON String. This property is managed internally and not exposed in
     * a form that can be manipulated.
     */
    @Transient
    private Set<PermissionEntry> entrySet;

    public Permission() {
        super();
    }

    public Permission(IAMEEEntityReference principal, IAMEEEntityReference entity) {
        this();
        setPrincipalReference(new AMEEEntityReference(principal));
        setEntityReference(new AMEEEntityReference(entity));
    }

    public Permission(IAMEEEntityReference principal, IAMEEEntityReference entity, PermissionEntry entry) {
        this(principal, entity);
        addEntry(entry);
    }

    public Permission(IAMEEEntityReference principal, IAMEEEntityReference entity, Collection<PermissionEntry> entries) {
        this(principal, entity);
        addEntries(entries);
    }

    public int compareTo(Object o) {
        if (this == o) return 0;
        if (equals(o)) return 0;
        Permission permission = (Permission) o;
        return getUid().compareTo(permission.getUid());
    }

    public JSONObject getJSONObject() throws JSONException {
        return getJSONObject(false);
    }

    public JSONObject getJSONObject(boolean detailed) throws JSONException {
        JSONObject obj = new JSONObject();
        obj.put("uid", getUid());
        JSONArray entriesArr = new JSONArray();
        for (PermissionEntry pe : this.getEntries()) {
            entriesArr.put(pe.getJSONObject());
        }
        obj.put("entries", entriesArr);
        obj.put("entity", getEntityReference().getJSONObject());
        obj.put("principal", getPrincipalReference().getJSONObject());
        if (detailed) {
            obj.put("created", getCreated());
            obj.put("modified", getModified());
            obj.put("environmentUid", Environment.ENVIRONMENT.getUid());
        }
        return obj;
    }

    public Element getElement(Document document) {
        return getElement(document, false);
    }

    public Element getElement(Document document, boolean detailed) {
        Element element = document.createElement("Permission");
        element.setAttribute("uid", getUid());
        Element entriesElement = document.createElement("Entries");
        for (PermissionEntry pe : this.getEntries()) {
            entriesElement.appendChild(pe.getElement(document));
        }
        element.appendChild(entriesElement);
        element.appendChild(getEntityReference().getElement(document, "Entity"));
        element.appendChild(getPrincipalReference().getElement(document, "Principal"));
        if (detailed) {
            element.setAttribute("created", getCreated().toString());
            element.setAttribute("modified", getModified().toString());
            element.appendChild(Environment.ENVIRONMENT.getIdentityElement(document));
        }
        return element;
    }

    /**
     * Returns the entityReference instance that associates this Permission
     * with the entity that the principal has permissions over.
     *
     * @return the entityReference instance
     */
    public AMEEEntityReference getEntityReference() {
        return entityReference;
    }

    /**
     * Update this Permission with the supplied entityReference representing the
     * entity for this Permission.
     *
     * @param entityReference instance to set
     */
    public void setEntityReference(AMEEEntityReference entityReference) {
        if (entityReference != null) {
            this.entityReference = entityReference;
        }
    }

    /**
     * Returns the principalReference instance that associates this Permission
     * with the principal that has permissions over the entity.
     *
     * @return the entityReference instance
     */
    public AMEEEntityReference getPrincipalReference() {
        return principalReference;
    }

    /**
     * Update this Permission with the supplied principalReference representing
     * the principal for this Permission.
     *
     * @param principalReference instance to set
     */
    public void setPrincipalReference(AMEEEntityReference principalReference) {
        if (principalReference != null) {
            this.principalReference = principalReference;
        }
    }

    /**
     * Returns an immutable Set of PermissionEntry instances. As PermissionEntry
     * instances are also immutable the returned set represents a read-only
     * view of the permission entries for this Permission instance. Use the addEntry
     * and removeEntry methods to modify the internal representation of entries.
     *
     * @return set of PermissionEntries
     */
    public Set<PermissionEntry> getEntries() {
        if (entrySet == null) {
            entrySet = new HashSet<PermissionEntry>();
            JSONObject json = getEntriesJSONObject();
            try {
                if (json.has("e")) {
                    JSONArray arr = json.getJSONArray("e");
                    for (int i = 0; i < arr.length(); i++) {
                        JSONObject obj = arr.getJSONObject(i);
                        String value = obj.has("v") ? obj.getString("v") : "";
                        String allow = obj.has("a") ? obj.getString("a") : "1";
                        AMEEStatus status = obj.has("s") ? AMEEStatus.values()[Integer.valueOf(obj.getString("s"))] : AMEEStatus.ACTIVE;
                        entrySet.add(new PermissionEntry(value, allow.equals("1"), status));
                    }
                }
            } catch (NumberFormatException e) {
                throw new RuntimeException("Caught NumberFormatException: " + e.getMessage(), e);
            } catch (JSONException e) {
                throw new RuntimeException("Caught JSONException: " + e.getMessage(), e);
            }
        }
        return Collections.unmodifiableSet(entrySet);
    }

    /**
     * Add a PermissionEntry to the entries. Will internally make sure the entries
     * set and string are updated.
     *
     * @param entry to add
     */
    public void addEntry(PermissionEntry entry) {
        // make sure entrySet is exists
        getEntries();
        // add the entry to entrySet
        entrySet.add(entry);
        // update the entries string
        updateEntriesJSONObject();
    }

    /**
     * Add PermissionEntries to the entries. Will internally make sure the entries
     * set and string are updated.
     *
     * @param entries to add
     */
    public void addEntries(Collection<PermissionEntry> entries) {
        // make sure entrySet is exists
        getEntries();
        // add the entries to entrySet
        entrySet.addAll(entries);
        // update the entries string
        updateEntriesJSONObject();
    }

    /**
     * Remove a PermissionEntry, matching the supplied PermissionEntry, from the
     * entries. Matching is based on the identity of the PermissionEntry as defined
     * by the equals method. Will internally make sure the entries set and
     * string are updated.
     *
     * @param entry to remove
     */
    public void removeEntry(PermissionEntry entry) {
        // TODO: Implement this.
        throw new UnsupportedOperationException();
    }

    private void updateEntriesJSONObject() {
        try {
            JSONArray arr = new JSONArray();
            for (PermissionEntry entry : getEntries()) {
                JSONObject obj = new JSONObject();
                obj.put("v", entry.getValue());
                if (!entry.isAllow()) {
                    obj.put("a", "0");
                }
                if (!entry.getStatus().equals(AMEEStatus.ACTIVE)) {
                    obj.put("s", entry.getStatus().ordinal());
                }
                arr.put(obj);
            }
            JSONObject json = new JSONObject();
            json.put("e", arr);
            entries = json.toString();
        } catch (JSONException e) {
            throw new RuntimeException("Caught JSONException: " + e.getMessage(), e);
        }
    }

    private JSONObject getEntriesJSONObject() {
        try {
            return new JSONObject(entries);
        } catch (JSONException e) {
            return new JSONObject();
        }
    }

    public ObjectType getObjectType() {
        return ObjectType.PRM;
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: dimaninc
 * Date: 31.08.2016
 * Time: 16:18
 */

namespace diCore\Helper;

class ArrayHelper
{
	const ESCAPE_NONE = 0;
	const ESCAPE_HTML = 1;

	public static function is($var)
	{
		return is_array($var) || (
			$var instanceof \ArrayAccess  &&
			$var instanceof \Traversable  &&
			//$var instanceof Serializable && todo: add this to diCollection!
			$var instanceof \Countable
		);
	}

	// simple, non associative, with sequential indexes
	public static function isSequential($ar)
    {
        if ($ar === []) {
            return true;
        }

        return array_keys($ar) === range(0, count($ar) - 1);
    }

    public static function hasStringKey($ar)
    {
        foreach ($ar as $key => $value) {
            if (is_string($key)) {
                return true;
            }
        }

        return false;
    }

	/**
	 * @param array $ar1
	 * @param array|null $ar2
	 * @return array
	 */
	public static function combine($ar1, $ar2 = null)
	{
		return $ar2 === null
			? array_combine($ar1, $ar1)
			: array_combine($ar1, $ar2);
	}

	/**
	 * @param $ar array
	 * @param $position integer
	 * @param $newItems array
	 *
	 * @return array
	 */
	public static function addItemsToAssocArray($ar, $position, $newItems)
	{
		return array_merge(
			array_slice($ar, 0, $position, true),
			$newItems,
			array_slice($ar, $position, count($ar) - $position, true)
		);
	}

	/**
	 * @param $ar
	 * @param $key
	 * @param $newItems
	 *
	 * @return array
	 * @throws \Exception
	 */
	public static function addItemsToAssocArrayAfterKey($ar, $key, $newItems)
	{
		$i = 0;

		foreach ($ar as $k => $v) {
			if ($k === $key) {
				return self::addItemsToAssocArray($ar, $i + 1, $newItems);
			}

			$i++;
		}

		throw new \Exception("No key '$key' found");
	}

	/**
	 * @param $ar
	 * @param $key
	 * @param $newItems
	 *
	 * @return array
	 * @throws \Exception
	 */
	public static function addItemsToAssocArrayBeforeKey($ar, $key, $newItems)
	{
		$i = 0;

		foreach ($ar as $k => $v) {
			if ($k === $key) {
				return self::addItemsToAssocArray($ar, $i, $newItems);
			}

			$i++;
		}

		throw new \Exception("No key '$key' found");
	}

	/**
	 * @param       $ar
	 * @param array $allowedKeys
	 * @param array $disallowedKeys
	 *
	 * @return array
	 */
	public static function filterByKey($ar, $allowedKeys = [], $disallowedKeys = [])
	{
		if ($allowedKeys) {
			$ar = array_intersect_key($ar, array_flip($allowedKeys));
		}

		if ($disallowedKeys) {
			$ar = array_diff_key($ar, array_flip($disallowedKeys));
		}

		return $ar;
	}

	public static function filterRecursive($ar, $callback = null)
    {
        foreach ($ar as &$value) {
            if (is_array($value)) {
                $value = self::filterRecursive($value, $callback);
            }
        }

        return array_filter($ar, $callback);
    }

	/**
	 * Flattens assoc array into an attributes string
	 *
	 * @param array $ar
	 * @return string
	 */
	public static function toAttributesString($ar, $skipNull = true, $escapeMethod = self::ESCAPE_NONE)
	{
		if ($skipNull) {
			$ar = array_filter($ar, function($v) {
				return $v !== null;
			});
		}

		array_walk($ar, function(&$value, $key) use($escapeMethod) {
			$raw = is_scalar($value) && !is_bool($value);

			$quote = $raw || $escapeMethod != self::ESCAPE_NONE ? '"' : "'";

			$value = $raw
				? $value
				: json_encode($value);

			switch ($escapeMethod) {
				default:
				case self::ESCAPE_NONE:
					$value = str_replace($quote, "\\" . $quote, $value);
					break;

				case self::ESCAPE_HTML:
					$value = StringHelper::out($value);
					break;
			}

			$value = $key . '=' . $quote . $value . $quote;
		});

		return join(' ', $ar);
	}

	public static function toString($ar, $pairSymbol = '=', $spaceSymbol = ' ')
    {
        $ar2 = [];

        foreach ($ar as $k => $v) {
            $ar2[] = $k . $pairSymbol . $v;
        }

        return join($spaceSymbol, $ar2);
    }

	/**
	 * Returns element of array by idx, setting proper type, if it exists, else returns default value
	 *
     * @deprecated use get() instead
	 * @param mixed $ar
	 * @param int|string|bool $idx
	 * @param mixed $defaultValue
	 * @param string $type
	 * @return mixed
	 */
	public static function getValue($ar, $idx, $defaultValue = null, $type = null)
	{
	    $ar = (array)$ar;

		$type = $type ?: gettype($defaultValue);

		if (isset($ar[$idx])) {
			$value = $ar[$idx];

			if ($type != 'NULL' && is_scalar($value)) {
			    if (in_array(strtolower($type), ['float', 'double'])) {
			        $value = StringHelper::fixFloatDot($value);
                }

				settype($value, $type);
			}

			return $value;
		} else {
			return $defaultValue;
		}
	}

    public static function get($deepArray, $path, $defaultValue = null, $type = null)
    {
        if (!$deepArray || is_scalar($deepArray)) {
            return $defaultValue;
        }

        $reduce = function ($xs, $x) {
            return $xs && array_key_exists($x, $xs) ? $xs[$x] : null;
        };

        if (!is_array($path)) {
            $path = explode('.', $path);
        }

        $value = array_reduce($path, $reduce, self::fromObject($deepArray)) ?? $defaultValue;
        $type = $type ?: gettype($defaultValue);

        if ($type != 'NULL' && is_scalar($value)) {
            if (in_array(strtolower($type), ['float', 'double'])) {
                $value = StringHelper::fixFloatDot($value);
            }

            settype($value, $type);
        }

        return $value;
    }

    /**
	 * @param array $array
	 * @return array
	 */
	public static function shuffleAssoc($array)
	{
		$new = array();
		$keys = array_keys($array);
		shuffle($keys);

		foreach($keys as $key) {
			$new[$key] = $array[$key];
		}

		return $new;
	}

	/**
	 * @param array $array
	 * @param mixed $value
	 * @return array
	 */
	public static function removeByValue($array, $value)
	{
		if (($key = array_search($value, $array)) !== false) {
			unset($array[$key]);
		}

		return $array;
	}

	/**
	 * @param array $ar
	 * @param string $defaultGlue
	 *
	 * @return string
	 */
	public static function recursiveJoin(array $ar, $defaultGlue = ' ')
	{
		$ar = array_filter($ar);

		foreach ($ar as $glue => &$value) {
		    // assoc array has `glue => array` structure, using default glue for simple arrays
		    if (!self::isAssoc($ar)) {
		        $glue = $defaultGlue;
            }

			if (is_array($value)) {
				$value = self::recursiveJoin($value, $glue);
			}
		}

		return join($defaultGlue, array_filter($ar));
	}

	/**
	 * Returns random $count elements from array
	 *
	 * @param array $ar
	 * @param int $count
	 *
	 * @return array
	 */
	public static function random(array $ar, $count = 1)
	{
		if ($count >= count($ar)) {
			return $ar;
		}

		$keys = array_rand($ar, $count);
		$out = [];

		foreach ($keys as $key) {
			$out[] = $ar[$key];
		}

		return $out;
	}

    public static function isAssoc(array $ar)
    {
        if ([] === $ar) {
            return false;
        }

        return array_keys($ar) !== range(0, count($ar) - 1);
    }

    /**
     * @param callable $f ($key, $value) => return ['new key', 'new value']
     * @param array $a
     * @return array
     */
    public static function mapAssoc(callable $f, array $a)
    {
        return array_column(array_map($f, array_keys($a), $a), 1, 0);
    }

    public static function fromObject($obj)
    {
        if (is_object($obj) || is_array($obj)) {
            $ret = (array)$obj;

            foreach ($ret as &$item) {
                $item = self::fromObject($item);
            }

            return $ret;
        } else {
            return $obj;
        }
    }

    public static function recursiveSum($array)
    {
        $sum = 0;

        foreach ($array as $key => $a) {
            if (is_array($a)) {
                $sum += self::recursiveSum($a);
            } else {
                $sum += $a;
            }
        }

        return $sum;
    }
}


text:
package io.quarkus.hibernate.validator.runtime;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import io.quarkus.arc.Subclass;

/**
 * Tests class normalization, which translates into getting the "original" class, without all the specializations instances of
 * {@link io.quarkus.arc.Subclass}. <br />
 * There's no need to be a @{@link io.quarkus.test.junit.QuarkusTest} because no Quarkus related feature is required.
 */
class ArcProxyBeanMetaDataClassNormalizerTest {

    @Test
    @DisplayName("Normalize should return same class if beanClass isn't a Subclass.")
    void normalize_simpleClass() {
        Class<Original> expected = Original.class;

        assertEquals(expected, new ArcProxyBeanMetaDataClassNormalizer().normalize(Original.class));
    }

    @Test
    @DisplayName("Normalize should return 'superclass' if beanClass is the only Subclass in it's class hierarchy.")
    void normalize_oneSubClass() {
        Class<Original> expected = Original.class;

        assertEquals(expected, new ArcProxyBeanMetaDataClassNormalizer().normalize(FirstSubclass.class));
    }

    @Test
    @DisplayName("Normalize should return upmost superclass if beanClass has more than one Subclass in it's class hierarchy.")
    void normalize_multipleSubClasses() {
        Class<Original> expected = Original.class;

        assertEquals(expected, new ArcProxyBeanMetaDataClassNormalizer().normalize(SecondSubclass.class));
    }

    private static class Original {
    }

    /**
     * Simulates an object injected through @{@link javax.inject.Inject}.
     */
    private static class FirstSubclass extends Original implements Subclass {
    }

    /**
     * Simulates an object injected through @{@link io.quarkus.test.junit.mockito.InjectMock}
     * or @{@link io.quarkus.test.junit.mockito.InjectSpy}.
     */
    private static class SecondSubclass extends FirstSubclass {
    }
}


text:
package net.krotscheck.util;

import net.krotscheck.test.UnitTest;
import org.apache.commons.io.input.NullInputStream;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.util.HashSet;
import java.util.Set;

/**
 * Unit tests for ResourceUtil.
 *
 * @author Michael Krotscheck
 */
@Category(UnitTest.class)
public final class ResourceUtilTest {

    /**
     * Assert that we can resolve a path in the resource directory.
     */
    @Test
    public void testGetPathForResource() {
        String name = "/valid-resource-file.txt";
        String path = ResourceUtil.getPathForResource(name);

        Assert.assertTrue(path.length() > 0);
        Assert.assertTrue(path.indexOf(name) > 0);

        String invalidName = "/invalid-resource-file.txt";
        String invalidPath = ResourceUtil.getPathForResource(invalidName);

        Assert.assertTrue(invalidPath.length() > 0);
        Assert.assertTrue(invalidPath.indexOf(invalidName) > 0);
    }

    /**
     * Assert that we can convert a resource path to a file.
     */
    @Test
    public void testGetFileForResource() {
        String name = "/valid-resource-file.txt";
        File resource = ResourceUtil.getFileForResource(name);

        Assert.assertEquals("valid-resource-file.txt", resource.getName());
        Assert.assertTrue(resource.exists());
        Assert.assertTrue(resource.isFile());

        String invalidName = "/invalid-resource-file.txt";
        File invalidResource = ResourceUtil.getFileForResource(invalidName);

        Assert.assertEquals("invalid-resource-file.txt",
                invalidResource.getName());
        Assert.assertFalse(invalidResource.exists());
        Assert.assertFalse(invalidResource.isFile());
    }

    /**
     * Assert that we can read a resource as a string.
     *
     * @throws Exception Should not be thrown.
     */
    @Test
    public void testGetResourceAsString() throws Exception {
        String name = "/valid-resource-file.txt";
        String content = ResourceUtil.getResourceAsString(name);

        Assert.assertEquals("valid resource content", content);

        String invalidName = "/invalid-resource-file.txt";
        String invalidContent = ResourceUtil.getResourceAsString(invalidName);

        Assert.assertEquals("", invalidContent);

        // Make the file write only
        File resource = ResourceUtil.getFileForResource(name);
        Set<PosixFilePermission> oldPerms = Files
                .getPosixFilePermissions(resource.toPath());
        Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        perms.add(PosixFilePermission.GROUP_WRITE);
        perms.add(PosixFilePermission.GROUP_EXECUTE);
        perms.add(PosixFilePermission.OTHERS_WRITE);
        perms.add(PosixFilePermission.OTHERS_EXECUTE);

        // Write only...
        Files.setPosixFilePermissions(resource.toPath(), perms);
        String writeOnlyName = "/valid-resource-file.txt";
        String writeOnlyContent = ResourceUtil
                .getResourceAsString(writeOnlyName);
        Assert.assertEquals("", writeOnlyContent);

        Files.setPosixFilePermissions(resource.toPath(), oldPerms);

    }

    /**
     * Assert that we can read a resource as a stream.
     *
     * @throws Exception Should not be thrown.
     */
    @Test
    public void testGetResourceAsStream() throws Exception {
        String name = "/valid-resource-file.txt";
        InputStream stream = ResourceUtil.getResourceAsStream(name);
        Assert.assertTrue(stream.available() > 0);

        String invalidName = "/invalid-resource-file.txt";
        InputStream invalidContent = ResourceUtil
                .getResourceAsStream(invalidName);

        Assert.assertTrue(invalidContent instanceof NullInputStream);
        Assert.assertTrue(invalidContent.available() == 0);

        // Make the file write only
        File resource = ResourceUtil.getFileForResource(name);
        Set<PosixFilePermission> oldPerms = Files
                .getPosixFilePermissions(resource.toPath());
        Set<PosixFilePermission> perms = new HashSet<>();
        perms.add(PosixFilePermission.OWNER_WRITE);
        perms.add(PosixFilePermission.OWNER_EXECUTE);
        perms.add(PosixFilePermission.GROUP_WRITE);
        perms.add(PosixFilePermission.GROUP_EXECUTE);
        perms.add(PosixFilePermission.OTHERS_WRITE);
        perms.add(PosixFilePermission.OTHERS_EXECUTE);

        // Write only...
        Files.setPosixFilePermissions(resource.toPath(), perms);
        String writeOnlyName = "/valid-resource-file.txt";
        InputStream writeOnlyContent = ResourceUtil
                .getResourceAsStream(writeOnlyName);
        Assert.assertTrue(writeOnlyContent instanceof NullInputStream);
        Assert.assertTrue(writeOnlyContent.available() == 0);

        Files.setPosixFilePermissions(resource.toPath(), oldPerms);
    }

    /**
     * Ensure the constructor is private.
     *
     * @throws Exception Tests throw exceptions.
     */
    @Test
    public void testConstructorIsPrivate() throws Exception {
        Constructor<ResourceUtil> constructor = ResourceUtil.class
                .getDeclaredConstructor();
        Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers()));

        // Override the private constructor and create an instance
        constructor.setAccessible(true);
        ResourceUtil util = constructor.newInstance();
        Assert.assertNotNull(util);
    }

    /**
     * Assert that nonexistent files provide the expected response.
     *
     * @throws Exception Should not be thrown.
     */
    @Test
    public void testGetNonexistentResource() throws Exception {
        String name = "/invalid-resource-file.txt";
        InputStream stream = ResourceUtil.getResourceAsStream(name);
        Assert.assertFalse(stream.available() > 0);

        String content = ResourceUtil.getResourceAsString(name);
        Assert.assertEquals("", content);
    }

    /**
     * Assert that nonexistent files provide the expected response.
     *
     * @throws Exception Should not be thrown.
     */
    @Test
    public void testGetDirectoryResource() throws Exception {
        String name = "/dir";
        InputStream stream = ResourceUtil.getResourceAsStream(name);
        Assert.assertFalse(stream.available() > 0);

        String content = ResourceUtil.getResourceAsString(name);
        Assert.assertEquals("", content);
    }
}


text:
import { GraphQLSchema } from 'graphql';
import { wrapResolvers } from '@adeira/graphql-resolve-wrapper';

const Schema = new GraphQLSchema({});

wrapResolvers(Schema, resolveFn => async (...args) => {
    const value = await resolveFn(...args);
    return typeof value === 'string' ? value.toUpperCase() : value;
});


text:
package org.hy.common.report.event;

import java.io.ByteArrayOutputStream;

import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Picture;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.hy.common.Help;
import org.hy.common.report.bean.RSystemValue;
import org.hy.common.report.bean.RTemplate;
import org.hy.common.report.bean.RWorkbook;
import org.hy.common.zxing.ZXingHelp;

import com.google.zxing.BarcodeFormat;

/**
 * 二维码的监听器
 *
 * @author      ZhengWei(HY)
 * @createDate  2017-10-30
 * @version     v1.0
 */
public class ZXingListener extends ImageListener implements ValueListener
{

    /** 二维码、条形码的类型 */
    private BarcodeFormat  barcodeFormat;

    /** 二维码的宽度 */
    private Integer        width;

    /** 二维码的高度 */
    private Integer        height;

    /**
     * 获取:二维码、条形码的类型
     */
    public BarcodeFormat getBarcodeFormat()
    {
        return barcodeFormat;
    }

    /**
     * 设置:二维码、条形码的类型
     *
     * @param barcodeFormat
     */
    public void setBarcodeFormat(BarcodeFormat barcodeFormat)
    {
        this.barcodeFormat = barcodeFormat;
    }

    /**
     * 获取:二维码的宽度
     */
    public Integer getWidth()
    {
        return width;
    }

    /**
     * 设置:二维码的宽度
     *
     * @param width
     */
    public void setWidth(Integer width)
    {
        this.width = width;
    }

    /**
     * 获取:二维码的高度
     */
    public Integer getHeight()
    {
        return height;
    }

    /**
     * 设置:二维码的高度
     *
     * @param height
     */
    public void setHeight(Integer height)
    {
        this.height = height;
    }

    /**
     * 对变量名称反射出来的值进行加工处理
     *
     * @author      ZhengWei(HY)
     * @createDate  2017-03-18
     * @version     v1.0
     *
     * @param i_RTemplate     模板
     * @param i_TemplateCell  模板单元格对象
     * @param i_DataCell      数据单元格对象
     * @param i_DataWorkbook  数据工作薄对象
     * @param i_RSystemValue  系统变量信息
     * @param i_Datas         本行对应的数据
     * @param i_Value         反射出来的变量名称对应的值(二维码原文)
     * @return
     */
    public String getValue(RTemplate i_RTemplate ,Cell i_TemplateCell ,Cell i_DataCell ,RWorkbook i_DataWorkbook ,RSystemValue i_RSystemValue ,Object i_Datas ,Object i_Value)
    {
        if ( i_Value == null )
        {
            return "";
        }

        String v_ZXingValue = i_Value.toString().trim();
        if ( Help.isNull(v_ZXingValue) )
        {
            return "";
        }

        ByteArrayOutputStream v_ByteArrayOut = new ByteArrayOutputStream();
        try
        {
            ZXingHelp.encodeToStream(this.barcodeFormat  ,v_ByteArrayOut ,v_ZXingValue ,this.width ,this.height);
        }
        catch (Exception exce)
        {
            exce.printStackTrace();
            return "";
        }

        Drawing<?>   v_Drawing      = i_DataCell.getSheet().createDrawingPatriarch();
        ClientAnchor v_ClientAnchor = null;
        int          v_PictureType  = 0;
        int          v_OffsetRow    = i_RTemplate.getRowCountData() * (i_RSystemValue.getRowNo() - 1);

        if ( v_Drawing instanceof HSSFPatriarch )
        {
            v_ClientAnchor = new HSSFClientAnchor(0 ,0 ,0 ,0
                                                 ,this.beginColumn
                                                 ,this.beginRow + v_OffsetRow
                                                 ,this.endColumn
                                                 ,this.endRow   + v_OffsetRow);
        }
        else if ( v_Drawing instanceof XSSFDrawing )
        {
            v_ClientAnchor = new XSSFClientAnchor(0 ,0 ,0 ,0
                                                 ,this.beginColumn
                                                 ,this.beginRow + v_OffsetRow
                                                 ,this.endColumn
                                                 ,this.endRow   + v_OffsetRow);
        }
        else if ( v_Drawing instanceof SXSSFDrawing )
       {
            v_ClientAnchor = new XSSFClientAnchor(0 ,0 ,0 ,0
                                                 ,this.beginColumn
                                                 ,this.beginRow + v_OffsetRow
                                                 ,this.endColumn
                                                 ,this.endRow   + v_OffsetRow);
        }
        else
        {
            throw new java.lang.ClassCastException(v_Drawing.getClass().getName() + " is not find Type.");
        }

        v_ClientAnchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

        v_PictureType = Workbook.PICTURE_TYPE_PNG;

        int v_PictureIndex = i_DataCell.getSheet().getWorkbook().addPicture(v_ByteArrayOut.toByteArray() ,v_PictureType);
        Picture v_Picture  = v_Drawing.createPicture(v_ClientAnchor ,v_PictureIndex);

        this.resizeMarginLeftTop(v_Picture ,null ,this.isScale ,Help.NVL(this.scaleX ,1D) ,Help.NVL(this.scaleY ,1D));

        return "";
    }

}


text:
'use strict';

/**
 * @fileoverview Creates an http server to handle static
 * files and list directories for use with the gulp live server
 */
const app = require(require.resolve('./app.js'));
const colors = require('ansi-colors');
const gulp = require('gulp-help')(require('gulp'));
const isRunning = require('is-running');
const log = require('fancy-log');
const morgan = require('morgan');
const webserver = require('gulp-webserver');

const {
  SERVE_HOST: host,
  SERVE_PORT: port,
  SERVE_PROCESS_ID: gulpProcess,
} = process.env;

const useHttps = process.env.SERVE_USEHTTPS == 'true';
const quiet = process.env.SERVE_QUIET == 'true';
const sendCachingHeaders = process.env.SERVE_CACHING_HEADERS == 'true';
const header = require('connect-header');

// Exit if the port is in use.
process.on('uncaughtException', function(err) {
  if (err.errno === 'EADDRINUSE') {
    log(colors.red('Port', port, 'in use, shutting down server'));
  } else {
    log(colors.red(err));
  }
  process.kill(gulpProcess, 'SIGINT');
  process.exit(1);
});

// Exit in the event of a crash in the parent gulp process.
setInterval(function() {
  if (!isRunning(gulpProcess)) {
    process.exit(1);
  }
}, 1000);

const middleware = [];
if (!quiet) {
  middleware.push(morgan('dev'), app);
}
if (sendCachingHeaders) {
  middleware.push(header({
    'cache-control': ' max-age=600',
  }));
}

// Start gulp webserver
gulp.src(process.cwd())
    .pipe(webserver({
      port,
      host,
      directoryListing: true,
      https: useHttps,
      middleware,
    }));


text:
This repository contains a PowerShell module with a DSC resource that can be used to install the [Octopus Deploy](http://octopusdeploy.com) Tentacle agent.

## Install Tentacle Package
Installation of the MSI Package has been extracted from this resource, make use of the Package resource to install as demonstrated below

```
File OctopusPath{
	Ensure = "Present"
	Type = "Directory"
	DestinationPath = "C:\Octopus"
}
Package OctoTentacle{
	Name = "Octopus Deploy Tentacle"
	Ensure = "Present"
	Path = "https://download.octopusdeploy.com/octopus/Octopus.Tentacle.2.6.5.1010-x64.msi"
	Arguments = "/l*v $($env:SystemDrive)\Octopus\Tentacle.msi.log"
	ProductId = ""
	DependsOn = @("[File]OctopusPath")
}
```

## Sample

First, ensure the OctopusDSC module is on your `$env:PSModulePath`. Then you can create and apply configuration like this.

```
Configuration SampleConfig
{
    param ($ApiKey, $OctopusServerUrl, $Environments, $Roles, $ListenPort)

    Import-DscResource -Module OctopusDSC

    Node "localhost"
    {
        cTentacleAgent OctopusTentacle{
            Ensure = "Present"
            State = "Started"

            # Tentacle instance name. Leave it as 'Tentacle' unless you have more
            # than one instance
            Name = "Tentacle"

            # Registration - all parameters required
            ApiKey = "API-ABCDEF12345678910"
            OctopusServerUrl = "https://demo.octopusdeploy.com" #Please ensure there is no trailing forward slash in the URL
            Environments = "Staging"
            Roles = @("web-server", "app-server")

            # Optional settings
            ListenPort = 10933
            nicType = "detect"
				<#
				- "detect" #This sets the value for what kind of NIC we should expect. "detect" will test the connection to the octopus server and use the NIC that successfully connects, it is the default value.
				- "named" is where you know the name of the NIC and the connection will be tested and verify the NIC named is the one that reached the octopus server. "nicName" variable is required if this is set.
				- "natted" will verify a connection to the octopus server and then it will call a 3rd party service to determine it's public IP
				#>
			# nicName # only required if nicType is set to "named" - will be ignored otherwise
            DefaultApplicationDirectory = "C:\Octopus"
        }
    }
}

SampleConfig -ApiKey "API-ABCDEF12345678910" -OctopusServerUrl "https://demo.octopusdeploy.com/" -Environments @("Development") -Roles @("web-server", "app-server") -ListenPort 10933

Start-DscConfiguration .\SampleConfig -Verbose -wait

Test-DscConfiguration
```

## Deploying Projects
```
Configuration SampleConfig
{
    param ($ApiKey, $OctopusServerUrl, $DeployProject, $DeployVersion, $Environments, $Roles, $ListenPort)

    Import-DscResource -Module OctopusDSC

    Node "localhost"
	{
		cProjectDeploy Config{
            ApiKey = "API-ABCDEF12345678910"
            OctopusServerUrl = "https://demo.octopusdeploy.com/"
            DeployProject = "Sample Project"
            Environments = "Staging"
            DeployVersion = "1.1.0.121"
        }
	}
}

SampleConfig -ApiKey "API-ABCDEF12345678910" -OctopusServerUrl "https://demo.octopusdeploy.com/" -DeployProject "DotNet Project" -DeployVersion "1.0.3" -Environments @("Development") -Roles @("web-server", "app-server") -ListenPort 10933

Start-DscConfiguration .\SampleConfig -Verbose -wait

Test-DscConfiguration
```

Repeat this config block as many times as necessary to deploy all projects.

## Settings

When `Ensure` is set to `Present`, the resource will:

 1. Download the Tentacle MSI from the internet
 2. Install the MSI
 3. Configure Tentacle in listening mode on the specified port (10933 by default)
 4. Add a Windows firewall exception for the listening port
 5. Register the Tentacle with your Octopus server, using the registration settings

When `Ensure` is set to `Absent`, the resource will:

 1. De-register the Tentacle from your Octopus server, using the registration settings
 2. Delete the Tentacle windows service
 3. Uninstall using the MSI

When `State` is `Started`, the resource will ensure that the Tentacle windows service is running. When `Stopped`, it will ensure the service is stopped.

## Drift

Currently the resource only considers the `Ensure` and `State` properties when testing for drift.

This means that if you set `Ensure` to `Present` to install Tentacle, then later set it to `Absent`, testing the configuration will return `$false`. Likewise if you set the `State` to `Stopped` and the service is running.

However, if you were to set the `ListenPort` to a new port, the drift detection isn't smart enough to check the old configuration, nor update the registered machine. You'll need to uninstall and reinstall for these other settings to take effect.

## Development
If you are making changes to the module, keep in mind that your changes may not be loaded, as the module gets cached by `WmiPrvSE`. You can use the following command to kill `WmiPrvSE`:

```
Stop-Process -Name WmiPrvSE -Force -ErrorAction SilentlyContinue | out-null
```


text:
***********************
The HTTP-SERVER library
***********************

.. current-library:: http-server
.. current-module:: http-server

The HTTP-SERVER module
======================

.. variable:: *command-line-parser*

.. variable:: *log-content?*

.. class:: <abstract-resource>
   :open:
   :abstract:

   :superclasses: <object>

.. class:: <abstract-rewrite-rule>
   :open:
   :abstract:

   :superclasses: <object>

   :keyword redirect-code:
   :keyword terminal?:

.. class:: <abstract-router>
   :open:
   :abstract:

   :superclasses: <object>

.. class:: <configuration-error>

   :superclasses: <http-server-api-error>

.. class:: <directory-resource>
   :open:

   :superclasses: <resource>

   :keyword allow-directory-listing?:
   :keyword allow-multi-views?:
   :keyword default-documents:
   :keyword directory:
   :keyword follow-symlinks?:

.. class:: <function-resource>
   :open:

   :superclasses: <resource>

   :keyword function:
   :keyword methods:

.. class:: <http-server>
   :open:

   :superclasses: <multi-logger-mixin>:httpi, <abstract-router>

   :keyword clients-shutdown-notification:
   :keyword debug:
   :keyword default-virtual-host:
   :keyword listeners:
   :keyword listeners-shutdown-notification:
   :keyword lock:
   :keyword media-type-map:
   :keyword server-root:
   :keyword session-id:
   :keyword session-max-age:
   :keyword use-default-virtual-host?:
   :keyword virtual-hosts:

.. class:: <http-server-api-error>
   :open:

   :superclasses: <http-server-error>:httpi

.. class:: <page-context>

   :superclasses: <attributes-mixin>:http-common:http-common

.. class:: <redirecting-resource>

   :superclasses: <resource>

   :keyword target:

.. class:: <request>
   :open:
   :primary:

   :superclasses: <chunking-input-stream>:http-common:http-common, <base-http-request>:http-common:http-common

.. class:: <resource>
   :open:

   :superclasses: <abstract-resource>, <abstract-router>

.. class:: <response>
   :open:
   :primary:

   :superclasses: <string-stream>:streams:io, <base-http-response>:http-common:http-common

   :keyword direction:

.. class:: <rewrite-rule>

   :superclasses: <abstract-rewrite-rule>

   :keyword regex:
   :keyword replacement:

.. class:: <session>
   :open:
   :primary:

   :superclasses: <attributes-mixin>:http-common:http-common

   :keyword id:
   :keyword server:

.. class:: <virtual-host>

   :superclasses: <multi-logger-mixin>:httpi, <abstract-router>, <abstract-resource>

   :keyword router:

.. generic-function:: add-cookie

   :signature: add-cookie (response name value) => (#rest results)

   :parameter response: An instance of ``<object>``.
   :parameter name: An instance of ``<object>``.
   :parameter value: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: add-resource
   :open:

   :signature: add-resource (router url resource #key #all-keys) => (#rest results)

   :parameter router: An instance of ``<abstract-router>``.
   :parameter url: An instance of ``<object>``.
   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: add-resource-name
   :open:

   :signature: add-resource-name (name resource) => (#rest results)

   :parameter name: An instance of ``<string>``.
   :parameter resource: An instance of ``<resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: add-virtual-host
   :open:

   :signature: add-virtual-host (server fqdn vhost) => ()

   :parameter server: An instance of ``<http-server>``.
   :parameter fqdn: An instance of ``<string>``.
   :parameter vhost: An instance of ``<virtual-host>``.

.. generic-function:: clear-session

   :signature: clear-session (request) => (#rest results)

   :parameter request: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: configure-server

   :signature: configure-server (server config-file) => (#rest results)

   :parameter server: An instance of ``<object>``.
   :parameter config-file: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. function:: count-query-values

   :signature: count-query-values () => (count)

   :value count: An instance of ``<integer>``.

.. function:: current-request

   :signature: current-request () => (request)

   :value request: An instance of ``<request>``.

.. function:: current-response

   :signature: current-response () => (response)

   :value response: An instance of ``<response>``.

.. function:: current-server

   :signature: current-server () => (server)

   :value server: An instance of ``<http-server>``.

.. generic-function:: debugging-enabled?

   :signature: debugging-enabled? (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: debugging-enabled?-setter

   :signature: debugging-enabled?-setter (value object) => (#rest results)

   :parameter value: An instance of ``<object>``.
   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: default-content-type
   :open:

   :signature: default-content-type (resource) => (content-type)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value content-type: An instance of ``type-union(<mime-type>, <string>)``.

.. generic-function:: default-documents

   :signature: default-documents (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: default-virtual-host

   :signature: default-virtual-host (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: default-virtual-host-setter

   :signature: default-virtual-host-setter (value object) => (#rest results)

   :parameter value: An instance of ``<object>``.
   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: do-query-values

   :signature: do-query-values (f) => (#rest results)

   :parameter f: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: do-resources
   :open:

   :signature: do-resources (router function #key seen) => ()

   :parameter router: An instance of ``<abstract-router>``.
   :parameter function: An instance of ``<function>``.
   :parameter #key seen: An instance of ``<object>``.

.. generic-function:: ensure-session

   :signature: ensure-session (request) => (#rest results)

   :parameter request: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. function:: file-contents

   :signature: file-contents (filename #key error?) => (contents)

   :parameter filename: An instance of ``<pathname>:file-system:system``.
   :parameter #key error?: An instance of ``<boolean>``.
   :value contents: An instance of ``false-or(<string>)``.

.. generic-function:: find-resource
   :open:

   :signature: find-resource (router url) => (resource prefix suffix)

   :parameter router: An instance of ``<abstract-router>``.
   :parameter url: An instance of ``<object>``.
   :value resource: An instance of ``<abstract-resource>``.
   :value prefix: An instance of ``<list>``.
   :value suffix: An instance of ``<list>``.

.. generic-function:: find-virtual-host
   :open:

   :signature: find-virtual-host (server fqdn) => (vhost)

   :parameter server: An instance of ``<http-server>``.
   :parameter fqdn: An instance of ``<string>``.
   :value vhost: An instance of ``<virtual-host>``.

.. function:: function-resource

   :signature: function-resource (function #key methods) => (resource)

   :parameter function: An instance of ``<function>``.
   :parameter #key methods: An instance of ``<object>``.
   :value resource: An instance of ``<resource>``.

.. generic-function:: generate-url
   :open:

   :signature: generate-url (router name #key #all-keys) => (url)

   :parameter router: An instance of ``<abstract-router>``.
   :parameter name: An instance of ``<string>``.
   :value url: An instance of ``<object>``.

.. generic-function:: get-attr

   :signature: get-attr (node attrib) => (#rest results)

   :parameter node: An instance of ``<object>``.
   :parameter attrib: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. function:: get-query-value

   :signature: get-query-value (key #key as) => (value)

   :parameter key: An instance of ``<string>``.
   :parameter #key as: An instance of ``false-or(<type>)``.
   :value value: An instance of ``<object>``.

   Return the first (and usually the only) query value associated with ``key``,
   or ``#f`` if no value found.

   Query values are any values from the query portion of the URL or from POST
   data for requests encoded as either ``application/x-www-form-urlencoded`` or
   ``multipart/form-data``.

   See also: :func:`get-query-values`

.. function:: get-query-values

   :signature: get-query-values (key) => (values)

   :parameter key: An instance of ``<string>``.
   :value values: An instance of ``<sequence>``.

   Returns all query values associated with ``key``, or an empty sequence if no
   values are found.

   Query values are any values from the query portion of the URL or from POST
   data for requests encoded as either ``application/x-www-form-urlencoded`` or
   ``multipart/form-data``. In some cases, such as file upload that allows
   multiple file to be selected, there may be several values for a single key
   and :func:`get-query-values` is what you need in that case.

   For most common cases, however, :func:`get-query-value` is the right choice.

.. generic-function:: get-session

   :signature: get-session (request) => (#rest results)

   :parameter request: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. function:: http-server-main

   :signature: http-server-main (#key server description before-startup) => ()

   :parameter #key server: An instance of ``false-or(<http-server>)``.
   :parameter #key description: An instance of ``false-or(<string>)``.
   :parameter #key before-startup: An instance of ``false-or(<function>)``.

.. generic-function:: log-content

   :signature: log-content (content) => (#rest results)

   :parameter content: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. constant:: log-debug

.. constant:: log-error

.. constant:: log-info

.. constant:: log-trace

.. constant:: log-warning

.. function:: output

   :signature: output (format-string #rest format-args) => (#rest results)

   :parameter format-string: An instance of ``<object>``.
   :parameter #rest format-args: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: page-context

   :signature: page-context () => (#rest results)

   :value #rest results: An instance of ``<object>``.

.. generic-function:: process-config-element
   :open:

   :signature: process-config-element (server node name) => (#rest results)

   :parameter server: An instance of ``<http-server>``.
   :parameter node: An instance of ``<object>``.
   :parameter name: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: process-request-content
   :open:

   :signature: process-request-content (request content-type) => (#rest results)

   :parameter request: An instance of ``<request>``.
   :parameter content-type: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: redirect-temporarily-to
   :open:

   :signature: redirect-temporarily-to (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: redirect-to
   :open:

   :signature: redirect-to (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: request-absolute-url

   :signature: request-absolute-url (request) => (#rest results)

   :parameter request: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. function:: request-content-type

   :signature: request-content-type (request) => (#rest results)

   :parameter request: An instance of ``<request>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: request-host

   :signature: request-host (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: request-query-values

   :signature: request-query-values (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: request-url-path-prefix

   :signature: request-url-path-prefix (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: request-url-path-suffix

   :signature: request-url-path-suffix (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond
   :open:

   :signature: respond (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond-to-connect
   :open:

   :signature: respond-to-connect (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond-to-delete
   :open:

   :signature: respond-to-delete (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond-to-get
   :open:

   :signature: respond-to-get (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond-to-head
   :open:

   :signature: respond-to-head (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond-to-options
   :open:

   :signature: respond-to-options (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond-to-post
   :open:

   :signature: respond-to-post (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond-to-put
   :open:

   :signature: respond-to-put (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: respond-to-trace
   :open:

   :signature: respond-to-trace (resource #key #all-keys) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: rewrite-url
   :open:

   :signature: rewrite-url (url rule) => (url extra)

   :parameter url: An instance of ``<string>``.
   :parameter rule: An instance of ``<object>``.
   :value url: An instance of ``<string>``.
   :value extra: An instance of ``<object>``.

.. generic-function:: route-request

   :signature: route-request (server request) => (#rest results)

   :parameter server: An instance of ``<object>``.
   :parameter request: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: serve-static-file

   :signature: serve-static-file (policy locator) => (#rest results)

   :parameter policy: An instance of ``<object>``.
   :parameter locator: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: server-root

   :signature: server-root (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: start-server
   :open:

   :signature: start-server (server #key background wait) => (started?)

   :parameter server: An instance of ``<http-server>``.
   :parameter #key background: An instance of ``<boolean>``.
   :parameter #key wait: An instance of ``<boolean>``.
   :value started?: An instance of ``<boolean>``.

.. generic-function:: stop-server
   :open:

   :signature: stop-server (server #key abort) => (#rest results)

   :parameter server: An instance of ``<http-server>``.
   :parameter #key abort: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: unmatched-url-suffix
   :open:

   :signature: unmatched-url-suffix (resource unmatched-path) => (#rest results)

   :parameter resource: An instance of ``<abstract-resource>``.
   :parameter unmatched-path: An instance of ``<sequence>``.
   :value #rest results: An instance of ``<object>``.

.. generic-function:: use-default-virtual-host?

   :signature: use-default-virtual-host? (object) => (#rest results)

   :parameter object: An instance of ``<object>``.
   :value #rest results: An instance of ``<object>``.

.. macro:: with-query-values


text:
import Ember from 'ember';

export default Ember.Mixin.create({
    actions: {
        error(error, transition) {
            if (error.errors && error.errors[0].errorType === 'NotFoundError') {
                transition.abort();

                let routeInfo = transition.handlerInfos[transition.handlerInfos.length - 1];
                let router = this.get('router');
                let params = [];

                for (const key of Object.keys(routeInfo.params)) {
                    params.push(routeInfo.params[key]);
                }

                return this.transitionTo('error404', router.generate(routeInfo.name, ...params).replace('/ghost/', '').replace(/^\//g, ''));
            }

            return this._super(...arguments);
        }
    }
});


text:
<manifest package="io.demor.nuts.rx">

    <application/>
</manifest>


text:
require 'test_helper'

class UserTest < ActiveSupport::TestCase
  test 'should get all users who have not made an order so far' do
    users(:one).orders = [orders(:one)]

    assert_equal [users(:three)], User.users_without_current_orders
  end
end


text:
package com.terremark.api;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlType;

/**
 *

 * Java class for Template complex type.
 *

 * The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="Template">
 *   <complexContent>
 *     <extension base="{}Resource">
 *       <sequence>
 *         <element name="OperatingSystem" type="{}Reference" minOccurs="0"/>
 *         <element name="Description" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *         <element name="ComputeMatrix" type="{}ComputeMatrix" minOccurs="0"/>
 *         <element name="Processor" type="{}ConfigurationOptionRange" minOccurs="0"/>
 *         <element name="Memory" type="{}ResourceCapacityRange" minOccurs="0"/>
 *         <element name="Storage" type="{}TemplateStorage" minOccurs="0"/>
 *         <element name="NetworkAdapters" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="Customization" type="{}CustomizationOption" minOccurs="0"/>
 *         <element name="LicensedSoftware" type="{}DeviceLicensedSoftware" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Template", propOrder = {"operatingSystem", "description", "computeMatrix", "processor", "memory",
                "storage", "networkAdapters", "customization", "licensedSoftware"})
@javax.xml.bind.annotation.XmlRootElement(name = "Template")
public final class Template extends Resource {

    @XmlElement(name = "OperatingSystem", nillable = true)
    protected Reference operatingSystem;
    @XmlElement(name = "Description", nillable = true)
    protected String description;
    @XmlElement(name = "Processor", nillable = true)
    protected ConfigurationOptionRange processor;
    @XmlElement(name = "Memory", nillable = true)
    protected ResourceCapacityRange memory;
    @XmlElement(name = "Storage", nillable = true)
    protected TemplateStorage storage;
    @XmlElement(name = "NetworkAdapters")
    protected Integer networkAdapters;
    @XmlElement(name = "Customization", nillable = true)
    protected CustomizationOption customization;
    @XmlElement(name = "LicensedSoftware", nillable = true)
    protected DeviceLicensedSoftware licensedSoftware;
    @XmlElementWrapper(name = "ComputeMatrix")
    @XmlElement(name = "Entry")
    protected List<ComputeMatrixEntry> computeMatrix;

    /**
     * Gets the value of the operatingSystem property.
     *
     * @return possible object is {@link Reference }
     */
    public Reference getOperatingSystem() {
        return operatingSystem;
    }

    /**
     * Sets the value of the operatingSystem property.
     *
     * @param value allowed object is {@link Reference }
     */
    public void setOperatingSystem(final Reference value) {
        this.operatingSystem = value;
    }

    /**
     * Gets the value of the description property.
     *
     * @return possible object is {@link String }
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the value of the description property.
     *
     * @param value allowed object is {@link String }
     */
    public void setDescription(final String value) {
        this.description = value;
    }

    /**
     * Gets the value of the processor property.
     *
     * @return possible object is {@link ConfigurationOptionRange }
     */
    public ConfigurationOptionRange getProcessor() {
        return processor;
    }

    /**
     * Sets the value of the processor property.
     *
     * @param value allowed object is {@link ConfigurationOptionRange }
     */
    public void setProcessor(final ConfigurationOptionRange value) {
        this.processor = value;
    }

    /**
     * Gets the value of the memory property.
     *
     * @return possible object is {@link ResourceCapacityRange }
     */
    public ResourceCapacityRange getMemory() {
        return memory;
    }

    /**
     * Sets the value of the memory property.
     *
     * @param value allowed object is {@link ResourceCapacityRange }
     */
    public void setMemory(final ResourceCapacityRange value) {
        this.memory = value;
    }

    /**
     * Gets the value of the storage property.
     *
     * @return possible object is {@link TemplateStorage }
     */
    public TemplateStorage getStorage() {
        return storage;
    }

    /**
     * Sets the value of the storage property.
     *
     * @param value allowed object is {@link TemplateStorage }
     */
    public void setStorage(final TemplateStorage value) {
        this.storage = value;
    }

    /**
     * Gets the value of the networkAdapters property.
     *
     * @return possible object is {@link Integer }
     */
    public Integer getNetworkAdapters() {
        return networkAdapters;
    }

    /**
     * Sets the value of the networkAdapters property.
     *
     * @param value allowed object is {@link Integer }
     */
    public void setNetworkAdapters(final Integer value) {
        this.networkAdapters = value;
    }

    /**
     * Gets the value of the customization property.
     *
     * @return possible object is {@link CustomizationOption }
     */
    public CustomizationOption getCustomization() {
        return customization;
    }

    /**
     * Sets the value of the customization property.
     *
     * @param value allowed object is {@link CustomizationOption }
     */
    public void setCustomization(final CustomizationOption value) {
        this.customization = value;
    }

    /**
     * Gets the value of the licensedSoftware property.
     *
     * @return possible object is {@link DeviceLicensedSoftware }
     */
    public DeviceLicensedSoftware getLicensedSoftware() {
        return licensedSoftware;
    }

    /**
     * Sets the value of the licensedSoftware property.
     *
     * @param value allowed object is {@link DeviceLicensedSoftware }
     */
    public void setLicensedSoftware(final DeviceLicensedSoftware value) {
        this.licensedSoftware = value;
    }

    public List<ComputeMatrixEntry> getComputeMatrix() {
        if (computeMatrix == null) {
            computeMatrix = new ArrayList<ComputeMatrixEntry>();
        }
        return computeMatrix;
    }
}


text:
<!-- Container #2 -->

<div flex layout="row">

    <!-- Container #3 -->
    <md-sidenav class="md-whiteframe-4dp" md-is-locked-open="$mdMedia('gt-sm')"
                md-component-id="left" ng-click="app.toggleList()">
        <!-- Custom UsersList component -->
        <product-list
                users="app.users"
                selected="app.selected"
                on-selected="app.selectUser(user)">
        </product-list>
    </md-sidenav>

    <!-- Container #4 -->
    <md-content flex id="content">

        <md-fab-toolbar md-direction="left">
            <md-fab-trigger  class="align-with-text">
                <md-button class="md-fab md-primary" aria-label="Add...">
                    <md-icon>
                        <i class="material-icons"></i>
                    </md-icon>
                </md-button>
            </md-fab-trigger>

            <md-toolbar class="md-toolbar-tools">
                <md-fab-actions>
                    <download-report-data/>
                </md-fab-actions>
            </md-toolbar>
        </md-fab-toolbar>
        <!-- Custom ObjectDetails component -->
        <product-details
                selected="app.selected">
        </product-details>
    </md-content>

</div>


text:
/*
 * Swaggy Jenkins
 *
 * Jenkins API clients generated from Swagger / Open API specification
 *
 * The version of the OpenAPI document: 1.5.1-pre.0
 * Contact: blah@cliffano.com
 * Generated by: https://openapi-generator.tech
 */

#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)]
pub struct PipelineBranchesitem {
    #[serde(rename = "displayName", skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(rename = "estimatedDurationInMillis", skip_serializing_if = "Option::is_none")]
    pub estimated_duration_in_millis: Option<i32>,
    #[serde(rename = "name", skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(rename = "weatherScore", skip_serializing_if = "Option::is_none")]
    pub weather_score: Option<i32>,
    #[serde(rename = "latestRun", skip_serializing_if = "Option::is_none")]
    pub latest_run: Option<Box<crate::models::PipelineBranchesitemlatestRun>>,
    #[serde(rename = "organization", skip_serializing_if = "Option::is_none")]
    pub organization: Option<String>,
    #[serde(rename = "pullRequest", skip_serializing_if = "Option::is_none")]
    pub pull_request: Option<Box<crate::models::PipelineBranchesitempullRequest>>,
    #[serde(rename = "totalNumberOfPullRequests", skip_serializing_if = "Option::is_none")]
    pub total_number_of_pull_requests: Option<i32>,
    #[serde(rename = "_class", skip_serializing_if = "Option::is_none")]
    pub _class: Option<String>,
}

impl PipelineBranchesitem {
    pub fn new() -> PipelineBranchesitem {
        PipelineBranchesitem {
            display_name: None,
            estimated_duration_in_millis: None,
            name: None,
            weather_score: None,
            latest_run: None,
            organization: None,
            pull_request: None,
            total_number_of_pull_requests: None,
            _class: None,
        }
    }
}


text:
name: warnings/invalid-arithmetic
---

## Summary


text:
#region Copyright & License

// Copyright © 2012 - 2015 François Chabot, Yves Dierick
//
// 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
//
// http://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.

#endregion

using Be.Stateless.BizTalk.Unit.Component;
using NUnit.Framework;

namespace Be.Stateless.BizTalk.Component
{
	[TestFixture]
	public class MessageConsumerComponentFixture : PipelineComponentFixture<MessageConsumerComponent> { }
}


text:
/* HEADER GOES HERE */
#import <Foundation/Foundation.h>
#import "QredoClient.h"
#import "CryptoImpl.h"
#import "QredoVaultCrypto.h"

@class QredoUserCredentials;

extern NS_ENUM (NSInteger,QredoCredentialType) {
    QredoCredentialTypeNoCredential = 0,
    QredoCredentialTypePIN = 1,
    QredoCredentialTypePattern = 2,
    QredoCredentialTypeFingerprint = 3,
    QredoCredentialTypePassword = 4,
    QredoCredentialTypePassphrase = 5,
    QredoCredentialTypeRandomBytes = 6
};

@interface QredoKeychain :NSObject

@property QLFOperatorInfo *operatorInfo;

@property QredoVaultKeys *systemVaultKeys;
@property QredoVaultKeys *defaultVaultKeys;

-(instancetype)initWithOperatorInfo:(QLFOperatorInfo *)operatorInfo;

//used in tests only
-(instancetype)initWithData:(NSData *)serializedData;

-(NSData *)data;
-(void)generateNewKeys:(QredoUserCredentials *)userCredentials;

@end


text:
package org.motechproject.commcare.tasks;

import org.motechproject.commcare.tasks.builder.ChannelRequestBuilder;
import org.motechproject.tasks.contract.ChannelRequest;
import org.motechproject.tasks.service.ChannelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The TasksChannelServiceInstance class, holds Tasks-related beans. The reason this class
 * must exist is because no Spring beans should be initialised if the Tasks module is not present. Therefore,
 * we should first make sure that the Tasks module is present and only then we use Tasks classes, to
 * avoid NoClassDefFoundError.
 */
public class TasksChannelServiceInstance {

    private static final Logger LOGGER = LoggerFactory.getLogger(TasksChannelServiceInstance.class);

    private ChannelService channelService;
    private ChannelRequestBuilder channelRequestBuilder;

    public TasksChannelServiceInstance(Object service, ChannelRequestBuilder builder) {
        if (service instanceof ChannelService) {
            this.channelService = (ChannelService) service;
        }
        this.channelRequestBuilder = builder;
    }

    /**
     * Registers or updates the task channel if it contains any task triggers, if it doesn't the channel
     * will be unregistered.
     */
    public void updateTaskChannel() {

        ChannelRequest channelRequest = channelRequestBuilder.buildChannelRequest();

        if (channelService != null) {
            if (!channelRequest.getTriggerTaskEvents().isEmpty()) {
                LOGGER.trace("Registering channel with the following request: {}", channelRequest);
                channelService.registerChannel(channelRequest);
            } else {
                LOGGER.trace("Unregistering channel with the following request: {}", channelRequest);
                channelService.unregisterChannel(channelRequest.getModuleName());
            }
        }
    }
}


text:
#include <stdio.h>
#include <string.h>

#include "ch.h"
#include "hal.h"
#include "test.h"

#include "shell.h"
#include "chprintf.h"

#include "usbcfg.h"

/*===========================================================================*/
/* Command line related.                                                     */
/*===========================================================================*/

#define SHELL_WA_SIZE   THD_WORKING_AREA_SIZE(2048)
#define TEST_WA_SIZE    THD_WORKING_AREA_SIZE(256)

static void cmd_mem(BaseSequentialStream *chp, int argc, char *argv[]) {
  size_t n, size;

  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: mem\r\n");
    return;
  }
  n = chHeapStatus(NULL, &size);
  chprintf(chp, "core free memory : %u bytes\r\n", chCoreGetStatusX());
  chprintf(chp, "heap fragments   : %u\r\n", n);
  chprintf(chp, "heap free total  : %u bytes\r\n", size);
}

static void cmd_threads(BaseSequentialStream *chp, int argc, char *argv[]) {
  static const char *states[] = {CH_STATE_NAMES};
  thread_t *tp;

  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: threads\r\n");
    return;
  }
  chprintf(chp, "    addr    stack prio refs     state time\r\n");
  tp = chRegFirstThread();
  do {
    chprintf(chp, "%08lx %08lx %4lu %4lu %9s\r\n",
            (uint32_t)tp, (uint32_t)tp->p_ctx.r13,
            (uint32_t)tp->p_prio, (uint32_t)(tp->p_refs - 1),
            states[tp->p_state]);
    tp = chRegNextThread(tp);
  } while (tp != NULL);
}

static void cmd_test(BaseSequentialStream *chp, int argc, char *argv[]) {
  thread_t *tp;

  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: test\r\n");
    return;
  }
  tp = chThdCreateFromHeap(NULL, TEST_WA_SIZE, chThdGetPriorityX(),
                           TestThread, chp);
  if (tp == NULL) {
    chprintf(chp, "out of memory\r\n");
    return;
  }
  chThdWait(tp);
}

/* Can be measured using dd if=/dev/xxxx of=/dev/null bs=512 count=10000.*/
static void cmd_write(BaseSequentialStream *chp, int argc, char *argv[]) {
  static uint8_t buf[] =
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
      "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

  (void)argv;
  if (argc > 0) {
    chprintf(chp, "Usage: write\r\n");
    return;
  }

  while (chnGetTimeout((BaseChannel *)chp, TIME_IMMEDIATE) == Q_TIMEOUT) {
#if 1
    /* Writing in channel mode.*/
    chnWrite(&SDU1, buf, sizeof buf - 1);
#else
    /* Writing in buffer mode.*/
    (void) obqGetEmptyBufferTimeout(&SDU1.obqueue, TIME_INFINITE);
    memcpy(SDU1.obqueue.ptr, buf, SERIAL_USB_BUFFERS_SIZE);
    obqPostFullBuffer(&SDU1.obqueue, SERIAL_USB_BUFFERS_SIZE);
#endif
  }
  chprintf(chp, "\r\n\nstopped\r\n");
}

static const ShellCommand commands[] = {
  {"mem", cmd_mem},
  {"threads", cmd_threads},
  {"test", cmd_test},
  {"write", cmd_write},
  {NULL, NULL}
};

static const ShellConfig shell_cfg1 = {
  (BaseSequentialStream *)&SDU1,
  commands
};

/*===========================================================================*/
/* Generic code.                                                             */
/*===========================================================================*/

/*
 * LED blinker thread, times are in milliseconds.
 */
static THD_WORKING_AREA(waThread1, 128);
static THD_FUNCTION(Thread1, arg) {

  (void)arg;
  chRegSetThreadName("blinker");
  while (true) {
    systime_t time;

    time = serusbcfg.usbp->state == USB_ACTIVE ? 250 : 500;
#if defined(BOARD_ST_STM32F4_DISCOVERY)
    palClearPad(GPIOD, GPIOD_LED4);
    chThdSleepMilliseconds(time);
    palSetPad(GPIOD, GPIOD_LED4);
    chThdSleepMilliseconds(time);
#else
    palClearPad(GPIOC, GPIOC_LED);
    chThdSleepMilliseconds(time);
    palSetPad(GPIOC, GPIOC_LED);
    chThdSleepMilliseconds(time);
#endif
  }
}

/*
 * Application entry point.
 */
int main(void) {
  thread_t *shelltp = NULL;

  /*
   * System initializations.
   * - HAL initialization, this also initializes the configured device drivers
   *   and performs the board-specific initializations.
   * - Kernel initialization, the main() function becomes a thread and the
   *   RTOS is active.
   */
  halInit();
  chSysInit();

  /*
   * Initializes a serial-over-USB CDC driver.
   */
  sduObjectInit(&SDU1);
  sduStart(&SDU1, &serusbcfg);

  /*
   * Activates the USB driver and then the USB bus pull-up on D+.
   * Note, a delay is inserted in order to not have to disconnect the cable
   * after a reset.
   */
  usbDisconnectBus(serusbcfg.usbp);
  chThdSleepMilliseconds(1500);
  usbStart(serusbcfg.usbp, &usbcfg);
  usbConnectBus(serusbcfg.usbp);

  /*
   * Shell manager initialization.
   */
  shellInit();

  /*
   * Creates the blinker thread.
   */
  chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO, Thread1, NULL);

  /*
   * Normal main() thread activity, in this demo it does nothing except
   * sleeping in a loop and check the button state.
   */
  while (true) {
    if (!shelltp && (SDU1.config->usbp->state == USB_ACTIVE))
      shelltp = shellCreate(&shell_cfg1, SHELL_WA_SIZE, NORMALPRIO);
    else if (chThdTerminatedX(shelltp)) {
      chThdRelease(shelltp);    /* Recovers memory of the previous shell.   */
      shelltp = NULL;           /* Triggers spawning of a new shell.        */
    }
    chThdSleepMilliseconds(1000);
  }
}


text:
@implementation NSData (HexString)

- (NSString *) hexString
{
    if ([self length] == 0) {
        return nil;
    }

    const uint8_t * bytes = [self bytes];
    NSUInteger length = [self length];
    NSMutableString * stringy = [[NSMutableString alloc] initWithCapacity:(length * 2)];
    for (NSUInteger i=0; i < length; i++) {
        [stringy appendString:[NSString stringWithFormat:@"%02.2hhx", bytes[i]]];
    }

    return stringy;
}

@end