text:
package cn.vfinance.demo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.util.HashMap;
import java.util.Map;
import cn.vfinance.demo.R;
import cn.vfinance.demo.util.BillUtils;
import cn.vfinance.demo.util.DisplayUtils;

import cn.vfinance.wallet.VFPay;
import cn.vfinance.wallet.async.VFCallback;
import cn.vfinance.wallet.async.VFResult;
import cn.vfinance.wallet.entity.VFQRCodeResult;

/**
 * 用于展示如何生成二维码支付
 */
public class QRCodeEntryActivity extends Activity {
    private static final String Tag = "QRCodeEntryActivity";
    private ProgressDialog loadingDialog;

    Button btnReqALIQRCode;

    private Handler mHandler;

    private String aliQRHtml;
    private String aliQRURL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode_entry);

        DisplayUtils.initBack(this);

        loadingDialog = new ProgressDialog(QRCodeEntryActivity.this);
        loadingDialog.setMessage("正在请求服务器, 请稍候...");
        loadingDialog.setIndeterminate(true);
        loadingDialog.setCancelable(true);

        btnReqALIQRCode = (Button) findViewById(R.id.btnReqALIQRCode);

        // Defines a Handler object that's attached to the UI thread
        mHandler = new Handler(new Handler.Callback() {

            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 2:
                        //建议在新的activity显示ali内嵌二维码
                        Intent intent = new Intent(QRCodeEntryActivity.this, ALIQRCodeActivity.class);
                        intent.putExtra("aliQRURL", aliQRURL);
                        intent.putExtra("aliQRHtml", aliQRHtml);
                        startActivity(intent);
                        break;
                }

                return true;
            }
        });

        btnReqALIQRCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadingDialog.show();

                Map<String, String> mapOptional = new HashMap<String, String>();

                mapOptional.put("testalikey1", "测试value值1");
                VFPay.getInstance(QRCodeEntryActivity.this).reqAliInlineQRCodeAsync(
                        "支付宝内嵌二维码支付测试", //商品描述
                        1,                       //总金额, 以分为单位, 必须是正整数
                        BillUtils.genBillNum(),  //流水号
                        mapOptional,             //扩展参数
                        "https://www.vfnetwork.cn/",  //支付成功之后的返回url
                        "1",   /* 注: 二维码类型含义
                                * null则支付宝生成默认类型, 不建议
                                * "0": 订单码-简约前置模式, 对应 iframe 宽度不能小于 600px, 高度不能小于 300px
                                * "1": 订单码-前置模式, 对应 iframe 宽度不能小于 300px, 高度不能小于 600px
                                * "3": 订单码-迷你前置模式, 对应 iframe 宽度不能小于 75px, 高度不能小于 75px
                                */
                        new VFCallback() {     //回调入口
                            @Override
                            public void done(VFResult vfResult) {

                                //此处关闭loading界面
                                loadingDialog.dismiss();

                                final VFQRCodeResult vfqrCodeResult = (VFQRCodeResult) vfResult;

                                //resultCode为0表示请求成功
                                if (vfqrCodeResult.getResultCode() == 0) {
                                    aliQRURL = vfqrCodeResult.getQrCodeRawContent();
                                    aliQRHtml = vfqrCodeResult.getAliQRCodeHtml();
                                    Log.w(Tag, "ali qrcode url: " + aliQRURL);
                                    Log.w(Tag, "ali qrcode html: " + aliQRHtml);

                                    Message msg = mHandler.obtainMessage();
                                    msg.what = 2;
                                    mHandler.sendMessage(msg);

                                } else {

                                    QRCodeEntryActivity.this.runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {

                                            String toastMsg = "err code:" + vfqrCodeResult.getResultCode() +
                                                    "; err msg: " + vfqrCodeResult.getResultMsg() +
                                                    "; err detail: " + vfqrCodeResult.getErrDetail();

                                            /**
                                             * 你发布的项目中不应该出现如下错误,此处由于支付宝政策原因,
                                             * 不再提供支付宝支付的测试功能,所以给出提示说明
                                             */
                                            if (vfqrCodeResult.getResultMsg().equals("PAY_FACTOR_NOT_SET") &&
                                                    vfqrCodeResult.getErrDetail().startsWith("支付宝参数")) {
                                                toastMsg = "支付失败:由于支付宝政策原因,故不再提供支付宝支付的测试功能,给您带来的不便,敬请谅解";
                                            }
                                            Toast.makeText(QRCodeEntryActivity.this, toastMsg, Toast.LENGTH_LONG).show();
                                        }
                                    });
                                }
                            }
                        }
                );
            }
        });
        initOfflineReqBtn();
    }

    void initOfflineReqBtn() {
        Button btnReqWXQRCode = (Button)findViewById(R.id.btnReqWXQRCode);
        btnReqWXQRCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(QRCodeEntryActivity.this, GenQRCodeActivity.class);
                intent.putExtra("type", "WX");
                startActivity(intent);
            }
        });

        Button btnReqALIOfflineQRCode = (Button)findViewById(R.id.btnReqALIOfflineQRCode);
        btnReqALIOfflineQRCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(QRCodeEntryActivity.this, GenQRCodeActivity.class);
                intent.putExtra("type", "ALI");
                startActivity(intent);
            }
        });

        Button btnReqWXScan = (Button)findViewById(R.id.btnReqWXScan);
        btnReqWXScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(QRCodeEntryActivity.this, PayViaAuthCodeActivity.class);
                intent.putExtra("type", "WX");
                startActivity(intent);
            }
        });

        Button btnReqALIScan = (Button)findViewById(R.id.btnReqALIScan);
        btnReqALIScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(QRCodeEntryActivity.this, PayViaAuthCodeActivity.class);
                intent.putExtra("type", "ALI");
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //用到 VFPay 的 activity 在结束前,清理 context 引用
        VFPay.clear();
    }
}


text:
package rulevalidation

import (
	"reflect"
	"sort"
	"testing"

	"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/apimachinery/pkg/util/sets"
	kapi "k8s.io/kubernetes/pkg/api"

	"github.com/openshift/origin/pkg/authorization/api"
)

func TestCompactRules(t *testing.T) {
	testcases := map[string]struct {
		Rules    []api.PolicyRule
		Expected []api.PolicyRule
	}{
		"empty": {
			Rules:    []api.PolicyRule{},
			Expected: []api.PolicyRule{},
		},
		"simple": {
			Rules: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds")},
				{Verbs: sets.NewString("list"), APIGroups: []string{""}, Resources: sets.NewString("builds")},
				{Verbs: sets.NewString("update", "patch"), APIGroups: []string{""}, Resources: sets.NewString("builds")},

				{Verbs: sets.NewString("create"), APIGroups: []string{"extensions"}, Resources: sets.NewString("daemonsets")},
				{Verbs: sets.NewString("delete"), APIGroups: []string{"extensions"}, Resources: sets.NewString("daemonsets")},

				{Verbs: sets.NewString("educate"), APIGroups: []string{""}, Resources: sets.NewString("dolphins")},

				// nil verbs are preserved in non-merge cases.
				// these are the pirates who don't do anything.
				{Verbs: nil, APIGroups: []string{""}, Resources: sets.NewString("pirates")},

				// Test merging into a nil Verbs string set
				{Verbs: nil, APIGroups: []string{""}, Resources: sets.NewString("pods")},
				{Verbs: sets.NewString("create"), APIGroups: []string{""}, Resources: sets.NewString("pods")},
			},
			Expected: []api.PolicyRule{
				{Verbs: sets.NewString("create", "delete"), APIGroups: []string{"extensions"}, Resources: sets.NewString("daemonsets")},
				{Verbs: sets.NewString("get", "list", "update", "patch"), APIGroups: []string{""}, Resources: sets.NewString("builds")},
				{Verbs: sets.NewString("educate"), APIGroups: []string{""}, Resources: sets.NewString("dolphins")},
				{Verbs: nil, APIGroups: []string{""}, Resources: sets.NewString("pirates")},
				{Verbs: sets.NewString("create"), APIGroups: []string{""}, Resources: sets.NewString("pods")},
			},
		},
		"complex multi-group": {
			Rules: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{"", "builds.openshift.io"}, Resources: sets.NewString("builds")},
				{Verbs: sets.NewString("list"), APIGroups: []string{"", "builds.openshift.io"}, Resources: sets.NewString("builds")},
			},
			Expected: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{"", "builds.openshift.io"}, Resources: sets.NewString("builds")},
				{Verbs: sets.NewString("list"), APIGroups: []string{"", "builds.openshift.io"}, Resources: sets.NewString("builds")},
			},
		},

		"complex multi-resource": {
			Rules: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds", "images")},
				{Verbs: sets.NewString("list"), APIGroups: []string{""}, Resources: sets.NewString("builds", "images")},
			},
			Expected: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds", "images")},
				{Verbs: sets.NewString("list"), APIGroups: []string{""}, Resources: sets.NewString("builds", "images")},
			},
		},

		"complex named-resource": {
			Rules: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), ResourceNames: sets.NewString("mybuild")},
				{Verbs: sets.NewString("list"), APIGroups: []string{""}, Resources: sets.NewString("builds"), ResourceNames: sets.NewString("mybuild2")},
			},
			Expected: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), ResourceNames: sets.NewString("mybuild")},
				{Verbs: sets.NewString("list"), APIGroups: []string{""}, Resources: sets.NewString("builds"), ResourceNames: sets.NewString("mybuild2")},
			},
		},

		"complex non-resource": {
			Rules: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), NonResourceURLs: sets.NewString("/")},
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), NonResourceURLs: sets.NewString("/foo")},
			},
			Expected: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), NonResourceURLs: sets.NewString("/")},
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), NonResourceURLs: sets.NewString("/foo")},
			},
		},

		"complex attributes": {
			Rules: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), AttributeRestrictions: &api.IsPersonalSubjectAccessReview{}},
				{Verbs: sets.NewString("list"), APIGroups: []string{""}, Resources: sets.NewString("builds"), AttributeRestrictions: &api.IsPersonalSubjectAccessReview{}},
			},
			Expected: []api.PolicyRule{
				{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), AttributeRestrictions: &api.IsPersonalSubjectAccessReview{}},
				{Verbs: sets.NewString("list"), APIGroups: []string{""}, Resources: sets.NewString("builds"), AttributeRestrictions: &api.IsPersonalSubjectAccessReview{}},
			},
		},
	}

	for k, tc := range testcases {
		rules := tc.Rules
		originalRules, err := kapi.Scheme.DeepCopy(tc.Rules)
		if err != nil {
			t.Errorf("%s: couldn't copy rules: %v", k, err)
			continue
		}
		compacted, err := CompactRules(tc.Rules)
		if err != nil {
			t.Errorf("%s: unexpected error: %v", k, err)
			continue
		}
		if !reflect.DeepEqual(rules, originalRules) {
			t.Errorf("%s: CompactRules mutated rules. Expected\n%#v\ngot\n%#v", k, originalRules, rules)
			continue
		}
		if covers, missing := Covers(compacted, rules); !covers {
			t.Errorf("%s: compacted rules did not cover original rules. missing: %#v", k, missing)
			continue
		}
		if covers, missing := Covers(rules, compacted); !covers {
			t.Errorf("%s: original rules did not cover compacted rules. missing: %#v", k, missing)
			continue
		}

		sort.Stable(api.SortableRuleSlice(compacted))
		sort.Stable(api.SortableRuleSlice(tc.Expected))
		if !reflect.DeepEqual(compacted, tc.Expected) {
			t.Errorf("%s: Expected\n%#v\ngot\n%#v", k, tc.Expected, compacted)
			continue
		}
	}
}

func TestIsSimpleResourceRule(t *testing.T) {
	testcases := map[string]struct {
		Rule     api.PolicyRule
		Simple   bool
		Resource schema.GroupResource
	}{
		"simple, no verbs": {
			Rule:     api.PolicyRule{Verbs: sets.NewString(), APIGroups: []string{""}, Resources: sets.NewString("builds")},
			Simple:   true,
			Resource: schema.GroupResource{Group: "", Resource: "builds"},
		},
		"simple, one verb": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds")},
			Simple:   true,
			Resource: schema.GroupResource{Group: "", Resource: "builds"},
		},
		"simple, multi verb": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get", "list"), APIGroups: []string{""}, Resources: sets.NewString("builds")},
			Simple:   true,
			Resource: schema.GroupResource{Group: "", Resource: "builds"},
		},

		"complex, empty": {
			Rule:     api.PolicyRule{},
			Simple:   false,
			Resource: schema.GroupResource{},
		},
		"complex, no group": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get"), APIGroups: []string{}, Resources: sets.NewString("builds")},
			Simple:   false,
			Resource: schema.GroupResource{},
		},
		"complex, multi group": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get"), APIGroups: []string{"a", "b"}, Resources: sets.NewString("builds")},
			Simple:   false,
			Resource: schema.GroupResource{},
		},
		"complex, no resource": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString()},
			Simple:   false,
			Resource: schema.GroupResource{},
		},
		"complex, multi resource": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds", "images")},
			Simple:   false,
			Resource: schema.GroupResource{},
		},
		"complex, resource names": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), ResourceNames: sets.NewString("foo")},
			Simple:   false,
			Resource: schema.GroupResource{},
		},
		"complex, attribute restrictions": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), AttributeRestrictions: &api.IsPersonalSubjectAccessReview{}},
			Simple:   false,
			Resource: schema.GroupResource{},
		},
		"complex, non-resource urls": {
			Rule:     api.PolicyRule{Verbs: sets.NewString("get"), APIGroups: []string{""}, Resources: sets.NewString("builds"), NonResourceURLs: sets.NewString("/")},
			Simple:   false,
			Resource: schema.GroupResource{},
		},
	}

	for k, tc := range testcases {
		resource, simple := isSimpleResourceRule(&tc.Rule)
		if simple != tc.Simple {
			t.Errorf("%s: expected simple=%v, got simple=%v", k, tc.Simple, simple)
			continue
		}
		if resource != tc.Resource {
			t.Errorf("%s: expected resource=%v, got resource=%v", k, tc.Resource, resource)
			continue
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
package local

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/moby/buildkit/cache"
	"github.com/moby/buildkit/cache/contenthash"
	"github.com/moby/buildkit/cache/metadata"
	"github.com/moby/buildkit/client"
	"github.com/moby/buildkit/session"
	"github.com/moby/buildkit/session/filesync"
	"github.com/moby/buildkit/snapshot"
	"github.com/moby/buildkit/source"
	"github.com/moby/buildkit/util/progress"
	digest "github.com/opencontainers/go-digest"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/tonistiigi/fsutil"
	bolt "go.etcd.io/bbolt"
	"golang.org/x/time/rate"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

const keySharedKey = "local.sharedKey"

type Opt struct {
	CacheAccessor cache.Accessor
	MetadataStore *metadata.Store
}

func NewSource(opt Opt) (source.Source, error) {
	ls := &localSource{
		cm: opt.CacheAccessor,
		md: opt.MetadataStore,
	}
	return ls, nil
}

type localSource struct {
	cm cache.Accessor
	md *metadata.Store
}

func (ls *localSource) ID() string {
	return source.LocalScheme
}

func (ls *localSource) Resolve(ctx context.Context, id source.Identifier, sm *session.Manager) (source.SourceInstance, error) {
	localIdentifier, ok := id.(*source.LocalIdentifier)
	if !ok {
		return nil, errors.Errorf("invalid local identifier %v", id)
	}

	return &localSourceHandler{
		src:         *localIdentifier,
		sm:          sm,
		localSource: ls,
	}, nil
}

type localSourceHandler struct {
	src source.LocalIdentifier
	sm  *session.Manager
	*localSource
}

func (ls *localSourceHandler) CacheKey(ctx context.Context, index int) (string, bool, error) {
	sessionID := ls.src.SessionID

	if sessionID == "" {
		id := session.FromContext(ctx)
		if id == "" {
			return "", false, errors.New("could not access local files without session")
		}
		sessionID = id
	}
	dt, err := json.Marshal(struct {
		SessionID       string
		IncludePatterns []string
		ExcludePatterns []string
		FollowPaths     []string
	}{SessionID: sessionID, IncludePatterns: ls.src.IncludePatterns, ExcludePatterns: ls.src.ExcludePatterns, FollowPaths: ls.src.FollowPaths})
	if err != nil {
		return "", false, err
	}
	return "session:" + ls.src.Name + ":" + digest.FromBytes(dt).String(), true, nil
}

func (ls *localSourceHandler) Snapshot(ctx context.Context) (out cache.ImmutableRef, retErr error) {

	id := session.FromContext(ctx)
	if id == "" {
		return nil, errors.New("could not access local files without session")
	}

	timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
	defer cancel()

	caller, err := ls.sm.Get(timeoutCtx, id)
	if err != nil {
		return nil, err
	}

	sharedKey := keySharedKey + ":" + ls.src.Name + ":" + ls.src.SharedKeyHint + ":" + caller.SharedKey() // TODO: replace caller.SharedKey() with source based hint from client(absolute-path+nodeid)

	var mutable cache.MutableRef
	sis, err := ls.md.Search(sharedKey)
	if err != nil {
		return nil, err
	}
	for _, si := range sis {
		if m, err := ls.cm.GetMutable(ctx, si.ID()); err == nil {
			logrus.Debugf("reusing ref for local: %s", m.ID())
			mutable = m
			break
		}
	}

	if mutable == nil {
		m, err := ls.cm.New(ctx, nil, cache.CachePolicyRetain, cache.WithRecordType(client.UsageRecordTypeLocalSource), cache.WithDescription(fmt.Sprintf("local source for %s", ls.src.Name)))
		if err != nil {
			return nil, err
		}
		mutable = m
		logrus.Debugf("new ref for local: %s", mutable.ID())
	}

	defer func() {
		if retErr != nil && mutable != nil {
			go mutable.Release(context.TODO())
		}
	}()

	mount, err := mutable.Mount(ctx, false)
	if err != nil {
		return nil, err
	}

	lm := snapshot.LocalMounter(mount)

	dest, err := lm.Mount()
	if err != nil {
		return nil, err
	}

	defer func() {
		if retErr != nil && lm != nil {
			lm.Unmount()
		}
	}()

	cc, err := contenthash.GetCacheContext(ctx, mutable.Metadata())
	if err != nil {
		return nil, err
	}

	opt := filesync.FSSendRequestOpt{
		Name:             ls.src.Name,
		IncludePatterns:  ls.src.IncludePatterns,
		ExcludePatterns:  ls.src.ExcludePatterns,
		FollowPaths:      ls.src.FollowPaths,
		OverrideExcludes: false,
		DestDir:          dest,
		CacheUpdater:     &cacheUpdater{cc},
		ProgressCb:       newProgressHandler(ctx, "transferring "+ls.src.Name+":"),
	}

	if err := filesync.FSSync(ctx, caller, opt); err != nil {
		if status.Code(err) == codes.NotFound {
			return nil, errors.Errorf("local source %s not enabled from the client", ls.src.Name)
		}
		return nil, err
	}

	if err := lm.Unmount(); err != nil {
		return nil, err
	}
	lm = nil

	if err := contenthash.SetCacheContext(ctx, mutable.Metadata(), cc); err != nil {
		return nil, err
	}

	// skip storing snapshot by the shared key if it already exists
	skipStoreSharedKey := false
	si, _ := ls.md.Get(mutable.ID())
	if v := si.Get(keySharedKey); v != nil {
		var str string
		if err := v.Unmarshal(&str); err != nil {
			return nil, err
		}
		skipStoreSharedKey = str == sharedKey
	}
	if !skipStoreSharedKey {
		v, err := metadata.NewValue(sharedKey)
		if err != nil {
			return nil, err
		}
		v.Index = sharedKey
		if err := si.Update(func(b *bolt.Bucket) error {
			return si.SetValue(b, sharedKey, v)
		}); err != nil {
			return nil, err
		}
		logrus.Debugf("saved %s as %s", mutable.ID(), sharedKey)
	}

	snap, err := mutable.Commit(ctx)
	if err != nil {
		return nil, err
	}

	mutable = nil // avoid deferred cleanup

	return snap, nil
}

func newProgressHandler(ctx context.Context, id string) func(int, bool) {
	limiter := rate.NewLimiter(rate.Every(100*time.Millisecond), 1)
	pw, _, _ := progress.FromContext(ctx)
	now := time.Now()
	st := progress.Status{
		Started: &now,
		Action:  "transferring",
	}
	pw.Write(id, st)
	return func(s int, last bool) {
		if last || limiter.Allow() {
			st.Current = s
			if last {
				now := time.Now()
				st.Completed = &now
			}
			pw.Write(id, st)
			if last {
				pw.Close()
			}
		}
	}
}

type cacheUpdater struct {
	contenthash.CacheContext
}

func (cu *cacheUpdater) MarkSupported(bool) {
}

func (cu *cacheUpdater) ContentHasher() fsutil.ContentHasher {
	return contenthash.NewFromStat
}


text:
from __future__ import absolute_import, division, print_function

from ramlfications.config import setup_config
from ramlfications.parser import parse_raml

from ramlfications._helpers import load_file, load_string

__author__ = "Lynn Root"
__version__ = "0.1.9"
__license__ = "Apache 2.0"

__email__ = "lynn@spotify.com"
__uri__ = "https://ramlfications.readthedocs.io"
__description__ = "A Python RAML parser"

def load(raml_file):
    """
    Module helper function to load a RAML File using \
    :py:class:`.loader.RAMLLoader`.

    :param str raml_file: String path to RAML file
    :return: loaded RAML
    :rtype: dict
    :raises LoadRAMLError: If error occurred trying to load the RAML file
    """
    return load_file(raml_file)

def loads(raml_string):
    """
    Module helper function to load a RAML File using \
    :py:class:`.loader.RAMLLoader`.

    :param str raml_string: String of RAML data
    :return: loaded RAML
    :rtype: dict
    :raises LoadRAMLError: If error occurred trying to load the RAML file
    """
    return load_string(raml_string)

def parse(raml, config_file=None):
    """
    Module helper function to parse a RAML File.  First loads the RAML file
    with :py:class:`.loader.RAMLLoader` then parses with
    :py:func:`.parser.parse_raml` to return a :py:class:`.raml.RAMLRoot`
    object.

    :param raml: Either string path to the RAML file, a file object, or \
        a string representation of RAML.
    :param str config_file:  String path to desired config file, if any.
    :return: parsed API
    :rtype: RAMLRoot
    :raises LoadRAMLError: If error occurred trying to load the RAML file
        (see :py:class:`.loader.RAMLLoader`)
    :raises InvalidRootNodeError: API metadata is invalid according to RAML \
        `specification <http://raml.org/spec.html>`_.
    :raises InvalidResourceNodeError: API resource endpoint is invalid \
        according to RAML `specification <http://raml.org/spec.html>`_.
    :raises InvalidParameterError: Named parameter is invalid \
        according to RAML `specification <http://raml.org/spec.html>`_.
    """
    loader = load(raml)
    config = setup_config(config_file)
    return parse_raml(loader, config)

def validate(raml, config_file=None):
    """
    Module helper function to validate a RAML File.  First loads \
    the RAML file \
    with :py:class:`.loader.RAMLLoader` then validates with \
    :py:func:`.validate.validate_raml`.

    :param str raml: Either string path to the RAML file, a file object, \or
        a string representation of RAML.
    :param str config_file:  String path to desired config file, if any.
    :return: No return value if successful
    :raises LoadRAMLError: If error occurred trying to load the RAML file
        (see :py:class:`.loader.RAMLLoader`)
    :raises InvalidRootNodeError: API metadata is invalid according to RAML \
        `specification <http://raml.org/spec.html>`_.
    :raises InvalidResourceNodeError: API resource endpoint is invalid \
        according to RAML `specification <http://raml.org/spec.html>`_.
    :raises InvalidParameterError: Named parameter is invalid \
        according to RAML `specification <http://raml.org/spec.html>`_.
    :raises InvalidRAMLError: RAML file is invalid according to RAML \
        `specification <http://raml.org/spec.html>`_.
    """
    loader = load(raml)
    config = setup_config(config_file)
    config["validate"] = True
    parse_raml(loader, config)


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Gentiana dolichocalyx T.N.Ho

### Remarks
null


text:
<?php

    namespace NRtworks\BusinessDimensionBundle\Entity;

    use Doctrine\ORM\Mapping as ORM;
    use Doctrine\Common\Collections\ArrayCollection;
    use JsonSerializable;
    use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="Account")
 * @ORM\Entity
 */

    class Account implements JsonSerializable
    {
        /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */

    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     */

    protected $name;

     /**
     * @ORM\Column(type="string", length=50)
     */

    protected $code;

    /**
     * @ORM\Column(type="string", length=2)
     */

    protected $sense;

     /**
     * @ORM\Column(name="root", type="integer",nullable=true)
     */
    protected $root;

    /**
     * @ORM\ManyToOne(targetEntity="Account", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $parent;

    /**
     * @ORM\OneToMany(targetEntity="Account", mappedBy="parent")
     */
    protected $children;

    /**
     * @ORM\ManyToOne(targetEntity="NRtworks\BusinessDimensionBundle\Entity\ChartOfAccounts", inversedBy="accounts")
     * @ORM\JoinColumn(name="chartofaccounts_id", referencedColumnName="id")
     */

    private $chartofaccount;

    /**
     * Constructor
     */
    public function __construct($id = NULL)
    {
        //the basic constructor is set to create a default object as we want it when creating a new one
        $this->children = new \Doctrine\Common\Collections\ArrayCollection();
        $this->id = $id;
        $this->name = "New account";
        $this->code = "xxxxxx";
        $this->sense = "DR";
        $this->root = 0;
    }

    public function fillWithArray($array)
    {
        foreach ($array as $key => $value)
        {
            if ( property_exists ( $this , $key ) ){
                $this->{$key} = $value;
            }
        }
    }

    //this method returns an array with default values
    public function getDefaultObject()
    {
        $result = Array();
        $result['id'] = $this->id;
        $result['name'] = $this->name;
        $result['code'] = $this->code;
        $result['sense'] = $this->sense;
        $result["action"] = "new";
        $result["root"] = 0;
        $result["nodes"] = [];
        return $result;
    }

    /**
     * Get id
     */
    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;
    }

    /**
     * Set name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

    /**
     * Get name
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set code
     */
    public function setCode($code)
    {
        $this->code = $code;
    }

    /**
     * Get code
     */
    public function getCode()
    {
        return $this->code;
    }

   /**
     * Set sense
     */
    public function setSense($sense)
    {
        $this->sense = $sense;
    }

    /**
     * Get sense
     */
    public function getSense()
    {
        return $this->sense;
    }

    public function setParent(Account $parent=null)
    {
        $this->parent = $parent;
    }

    public function getParent()
    {
        return $this->parent;
    }

    /**
     * Set root
     */
    public function setRoot($root)
    {
        $this->root = $root;
    }

    /**
     * Get root
     */
    public function getRoot()
    {
        return $this->root;
    }

    /**
     * Add children
     *
     * @param \NRtworks\BusinessDimensionBundle\Entity\Account $children
     * @return Account
     */
    public function addChild(\NRtworks\BusinessDimensionBundle\Entity\Account $children)
    {
        $this->children[] = $children;
        return $this;
    }

    /**
     * Remove children
     *
     * @param \NRtworks\BusinessDimensionBundle\Entity\Account $children
     */
    public function removeChild(\NRtworks\BusinessDimensionBundle\Entity\Account $children)
    {
        $this->children->removeElement($children);
    }

    /**
     * Get children
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getChildren()
    {
        return $this->children;
    }

    /**
     * Set COA
     */
    public function setChartOfAccount(\NRtworks\BusinessDimensionBundle\Entity\ChartOfAccounts $chartofaccount = null)
    {
        $this->chartofaccount = $chartofaccount;
    }

    /**
     * Get COA
     */
    public function getChartOfAccount()
    {
        return $this->chartofaccount;
    }

    //this method returns the list of the field's name to be edited in the tree editing
    public function fieldsToEditinTreeEdit()
    {
        $toEdit[0] = array(0=>"id",1=>0,2=>"text");
        $toEdit[1] = array(0=>"name",1=>1,2=>"text");
        $toEdit[2] = array(0=>"code",1=>1,2=>"text");
        $toEdit[3] = array(0=>"sense",1=>1,2=>"select",3=>array(0=>array("value"=>"DR","text"=>"DR"),1=>array("value"=>"CR","text"=>"CR")));
        $toEdit[4] = array(0=>"root",1=>0,2=>"text");
        $toEdit[5] = array(0=>"nodes",1=>0,2=>"text");
        return $toEdit;
    }

    public function getFieldsParameters()
    {
        $info[0] = array("fieldName"=>"id","toDo"=>"noShow","editType"=>"text","options"=>"none");
        $info[1] = array("fieldName"=>"name","toDo"=>"edit","editType"=>"text","options"=>"none");
        $info[2] = array("fieldName"=>"code","toDo"=>"edit","editType"=>"text","options"=>"none");
        $info[3] = array("fieldName"=>"sense","toDo"=>"edit","editType"=>"select","options"=>array("remote"=>"no","fieldFilter"=>"no"));
        $info[4] = array("fieldName"=>"root","toDo"=>"noShow","editType"=>"select","options"=>"none");
        $info[5] = array("fieldName"=>"nodes","toDo"=>"noShow","editType"=>"select","options"=>"none");
        $info[6] = array("fieldName"=>"parentid","toDo"=>"noShow","editType"=>"select","options"=>"none");
        return $info;
    }

    public function arrayalizeForTreeFlatView()
    {
        return array(
            'id' =>  $this->id,
            'name' => $this->name,
            'code' => $this->code,
            'sense' =>$this->sense,
            'root'=>$this->root,
            'nodes'=> [],
            'parentid'=> $this->parent,

        );
    }

    public function jsonSerialize()
    {
        return array(
            'id' =>  $this->id,
            'name' => $this->name,
            'code' => $this->code,
            'sense' =>$this->sense,
            'nodes'=> [],
            'parentid'=> $this->parent,
            'root'=>$this->root
        );
    }

}
?>


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// 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.

package com.google.devtools.build.singlejar;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * An implementation based on java.io.
 */
public final class JavaIoFileSystem implements SimpleFileSystem {

  @Override
  public InputStream getInputStream(String filename) throws IOException {
    return new FileInputStream(filename);
  }

  @Override
  public OutputStream getOutputStream(String filename) throws IOException {
    return new FileOutputStream(filename);
  }

  @Override
  public File getFile(String filename) throws IOException {
    return new File(filename);
  }

  @Override
  public boolean delete(String filename) {
    return new File(filename).delete();
  }
}


text:
class MoveActionWithObjectToActivity < ActiveRecord::Migration
  def self.up
    trans_res = ActiveRecord::Base.connection.execute('select * from translated_action_with_objects').all_hashes
    # Build a fake result set, id => name hash:
    actions = {}
    trans_res.each do |res|
      actions[res["action_with_object_id"].to_i] = {:name => res["action_code"]}
    end
    # First, create (or find) entries in activities for each of the existing ActionWithObject entries.
    actions.keys.each do |id|
      # if it exists, move on
      c = Activity.connection.execute("select count(*) from activities where name = '#{actions[id][:name]}'").
            all_hashes.first.values.first.to_i
      unless c > 0
        # otherwise, insert it
        foo = Activity.connection.execute("insert into activities (name) values ('#{actions[id][:name]}')")
      end
      actions[id][:activity] = Activity.find_by_sql("select * from activities where name = '#{actions[id][:name]}'").first
    end
    # Now update the curator_activity_logs to use the new ids where the old ones were before
    add_column :curator_activity_logs, :activity_id, :integer rescue nil
    actions.keys.each do |id|
      SpeciesSchemaModel.connection.execute(ActiveRecord::Base.sanitize_sql_array([
        "UPDATE curator_activity_logs SET activity_id = ? WHERE action_with_object_id = ?",
        actions[id][:activity].id, id ]))
    end
    remove_column :curator_activity_logs, :action_with_object_id
    drop_table :translated_action_with_objects
    drop_table :action_with_objects
  end

  def self.down
    raise ActiveRecord::IrreversibleMigration.new("We moved the action_with_object_ids to activity_ids, and we're not sure which activities need to become ActionWithObjects, so... sorry.")
  end
end


text:
<project name="MyProject" default="dist" basedir=".">
    <description>
        simple example build file
    </description>

    <property name="report" value="./build/test_logs" />

  	<target name="test">
		<junitreport todir="${report}">
			<fileset dir="${report}">
				<include name="TEST-*.xml" />
			</fileset>
			<report format="frames" todir="${report}/html" />
		</junitreport>
  	</target>
</project>


text:
<?php

namespace Codeception;

use Codeception\Exception\ConditionalAssertionFailed;
use Codeception\Util\Debug;
use Symfony\Component\EventDispatcher\Event;

abstract class TestCase extends \PHPUnit_Framework_TestCase implements \PHPUnit_Framework_SelfDescribing
{
    protected $scenario;

    protected $trace = array();

    protected $backupGlobalsBlacklist = array('app');

    public function getFeature()
    {
        return null;
    }

    public function getFileName()
    {
        return get_class($this) . '::' . $this->getName(false);
    }

    public function runStep(\Codeception\Step $step)
    {
        $this->trace[] = $step;
        $this->fire('step.before', new \Codeception\Event\Step($this, $step));
        try {
            $result = $step->run();
        } catch (ConditionalAssertionFailed $f) {
            $result = $this->getTestResultObject();
            $result->addFailure(clone($this), $f, $result->time());
        } catch (\Exception $e) {
            $this->fire('step.after', new \Codeception\Event\Step($this, $step));
            throw $e;
        }
        $this->fire('step.after', new \Codeception\Event\Step($this, $step));
        return $result;
    }

    protected function fire($event, Event $eventType)
    {
        foreach ($this->scenario->getGroups() as $group) {
            $this->dispatcher->dispatch($event.'.'.$group, $eventType);
        }
        $this->dispatcher->dispatch($event, $eventType);
    }

    /**
     * @return \Codeception\Scenario
     */
    public function getScenario()
    {
        return $this->scenario;
    }

    public function getTrace()
    {
        return $this->trace;
    }

    public function toString()
    {
        return $this->getFeature();
    }

    protected $dependencies;

    public function setDependencies(array $dependencies)
    {
        $this->dependencies = $dependencies;
    }

    protected function handleDependencies()
    {
        if (empty($this->dependencies)) return true;

        $passed     = $this->getTestResultObject()->passed();
        $testNames = array_map(function($testname) {
            if ($this instanceof \Codeception\TestCase\Cest) {
                $testname = str_replace('Codeception\TestCase\Cest::', get_class($this->getTestClass()).'::', $testname);
            }
            return preg_replace('~with data set (.*?)~','', $testname);
        }, array_keys($passed));
        $testNames = array_unique($testNames);

        $dependencyInput = array();
        foreach ($this->dependencies as $dependency) {
            if (strpos($dependency, '::') === FALSE) {
                $className = $this instanceof \Codeception\TestCase\Cest
                    ? get_class($this->getTestClass())
                    : get_class($this);
                $dependency = "$className::$dependency";
            }

            if (!in_array($dependency, $testNames)) {
                $this->getTestResultObject()->addError($this, new \PHPUnit_Framework_SkippedTestError("This test depends on '$dependency' to pass."),0);
                return false;
            }
            if (isset($passed[$dependency])) {
                $dependencyInput[] = $passed[$dependency]['result'];
            } else {
                $dependencyInput[] = NULL;
            }
        }
        $this->setDependencyInput($dependencyInput);

        return true;
    }

}


text:
package services // import "google.golang.org/genproto/googleapis/ads/googleads/v0/services"

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
import resources "google.golang.org/genproto/googleapis/ads/googleads/v0/resources"
import _ "google.golang.org/genproto/googleapis/api/annotations"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

// Request message for [ProductGroupViewService.GetProductGroupView][google.ads.googleads.v0.services.ProductGroupViewService.GetProductGroupView].
type GetProductGroupViewRequest struct {
	// The resource name of the product group view to fetch.
	ResourceName         string   `protobuf:"bytes,1,opt,name=resource_name,json=resourceName,proto3" json:"resource_name,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *GetProductGroupViewRequest) Reset()         { *m = GetProductGroupViewRequest{} }
func (m *GetProductGroupViewRequest) String() string { return proto.CompactTextString(m) }
func (*GetProductGroupViewRequest) ProtoMessage()    {}
func (*GetProductGroupViewRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_product_group_view_service_f4b2d412721c0b18, []int{0}
}
func (m *GetProductGroupViewRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_GetProductGroupViewRequest.Unmarshal(m, b)
}
func (m *GetProductGroupViewRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_GetProductGroupViewRequest.Marshal(b, m, deterministic)
}
func (dst *GetProductGroupViewRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_GetProductGroupViewRequest.Merge(dst, src)
}
func (m *GetProductGroupViewRequest) XXX_Size() int {
	return xxx_messageInfo_GetProductGroupViewRequest.Size(m)
}
func (m *GetProductGroupViewRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_GetProductGroupViewRequest.DiscardUnknown(m)
}

var xxx_messageInfo_GetProductGroupViewRequest proto.InternalMessageInfo

func (m *GetProductGroupViewRequest) GetResourceName() string {
	if m != nil {
		return m.ResourceName
	}
	return ""
}

func init() {
	proto.RegisterType((*GetProductGroupViewRequest)(nil), "google.ads.googleads.v0.services.GetProductGroupViewRequest")
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4

// ProductGroupViewServiceClient is the client API for ProductGroupViewService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type ProductGroupViewServiceClient interface {
	// Returns the requested product group view in full detail.
	GetProductGroupView(ctx context.Context, in *GetProductGroupViewRequest, opts ...grpc.CallOption) (*resources.ProductGroupView, error)
}

type productGroupViewServiceClient struct {
	cc *grpc.ClientConn
}

func NewProductGroupViewServiceClient(cc *grpc.ClientConn) ProductGroupViewServiceClient {
	return &productGroupViewServiceClient{cc}
}

func (c *productGroupViewServiceClient) GetProductGroupView(ctx context.Context, in *GetProductGroupViewRequest, opts ...grpc.CallOption) (*resources.ProductGroupView, error) {
	out := new(resources.ProductGroupView)
	err := c.cc.Invoke(ctx, "/google.ads.googleads.v0.services.ProductGroupViewService/GetProductGroupView", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// ProductGroupViewServiceServer is the server API for ProductGroupViewService service.
type ProductGroupViewServiceServer interface {
	// Returns the requested product group view in full detail.
	GetProductGroupView(context.Context, *GetProductGroupViewRequest) (*resources.ProductGroupView, error)
}

func RegisterProductGroupViewServiceServer(s *grpc.Server, srv ProductGroupViewServiceServer) {
	s.RegisterService(&_ProductGroupViewService_serviceDesc, srv)
}

func _ProductGroupViewService_GetProductGroupView_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(GetProductGroupViewRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(ProductGroupViewServiceServer).GetProductGroupView(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/google.ads.googleads.v0.services.ProductGroupViewService/GetProductGroupView",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(ProductGroupViewServiceServer).GetProductGroupView(ctx, req.(*GetProductGroupViewRequest))
	}
	return interceptor(ctx, in, info, handler)
}

var _ProductGroupViewService_serviceDesc = grpc.ServiceDesc{
	ServiceName: "google.ads.googleads.v0.services.ProductGroupViewService",
	HandlerType: (*ProductGroupViewServiceServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "GetProductGroupView",
			Handler:    _ProductGroupViewService_GetProductGroupView_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "google/ads/googleads/v0/services/product_group_view_service.proto",
}

func init() {
	proto.RegisterFile("google/ads/googleads/v0/services/product_group_view_service.proto", fileDescriptor_product_group_view_service_f4b2d412721c0b18)
}

var fileDescriptor_product_group_view_service_f4b2d412721c0b18 = []byte{
	// 348 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x84, 0x52, 0x3f, 0x4b, 0xc3, 0x40,
	0x14, 0x27, 0x15, 0x04, 0x83, 0x2e, 0x71, 0x50, 0x42, 0x87, 0x52, 0x1d, 0xa4, 0xc3, 0x5d, 0xb0,
	0xb8, 0x58, 0x1d, 0xd2, 0x25, 0x4e, 0x52, 0x2a, 0x74, 0x90, 0x40, 0x38, 0x93, 0xe3, 0x08, 0x34,
	0x79, 0xf1, 0xde, 0x25, 0x1d, 0xc4, 0xc5, 0xaf, 0xe0, 0x37, 0x70, 0xf4, 0x7b, 0xb8, 0xb8, 0xba,
	0xba, 0x08, 0x7e, 0x10, 0x49, 0xaf, 0x17, 0xb0, 0x34, 0x74, 0xfb, 0x91, 0x7b, 0xbf, 0x3f, 0xef,
	0xf7, 0x62, 0xfb, 0x02, 0x40, 0xcc, 0x39, 0x65, 0x09, 0x52, 0x0d, 0x6b, 0x54, 0x79, 0x14, 0xb9,
	0xac, 0xd2, 0x98, 0x23, 0x2d, 0x24, 0x24, 0x65, 0xac, 0x22, 0x21, 0xa1, 0x2c, 0xa2, 0x2a, 0xe5,
	0x8b, 0x68, 0xf5, 0x46, 0x0a, 0x09, 0x0a, 0x9c, 0x9e, 0xe6, 0x11, 0x96, 0x20, 0x69, 0x24, 0x48,
	0xe5, 0x11, 0x23, 0xe1, 0x5e, 0xb6, 0x99, 0x48, 0x8e, 0x50, 0xca, 0xcd, 0x2e, 0x5a, 0xdd, 0xed,
	0x1a, 0x6e, 0x91, 0x52, 0x96, 0xe7, 0xa0, 0x98, 0x4a, 0x21, 0x47, 0xfd, 0xda, 0xf7, 0x6d, 0x37,
	0xe0, 0x6a, 0xa2, 0xc9, 0x41, 0xcd, 0x9d, 0xa5, 0x7c, 0x31, 0xe5, 0x8f, 0x25, 0x47, 0xe5, 0x9c,
	0xd8, 0x07, 0xc6, 0x21, 0xca, 0x59, 0xc6, 0x8f, 0xad, 0x9e, 0x75, 0xb6, 0x37, 0xdd, 0x37, 0x1f,
	0x6f, 0x59, 0xc6, 0xcf, 0x7f, 0x2c, 0xfb, 0x68, 0x5d, 0xe0, 0x4e, 0x27, 0x77, 0x3e, 0x2c, 0xfb,
	0x70, 0x83, 0xbe, 0x73, 0x45, 0xb6, 0xed, 0x4c, 0xda, 0x63, 0xb9, 0xc3, 0x56, 0x76, 0xd3, 0x07,
	0x59, 0xe7, 0xf6, 0x47, 0x2f, 0x5f, 0xbf, 0xaf, 0x9d, 0x0b, 0x67, 0x58, 0xf7, 0xf6, 0xf4, 0x6f,
	0xad, 0xeb, 0xb8, 0x44, 0x05, 0x19, 0x97, 0x48, 0x07, 0xa6, 0xc8, 0x86, 0x88, 0x74, 0xf0, 0x3c,
	0xfe, 0xb6, 0xec, 0xd3, 0x18, 0xb2, 0xad, 0xa9, 0xc7, 0xdd, 0x96, 0x26, 0x26, 0x75, 0xdb, 0x13,
	0xeb, 0xfe, 0x66, 0xa5, 0x20, 0x60, 0xce, 0x72, 0x41, 0x40, 0x0a, 0x2a, 0x78, 0xbe, 0xbc, 0x85,
	0xb9, 0x6c, 0x91, 0x62, 0xfb, 0xdf, 0x34, 0x32, 0xe0, 0xad, 0xb3, 0x13, 0xf8, 0xfe, 0x7b, 0xa7,
	0x17, 0x68, 0x41, 0x3f, 0x41, 0xa2, 0x61, 0x8d, 0x66, 0x1e, 0x59, 0x19, 0xe3, 0xa7, 0x19, 0x09,
	0xfd, 0x04, 0xc3, 0x66, 0x24, 0x9c, 0x79, 0xa1, 0x19, 0x79, 0xd8, 0x5d, 0x06, 0x18, 0xfe, 0x05,
	0x00, 0x00, 0xff, 0xff, 0xc2, 0xc3, 0x37, 0x48, 0xcd, 0x02, 0x00, 0x00,
}


text:
#import <AppKit/NSControl.h>
#import <AppKit/NSButtonCell.h>

@interface NSButton : NSControl

- (BOOL)isTransparent;
- (NSString *)keyEquivalent;
- (NSUInteger)keyEquivalentModifierMask;
- (NSImage *)image;
- (NSCellImagePosition)imagePosition;
- (NSString *)title;
- (NSInteger)state;
- (BOOL)allowsMixedState;
- (NSSound *)sound;

- (NSBezelStyle)bezelStyle;
- (NSString *)alternateTitle;
- (NSImage *)alternateImage;
- (NSAttributedString *)attributedTitle;
- (NSAttributedString *)attributedAlternateTitle;
- (BOOL)showsBorderOnlyWhileMouseInside;
- (void)getPeriodicDelay:(float *)delay interval:(float *)interval;

- (void)setTransparent:(BOOL)value;
- (void)setKeyEquivalent:(NSString *)value;
- (void)setKeyEquivalentModifierMask:(NSUInteger)value;
- (void)setImage:(NSImage *)value;
- (void)setImagePosition:(NSCellImagePosition)value;
- (void)setTitle:(NSString *)value;
- (void)setState:(NSInteger)value;
- (void)setNextState;
- (void)setAllowsMixedState:(BOOL)value;
- (void)setSound:(NSSound *)value;

- (void)setBezelStyle:(NSBezelStyle)value;
- (void)setAlternateTitle:(NSString *)value;
- (void)setAlternateImage:(NSImage *)value;
- (void)setAttributedTitle:(NSAttributedString *)value;
- (void)setAttributedAlternateTitle:(NSAttributedString *)value;
- (void)setShowsBorderOnlyWhileMouseInside:(BOOL)value;
- (void)setPeriodicDelay:(float)delay interval:(float)interval;

- (void)setButtonType:(NSButtonType)value;
- (void)setTitleWithMnemonic:(NSString *)value;

- (void)highlight:(BOOL)value;
- (BOOL)performKeyEquivalent:(NSEvent *)event;
- (void)performClick:sender;

@end


text:
class CreateUserModels < ActiveRecord::Migration
  def change
    create_table :user_models do |t|
      t.integer :user_id
      t.integer :tops_type
      t.integer :tops_style
      t.integer :tops_color
      t.integer :bottoms_type
      t.integer :bottoms_style
      t.integer :bottoms_color
      t.integer :priority

      t.timestamps null: false
    end
  end
end


text:
/**
 *
 */
package com.github.phantomthief.thrift.client.pool;

import org.apache.thrift.transport.TTransport;

import com.pheu.common.ThriftServerInfo;

/**
 *

 * ThriftConnectionPoolProvider interface.
 *

 *
 * @author w.vela
 * @version $Id: $Id
 */
public interface ThriftConnectionPoolProvider {

    /**
     *

     * getConnection.
     *

     *
     * @param thriftServerInfo a
     *        {@link com.pheu.common.ThriftServerInfo} object.
     * @return a {@link org.apache.thrift.transport.TTransport} object.
     */
    TTransport getConnection(ThriftServerInfo thriftServerInfo);

    /**
     *

     * returnConnection.
     *

     *
     * @param thriftServerInfo a
     *        {@link com.pheu.common.ThriftServerInfo} object.
     * @param transport a {@link org.apache.thrift.transport.TTransport}
     *        object.
     */
    void returnConnection(ThriftServerInfo thriftServerInfo, TTransport transport);

    /**
     *

     * returnBrokenConnection.
     *

     *
     * @param thriftServerInfo a
     *        {@link com.pheu.common.ThriftServerInfo} object.
     * @param transport a {@link org.apache.thrift.transport.TTransport}
     *        object.
     */
    void returnBrokenConnection(ThriftServerInfo thriftServerInfo, TTransport transport);

}


text:
if (typeof params.insecure === 'string' || !params.insecure) {
    params.insecure = params.insecure === 'true' ? true : false;
}
var fixUrl = function(url) {
    fixedUrl = '';
    if (url.indexOf("http") !== 0) {
        if (params.insecure) {
            fixedUrl = 'http://' + url;
        } else {
            fixedUrl = 'https://' + url;
        }
    }
    return fixedUrl;
};
var parseResponse = function(resp) {
    var res = null;
    if (resp.StatusCode >= 200 && resp.StatusCode < 300) {
        try {
            res = JSON.parse(resp.Body);
        } catch (e) {
            res = resp.Body;
        }
    } else {
      err = resp.Status;
      if (resp.Body) {
          err += '\n' + resp.Body;
      }
      throw err;
    }
    if (res && res.length && res.length > 1 ) {
        // response body is array, then put it into object
        // we don't want to return array
        return { result: res };
    } else if (res && res.length === 0) {
        return {};
    } else {
        return res;
    }
};
var url = fixUrl(params.url);
var login = function(params) {
    var fullUrl = fixUrl(params.url) + '/cm/api/v1.0/oauth2/token';
    var body = {
        grant_type: 'client_credentials',
        client_id: params.clientId,
        client_secret: params.clientSecret
    };
    var res = httpMultipart(
        fullUrl,
        '',
        {
            Method: 'POST'
        },
        body,
        params.insecure
    );
    return parseResponse(res);
};
var listEndpoints = function(url, token) {
    var fullUrl = fixUrl(url) + '/cm/api/v1.0/endpoint';
    var res = http(
        fullUrl,
        {
            Method: 'GET',
            Headers: {'Authorization': ['Bearer ' + token]}
        },
        params.insecure
    );
    return parseResponse(res);
};
var setEndpointStatus = function(url, token, endpointId, action) {
    // validate action
    // action can be "enroll" or "revoke"
    if (action !== 'enroll' && action !== 'revoke') {
        throw 'action must be "enroll" or "revoke"!';
    }
    var fullUrl = fixUrl(url) + '/cm/api/v1.0/endpoint/' + endpointId;
    var res = http(
        fullUrl,
        {
            Method: 'POST',
            Headers: {
                'Authorization': ['Bearer ' + token],
                'Content-Type': ['application/json']
            },
            Body: JSON.stringify({
                action: action
            })
        },
        params.insecure
    );
    parseResponse(res);
    return 'Success';
};
switch(command) {
    case 'test-module':
        login(params);
        return true;
    case 'imp-sf-list-endpoints':
        var loginRes = login(params);
        return listEndpoints(params.url, loginRes.access_token);
    case 'imp-sf-set-endpoint-status':
        var loginRes = login(params);
        return setEndpointStatus(params.url, loginRes.access_token, args.endpointId, args.action);
    default:
        return true;
}


text:
var thisRef = this;

function sampleApp1()
{
    this.live2DMgr = new LAppLive2DManager();

    this.isDrawStart = false;

    this.gl = null;
    this.canvas = null;

    this.dragMgr = null; /*new L2DTargetPoint();*/
    this.viewMatrix = null; /*new L2DViewMatrix();*/
    this.projMatrix = null; /*new L2DMatrix44()*/
    this.deviceToScreen = null; /*new L2DMatrix44();*/

    this.drag = false;

    this.lastMouseX = 0;
    this.lastMouseY = 0;

    initL2dCanvas("glcanvas");

    init();
}

function initL2dCanvas(canvasId)
{
    l2dLog("--> onCreateContext()");

	this.canvas = document.getElementById(canvasId);

    if(this.canvas.addEventListener) {
        this.canvas.addEventListener("mousewheel", onWheel, false);
        this.canvas.addEventListener("click", onClick, true);
        this.canvas.addEventListener("mousedown", onMouseDown, false);
        this.canvas.addEventListener("mousemove", onMouseMove, false);
        this.canvas.addEventListener("mouseup", onMouseUp, false);
        this.canvas.addEventListener("mouseout", onMouseOut, false);
        this.canvas.addEventListener("contextmenu", onMouseRightClick, false);
    }
}

function init()
{
    l2dLog("--> init()");

    var width = this.canvas.width;
    var height = this.canvas.height;

    this.dragMgr = new L2DTargetPoint();

    var ratio = height / width;
    var left = LAppDefine.VIEW_LOGICAL_LEFT;
    var right = LAppDefine.VIEW_LOGICAL_RIGHT;
    var bottom = -ratio;
    var top = ratio;

    this.viewMatrix = new L2DViewMatrix();

    this.viewMatrix.setScreenRect(left, right, bottom, top);

    this.viewMatrix.setMaxScreenRect(LAppDefine.VIEW_LOGICAL_MAX_LEFT,
                                     LAppDefine.VIEW_LOGICAL_MAX_RIGHT,
                                     LAppDefine.VIEW_LOGICAL_MAX_BOTTOM,
                                     LAppDefine.VIEW_LOGICAL_MAX_TOP);

    this.viewMatrix.setMaxScale(LAppDefine.VIEW_MAX_SCALE);
    this.viewMatrix.setMinScale(LAppDefine.VIEW_MIN_SCALE);

    this.projMatrix = new L2DMatrix44();
    this.projMatrix.multScale(1, (width / height));

    this.deviceToScreen = new L2DMatrix44();
    this.deviceToScreen.multTranslate(-width / 2.0, -height / 2.0);
    this.deviceToScreen.multScale(2 / width, -2 / width);

	this.gl = getWebGLContext();
	if (!this.gl) {
        l2dError("Failed to create WebGL context.");
        return;
    }

	this.gl.clearColor(0.0, 0.0, 0.0, 0.0);

    changeModel();

    startDraw();
}

function startDraw() {
    if(!this.isDrawStart) {
        this.isDrawStart = true;
        (function tick() {
                draw();

                var requestAnimationFrame =
                    window.requestAnimationFrame ||
                    window.mozRequestAnimationFrame ||
                    window.webkitRequestAnimationFrame ||
                    window.msRequestAnimationFrame;

                requestAnimationFrame(tick ,this.canvas);
        })();
    }
}

function draw()
{
    // l2dLog("--> draw()");

    MatrixStack.reset();
    MatrixStack.loadIdentity();

    this.dragMgr.update();
    this.live2DMgr.setDrag(this.dragMgr.getX(), this.dragMgr.getY());

	this.gl.clear(this.gl.COLOR_BUFFER_BIT);

    MatrixStack.multMatrix(projMatrix.getArray());
    MatrixStack.multMatrix(viewMatrix.getArray());
    MatrixStack.push();

    for (var i = 0; i < this.live2DMgr.numModels(); i++)
    {
        var model = this.live2DMgr.getModel(i);

        if(model == null) return;

        if (model.initialized && !model.updating)
        {
            model.update();
            model.draw(this.gl);
        }
    }

    MatrixStack.pop();
}

function changeModel()
{
    this.live2DMgr.reloadFlg = true;
    this.live2DMgr.count++;

    this.live2DMgr.changeModel(this.gl);
}

function onWheel(e)
{
    e.preventDefault();

    if (e.clientX < 0 || thisRef.canvas.clientWidth < e.clientX ||
        e.clientY < 0 || thisRef.canvas.clientHeight < e.clientY)
    {
        return;
    }

    var sx = transformScreenX(e.clientX);
    var sy = transformScreenY(e.clientY);
    var vx = transformViewX(e.clientX);
    var vy = transformViewY(e.clientY);

    if (LAppDefine.DEBUG_MOUSE_LOG)
        l2dLog("onWheel device( x:" + e.clientX + " y:" + e.clientY + " ) screen( x:" + sx + " y:" + sy + ")" + " ) view( x:" + vx + " y:" + vy + ")");

    var isMaxScale = thisRef.viewMatrix.isMaxScale();
    var isMinScale = thisRef.viewMatrix.isMinScale();

    if (e.wheelDelta > 0)
    {

        thisRef.viewMatrix.adjustScale(sx, sy, 1.1);
    }
    else
    {

        thisRef.viewMatrix.adjustScale(sx, sy, 0.9);
    }

    if (!isMaxScale)
    {
        if (thisRef.viewMatrix.isMaxScale())
        {
            thisRef.live2DMgr.maxScaleEvent();
        }
    }

    if (!isMinScale)
    {
        if (thisRef.viewMatrix.isMinScale())
        {
            thisRef.live2DMgr.minScaleEvent();
        }
    }

}

function onClick(e)
{

    if(e.button != 0) return;

    var sx = transformScreenX(e.clientX);
    var sy = transformScreenY(e.clientY);
    var vx = transformViewX(e.clientX);
    var vy = transformViewY(e.clientY);

    if (LAppDefine.DEBUG_MOUSE_LOG)
        l2dLog("onClick device( x:" + e.clientX + " y:" + e.clientY + " ) screen( x:" + sx + " y:" + sy + ")" + " ) view( x:" + vx + " y:" + vy + ")");

    thisRef.live2DMgr.tapEvent(vx, vy);
}

function onMouseDown(e)
{

    if(e.button != 0) return;

    thisRef.drag = true;
    var sx = transformScreenX(e.clientX);
    var sy = transformScreenY(e.clientY);
    var vx = transformViewX(e.clientX);
    var vy = transformViewY(e.clientY);
    if (LAppDefine.DEBUG_MOUSE_LOG)
        l2dLog("onMouseDown device( x:" + e.clientX + " y:" + e.clientY + " ) view( x:" + vx + " y:" + vy + ")");

    thisRef.lastMouseX = sx;
    thisRef.lastMouseY = sy;

    thisRef.dragMgr.setPoint(vx, vy);
}

function onMouseMove(e)
{
    var sx = transformScreenX(e.clientX);
    var sy = transformScreenY(e.clientY);
    var vx = transformViewX(e.clientX);
    var vy = transformViewY(e.clientY);
    if (LAppDefine.DEBUG_MOUSE_LOG)
        l2dLog("onMouseMove device( x:" + e.clientX + " y:" + e.clientY + " ) view( x:" + vx + " y:" + vy + ")");

    if (thisRef.drag)
    {
        thisRef.lastMouseX = sx;
        thisRef.lastMouseY = sy;

        thisRef.dragMgr.setPoint(vx, vy);
    }
}

function onMouseUp(e)
{
    if (thisRef.drag)
    {
        thisRef.drag = false;
    }
    var x = transformViewX(e.clientX);
    var y = transformViewY(e.clientY);
    if (LAppDefine.DEBUG_MOUSE_LOG)
        l2dLog("onMouseUp device( x:" + e.clientX + " y:" + e.clientY + " ) view( x:" + x + " y:" + y + ")");

    thisRef.dragMgr.setPoint(0, 0);
}

function onMouseOut(e)
{
    if (thisRef.drag)
    {
        thisRef.drag = false;
    }

    thisRef.dragMgr.setPoint(0, 0);
}

function onMouseRightClick(e)
{
    e.preventDefault();

    changeModel();

    // init(this);
}

function transformViewX(deviceX)
{
    var screenX = this.deviceToScreen.transformX(deviceX);
    return viewMatrix.invertTransformX(screenX);
}

function transformViewY(deviceY)
{
    var screenY = this.deviceToScreen.transformY(deviceY);
    return viewMatrix.invertTransformY(screenY);
}

function transformScreenX(deviceX)
{
    return this.deviceToScreen.transformX(deviceX);
}

function transformScreenY(deviceY)
{
    return this.deviceToScreen.transformY(deviceY);
}

function getWebGLContext()
{
	var NAMES = [ "webgl" , "experimental-webgl" , "webkit-3d" , "moz-webgl"];

	for( var i = 0; i < NAMES.length; i++ ){
		try{
			var ctx = this.canvas.getContext(NAMES[i]);
			if(ctx) return ctx;
		}
		catch(e){}
	}
	return null;
};

function l2dLog(msg) {
    if(!LAppDefine.DEBUG_LOG) return;

    console.log(msg);
}

function l2dError(msg)
{
    if(!LAppDefine.DEBUG_LOG) return;

	console.error(msg);
};


text:
import base64
import glob
import gzip
import hashlib
import json
import os
import logging
import pwd
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.request, urllib.error, urllib.parse

APP_NAME = 'archbuilder'
BUILDER_USER = APP_NAME
ETC_LOCALE_GEN = '''
en_US.UTF-8 UTF-8
en_US ISO-8859-1
'''

def LogStep(msg):
  logging.info('- %s', msg)

def SetupLogging(quiet=False, verbose=False):
  if not quiet:
    root = logging.getLogger()
    stdout_logger = logging.StreamHandler(sys.stdout)
    if verbose:
      stdout_logger.setLevel(logging.DEBUG)
    else:
      stdout_logger.setLevel(logging.WARNING)
    stdout_logger.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
    root.addHandler(stdout_logger)
    root.setLevel(logging.DEBUG)

def Sed(file_path, modification):
  Run(['sed', '-i', modification, file_path])

def Replace(file_path, pattern, replacement):
  Sed(file_path, 's/%s/%s/g' % (pattern, replacement))

def ReplaceLine(file_path, pattern, replacement):
  Sed(file_path, '/%s/c\%s' % (pattern, replacement))

def SudoRun(params, cwd=None, capture_output=False):
  if os.geteuid() != 0:
    params = ['sudo'] + params
  return Run(params, capture_output=capture_output)

def UserExists(username):
  try:
    pwd.getpwnam(username)
    return True
  except:
    return False

def CreateBuildUser():
  if not UserExists(BUILDER_USER):
    Run(['useradd', BUILDER_USER, '-d', '/home/%s' % BUILDER_USER])

def Run(params, cwd=None, capture_output=False, shell=False, env=None, wait=True):
  try:
    logging.debug(params)
    if env:
      new_env = os.environ.copy()
      new_env.update(env)
      env = new_env
    out_pipe = None
    if capture_output:
      out_pipe = subprocess.PIPE
    proc = subprocess.Popen(params, stdout=out_pipe, cwd=cwd, shell=shell, env=env)
    if not wait:
      return 0, '', ''
    out, err = proc.communicate()
    if capture_output:
      logging.debug(out)

    if out:
      out = out.decode(encoding='UTF-8')
    if err:
      err = err.decode(encoding='UTF-8')
  except KeyboardInterrupt:
    return 1, '', ''
  except:
    logging.error(sys.exc_info()[0])
    logging.error(sys.exc_info())
    Run(['/bin/bash'])
    return 1, '', ''

  return proc.returncode, out, err

def DownloadFile(url, file_path):
  Run(['wget', '-O', file_path, url, '-nv'])

def HttpGet(url):
  return str(urllib.request.urlopen(url).read(), encoding='utf8')

def Sha1Sum(file_path):
  with open(file_path, 'rb') as fp:
    return hashlib.sha1(fp.read()).hexdigest()

def Untar(file_path, dest_dir):
  Run(['tar', '-C', dest_dir, '-xzf', file_path])

def Chmod(fp, mode):
  Run(['chmod', str(mode), fp])

def CreateDirectory(dir_path):
  dir_path = ToAbsolute(dir_path)
  if not os.path.isdir(dir_path):
    os.makedirs(dir_path)

def ToAbsolute(path):
  if not path:
    return path
  return os.path.expandvars(os.path.expanduser(path))

def DeleteFile(file_pattern):
  DeleteFileFunc(file_pattern, lambda item: os.remove(item))

def SecureDeleteFile(file_pattern):
  DeleteFileFunc(file_pattern, lambda item: Run(['shred', '--remove', '--zero', item]))

def DeleteFileFunc(file_pattern, delete_func):
  items = glob.glob(ToAbsolute(file_pattern))
  for item in items:
    logging.warning('Deleting %s', item)
    delete_func(item)

def DeleteDirectory(dir_path):
  shutil.rmtree(dir_path)

def CreateTempDirectory(base_dir=None):
  return tempfile.mkdtemp(dir=ToAbsolute(base_dir), prefix='gcearch')

def WriteFile(path, content):
  with open(ToAbsolute(path), 'w') as fp:
    fp.write(content)

def AppendFile(path, content):
  with open(ToAbsolute(path), 'a') as fp:
    fp.write(content)

def RunChroot(base_dir, command, use_custom_path=True):
  base_dir = ToAbsolute(base_dir)
  if use_custom_path:
    chroot_file = os.path.join(base_dir, 'bin/arch-chroot')
  else:
    chroot_file = 'arch-chroot'
  SudoRun([chroot_file, base_dir, '/bin/bash', '-c', command])

def CopyFiles(source_pattern, dest):
  """Copies a set of files based on glob pattern to a directory.
     Avoiding shutil.copyfile because of bugs.python.org/issue10016."""
  items = glob.glob(ToAbsolute(source_pattern))
  for item in items:
    Run(['cp', '-Rf', item, dest])

def CopyBuilder(base_dir):
  script_dir = os.path.dirname(os.path.realpath(__file__))
  temp_dir = CreateTempDirectory(base_dir=base_dir)
  DeleteDirectory(temp_dir)
  relative_dir = os.path.relpath(temp_dir, base_dir)
  shutil.copytree(script_dir, temp_dir, ignore=shutil.ignore_patterns('*.tar.gz', '*.raw'))
  return relative_dir

def EncodeArgs(decoded_args):
  return base64.standard_b64encode(gzip.compress(bytes(json.dumps(decoded_args), 'utf-8'))).decode('utf-8')

def DecodeArgs(encoded_args):
  return json.loads(gzip.decompress(base64.standard_b64decode(encoded_args)).decode('utf-8'))

def DebugBash():
  Run(['/bin/bash'])

def DebugPrintFile(file_path):
  logging.info('==============================================================')
  logging.info('File: %s', file_path)
  logging.info('==============================================================')
  Run(['cat', file_path])

def Sync():
  Run(['sync'])

def EnableService(service_name):
  Run(['systemctl', 'enable', service_name])

def DisableService(service_name):
  Run(['systemctl', 'disable', service_name])

def Symlink(source_file, dest_file):
  Run(['ln', '-s', source_file, dest_file])

def ChangeDirectoryOwner(username, directory):
  SudoRun(['chown', '-R', username, directory])

def AurInstall(name=None, pkbuild_url=None):
  CreateBuildUser()
  if name:
    pkbuild_url = 'https://aur.archlinux.org/cgit/aur.git/plain/PKGBUILD?h=%s' % name.lower()
  workspace_dir = CreateTempDirectory()
  DownloadFile(pkbuild_url, os.path.join(workspace_dir, 'PKGBUILD'))
  ChangeDirectoryOwner(BUILDER_USER, workspace_dir)
  Run(['runuser', '-l', BUILDER_USER, '-c', 'makepkg'], cwd=workspace_dir)
  tarball = glob.glob(os.path.join(workspace_dir, '*.tar*'))
  tarball = tarball[0]
  Pacman(['-U', tarball], cwd=workspace_dir)
  return tarball

def Pacstrap(base_dir, params):
  Run(['pacstrap', base_dir] + params)

def Pacman(params, cwd=None):
  #, '--debug'
  Run(['pacman', '--noconfirm'] + params, cwd=cwd)

def InstallPackages(package_list):
  Pacman(['-S'] + package_list)

def SetupArchLocale():
  AppendFile('/etc/locale.gen', ETC_LOCALE_GEN)
  Run(['locale-gen'])
  Run(['localectl', 'set-locale', 'LANG="en_US.UTF-8"', 'LC_COLLATE="C"'])

class ImageMapper(object):
  """Interface for kpartx, mount, and umount."""
  def __init__(self, raw_disk, mount_path):
    self._raw_disk = raw_disk
    self._mount_path = mount_path
    self._device_map = None
    self._mount_points = None

  def _LoadPartitionsIfNeeded(self):
    if not self._device_map:
      self.LoadPartitions()

  def LoadPartitions(self):
    return_code, out, err = SudoRun(['kpartx', '-l', self._raw_disk], capture_output=True)
    # Expected Format
    # loop2p1 : 0 10483712 /dev/loop2 2048
    # loop2p2 : 0 1 /dev/loop2 2047
    # loop deleted : /dev/loop2

    self._device_map = {}
    lines = out.splitlines()
    for line in lines:
      parts = str(line).split()
      if len(parts) == 6:
        mapping = {
            'name': parts[0],
            'size_blocks': parts[3],
            'parent': parts[4],
            'start_block': parts[5],
            'path': '/dev/mapper/%s' % str(parts[0])
          }
        logging.info('Mapping: %s', mapping)
        self._device_map[mapping['name']] = mapping
    if len(self._device_map) == 1:
      self._mount_points = [self._mount_path]
    else:
      self._mount_points = []
      for name in list(self._device_map.keys()):
        self._mount_points.append(os.path.join(self._mount_path, name))

  def ForEachDevice(self, func):
    for name in list(self._device_map.keys()):
      spec = self._device_map[name]
      func(spec)

  def ForEachDeviceWithIndex(self, func):
    i = 0
    for name in list(self._device_map.keys()):
      spec = self._device_map[name]
      func(i, spec)
      i += 1

  def GetFirstMapping(self):
    logging.info('DeviceMap: %s', self.GetDeviceMap())
    return next(iter(self.GetDeviceMap().values()))

  def GetDeviceMap(self):
    return self._device_map

  def Sync(self):
    Run(['sync'])

  def Map(self):
    SudoRun(['kpartx', '-a', '-v', '-s', self._raw_disk])
    self.LoadPartitions()

  def Unmap(self):
    self.Sync()
    time.sleep(2)
    SudoRun(['kpartx', '-d', '-v', '-s', self._raw_disk])
    self._device_map = None

  def Mount(self):
    self._LoadPartitionsIfNeeded()
    self._ThrowIfBadMountMap()
    def MountCmd(index, spec):
      mount_point = self._mount_points[index]
      CreateDirectory(mount_point)
      SudoRun(['mount', spec['path'], mount_point])
    self.ForEachDeviceWithIndex(MountCmd)

  def Unmount(self):
    self._LoadPartitionsIfNeeded()
    self._ThrowIfBadMountMap()
    for path in self._mount_points:
      SudoRun(['umount', path])
    self.Sync()
    time.sleep(2)

  def _ThrowIfBadMountMap(self):
    if not self._mount_points:
      raise IOError('Attempted to found {0} without a mount points.'.format(self._raw_disk))
    if len(self._mount_points) != len(list(self._device_map.keys())):
      raise IOError('Number of device maps ({0}) does not match mount points ({1}).'.format(
          len(list(self._device_map.keys())), len(self._mount_points)
      ))


text:
#include <cassert>
#include <numeric>

#include "base/cast.hh"
#include "base/stl_helpers.hh"
#include "mem/ruby/buffers/MessageBuffer.hh"
#include "mem/ruby/common/NetDest.hh"
#include "mem/ruby/network/BasicLink.hh"
#include "mem/ruby/network/simple/SimpleLink.hh"
#include "mem/ruby/network/simple/SimpleNetwork.hh"
#include "mem/ruby/network/simple/Switch.hh"
#include "mem/ruby/network/simple/Throttle.hh"
#include "mem/ruby/network/Topology.hh"
#include "mem/ruby/profiler/Profiler.hh"
#include "mem/ruby/system/System.hh"

using namespace std;
using m5::stl_helpers::deletePointers;

SimpleNetwork::SimpleNetwork(const Params *p)
    : Network(p)
{
    m_buffer_size = p->buffer_size;
    m_endpoint_bandwidth = p->endpoint_bandwidth;
    m_adaptive_routing = p->adaptive_routing;

    // Note: the parent Network Object constructor is called before the
    // SimpleNetwork child constructor.  Therefore, the member variables
    // used below should already be initialized.

    m_endpoint_switches.resize(m_nodes);

    m_in_use.resize(m_virtual_networks);
    m_ordered.resize(m_virtual_networks);
    for (int i = 0; i < m_virtual_networks; i++) {
        m_in_use[i] = false;
        m_ordered[i] = false;
    }

    // Allocate to and from queues
    m_toNetQueues.resize(m_nodes);
    m_fromNetQueues.resize(m_nodes);
    for (int node = 0; node < m_nodes; node++) {
        m_toNetQueues[node].resize(m_virtual_networks);
        m_fromNetQueues[node].resize(m_virtual_networks);
        for (int j = 0; j < m_virtual_networks; j++) {
            m_toNetQueues[node][j] =
                new MessageBuffer(csprintf("toNet node %d j %d", node, j));
            m_fromNetQueues[node][j] =
                new MessageBuffer(csprintf("fromNet node %d j %d", node, j));
        }
    }

    // record the routers
    for (vector<BasicRouter*>::const_iterator i =
             m_topology_ptr->params()->routers.begin();
         i != m_topology_ptr->params()->routers.end(); ++i) {
        Switch* s = safe_cast<Switch*>(*i);
        m_switch_ptr_vector.push_back(s);
        s->init_net_ptr(this);
    }
}

void
SimpleNetwork::init()
{
    Network::init();

    // The topology pointer should have already been initialized in
    // the parent class network constructor.
    assert(m_topology_ptr != NULL);
    // false because this isn't a reconfiguration
    m_topology_ptr->createLinks(this, false);
}

void
SimpleNetwork::reset()
{
    for (int node = 0; node < m_nodes; node++) {
        for (int j = 0; j < m_virtual_networks; j++) {
            m_toNetQueues[node][j]->clear();
            m_fromNetQueues[node][j]->clear();
        }
    }

    for(int i = 0; i < m_switch_ptr_vector.size(); i++){
        m_switch_ptr_vector[i]->clearBuffers();
    }
}

SimpleNetwork::~SimpleNetwork()
{
    for (int i = 0; i < m_nodes; i++) {
        deletePointers(m_toNetQueues[i]);
        deletePointers(m_fromNetQueues[i]);
    }
    deletePointers(m_switch_ptr_vector);
    deletePointers(m_buffers_to_free);
    // delete m_topology_ptr;
}

// From a switch to an endpoint node
void
SimpleNetwork::makeOutLink(SwitchID src, NodeID dest, BasicLink* link,
                           LinkDirection direction,
                           const NetDest& routing_table_entry,
                           bool isReconfiguration)
{
    assert(dest < m_nodes);
    assert(src < m_switch_ptr_vector.size());
    assert(m_switch_ptr_vector[src] != NULL);

    if (isReconfiguration) {
        m_switch_ptr_vector[src]->reconfigureOutPort(routing_table_entry);
        return;
    }

    SimpleExtLink *simple_link = safe_cast<SimpleExtLink*>(link);

    m_switch_ptr_vector[src]->addOutPort(m_fromNetQueues[dest],
                                         routing_table_entry,
                                         simple_link->m_latency,
                                         simple_link->m_bw_multiplier);

    m_endpoint_switches[dest] = m_switch_ptr_vector[src];
}

// From an endpoint node to a switch
void
SimpleNetwork::makeInLink(NodeID src, SwitchID dest, BasicLink* link,
                          LinkDirection direction,
                          const NetDest& routing_table_entry,
                          bool isReconfiguration)
{
    assert(src < m_nodes);
    if (isReconfiguration) {
        // do nothing
        return;
    }

    m_switch_ptr_vector[dest]->addInPort(m_toNetQueues[src]);
}

// From a switch to a switch
void
SimpleNetwork::makeInternalLink(SwitchID src, SwitchID dest, BasicLink* link,
                                LinkDirection direction,
                                const NetDest& routing_table_entry,
                                bool isReconfiguration)
{
    if (isReconfiguration) {
        m_switch_ptr_vector[src]->reconfigureOutPort(routing_table_entry);
        return;
    }

    // Create a set of new MessageBuffers
    std::vector<MessageBuffer*> queues;
    for (int i = 0; i < m_virtual_networks; i++) {
        // allocate a buffer
        MessageBuffer* buffer_ptr = new MessageBuffer;
        buffer_ptr->setOrdering(true);
        if (m_buffer_size > 0) {
            buffer_ptr->resize(m_buffer_size);
        }
        queues.push_back(buffer_ptr);
        // remember to deallocate it
        m_buffers_to_free.push_back(buffer_ptr);
    }
    // Connect it to the two switches
    SimpleIntLink *simple_link = safe_cast<SimpleIntLink*>(link);

    m_switch_ptr_vector[dest]->addInPort(queues);
    m_switch_ptr_vector[src]->addOutPort(queues, routing_table_entry,
                                         simple_link->m_latency,
                                         simple_link->m_bw_multiplier);
}

void
SimpleNetwork::checkNetworkAllocation(NodeID id, bool ordered, int network_num)
{
    assert(id < m_nodes);
    assert(network_num < m_virtual_networks);

    if (ordered) {
        m_ordered[network_num] = true;
    }
    m_in_use[network_num] = true;
}

MessageBuffer*
SimpleNetwork::getToNetQueue(NodeID id, bool ordered, int network_num,
                             std::string vnet_type)
{
    checkNetworkAllocation(id, ordered, network_num);
    return m_toNetQueues[id][network_num];
}

MessageBuffer*
SimpleNetwork::getFromNetQueue(NodeID id, bool ordered, int network_num,
                               std::string vnet_type)
{
    checkNetworkAllocation(id, ordered, network_num);
    return m_fromNetQueues[id][network_num];
}

const std::vector<Throttle*>*
SimpleNetwork::getThrottles(NodeID id) const
{
    assert(id >= 0);
    assert(id < m_nodes);
    assert(m_endpoint_switches[id] != NULL);
    return m_endpoint_switches[id]->getThrottles();
}

void
SimpleNetwork::printStats(ostream& out) const
{
    out << endl;
    out << "Network Stats" << endl;
    out << "-------------" << endl;
    out << endl;

    //
    // Determine total counts before printing out each switch's stats
    //
    std::vector<uint64> total_msg_counts;
    total_msg_counts.resize(MessageSizeType_NUM);
    for (MessageSizeType type = MessageSizeType_FIRST;
         type < MessageSizeType_NUM;
         ++type) {
        total_msg_counts[type] = 0;
    }

    for (int i = 0; i < m_switch_ptr_vector.size(); i++) {
        const std::vector<Throttle*>* throttles =
            m_switch_ptr_vector[i]->getThrottles();

        for (int p = 0; p < throttles->size(); p++) {

            const std::vector<std::vector<int> >& message_counts =
                ((*throttles)[p])->getCounters();

            for (MessageSizeType type = MessageSizeType_FIRST;
                 type < MessageSizeType_NUM;
                 ++type) {

                const std::vector<int> &mct = message_counts[type];
                int sum = accumulate(mct.begin(), mct.end(), 0);
                total_msg_counts[type] += uint64(sum);
            }
        }
    }
    uint64 total_msgs = 0;
    uint64 total_bytes = 0;
    for (MessageSizeType type = MessageSizeType_FIRST;
         type < MessageSizeType_NUM;
         ++type) {

        if (total_msg_counts[type] > 0) {
            out << "total_msg_count_" << type << ": " << total_msg_counts[type]
                << " " << total_msg_counts[type] *
                uint64(MessageSizeType_to_int(type))
                << endl;

            total_msgs += total_msg_counts[type];

            total_bytes += total_msg_counts[type] *
                uint64(MessageSizeType_to_int(type));
        }
    }

    out << "total_msgs: " << total_msgs
        << " total_bytes: " << total_bytes << endl;

    out << endl;
    for (int i = 0; i < m_switch_ptr_vector.size(); i++) {
        m_switch_ptr_vector[i]->printStats(out);
    }
}

void
SimpleNetwork::clearStats()
{
    for (int i = 0; i < m_switch_ptr_vector.size(); i++) {
        m_switch_ptr_vector[i]->clearStats();
    }
}

void
SimpleNetwork::print(ostream& out) const
{
    out << "[SimpleNetwork]";
}

SimpleNetwork *
SimpleNetworkParams::create()
{
    return new SimpleNetwork(this);
}

/*
 * The simple network has an array of switches. These switches have buffers
 * that need to be accessed for functional reads and writes. Also the links
 * between different switches have buffers that need to be accessed.
 */
bool
SimpleNetwork::functionalRead(Packet *pkt)
{
    for (unsigned int i = 0; i < m_switch_ptr_vector.size(); i++) {
        if (m_switch_ptr_vector[i]->functionalRead(pkt)) {
            return true;
        }
    }

    for (unsigned int i = 0; i < m_buffers_to_free.size(); ++i) {
        if (m_buffers_to_free[i]->functionalRead(pkt)) {
            return true;
        }
    }

    return false;
}

uint32_t
SimpleNetwork::functionalWrite(Packet *pkt)
{
    uint32_t num_functional_writes = 0;

    for (unsigned int i = 0; i < m_switch_ptr_vector.size(); i++) {
        num_functional_writes += m_switch_ptr_vector[i]->functionalWrite(pkt);
    }

    for (unsigned int i = 0; i < m_buffers_to_free.size(); ++i) {
        num_functional_writes += m_buffers_to_free[i]->functionalWrite(pkt);
    }
    return num_functional_writes;
}