text:
package pagination

import (
	"fmt"
	"html/template"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"

	X "github.com/webx-top/webx"
	"github.com/webx-top/webx/lib/forms/common"
)

type Paginationer interface {
	//设置导航条模板
	SetTmpl(tmpl string) Paginationer

	//设置从URL中获取的参数名:页码参数名,每页数据量参数名,数据总量参数名
	SetQueryName(args ...string) Paginationer

	//设置各项参数
	SetPage(args ...int64) Paginationer

	//准备渲染所必须的数据
	Ready(linkNum int64, args ...string) Paginationer

	//ajax导航时更新的容器ID
	SetContainerId(containerId string) Paginationer

	//唯一ID。用于在相同页面内区分多个导航条
	UniqueId() string

	//设置唯一ID
	SetUniqueId(uniqueId string) Paginationer

	//渲染输出导航条HTML对象
	Render() template.HTML

	//渲染输出导航条字符串
	String() string

	//组合数据并渲染输出导航条HTML对象
	HTML(linkNum int64, args ...string) template.HTML

	//数据库查询所需的游标
	Limit() (limit, offset int64)

	//设置计算数据总量的操作函数
	SetCount(fn func() int64) Paginationer

	//登记查询出来的数据结果,并检查是否为空
	CheckData(data interface{}) Paginationer

	//获取登记的数据结果
	Data() interface{}
	Pagebar() *Pagebar

	//URL中的"页码"变量标识
	PageKey() string

	//URL中的"每页数据量"变量标识
	PageRowsKey() string

	//URL中的"数据总量"变量标识
	TotalRowsKey() string

	CleanURL(string, ...string) string
}

type Pages struct {
	Data interface{}
	Page Paginationer
}

func NewPagebar() *Pagebar {
	return &Pagebar{}
}

type Pagebar struct {
	Url         string  //网址
	Rows        int64   //每页显示行数
	RowsOptions []int64 //可切换的每页显示行数
	PageRowsUrl string  //页面行数切换网址
	Page        int64   //页码
	Pages       []int64 //列出的页面
	Total       int64   //页码总数
	NextPage    int64   //下一页页码
	PrevPage    int64   //上一页页码
	ContainerId string
	UniqueId    string //唯一ID
}

type Pagination struct {
	*X.Context
	pageNum      int64
	pageRows     int64
	maxPageRows  int64
	TotalRows    int64
	countFunc    func() int64 //统计TotalRows的函数
	pageKey      string
	pageRowsKey  string
	totalRowsKey string
	Tmpl         string
	pagebar      *Pagebar
	emptyData    bool
	data         interface{}
	paramsLoaded bool
}

func New(ctx *X.Context) Paginationer {
	b := &Pagination{
		Context:      ctx,
		TotalRows:    -1,
		pageKey:      `page`,
		pageRowsKey:  `pagerows`,
		totalRowsKey: `totalrows`,
		maxPageRows:  1000,
		pageRows:     10,
	}
	//b.SetTmpl(`default`).SetPage(args...)
	return b
}

func (this *Pagination) SetTmpl(tmpl string) Paginationer {
	if tmpl == `` {
		return this
	}
	switch tmpl[0] {
	case '#':
		this.Tmpl = filepath.Join(this.Context.Server.RootDir(), `data`, `widgets`, tmpl[1:]+`.html`)
	case '@':
		tmpl = tmpl[1:]
		var tdir string
		if pos := strings.Index(tmpl, `:`); pos > 0 {
			module := this.Context.Server.Module(tmpl[0:pos])
			tmpl = tmpl[pos+1:]
			tdir = module.Renderer.TmplDir()
		} else {
			tdir = this.Context.Module.Renderer.TmplDir()
		}
		this.Tmpl = filepath.Join(tdir, tmpl+`.html`)
	default:
		this.Tmpl = filepath.Join(this.Context.Module.Renderer.TmplDir(), tmpl+`.html`)
	}
	return this
}

//SetQueryName 1-页码变量名 2-每页数据量变量名 3-总数据量变量名
func (this *Pagination) SetQueryName(args ...string) Paginationer {
	switch len(args) {
	case 3:
		if args[2] != `` {
			this.totalRowsKey = args[2]
		}
		fallthrough
	case 2:
		if args[1] != `` {
			this.pageRowsKey = args[1]
		}
		fallthrough
	case 1:
		if args[0] != `` {
			this.pageKey = args[0]
		}
	}
	return this
}

func (this *Pagination) QueryValue() Paginationer {
	if v := this.Context.Form(this.pageKey); v != `` {
		if num, err := strconv.Atoi(v); err == nil && num > 1 {
			this.pageNum = int64(num)
		}
	}
	if v := this.Context.Form(this.pageRowsKey); v != `` {
		if num, err := strconv.Atoi(v); err == nil && num > 0 && int64(num) <= this.maxPageRows {
			this.pageRows = int64(num)
		}
	}
	if v := this.Context.Form(this.totalRowsKey); v != `` {
		if num, err := strconv.Atoi(v); err == nil && num > 0 {
			this.TotalRows = int64(num)
		}
	}
	return this
}

//SetPage 1-总数据量 2-每页数据量 3-页码
func (this *Pagination) SetPage(args ...int64) Paginationer {
	switch len(args) {
	case 4:
		this.maxPageRows = args[3]
		fallthrough
	case 3:
		this.pageNum = args[2]
		fallthrough
	case 2:
		if args[1] > 0 && args[1] <= this.maxPageRows {
			this.pageRows = args[1]
		}
		fallthrough
	case 1:
		this.TotalRows = args[0]
	default:
		this.QueryValue()
	}
	if this.pageNum < 1 {
		this.pageNum = 1
	}
	this.paramsLoaded = true
	return this
}

func (this *Pagination) Pages(total, limit int64) int64 {
	if total <= 0 {
		return 1
	} else {
		x := total % limit
		if x > 0 {
			return total/limit + 1
		} else {
			return total / limit
		}
	}
}

func (this *Pagination) Ready(linkNum int64, args ...string) Paginationer {
	if !this.paramsLoaded {
		this.SetPage()
	}
	pageRows := this.pageRows
	totalRows := this.TotalRows
	if totalRows < 0 {
		if this.countFunc != nil {
			totalRows = this.countFunc()
		} else {
			totalRows = 0
		}
		this.TotalRows = totalRows
	}

	var urlFormat string
	if len(args) <= 0 || args[0] == `` {
		urlFormat = this.ReqURI()
	} else {
		urlFormat = args[0]
	}
	page := this.pageNum

	if this.emptyData && totalRows > 0 && page > 1 {
		this.Context.Redir(urlFormat)
		this.pagebar = nil
		return this
	}
	totalPages := this.Pages(totalRows, pageRows)
	if page < 1 {
		page = 1
	}
	if page > totalPages && page > 1 {
		this.Context.Redir(urlFormat)
		this.pagebar = nil
		return this
	}
	separator := `&`
	if strings.Contains(urlFormat, `?`) == false {
		urlFormat += `?`
	} else {
		urlFormat += separator
	}

	urlFormat += this.pageKey + `=%v`
	if pageRows > 0 && this.pageRowsKey != `` {
		urlFormat += separator + this.pageRowsKey + `=` + fmt.Sprintf(`%d`, this.pageRows)
	}
	if totalRows > 0 && this.totalRowsKey != `` {
		urlFormat += separator + this.totalRowsKey + `=` + fmt.Sprintf(`%d`, totalRows)
	}
	var (
		start int64 = 1
		end   int64 = totalPages
	)
	halfNum := int64(linkNum / 2)
	endNum := page + halfNum
	if page > halfNum {
		start = page - halfNum
	}
	if start+linkNum > endNum {
		endNum = start + linkNum
	}
	if totalPages > endNum {
		end = endNum
	} else {
		if end > linkNum {
			start = end - linkNum
		}
	}
	pg := NewPagebar()
	pg.Rows = this.pageRows
	var pgrows string
	if pos := strings.LastIndex(urlFormat, this.pageRowsKey+`=`); pos > 0 {
		pgrows = fmt.Sprintf(urlFormat[0:pos], 1) + this.pageRowsKey + `=`
	} else {
		pgrows = fmt.Sprintf(urlFormat, 1) + separator + this.pageRowsKey + `=`
	}
	pg.PageRowsUrl = pgrows
	pg.Page = page
	pg.RowsOptions = []int64{10, 20, 50, 100, 200, 300, 500, 1000}
	pg.PrevPage = page - 1
	pg.NextPage = page + 1
	pg.Total = totalPages
	pg.Url = urlFormat
	pg.Pages = make([]int64, 0)
	for i := start; i <= end; i++ {
		pg.Pages = append(pg.Pages, i)
	}
	this.pagebar = pg
	return this
}

func (this *Pagination) SetContainerId(containerId string) Paginationer {
	if this.pagebar != nil {
		this.pagebar.ContainerId = containerId
		this.pagebar.UniqueId = fmt.Sprintf(`%x`, containerId)
	}
	return this
}

func (this *Pagination) UniqueId() (r string) {
	if this.pagebar != nil {
		r = this.pagebar.UniqueId
	}
	return
}

func (this *Pagination) SetUniqueId(uniqueId string) Paginationer {
	if this.pagebar != nil {
		this.pagebar.UniqueId = uniqueId
	}
	return this
}

func (this *Pagination) Render() template.HTML {
	return template.HTML(this.String())
}

func (this *Pagination) String() string {
	if this.pagebar == nil {
		return ``
	}
	funcMap := this.Context.Server.FuncMap
	contexFuncMap := this.Context.Funcs()
	if contexFuncMap != nil {
		for name, fn := range contexFuncMap {
			funcMap[name] = fn
		}
	}
	return formcommon.ParseTmpl(this.pagebar, funcMap, nil, this.Tmpl)
}

func (this *Pagination) HTML(linkNum int64, args ...string) template.HTML {
	return this.Ready(linkNum, args...).Render()
}

func (this *Pagination) Limit() (limit, offset int64) {
	pn := this.pageNum
	if pn < 1 {
		pn = 1
	}
	limit = this.pageRows
	offset = (pn - 1) * limit
	return
}

func (this *Pagination) SetCount(fn func() int64) Paginationer {
	this.countFunc = fn
	return this
}

func (this *Pagination) CheckData(data interface{}) Paginationer {
	if data == nil || fmt.Sprintf(`%v`, data) == `[]` {
		this.emptyData = true
	}
	this.data = data
	return this
}

func (this *Pagination) Data() interface{} {
	return this.data
}

func (this *Pagination) Pagebar() *Pagebar {
	return this.pagebar
}

func (this *Pagination) PageNum() int64 {
	return this.pageNum
}

func (this *Pagination) PageRows() int64 {
	return this.pageRows
}

func (this *Pagination) PageKey() string {
	return this.pageKey
}

func (this *Pagination) PageRowsKey() string {
	return this.pageRowsKey
}

func (this *Pagination) TotalRowsKey() string {
	return this.totalRowsKey
}

func (this *Pagination) ReqURI() (r string) {
	r = this.Context.Request().URL().Path()
	q := this.Context.Request().URL().RawQuery()
	cr, err := regexp.Compile(`(&|^)(` + this.pageKey + `|` + this.pageRowsKey + `|` + this.totalRowsKey + `)=[\d]*`)
	if err != nil {
		return err.Error()
	}
	q = cr.ReplaceAllString(q, ``)
	if this.Context.Query(`_pjax`) != `` {
		cr, _ := regexp.Compile(`(&|^)_pjax=[^&]*`)
		q = cr.ReplaceAllString(q, ``)
	}
	q = strings.Trim(q, `&`)
	if q != `` {
		r += `?` + q
	}
	return
}

func (this *Pagination) CleanURL(q string, keys ...string) (r string) {
	cr, err := regexp.Compile(`(&|^)(` + strings.Join(keys, `|`) + `)=[^&]*`)
	if err != nil {
		return err.Error()
	}
	r = cr.ReplaceAllString(q, ``)
	r = strings.Trim(r, `&`)
	return
}


text:
namespace kudu {

namespace rpc {
class PeriodicTimer;
class Messenger;
} // namespace rpc

namespace tools {

class KsckCluster;
class KsckTablet;
class KsckTabletServer;

// Options for checksum scans.
struct KsckChecksumOptions {
  // A checksum with this snapshot timestamp will choose a timestamp for each
  // tablet, from one of the tablet servers hosting a replica, at the
  // time the checksums are started.
  static constexpr uint64_t kCurrentTimestamp = 0;

  KsckChecksumOptions();

  KsckChecksumOptions(std::vector<std::string> table_filters,
                      std::vector<std::string> tablet_id_filters);

  KsckChecksumOptions(MonoDelta timeout,
                      MonoDelta idle_timeout,
                      int scan_concurrency,
                      bool use_snapshot,
                      uint64_t snapshot_timestamp);

  KsckChecksumOptions(MonoDelta timeout,
                      MonoDelta idle_timeout,
                      int scan_concurrency,
                      bool use_snapshot,
                      uint64_t snapshot_timestamp,
                      std::vector<std::string> table_filters,
                      std::vector<std::string> tablet_id_filters);

  // The maximum total time to wait for results to come back from all replicas.
  MonoDelta timeout;

  // The maximum amount of time to wait for progress to be made. Progress
  // means at least one additional row is checksummed.
  MonoDelta idle_timeout;

  // The maximum number of concurrent checksum scans to run per tablet server.
  int scan_concurrency;

  // Whether to use a snapshot checksum scanner.
  bool use_snapshot;

  // The snapshot timestamp to use for snapshot checksum scans.
  uint64_t snapshot_timestamp;

  // Filters for the table names and tablet ids whose contents should be
  // checksummed.
  std::vector<std::string> table_filters;
  std::vector<std::string> tablet_id_filters;
};

typedef std::pair<Status, uint64_t> ReplicaChecksumResult;
typedef std::unordered_map<std::string, ReplicaChecksumResult> TabletChecksumResult;
typedef std::unordered_map<std::string, TabletChecksumResult> TabletChecksumResultsMap;

// A convenience struct containing info needed to checksum a particular tablet.
struct TabletChecksumInfo {
  TabletChecksumInfo(std::shared_ptr<KsckTablet> tablet, Schema schema)
    : tablet(std::move(tablet)),
      schema(std::move(schema)) {}

  // The tablet to be checksummed.
  std::shared_ptr<KsckTablet> tablet;

  // The schema of the tablet's table.
  Schema schema;
};

typedef std::unordered_map<std::string, TabletChecksumInfo> TabletInfoMap;

// Map (tablet server UUID -> number of open slots available for checksum scans).
typedef std::unordered_map<std::string, int> TabletServerChecksumScanSlotsMap;

typedef std::vector<std::shared_ptr<KsckTabletServer>> TabletServerList;

// Class to coordinate a checksum process. Checksums are started on all replicas
// of a tablet at once while respecting per-tablet-server checksum scan
// concurrency limits.
class KsckChecksumManager : public std::enable_shared_from_this<KsckChecksumManager>,
                            public enable_make_shared<KsckChecksumManager> {
 public:
  // Return in 'manager' a new KsckChecksumManager created from the given
  // parameters. All replicas of tablet in 'tablet_infos' must be on tablet
  // servers in 'tservers'. Because its ownership is shared with callbacks that
  // are part of the checksum process, a KsckChecksumManager should always be
  // wrapped in a shared_ptr.
  // If 'messenger' is non-null, it will be used by the instance; otherwise, a
  // new messenger will be constructed.
  static Status New(KsckChecksumOptions opts,
                    TabletInfoMap tablet_infos,
                    TabletServerList tservers,
                    std::shared_ptr<rpc::Messenger> messenger,
                    std::shared_ptr<KsckChecksumManager>* manager);

  // Reports an increase in the number of rows and bytes from disk processed
  // by checksums to this KsckChecksumManager. This information is used in
  // progress messages.
  void ReportProgress(int64_t delta_rows, int64_t delta_bytes);

  // Reports the result of checksumming all the replicas of tablet to this
  // KsckChecksumManager.
  void ReportResult(const std::string& tablet_id,
                    const std::string& replica_uuid,
                    const Status& status,
                    uint64_t checksum);

  // The possible final outcomes of a checksum process.
  enum class Outcome {
    // All replicas finished their checksums (either successfully or not).
    FINISHED,
    // The checksum process timed out.
    TIMED_OUT,
    // The checksum process went too long without making progress.
    IDLE_TIMED_OUT,
  };

  // Blocks until the number of replica results and errors reported equals
  // the number of replicas that need to be processed, until the this instnce's
  // timeout expires, or until the checksum process makes no progress for longer
  // than this instance's idle timeout, whichever comes first. Progress messages
  // are printed to 'out' if it is non-null.
  Outcome WaitFor(std::ostream* out);

  // Run the checksum process asynchronously.
  // The caller should wait for results with WaitFor().
  Status RunChecksumsAsync();

  // Get a snapshot of results reported so far.
  TabletChecksumResultsMap checksums() const {
    std::lock_guard<simple_spinlock> guard(lock_);
    return checksums_;
  }

 protected:
  KsckChecksumManager(int num_replicas,
                      KsckChecksumOptions opts,
                      TabletInfoMap tablet_infos,
                      TabletServerList tservers,
                      std::shared_ptr<rpc::Messenger> messenger);

 private:
  // Perform post-construction initialization that may fail.
  Status Init();

  // Shutdown this manager.
  void Shutdown();

  // Start as many tablet checksums as possible, given the per-tablet-server
  // concurrency limits on checksum scans.
  // Since this uses a brute force method, it is fairly expensive, and therefore
  // we run it on a threadpool instead of in the callback, which is run from a
  // reactor thread.
  void StartTabletChecksums();

  // Are there enough checksum scan slots available on the tablet servers
  // hosting replicas of 'tablet' to start a checksum scan on all of them?
  // If so, return true and reserve the slots. Else, return false.
  bool ReserveSlotsToChecksumUnlocked(const std::shared_ptr<KsckTablet>& tablet);

  // Begin the checksum on the tablet named in 'tablet_info'.
  void BeginTabletChecksum(const TabletChecksumInfo& tablet_info);

  // Initialize 'ts_open_slots_map_'.
  void InitializeTsSlotsMap();

  // Release a checksum scan slot on each tserver in 'tserver_uuids'.
  void ReleaseTsSlotsUnlocked(const std::vector<std::string>& ts_uuids);

  // Are there any open slots at all?
  bool HasOpenTsSlotsUnlocked() const;

  // Returns a summary of checksum scan slot usage across tablet servers.
  // This is useful as debug info to check how saturated the tablet servers are
  // with checksum scans.
  std::string OpenTsSlotSummaryString() const;

  // The options for the checksum process.
  const KsckChecksumOptions opts_;

  // A map of information about tablets to be checksummed. As tablet checksums
  // are started, entries are removed from this map.
  TabletInfoMap tablet_infos_;

  // Tracks the open slots for each tablet server that hosts a replica of the
  // tablets in 'tablet_infos_'.
  TabletServerChecksumScanSlotsMap ts_slots_open_map_;

  // checksums_ is an unordered_map of { tablet_id : { replica_uuid : checksum } }.
  TabletChecksumResultsMap checksums_;

  // Protects 'tablet_infos_', 'ts_slots_map_', and 'checksums_'.
  mutable simple_spinlock lock_;

  // The list of tablet servers that checksum scans will be run on. Every
  // replica of tablet to be checksummed must be located on one of these
  // tablet servers.
  const TabletServerList tservers_;

  const int expected_replica_count_;
  CountDownLatch responses_;

  // Used for the 'timestamp_update_timer_' periodic timer.
  std::shared_ptr<rpc::Messenger> messenger_;

  // A timer used to periodically refresh the timestamps of the tablet servers
  // in 'tablet_servers_', so that snapshot timestamps don't fall behind the
  // ancient history mark.
  std::shared_ptr<rpc::PeriodicTimer> timestamp_update_timer_;

  // A threadpool for running tasks that find additional tablets that can
  // be checksummed based on available slots on tablet servers.
  gscoped_ptr<ThreadPool> find_tablets_to_checksum_pool_;

  std::atomic<int64_t> rows_summed_;
  std::atomic<int64_t> disk_bytes_summed_;

  DISALLOW_COPY_AND_ASSIGN(KsckChecksumManager);
};

// A class for performing checksums on a Kudu cluster.
class KsckChecksummer {
 public:
   // 'cluster' must remain valid as long as this instance is alive.
  explicit KsckChecksummer(KsckCluster* cluster);

  // Checksum the data in the Kudu cluster according to the options provided in
  // 'opts'. Results will be populated in the 'checksum_results'. If non-null,
  // progress updates will be written to 'out_for_progress_updates'.
  // NOTE: Even if this method returns a bad Status, 'checksum_results' will be
  // populated with whatever checksum results were received.
  Status ChecksumData(const KsckChecksumOptions& opts,
                      KsckChecksumResults* checksum_results,
                      std::ostream* out_for_progress_updates);

 private:
  // Builds a map of tablets to-be-checksummed, given the options in 'opts' and
  // the cluster 'cluster'. The resulting tablets are populated in 'tablet_infos'
  // and the total number of replicas to be checksummed is set in 'num_replica'.
  Status BuildTabletInfoMap(const KsckChecksumOptions& opts,
                            TabletInfoMap* tablet_infos,
                            int* num_replicas) const;

  // Collates the results of checksums that are reported in 'checksums' into
  // 'table_checksum_map', with the total number of results returned as
  // 'num_results'.
  // NOTE: Even if this function returns a bad Status, 'table_checksum_map'
  // and 'num_results' will still be populated using whatever results are
  // available.
  Status CollateChecksumResults(
      const TabletChecksumResultsMap& checksums,
      KsckTableChecksumMap* table_checksum_map,
      int* num_results) const;

  KsckCluster* cluster_;

  DISALLOW_COPY_AND_ASSIGN(KsckChecksummer);
};
} // namespace tools
} // namespace kudu

redpajama_set_name: RedPajamaGithub


text:
from .common import *
import dj_database_url

# Set DEBUG to True for local development
DEBUG = True
ALLOWED_HOSTS = []

# Default database sqlite3
DATABASES['default'] = dj_database_url.config(
    default='sqlite:///' + os.path.join(BASE_DIR, 'db.sqlite3'),
    conn_max_age=500
)


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/layoutMainContainer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".login.ui.LoginActivity">

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/wrapperPassword">

        <EditText
            android:id="@+id/editTxtEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/login.message.email"
            android:inputType="textEmailAddress"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/wrapperPassword"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/layoutButtons">

        <EditText
            android:id="@+id/editTxtPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editText"
            android:layout_alignStart="@+id/editText"
            android:layout_below="@+id/editText"
            android:ems="10"
            android:hint="@string/login.message.password"
            android:inputType="textPassword"/>
    </android.support.design.widget.TextInputLayout>

    <LinearLayout
        android:id="@+id/layoutButtons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnSignin"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login.button.signin"/>

        <Button
            android:id="@+id/btnSignup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/login.button.gotosignup"/>
    </LinearLayout>

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/layoutButtons"
        android:layout_centerHorizontal="true"
        android:visibility="gone"/>
</RelativeLayout>


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>requrejs-sandbox grunt test suite</title>
	<link rel="stylesheet" href="../bower_components/qunit/qunit/qunit.css" />


text:
namespace base {
class Value;
}

namespace content {
class RenderViewHost;
class WebUI;
class WebUIMessageHandler;
}

class TestChromeWebUIControllerFactory;
class WebUITestHandler;

// This macro simplifies the declaration of simple javascript unit tests.
// Use:
//   WEB_UI_UNITTEST_F(MyWebUIPageTest, myJavascriptUnittest);
#define WEB_UI_UNITTEST_F(x, y) \
  IN_PROC_BROWSER_TEST_F(x, y) { \
    ASSERT_TRUE(RunJavascriptTest(#y)); \
  }

// The runner of WebUI javascript based tests.
// See chrome/test/data/webui/test_api.js for the javascript side test API's.
//
// These tests should follow the form given in:
// chrome/test/data/webui/sample_downloads.js.
// and the lone test within this class.
class WebUIBrowserTest : public InProcessBrowserTest {
 public:
  typedef ScopedVector<const base::Value> ConstValueVector;
  virtual ~WebUIBrowserTest();

  // Add a custom helper JS library for your test.
  // If a relative path is specified, it'll be read
  // as relative to the test data dir.
  void AddLibrary(const base::FilePath& library_path);

  // Runs a javascript function in the context of all libraries.
  // Note that calls to functions in test_api.js are not supported.
  // Takes ownership of Value* arguments.
  bool RunJavascriptFunction(const std::string& function_name);
  bool RunJavascriptFunction(const std::string& function_name,
                             base::Value* arg);
  bool RunJavascriptFunction(const std::string& function_name,
                             base::Value* arg1,
                             base::Value* arg2);
  bool RunJavascriptFunction(const std::string& function_name,
                             const ConstValueVector& function_arguments);

  // Runs a test fixture that may include calls to functions in test_api.js.
  bool RunJavascriptTestF(bool is_async,
                          const std::string& test_fixture,
                          const std::string& test_name);

  // Runs a test that may include calls to functions in test_api.js.
  // Takes ownership of Value* arguments.
  bool RunJavascriptTest(const std::string& test_name);
  bool RunJavascriptTest(const std::string& test_name,
                         base::Value* arg);
  bool RunJavascriptTest(const std::string& test_name,
                         base::Value* arg1,
                         base::Value* arg2);
  bool RunJavascriptTest(const std::string& test_name,
                         const ConstValueVector& test_arguments);

  // Runs a test that may include calls to functions in test_api.js, and waits
  // for call to testDone().  Takes ownership of Value* arguments.
  bool RunJavascriptAsyncTest(const std::string& test_name);
  bool RunJavascriptAsyncTest(const std::string& test_name,
                              base::Value* arg);
  bool RunJavascriptAsyncTest(const std::string& test_name,
                              base::Value* arg1,
                              base::Value* arg2);
  bool RunJavascriptAsyncTest(const std::string& test_name,
                              base::Value* arg1,
                              base::Value* arg2,
                              base::Value* arg3);
  bool RunJavascriptAsyncTest(const std::string& test_name,
                              const ConstValueVector& test_arguments);

  // Sends message through |preload_host| to preload javascript libraries and
  // sets the |libraries_preloaded| flag to prevent re-loading at next
  // javascript invocation.
  void PreLoadJavascriptLibraries(const std::string& preload_test_fixture,
                                  const std::string& preload_test_name,
                                  content::RenderViewHost* preload_host);

  // Called by javascript-generated test bodies to browse to a page and preload
  // the javascript for the given |preload_test_fixture| and
  // |preload_test_name|. chrome.send will be overridden to allow javascript
  // handler mocking.
  void BrowsePreload(const GURL& browse_to);

  // Called by javascript-generated test bodies to browse to a page and preload
  // the javascript for the given |preload_test_fixture| and
  // |preload_test_name|. chrome.send will be overridden to allow javascript
  // handler mocking.
  void BrowsePrintPreload(const GURL& browse_to);

 protected:
  // URL to dummy WebUI page for testing framework.
  static const char kDummyURL[];

  WebUIBrowserTest();

  // Accessors for preload test fixture and name.
  void set_preload_test_fixture(const std::string& preload_test_fixture);
  void set_preload_test_name(const std::string& preload_test_name);

  // Set up & tear down console error catching.
  virtual void SetUpOnMainThread() OVERRIDE;
  virtual void CleanUpOnMainThread() OVERRIDE;

  // Set a WebUI instance to run tests on.
  void SetWebUIInstance(content::WebUI* web_ui);

  // Returns a mock WebUI object under test (if any).
  virtual content::WebUIMessageHandler* GetMockMessageHandler();

  // Returns a file:// GURL constructed from |path| inside the test data dir for
  // webui tests.
  static GURL WebUITestDataPathToURL(const base::FilePath::StringType& path);

 private:
  // Builds a string containing all added javascript libraries.
  void BuildJavascriptLibraries(base::string16* content);

  // Builds a string with a call to the runTest JS function, passing the
  // given |is_async|, |test_name| and its |args|.
  base::string16 BuildRunTestJSCall(
      bool is_async,
      const std::string& test_name,
      const WebUIBrowserTest::ConstValueVector& args);

  // Loads all libraries added with AddLibrary(), and calls |function_name| with
  // |function_arguments|. When |is_test| is true, the framework wraps
  // |function_name| with a test helper function, which waits for completion,
  // logging an error message on failure, otherwise |function_name| is called
  // asynchronously. When |preload_host| is non-NULL, sends the javascript to
  // the RenderView for evaluation at the appropriate time before the onload
  // call is made. Passes |is_async| along to runTest wrapper.
  bool RunJavascriptUsingHandler(const std::string& function_name,
                                 const ConstValueVector& function_arguments,
                                 bool is_test,
                                 bool is_async,
                                 content::RenderViewHost* preload_host);

  // Attaches mock and test handlers.
  void SetupHandlers();

  // Handles test framework messages.
  scoped_ptr<WebUITestHandler> test_handler_;

  // Location of test data (currently test/data/webui).
  base::FilePath test_data_directory_;

  // Location of generated test data (<(PROGRAM_DIR)/test_data).
  base::FilePath gen_test_data_directory_;

  // User added libraries
  std::vector<base::FilePath> user_libraries_;

  // Indicates that the libraries have been pre-loaded and to not load them
  // again.
  bool libraries_preloaded_;

  // Saves the states of |test_fixture| and |test_name| for calling
  // PreloadJavascriptLibraries().
  std::string preload_test_fixture_;
  std::string preload_test_name_;

  // When this is non-NULL, this is The WebUI instance used for testing.
  // Otherwise the selected tab's web_ui is used.
  content::WebUI* override_selected_web_ui_;

  scoped_ptr<TestChromeWebUIControllerFactory> test_factory_;
};

#endif  // CHROME_TEST_BASE_WEB_UI_BROWSERTEST_H_


text:
IMPLEMENT_DYNCREATE(CMt5UIDoc, CDocument)

BEGIN_MESSAGE_MAP(CMt5UIDoc, CDocument)
END_MESSAGE_MAP()

// CMt5UIDoc construction/destruction

CMt5UIDoc::CMt5UIDoc()
{
	// TODO: add one-time construction code here

}

CMt5UIDoc::~CMt5UIDoc()
{
}

BOOL CMt5UIDoc::OnNewDocument()
{
	if (!CDocument::OnNewDocument())
		return FALSE;

	// TODO: add reinitialization code here
	// (SDI documents will reuse this document)

	return TRUE;
}

// CMt5UIDoc serialization

void CMt5UIDoc::Serialize(CArchive& ar)
{
	// CEditView contains an edit control which handles all serialization
	if (!m_viewList.IsEmpty())
	{
		reinterpret_cast<CEditView*>(m_viewList.GetHead())->SerializeRaw(ar);
	}
#ifdef SHARED_HANDLERS

	if (m_viewList.IsEmpty() && ar.IsLoading())
	{
		CFile* pFile = ar.GetFile();
		pFile->Seek(0, FILE_BEGIN);
		ULONGLONG nFileSizeBytes = pFile->GetLength();
		ULONGLONG nFileSizeChars = nFileSizeBytes/sizeof(TCHAR);
		LPTSTR lpszText = (LPTSTR)malloc(((size_t)nFileSizeChars + 1) * sizeof(TCHAR));
		if (lpszText != NULL)
		{
			ar.Read(lpszText, (UINT)nFileSizeBytes);
			lpszText[nFileSizeChars] = '\0';
			m_strThumbnailContent = lpszText;
			m_strSearchContent = lpszText;
		}
	}
#endif
}

#ifdef SHARED_HANDLERS

// Support for thumbnails
void CMt5UIDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds)
{
	// Modify this code to draw the document's data
	dc.FillSolidRect(lprcBounds, RGB(255, 255, 255));

	LOGFONT lf;

	CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT));
	pDefaultGUIFont->GetLogFont(&lf);
	lf.lfHeight = 36;

	CFont fontDraw;
	fontDraw.CreateFontIndirect(&lf);

	CFont* pOldFont = dc.SelectObject(&fontDraw);
	dc.DrawText(m_strThumbnailContent, lprcBounds, DT_CENTER | DT_WORDBREAK);
	dc.SelectObject(pOldFont);
}

// Support for Search Handlers
void CMt5UIDoc::InitializeSearchContent()
{
	// Set search contents from document's data.
	// The content parts should be separated by ";"

	// Use the entire text file content as the search content.
	SetSearchContent(m_strSearchContent);
}

void CMt5UIDoc::SetSearchContent(const CString& value)
{
	if (value.IsEmpty())
	{
		RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid);
	}
	else
	{
		CMFCFilterChunkValueImpl *pChunk = NULL;
		ATLTRY(pChunk = new CMFCFilterChunkValueImpl);
		if (pChunk != NULL)
		{
			pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT);
			SetChunkValue(pChunk);
		}
	}
}

#endif // SHARED_HANDLERS

// CMt5UIDoc diagnostics

#ifdef _DEBUG
void CMt5UIDoc::AssertValid() const
{
	CDocument::AssertValid();
}

void CMt5UIDoc::Dump(CDumpContext& dc) const
{
	CDocument::Dump(dc);
}
#endif //_DEBUG

// CMt5UIDoc commands


text:
package poolmgr

import (
	"fmt"
	"testing"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	fv1 "github.com/fission/fission/pkg/apis/core/v1"
)

func TestGetPoolName(t *testing.T) {
	tests := []struct {
		name string
		env  *fv1.Environment
		want string
	}{
		{
			"Under character limit",
			&fv1.Environment{
				TypeMeta: metav1.TypeMeta{
					Kind:       fv1.CRD_NAME_ENVIRONMENT,
					APIVersion: fv1.CRD_VERSION,
				},
				ObjectMeta: metav1.ObjectMeta{
					Name:            "test",
					Namespace:       "testns",
					ResourceVersion: "2517",
				},
			},
			"poolmgr-test-testns-2517",
		},
		{
			"Over character limit",
			&fv1.Environment{
				TypeMeta: metav1.TypeMeta{
					Kind:       fv1.CRD_NAME_ENVIRONMENT,
					APIVersion: fv1.CRD_VERSION,
				},
				ObjectMeta: metav1.ObjectMeta{
					Name:            "justtryingtoincreasethenumberofcharactersinthisstring",
					Namespace:       "checkingifthegetpoolfunctionworkswithcharactersmorethan18",
					ResourceVersion: "2518",
				},
			},
			"poolmgr-justtryingtoincrea-checkingifthegetpo-2518",
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if got := getPoolName(tt.env); got != tt.want {
				t.Errorf("getPoolName() = %s, want = %s len(getPoolName()) = %x len(want) = %x", got, tt.want, len(got), len(tt.want))
			} else {
				fmt.Printf("getPoolName() = %s,length of string = %x", got, len(got))
			}
		})
	}
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import scipy.linalg
import tensorflow.compat.v2 as tf
from tf_agents.specs import tensor_spec
from tf_agents.policies import tf_policy
from typing import Any, Callable, Iterable, Optional, Sequence, Tuple, Union

import dice_rl.data.dataset as dataset_lib
import dice_rl.estimators.estimator as estimator_lib

def _is_categorical_spec(spec):
  return (tensor_spec.is_discrete(spec) and tensor_spec.is_bounded(spec) and
          spec.shape == [] and spec.minimum == 0)

class TabularTeQDice(object):
  """Approximate the density ratio using exact matrix solves."""

  def __init__(self,
               dataset_spec,
               gamma: Union[float, tf.Tensor],
               max_trajectory_length: int,
               step_encoding: Optional[str] = None,
               reward_fn: Optional[Callable] = None,
               solve_for_state_action_ratio: bool = True):
    """Initializes the solver.

    Args:
      dataset_spec: The spec of the dataset that will be given.
      gamma: The discount factor to use.
      step_encoding: A string that describes the type of step encoding.
      max_trajectory_length: Evaluate up to this trajectory length.
      reward_fn: A function that takes in an EnvStep and returns the reward for
        that step. If not specified, defaults to just EnvStep.reward.
      solve_for_state_action_ratio: Whether to solve for state-action density
        ratio. Defaults to False, which instead solves for state density ratio.
        Although the estimated policy value should be the same, approximating
        using the state density ratio is much faster (especially in large
        environments) and more accurate (especially in low-data regimes).
    """
    self._dataset_spec = dataset_spec
    self._gamma = gamma
    self._step_encoding = step_encoding
    if reward_fn is None:
      reward_fn = lambda env_step: env_step.reward
    self._reward_fn = reward_fn

    self._solve_for_state_action_ratio = solve_for_state_action_ratio
    if (not self._solve_for_state_action_ratio and
        not self._dataset_spec.has_log_probability()):
      raise ValueError('Dataset must contain log-probability when '
                       'solve_for_state_action_ratio is False.')

    # Get number of states/actions.
    observation_spec = self._dataset_spec.observation
    action_spec = self._dataset_spec.action
    step_num_spec = self._dataset_spec.step_num
    if not _is_categorical_spec(observation_spec):
      raise ValueError('Observation spec must be discrete and bounded.')
    self._num_states = observation_spec.maximum + 1

    if not _is_categorical_spec(action_spec):
      raise ValueError('Action spec must be discrete and bounded.')
    self._num_actions = action_spec.maximum + 1

    if not _is_categorical_spec(step_num_spec):
      raise ValueError('Step number spec must be discrete and bounded.')
    self._num_steps = step_num_spec.maximum
    self._max_trajectory_length = max_trajectory_length

    self._dimension = (
        self._num_states * self._num_actions
        if self._solve_for_state_action_ratio else self._num_states)

    if self._step_encoding is not None:
      emb_blocks = np.repeat(self._create_step_emb(), self._dimension, axis=0)
      self._step_emb = scipy.linalg.block_diag(*emb_blocks)
      self._dimension *= self._num_steps

    self._nu = np.zeros([self._dimension])
    self._zeta = np.zeros([self._dimension])

  def _get_index(self, state, action, step_num):
    if self._solve_for_state_action_ratio:
      index = state * self._num_actions + action
    else:
      index = state
    if self._step_encoding is not None:
      index = index * self._num_steps + step_num
    return index

  def _create_step_emb(self):
    if self._step_encoding == 'one_hot':
      return np.eye(self._num_steps)[None, ...]

    d_step_emb = 5

    def get_angles(pos, i):
      angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(d_step_emb))
      return pos * angle_rates

    angle_rads = get_angles(0 + np.arange(self._num_steps)[:, np.newaxis],
                            0 + np.arange(d_step_emb)[np.newaxis, :])
    angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])
    angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])
    return angle_rads[np.newaxis, ...]

  def solve(self,
            dataset: dataset_lib.OffpolicyDataset,
            target_policy: tf_policy.TFPolicy,
            regularizer: float = 1e-8):
    """Solves for density ratios and then approximates target policy value.

    Args:
      dataset: The dataset to sample experience from.
      target_policy: The policy whose value we want to estimate.
      regularizer: A small constant to add to matrices before inverting them or
        to floats before taking square root.

    Returns:
      Estimated average per-step reward of the target policy.
    """
    td_residuals = np.zeros([self._dimension, self._dimension])
    total_weights = np.zeros([self._dimension])
    initial_weights = np.zeros([self._dimension])

    episodes, valid_steps = dataset.get_all_episodes(limit=None)
    tfagents_episodes = dataset_lib.convert_to_tfagents_timestep(episodes)

    for episode_num in range(tf.shape(valid_steps)[0]):
      # Precompute probabilites for this episode.
      this_episode = tf.nest.map_structure(lambda t: t[episode_num], episodes)
      first_step = tf.nest.map_structure(lambda t: t[0], this_episode)
      this_tfagents_episode = dataset_lib.convert_to_tfagents_timestep(
          this_episode)
      episode_target_log_probabilities = target_policy.distribution(
          this_tfagents_episode).action.log_prob(this_episode.action)
      episode_target_probs = target_policy.distribution(
          this_tfagents_episode).action.probs_parameter()

      for step_num in range(tf.shape(valid_steps)[1] - 1):
        this_step = tf.nest.map_structure(lambda t: t[episode_num, step_num],
                                          episodes)
        next_step = tf.nest.map_structure(
            lambda t: t[episode_num, step_num + 1], episodes)
        this_tfagents_step = dataset_lib.convert_to_tfagents_timestep(this_step)
        next_tfagents_step = dataset_lib.convert_to_tfagents_timestep(next_step)
        if this_step.is_last() or not valid_steps[episode_num, step_num]:
          continue

        weight = 1.0
        step_num_range = np.arange(self._num_steps - 1)
        nu_index = self._get_index(this_step.observation, this_step.action,
                                   step_num_range).numpy()
        td_residuals[nu_index, nu_index] += weight
        np.add.at(total_weights, nu_index, weight)

        policy_ratio = 1.0
        if not self._solve_for_state_action_ratio:
          policy_ratio = tf.exp(episode_target_log_probabilities[step_num] -
                                this_step.get_log_probability())

        # Need to weight next nu by importance weight.
        next_weight = (
            weight if self._solve_for_state_action_ratio else policy_ratio *
            weight)
        next_probs = episode_target_probs[step_num + 1]
        for next_action, next_prob in enumerate(next_probs):
          next_nu_index = self._get_index(next_step.observation, next_action,
                                          step_num_range + 1).numpy()
          td_residuals[next_nu_index,
                       nu_index] += (-next_prob * self._gamma * next_weight)

        initial_probs = episode_target_probs[0]
        for initial_action, initial_prob in enumerate(initial_probs):
          initial_nu_index = self._get_index(first_step.observation,
                                             initial_action, 0)
          initial_weights[initial_nu_index] += weight * initial_prob * len(
              step_num_range)

    td_residuals /= np.sqrt(regularizer + total_weights)[None, :]
    if self._step_encoding is not None:
      td_residuals = np.dot(self._step_emb.T, td_residuals)
      initial_weights = np.dot(self._step_emb.T, initial_weights)
    td_errors = np.dot(td_residuals, td_residuals.T)
    self._nu = np.linalg.solve(
        td_errors + regularizer * np.eye(td_errors.shape[0]),
        (1 - self._gamma) * initial_weights)
    self._zeta = np.dot(self._nu,
                        td_residuals) / np.sqrt(regularizer + total_weights)
    return self.estimate_average_reward(dataset, target_policy)

  def estimate_average_reward(self, dataset: dataset_lib.OffpolicyDataset,
                              target_policy: tf_policy.TFPolicy):
    """Estimates value (average per-step reward) of policy.

    The estimation is based on solved values of zeta, so one should call
    solve() before calling this function.

    Args:
      dataset: The dataset to sample experience from.
      target_policy: The policy whose value we want to estimate.

    Returns:
      Estimated average per-step reward of the target policy.
    """

    def weight_fn(env_step):
      if self._step_encoding is not None:
        zeta = 0.
        for step_num in range(self._max_trajectory_length):
          index = self._get_index(env_step.observation, env_step.action,
                                  step_num)
          zeta += self._gamma**step_num * self._zeta[index]
        zeta *= (1 - self._gamma) / (1 - self._gamma**(self._num_steps - 1))
      else:
        index = self._get_index(env_step.observation, env_step.action,
                                env_step.step_num)
        zeta = self._zeta[index]
        zeta = tf.where(env_step.step_num >= self._max_trajectory_length,
                        tf.zeros_like(zeta), zeta)

      policy_ratio = 1.0
      if not self._solve_for_state_action_ratio:
        tfagents_timestep = dataset_lib.convert_to_tfagents_timestep(env_step)
        target_log_probabilities = target_policy.distribution(
            tfagents_timestep).action.log_prob(env_step.action)
        policy_ratio = tf.exp(target_log_probabilities -
                              env_step.get_log_probability())

      return tf.cast(
          zeta, dtype=tf.float32) * tf.cast(
              policy_ratio, dtype=tf.float32)

    return estimator_lib.get_fullbatch_average(
        dataset,
        limit=None,
        by_steps=True,
        reward_fn=self._reward_fn,
        weight_fn=weight_fn)


text:
#ifndef SRC_TRANSFORMS_CENTROID_H_
#define SRC_TRANSFORMS_CENTROID_H_

#include "src/formats/single_format.h"
#include "src/transforms/common.h"

namespace sound_feature_extraction {
namespace transforms {

/// @brief Calculates \f$\frac{\displaystyle\sum_{f=0}^{SamplingRate / 2}{f
/// Value[f]}}{\displaystyle\sum_{f=0}^{SamplingRate / 2}{Value[f]}}\f$.
class Centroid : public OmpTransformBase<formats::ArrayFormatF,
                                         formats::SingleFormatF>  {
 public:
  TRANSFORM_INTRO("Centroid", "Window's center of mass in frequency domain "
                              "calculation.",
                  Centroid)

 protected:
  virtual void Do(const float* in,
                  float* out) const noexcept override;

  static float Do(bool simd, const float* input, size_t length) noexcept;
};

}  // namespace transforms
}  // namespace sound_feature_extraction
#endif  // SRC_TRANSFORMS_CENTROID_H_


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 10: 7 (1892)

#### Original name
Helotium ochraceum (Grev.) Berk., 1860

### Remarks
null


text:
namespace Gu.Wpf.Validation.Tests.Sandbox
{
    using System;
    using System.Windows;
    using System.Windows.Controls;

    using NUnit.Framework;

    [RequiresSTA]
    public class RoutedEventLeaks
    {
        private static readonly RoutedEventHandler OnLoadedHandler = new RoutedEventHandler(OnLoaded);

        [Test]
        public void AddHandler()
        {
            TextBox textBox = new TextBox();
            textBox.AddHandler(FrameworkElement.LoadedEvent, OnLoadedHandler);
            WeakReference wr = new WeakReference(textBox);
            textBox = null;
            GC.Collect();
            Assert.IsFalse(wr.IsAlive);
        }

        private static void OnLoaded(object sender, EventArgs e)
        {
        }
    }
}


text:
<?php

////////////////////////////////////////////
//
//CONFIGURATION
//
////////////////////////////////////////////

////////////////////////////////////////////
//FORCE_SSL -
//
//Default: True
//Description: Setting this to true requires that users access the page via https.
//		Requests sent using http will be redirected

define('FORCE_SSL', true);

////////////////////////////////////////////
//RESTRICT_USERS -
//
//Default: False
//Description: Setting this to true will only allow access to users
//		set in the $users array found below.
//		This array contains a whitelist of user login names (not summoner names)
//		they are lowercased before being sha1 checksumed

define('RESTRICT_USERS', false);

//This array of strings controls user access. Use sha1() hashes of lowercased usernames
$users = array (
);

////////////////////////////////////////////
//DEBUG -
//
//Default: False
//Description: Setting this to true will log HTTP responses to the file defined in LOG_FILE.
//		NOTE: Only outgoing headers and incoming responses are logged;
//		username/password information is NOT stored even with this enabled

define('DEBUG', false);

////////////////////////////////////////////
//
//LOG_FILE -
//
//Default: "log.txt"
//Description: Name of the log file used if DEBUG is enabled

define('LOG_FILE', "log.txt");

////////////////////////////////////////////
//
//END OF CONFIGURATION
//
////////////////////////////////////////////


text:
import { DOCUMENT } from '@angular/common';
import {
  AfterContentInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ContentChild,
  ElementRef,
  Inject,
  OnDestroy,
  OnInit,
  Optional,
} from '@angular/core';
import { SkyThemeService, SkyThemeSettings } from '@skyux/theme';

import { AgGridAngular } from 'ag-grid-angular';
import { CellEditingStartedEvent, DetailGridInfo } from 'ag-grid-community';
import { BehaviorSubject, Observable, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { SkyAgGridAdapterService } from './ag-grid-adapter.service';
import { SkyAgGridService } from './ag-grid.service';

let idIndex = 0;

@Component({
  selector: 'sky-ag-grid-wrapper',
  templateUrl: './ag-grid-wrapper.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SkyAgGridWrapperComponent
  implements AfterContentInit, OnDestroy, OnInit
{
  @ContentChild(AgGridAngular, {
    static: true,
  })
  public agGrid: AgGridAngular | undefined;

  public afterAnchorId: string;
  public beforeAnchorId: string;
  public gridId: string;
  public wrapperClasses$: Observable<string[]>;

  public get viewkeeperClasses(): string[] {
    return this.#_viewkeeperClasses;
  }

  public set viewkeeperClasses(value: string[]) {
    this.#_viewkeeperClasses = value;
    this.#changeDetector.markForCheck();
  }

  get #isInEditMode(): boolean {
    /* istanbul ignore else */
    if (this.agGrid && this.agGrid.api) {
      const primaryGridEditing = this.agGrid.api.getEditingCells().length > 0;
      if (primaryGridEditing) {
        return true;
      } else {
        let innerEditing = false;
        this.agGrid.api.forEachDetailGridInfo((detailGrid: DetailGridInfo) => {
          if (detailGrid?.api && detailGrid.api.getEditingCells().length > 0) {
            innerEditing = true;
          }
        });

        return innerEditing;
      }
    } else {
      return false;
    }
  }

  #_viewkeeperClasses: string[] = [];

  #agGridService: SkyAgGridService;
  #ngUnsubscribe = new Subject<void>();
  #themeSvc: SkyThemeService | undefined;
  #wrapperClasses = new BehaviorSubject<string[]>([`ag-theme-sky-default`]);
  #currentTheme: SkyThemeSettings | undefined = undefined;
  #adapterService: SkyAgGridAdapterService;
  #changeDetector: ChangeDetectorRef;
  #elementRef: ElementRef;
  #document: Document;

  constructor(
    adapterService: SkyAgGridAdapterService,
    changeDetector: ChangeDetectorRef,
    elementRef: ElementRef,
    @Inject(DOCUMENT) document: Document,
    agGridService: SkyAgGridService,
    @Optional() themeSvc?: SkyThemeService
  ) {
    this.#adapterService = adapterService;
    this.#changeDetector = changeDetector;
    this.#elementRef = elementRef;
    this.#document = document;

    idIndex++;
    this.afterAnchorId = 'sky-ag-grid-nav-anchor-after-' + idIndex;
    this.beforeAnchorId = 'sky-ag-grid-nav-anchor-before-' + idIndex;
    this.gridId = 'sky-ag-grid-' + idIndex;
    this.#agGridService = agGridService;
    this.#themeSvc = themeSvc;
    this.wrapperClasses$ = this.#wrapperClasses.asObservable();
  }

  public ngAfterContentInit(): void {
    if (this.agGrid) {
      if (
        this.agGrid.gridOptions &&
        this.agGrid.gridOptions.domLayout === 'autoHeight'
      ) {
        if (this.agGrid.gridOptions.context?.enableTopScroll) {
          this.viewkeeperClasses.push(
            '.ag-header',
            '.ag-body-horizontal-scroll'
          );
        } else {
          this.viewkeeperClasses.push('.ag-header');
        }
      }
      this.agGrid.gridReady
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe(() => {
          this.#moveHorizontalScroll();
        });
      this.agGrid.firstDataRendered
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe(() => {
          this.#moveHorizontalScroll();
        });
      this.agGrid.rowDataUpdated
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe(() => {
          this.#moveHorizontalScroll();
        });
      this.agGrid.cellEditingStarted
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe((params: CellEditingStartedEvent) => {
          if (params.colDef.type) {
            const types = Array.isArray(params.colDef.type)
              ? params.colDef.type
              : [params.colDef.type];
            const addClasses = types.map(
              (t) => `sky-ag-grid-cell-editing-${t}`
            );
            this.#wrapperClasses.next([
              ...this.#wrapperClasses.getValue(),
              ...addClasses,
            ]);
          }
        });
      this.agGrid.cellEditingStopped
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe(() => {
          this.#wrapperClasses.next(
            this.#wrapperClasses
              .getValue()
              .filter((c) => c.startsWith('ag-theme-'))
          );
        });
    }
  }

  public ngOnDestroy(): void {
    this.#ngUnsubscribe.next();
    this.#ngUnsubscribe.complete();
  }

  public ngOnInit(): void {
    this.#themeSvc?.settingsChange
      .pipe(takeUntil(this.#ngUnsubscribe))
      .subscribe((settings) => {
        let agThemeClass: string;
        if (settings.currentSettings.theme.name === 'modern') {
          agThemeClass = `ag-theme-sky-modern-${settings.currentSettings.mode.name}`;
        } else {
          agThemeClass = `ag-theme-sky-default`;
        }
        this.#wrapperClasses.next([
          ...this.#wrapperClasses
            .getValue()
            .filter((c) => !c.startsWith('ag-theme-')),
          agThemeClass,
        ]);
        if (!this.#currentTheme) {
          // Initial theme settings.
          this.#currentTheme = settings.currentSettings;
        } else if (this.agGrid?.api) {
          // On subsequent theme changes, we need to call the api to re-render the grid.
          this.#currentTheme = settings.currentSettings;
          this.agGrid.api.setHeaderHeight(
            this.#agGridService.getHeaderHeight()
          );
          this.agGrid.api.resetRowHeights();
          this.agGrid.api.refreshCells();
        }
      });
  }

  /**
   * Prevent closing a modal when focused in AG Grid.
   */
  public onKeyUpEscape($event: Event): void {
    $event.stopPropagation();
    this.agGrid?.api.stopEditing(true);
  }

  public onGridKeydown(event: KeyboardEvent): void {
    if (this.agGrid && !this.#isInEditMode && event.key === 'Tab') {
      const idToFocus = event.shiftKey
        ? this.beforeAnchorId
        : this.afterAnchorId;
      this.#adapterService.setFocusedElementById(
        this.#elementRef.nativeElement,
        idToFocus
      );
    }
  }

  public onAnchorFocus(event: FocusEvent): void {
    const gridId = this.gridId;
    const relatedTarget = event.relatedTarget as HTMLElement;
    const previousFocusedId = relatedTarget && relatedTarget.id;
    const previousWasCell =
      relatedTarget &&
      !!this.#adapterService.getElementOrParentWithClass(
        relatedTarget,
        'ag-cell'
      );

    if (previousFocusedId !== gridId && !previousWasCell) {
      const columns = this.agGrid?.columnApi.getAllDisplayedColumns();
      const firstColumn = columns?.[0];
      const rowIndex = this.agGrid?.api.getFirstDisplayedRow();

      if (firstColumn && rowIndex !== undefined && rowIndex >= 0) {
        this.agGrid?.api.setFocusedCell(rowIndex, firstColumn);
      }
    }
  }

  #moveHorizontalScroll(): void {
    if (this.agGrid && this.agGrid.api) {
      const toTop = !!this.agGrid.gridOptions.context?.enableTopScroll;
      const root: HTMLElement =
        this.#elementRef.nativeElement.querySelector('.ag-root');
      const header: HTMLDivElement | null = root.querySelector('.ag-header');
      const floatingBottom: HTMLDivElement | null = root.querySelector(
        '.ag-floating-bottom'
      );
      const scrollbar: HTMLDivElement | null = root.querySelector(
        '.ag-body-horizontal-scroll'
      );
      if (header && floatingBottom && scrollbar) {
        if (
          scrollbar.style.height !==
          scrollbar.style.getPropertyValue(
            '--sky-ag-body-horizontal-scroll-width'
          )
        ) {
          scrollbar.style.setProperty(
            '--sky-ag-body-horizontal-scroll-width',
            scrollbar.style.height
          );
        }
        const isTop = !!root.children[1].matches('.ag-body-horizontal-scroll');
        if (toTop && !isTop) {
          const fragment = this.#document.createDocumentFragment();
          fragment.appendChild(scrollbar);
          header.after(fragment);
        } else if (!toTop && isTop) {
          const fragment = this.#document.createDocumentFragment();
          fragment.appendChild(scrollbar);
          floatingBottom.after(fragment);
        }
      }
    }
  }
}


text:
import urllib
import urllib2
import base64
import os, sys
from datetime import datetime
from getpass import getpass

if sys.version_info < (2,6,):
  import simplejson as json
else:
  import json

baconfile_url = 'http://baconfile.com/'

"""Baconfile library"""

class FolderItem(object):
  def __init__(self, data):
    self.id = data.get('id')
    self.size = data.get('size', 0)
    self.permalink = data.get('permalink')
    self.name = data.get('name')
    self.url = data.get('url')
    self.file_url = data.get('file_url')
    self.time_modified = data.get('time_modified')
    self.tiny_url = data.get('tiny_url')
    self.user = data.get('user')
    self.is_folder = data.get('is_folder')
    self.path = data.get('path')
    self.content_type = data.get('content_type')
    self.type = data.get('type')
    self.description = data.get('description')

  def read_file(self, amt=None):
    r = urllib2.urlopen(self.file_url)
    return r.read(amt)

  def save_file(self, filepath):
    f = open(filepath, 'wb')
    f.write(self.read_file())
    f.close()

class BaconfileError(Exception):
  def __init__(self, reason='Baconfile error occured.'):
    self.reason = reason
  def __str__(self):
    return self.reason

def _build_url(username, path):
  return baconfile_url + os.path.join(username, path) + '.json'

def _make_request(url, data=None, headers={}):
  try:
    headers['User-Agent'] = 'baconfilepy/1.0'
    req = urllib2.Request(url, data, headers)
    return urllib2.urlopen(req)
  except urllib2.HTTPError, e:
    try:
      reason = str(json.loads(e.read())['error']['message'])
    except Exception:
      reason = 'unkown'
    raise BaconfileError(reason)

def fetch_folder(username, folder):
  r = _make_request(_build_url(username, folder))
  items = json.loads(r.read())['items']
  return list(FolderItem(i) for i in items)

def fetch_file(username, filepath):
  r = _make_request(_build_url(username, filepath))
  item = json.loads(r.read())
  return FolderItem(item)

def fetch_recent_files():
  r = _make_request(baconfile_url + 'public.json')
  items = json.loads(r.read())['items']
  return list(FolderItem(i) for i in items)

def _build_headers(credentials):
  return {
    'Authorization':
      'Basic %s' % base64.b64encode('%s:%s' % (credentials[0], credentials[1]))
  }

def new_folder(credentials, folder_name):
  headers = _build_headers(credentials)
  data = urllib.urlencode({'name': folder_name})
  r = _make_request(baconfile_url + credentials[0] + '.json', data, headers)
  item = json.loads(r.read())
  return FolderItem(item)

"""Baconfile commandline"""

def show_help(page=''):
  if page == 'fetch':
    print 'Download a file from baconfile.com'
    print 'Usage: fetch <user> <path> [dest]'
    print '    user   -  owner of file being fetched'
    print '    path   -  path to file'
    print '    dest   -  where to save file [optional]'
    print 'Example: baconfile fetch john pictures/tree.jpg /home/me/pictures'
    print ''
  elif page == 'ls':
    print 'List infomation about files/folders'
    print 'Usage: ls <user> [folder]'
    print '    user   -  owner of files/folders to list'
    print '    folder -  folder to list [default: user\'s root folder]'
    print 'Example: baconfile ls john music'
    print ''
  elif page == 'recent':
    print 'Get listing of most recently added files'
    print 'Usage: recent'
    print ''
  elif page == 'mkdir':
    print 'Create a new folder on baconfile.com'
    print 'Usage: mkdir <folder>'
    print '    folder -  path + folder name'
    print 'Example: baconfile mkdir docs/papers'
    print ''
  else:
    print 'Baconfile commandline tool'
    print 'Usage: <command> [options]...'
    print 'Commands:'
    print '    fetch  -  download a file from baconfile.com'
    print '    ls     -  list infomation about files/folders'
    print '    recent -  list most recently added files'
    print 'Type just the command name to get more infomation.'

# query user for username and password
def get_credentials():
  print 'Baconfile.com login credentials required.:'
  print 'Username: ',
  username = raw_input()
  password = getpass()
  return username, password

def print_items(items):
  for i in items:
    if i.size is None:
      size = 'D'
    else:
      size = str(i.size)
    time = str(datetime.fromtimestamp(i.time_modified))
    print '%s  %s  %s  %s' % (time, i.type.rjust(6), size.rjust(8), i.name)

  print '  %i items' % len(items)

def cmd_fetch(user, path, dest=''):
  try:
    f = fetch_file(user, path)
    f.save_file(os.path.join(dest, f.name))
  except BaconfileError, e:
    print e
    exit(1)

def cmd_ls(user, folder=''):
  try:
    items = fetch_folder(user, folder)
    print_items(items)
  except BaconfileError, e:
    print e
    exit(1)

def cmd_recent():
  try:
    items = fetch_recent_files()
    print_items(items)
  except BaconfileError, e:
    print e
    exit(1)

def cmd_mkdir(folder_name):
  try:
    new_folder(get_credentials(), folder_name)
  except BaconfileError, e:
    print e
    exit(1)

if __name__ == '__main__':
  # Get command and args
  if len(sys.argv) < 2:
    show_help()
    exit(1)
  command = sys.argv[1]
  args = sys.argv[2:]

  # Call command
  try:
    if command == 'fetch':
      cmd_fetch(*args)
    elif command == 'ls':
      cmd_ls(*args)
    elif command == 'recent':
      cmd_recent()
    elif command == 'mkdir':
      cmd_mkdir(*args)
    else:
      print '%s invalid command!' % command
      show_help()
  except TypeError:
    # missing required arguments
    if len(args) > 0:
      print 'Missing required parameters!'
    show_help(command)
  except KeyboardInterrupt:
    print ''


text:
import time, sys
import dlib
import numpy as np
import cozmo

# Load trained detector model
detector = dlib.simple_object_detector("detector.svm")
# Initialize window for results
win = dlib.image_window()

def displayImage(image):
	# Convert to numpy array
	img = np.array(image.raw_image)

	startTime = time.time()
	# Detect
	dets = detector(img)
	print('Took {:5.0f}'.format((time.time() - startTime) * 1000))

	win.clear_overlay()
	# Display raw Cozmo image
	win.set_image(img)
	# Display bounding rectangles
	win.add_overlay(dets)

def run(sdk_conn):
	'''The run method runs once Cozmo is connected.'''
	robot = sdk_conn.wait_for_robot()
	robot.camera.image_stream_enabled = True
	while(True):
		image = robot.world.latest_image
		# Cozmo may not immediately start video feed
		while image is None:
			image = robot.world.latest_image
			time.sleep(0.1)
		# Detect cubes and render image with bounding boxes
		displayImage(image)
		time.sleep(0.1)

if __name__ == '__main__':
	cozmo.setup_basic_logging()
	cozmo.robot.Robot.drive_off_charger_on_connect = False

	try:
		cozmo.connect(run)
	except cozmo.ConnectionError as e:
		sys.exit("A connection error occurred: %s" % e)


text:
// This file is part of OpenTSDB.
// Copyright (C) 2013  The OpenTSDB Authors.
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 2.1 of the License, or (at your
// option) any later version.  This program is distributed in the hope that it
// will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser
// General Public License for more details.  You should have received a copy
// of the GNU Lesser General Public License along with this program.  If not,
// see <http://www.gnu.org/licenses/>.
package net.opentsdb.tree;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.mock;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.TreeMap;

import net.opentsdb.core.TSDB;
import net.opentsdb.storage.MockBase;
import net.opentsdb.utils.Config;
import net.opentsdb.utils.JSON;

import org.hbase.async.DeleteRequest;
import org.hbase.async.GetRequest;
import org.hbase.async.HBaseClient;
import org.hbase.async.KeyValue;
import org.hbase.async.PutRequest;
import org.hbase.async.Scanner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PowerMockIgnore({"javax.management.*", "javax.xml.*",
                  "ch.qos.*", "org.slf4j.*",
                  "com.sum.*", "org.xml.*"})
@PrepareForTest({ TSDB.class, HBaseClient.class, GetRequest.class,
  PutRequest.class, KeyValue.class, Scanner.class, DeleteRequest.class })
public final class TestBranch {
  private static byte[] NAME_FAMILY = "name".getBytes(MockBase.ASCII());
  private MockBase storage;
  private Tree tree = TestTree.buildTestTree();
  final static private Method toStorageJson;
  static {
    try {
      toStorageJson = Branch.class.getDeclaredMethod("toStorageJson");
      toStorageJson.setAccessible(true);
    } catch (Exception e) {
      throw new RuntimeException("Failed in static initializer", e);
    }
  }

  final static private Method LeaftoStorageJson;
  static {
    try {
      LeaftoStorageJson = Leaf.class.getDeclaredMethod("toStorageJson");
      LeaftoStorageJson.setAccessible(true);
    } catch (Exception e) {
      throw new RuntimeException("Failed in static initializer", e);
    }
  }

  @Test
  public void copyConstructor() {
    final Branch branch = buildTestBranch(tree);
    final Branch copy = new Branch(branch);
    assertEquals(1, copy.getTreeId());
    assertEquals("ROOT", copy.getDisplayName());
    assertNotNull(copy.getBranches());
    assertTrue(copy.getBranches() != branch.getBranches());
    assertNotNull(copy.getLeaves());
    assertTrue(copy.getLeaves() != branch.getLeaves());
    assertNotNull(copy.getPath());
    assertTrue(copy.getPath() != branch.getPath());
  }

  @Test
  public void testHashCode() {
    final Branch branch = buildTestBranch(tree);
    assertEquals(2521314, branch.hashCode());
  }

  @Test
  public void testEquals() {
    final Branch branch = buildTestBranch(tree);;
    final Branch branch2 = buildTestBranch(tree);;
    assertTrue(branch.equals(branch2));
  }

  @Test
  public void equalsSameAddress() {
    final Branch branch = buildTestBranch(tree);;
    assertTrue(branch.equals(branch));
  }

  @Test
  public void equalsNull() {
    final Branch branch = buildTestBranch(tree);;
    assertFalse(branch.equals(null));
  }

  @Test
  public void equalsWrongClass() {
    final Branch branch = buildTestBranch(tree);;
    assertFalse(branch.equals(new Object()));
  }

  @Test
  public void compareTo() {
    final Branch branch = buildTestBranch(tree);;
    final Branch branch2 = buildTestBranch(tree);;
    assertEquals(0, branch.compareTo(branch2));
  }

  @Test
  public void compareToLess() {
    final Branch branch = buildTestBranch(tree);;
    final Branch branch2 = buildTestBranch(tree);;
    branch2.setDisplayName("Ardvark");
    assertTrue(branch.compareTo(branch2) > 0);
  }

  @Test
  public void compareToGreater() {
    final Branch branch = buildTestBranch(tree);;
    final Branch branch2 = buildTestBranch(tree);;
    branch2.setDisplayName("Zelda");
    assertTrue(branch.compareTo(branch2) < 0);
  }

  @Test
  public void getBranchIdRoot() {
    final Branch branch = buildTestBranch(tree);;
    assertEquals("0001", branch.getBranchId());
  }

  @Test
  public void getBranchIdChild() {
    final Branch branch = buildTestBranch(tree);;
    assertEquals("0001D119F20E", branch.getBranches().first().getBranchId());
  }

  @Test
  public void addChild() throws Exception {
    final Branch branch = buildTestBranch(tree);
    final Branch child = new Branch(tree.getTreeId());
    assertTrue(branch.addChild(child));
    assertEquals(3, branch.getBranches().size());
    assertEquals(2, branch.getLeaves().size());
  }

  @Test
  public void addChildNoLocalBranches() throws Exception {
    final Branch branch = buildTestBranch(tree);;
    final Branch child = new Branch(tree.getTreeId());
    Field branches = Branch.class.getDeclaredField("branches");
    branches.setAccessible(true);
    branches.set(branch, null);
    branches.setAccessible(false);
    assertTrue(branch.addChild(child));
    assertEquals(1, branch.getBranches().size());
    assertEquals(2, branch.getLeaves().size());
  }

  @Test
  public void addChildNoChanges() throws Exception {
    final Branch branch = buildTestBranch(tree);;
    final Branch child = new Branch(tree.getTreeId());
    assertTrue(branch.addChild(child));
    assertFalse(branch.addChild(child));
    assertEquals(3, branch.getBranches().size());
    assertEquals(2, branch.getLeaves().size());
  }

  @Test
  public void addLeafExists() throws Exception {
    final Tree tree = TestTree.buildTestTree();
    final Branch branch = buildTestBranch(tree);;

    Leaf leaf = new Leaf();
    leaf.setDisplayName("Alarms");
    leaf.setTsuid("ABCD");

    assertFalse(branch.addLeaf(leaf, tree));
    assertEquals(2, branch.getBranches().size());
    assertEquals(2, branch.getLeaves().size());
    assertNull(tree.getCollisions());
  }

  @Test
  public void addLeafCollision() throws Exception {
    final Tree tree = TestTree.buildTestTree();
    final Branch branch = buildTestBranch(tree);;

    Leaf leaf = new Leaf();
    leaf.setDisplayName("Alarms");
    leaf.setTsuid("0001");

    assertFalse(branch.addLeaf(leaf, tree));
    assertEquals(2, branch.getBranches().size());
    assertEquals(2, branch.getLeaves().size());
    assertEquals(1, tree.getCollisions().size());
  }

  @Test (expected = IllegalArgumentException.class)
  public void addChildNull() throws Exception {
    final Branch branch = buildTestBranch(tree);;
    branch.addChild(null);
  }

  @Test
  public void addLeaf() throws Exception {
    final Branch branch = buildTestBranch(tree);;

    Leaf leaf = new Leaf();
    leaf.setDisplayName("Application Servers");
    leaf.setTsuid("0004");

    assertTrue(branch.addLeaf(leaf, null));
  }

  @Test (expected = IllegalArgumentException.class)
  public void addLeafNull() throws Exception {
    final Branch branch = buildTestBranch(tree);;
    branch.addLeaf(null, null);
  }

  @Test
  public void compileBranchId() {
    final Branch branch = buildTestBranch(tree);;
    assertArrayEquals(new byte[] { 0, 1 }, branch.compileBranchId());
  }

  @Test
  public void compileBranchIdChild() {
    final Branch branch = buildTestBranch(tree);;
    assertArrayEquals(new byte[] { 0, 1 , (byte) 0xD1, 0x19, (byte) 0xF2, 0x0E },
        branch.getBranches().first().compileBranchId());
  }

  @Test (expected = IllegalArgumentException.class)
  public void compileBranchIdEmptyDisplayName() {
    final Branch branch = new Branch(1);
    branch.compileBranchId();
  }

  @Test (expected = IllegalArgumentException.class)
  public void compileBranchIdInvalidId() {
    final Branch branch = new Branch(0);
    branch.compileBranchId();
  }

  @Test
  public void fetchBranch() throws Exception {
    setupStorage();

    storage.addColumn(new byte[] { 0, 0, 1 },
        NAME_FAMILY,
        "metrics".getBytes(MockBase.ASCII()),
        "sys.cpu.0".getBytes(MockBase.ASCII()));
    storage.addColumn(new byte[] { 0, 0, 1 },
        NAME_FAMILY,
        "tagk".getBytes(MockBase.ASCII()),
        "host".getBytes(MockBase.ASCII()));
    storage.addColumn(new byte[] { 0, 0, 1 },
        NAME_FAMILY,
        "tagv".getBytes(MockBase.ASCII()),
        "web01".getBytes(MockBase.ASCII()));

    storage.addColumn(new byte[] { 0, 0, 2 },
        NAME_FAMILY,
        "metrics".getBytes(MockBase.ASCII()),
        "sys.cpu.1".getBytes(MockBase.ASCII()));
    storage.addColumn(new byte[] { 0, 0, 2 },
        NAME_FAMILY,
        "tagk".getBytes(MockBase.ASCII()),
        "owner".getBytes(MockBase.ASCII()));
    storage.addColumn(new byte[] { 0, 0, 2 },
        NAME_FAMILY,
        "tagv".getBytes(MockBase.ASCII()),
        "ops".getBytes(MockBase.ASCII()));

    final Branch branch = Branch.fetchBranch(storage.getTSDB(),
        Branch.stringToId("00010001BECD000181A8"), true).joinUninterruptibly();
    assertNotNull(branch);
    assertEquals(1, branch.getTreeId());
    assertEquals("cpu", branch.getDisplayName());
    assertEquals("00010001BECD000181A8", branch.getBranchId());
    assertEquals(1, branch.getBranches().size());
    assertEquals(2, branch.getLeaves().size());
  }

  @Test
  public void fetchBranchNSU() throws Exception {
    setupStorage();

    storage.addColumn(new byte[] { 0, 0, 1 },
        NAME_FAMILY,
        "metrics".getBytes(MockBase.ASCII()),
        "sys.cpu.0".getBytes(MockBase.ASCII()));
    storage.addColumn(new byte[] { 0, 0, 1 },
        NAME_FAMILY,
        "tagk".getBytes(MockBase.ASCII()),
        "host".getBytes(MockBase.ASCII()));
    storage.addColumn(new byte[] { 0, 0, 1 },
        NAME_FAMILY,
        "tagv".getBytes(MockBase.ASCII()),
        "web01".getBytes(MockBase.ASCII()));

    final Branch branch = Branch.fetchBranch(storage.getTSDB(),
        Branch.stringToId("00010001BECD000181A8"), true).joinUninterruptibly();
    assertNotNull(branch);
    assertEquals(1, branch.getTreeId());
    assertEquals("cpu", branch.getDisplayName());
    assertEquals("00010001BECD000181A8", branch.getBranchId());
    assertEquals(1, branch.getBranches().size());
    assertEquals(1, branch.getLeaves().size());
  }

  @Test
  public void fetchBranchNotFound() throws Exception {
    setupStorage();
    final Branch branch = Branch.fetchBranch(storage.getTSDB(),
        Branch.stringToId("00010001BECD000181A0"), false).joinUninterruptibly();
    assertNull(branch);
  }

  @Test
  public void fetchBranchOnly() throws Exception {
    setupStorage();
    final Branch branch = Branch.fetchBranchOnly(storage.getTSDB(),
        Branch.stringToId("00010001BECD000181A8")).joinUninterruptibly();
    assertNotNull(branch);
    assertEquals("cpu", branch.getDisplayName());
    assertNull(branch.getLeaves());
    assertNull(branch.getBranches());
  }

  @Test
  public void fetchBranchOnlyNotFound() throws Exception {
    setupStorage();
    final Branch branch = Branch.fetchBranchOnly(storage.getTSDB(),
        Branch.stringToId("00010001BECD000181A0")).joinUninterruptibly();
    assertNull(branch);
  }

  @Test
  public void storeBranch() throws Exception {
    setupStorage();
    final Branch branch = buildTestBranch(tree);
    branch.storeBranch(storage.getTSDB(), tree, true);
    assertEquals(3, storage.numRows());
    assertEquals(3, storage.numColumns(new byte[] { 0, 1 }));
    final Branch parsed = JSON.parseToObject(storage.getColumn(
        new byte[] { 0, 1 }, "branch".getBytes(MockBase.ASCII())),
        Branch.class);
    parsed.setTreeId(1);
    assertEquals("ROOT", parsed.getDisplayName());
  }

  @Test (expected = IllegalArgumentException.class)
  public void storeBranchMissingTreeID() throws Exception {
    setupStorage();
    final Branch branch = new Branch();
    branch.storeBranch(storage.getTSDB(), tree, false);
  }

  @Test (expected = IllegalArgumentException.class)
  public void storeBranchTreeID0() throws Exception {
    setupStorage();
    final Branch branch = buildTestBranch(tree);;
    branch.setTreeId(0);
    branch.storeBranch(storage.getTSDB(), tree, false);
  }

  @Test (expected = IllegalArgumentException.class)
  public void storeBranchTreeID65536() throws Exception {
    setupStorage();
    final Branch branch = buildTestBranch(tree);;
    branch.setTreeId(65536);
    branch.storeBranch(storage.getTSDB(), tree, false);
  }

  @Test
  public void storeBranchExistingLeaf() throws Exception {
    setupStorage();
    final Branch branch = buildTestBranch(tree);
    Leaf leaf = new Leaf("Alarms", "ABCD");
    byte[] qualifier = leaf.columnQualifier();
    storage.addColumn(branch.compileBranchId(), Tree.TREE_FAMILY(),
        qualifier, (byte[])LeaftoStorageJson.invoke(leaf));

    branch.storeBranch(storage.getTSDB(), tree, true);
    assertEquals(3, storage.numRows());
    assertEquals(3, storage.numColumns(new byte[] { 0, 1 }));
    assertNull(tree.getCollisions());
    final Branch parsed = JSON.parseToObject(storage.getColumn(
        new byte[] { 0, 1 }, "branch".getBytes(MockBase.ASCII())),
        Branch.class);
    parsed.setTreeId(1);
    assertEquals("ROOT", parsed.getDisplayName());
  }

  @Test
  public void storeBranchCollision() throws Exception {
    setupStorage();
    final Branch branch = buildTestBranch(tree);
    Leaf leaf = new Leaf("Alarms", "0101");
    byte[] qualifier = leaf.columnQualifier();
    storage.addColumn(branch.compileBranchId(), Tree.TREE_FAMILY(),
        qualifier, (byte[])LeaftoStorageJson.invoke(leaf));

    branch.storeBranch(storage.getTSDB(), tree, true);
    assertEquals(3, storage.numRows());
    assertEquals(3, storage.numColumns(new byte[] { 0, 1 }));
    assertEquals(1, tree.getCollisions().size());
    final Branch parsed = JSON.parseToObject(storage.getColumn(
        new byte[] { 0, 1 }, "branch".getBytes(MockBase.ASCII())),
        Branch.class);
    parsed.setTreeId(1);
    assertEquals("ROOT", parsed.getDisplayName());
  }

  @Test
  public void idToString() throws Exception {
    assertEquals("0EA8", Branch.idToString(new byte[] { 0x0E, (byte) 0xA8 }));
  }

  @Test
  public void idToStringZeroes() throws Exception {
    assertEquals("0000", Branch.idToString(new byte[] { 0, 0 }));
  }

  @Test (expected = NullPointerException.class)
  public void idToStringNull() throws Exception {
    Branch.idToString(null);
  }

  @Test
  public void stringToId() throws Exception {
    assertArrayEquals(new byte[] { 0x0E, (byte) 0xA8 },
        Branch.stringToId("0EA8"));
  }

  @Test
  public void stringToIdZeros() throws Exception {
    assertArrayEquals(new byte[] { 0, 0 }, Branch.stringToId("0000"));
  }

  @Test
  public void stringToIdZerosPadding() throws Exception {
    assertArrayEquals(new byte[] { 0, 0, 0 }, Branch.stringToId("00000"));
  }

  @Test
  public void stringToIdCase() throws Exception {
    assertArrayEquals(new byte[] { 0x0E, (byte) 0xA8 },
        Branch.stringToId("0ea8"));
  }

  @Test (expected = IllegalArgumentException.class)
  public void stringToIdNull() throws Exception {
    Branch.stringToId(null);
  }

  @Test (expected = IllegalArgumentException.class)
  public void stringToIdEmpty() throws Exception {
    Branch.stringToId("");
  }

  @Test (expected = IllegalArgumentException.class)
  public void stringToIdTooShort() throws Exception {
    Branch.stringToId("01");
  }

  @Test (expected = IllegalArgumentException.class)
  public void stringToIdNotHex() throws Exception {
    Branch.stringToId("HelloWorld!");
  }

  @Test
  public void BRANCH_QUALIFIER() throws Exception {
    assertArrayEquals("branch".getBytes(MockBase.ASCII()),
        Branch.BRANCH_QUALIFIER());
  }

  @Test
  public void prependParentPath() throws Exception {
    Branch branch = new Branch(1);
    branch.setDisplayName("cpu");
    final TreeMap<Integer, String> path = new TreeMap<Integer, String>();
    path.put(0, "ROOT");
    path.put(1, "sys");
    branch.prependParentPath(path);

    final Map<Integer, String> compiled_path = branch.getPath();
    assertNotNull(compiled_path);
    assertEquals(3, compiled_path.size());
  }

  @Test
  public void prependParentPathEmpty() throws Exception {
    Branch branch = new Branch(1);
    branch.setDisplayName("cpu");
    final TreeMap<Integer, String> path = new TreeMap<Integer, String>();
    branch.prependParentPath(path);

    final Map<Integer, String> compiled_path = branch.getPath();
    assertNotNull(compiled_path);
    assertEquals(1, compiled_path.size());
  }

  @Test (expected = IllegalArgumentException.class)
  public void prependParentPathNull() throws Exception {
    new Branch().prependParentPath(null);
  }

  /**
   * Helper to build a default branch for testing
   * @return A branch with some child branches and leaves
   */
  public static Branch buildTestBranch(final Tree tree) {
    final TreeMap<Integer, String> root_path = new TreeMap<Integer, String>();
    final Branch root = new Branch(tree.getTreeId());
    root.setDisplayName("ROOT");
    root_path.put(0, "ROOT");
    root.prependParentPath(root_path);

    Branch child = new Branch(1);
    child.prependParentPath(root_path);
    child.setDisplayName("System");
    root.addChild(child);

    child = new Branch(tree.getTreeId());
    child.prependParentPath(root_path);
    child.setDisplayName("Network");
    root.addChild(child);

    Leaf leaf = new Leaf("Alarms", "ABCD");
    root.addLeaf(leaf, tree);

    leaf = new Leaf("Employees in Office", "EF00");
    root.addLeaf(leaf, tree);

    return root;
  }

  /**
   * Mocks classes for testing the storage calls
   */
  private void setupStorage() throws Exception {
    final HBaseClient client = mock(HBaseClient.class);
    final Config config = new Config(false);
    PowerMockito.whenNew(HBaseClient.class)
      .withArguments(anyString(), anyString()).thenReturn(client);

    storage = new MockBase(new TSDB(config), client, true, true, true, true);

    Branch branch = new Branch(1);
    TreeMap<Integer, String> path = new TreeMap<Integer, String>();
    path.put(0, "ROOT");
    path.put(1, "sys");
    path.put(2, "cpu");
    branch.prependParentPath(path);
    branch.setDisplayName("cpu");
    storage.addColumn(branch.compileBranchId(), Tree.TREE_FAMILY(),
        "branch".getBytes(MockBase.ASCII()),
        (byte[])toStorageJson.invoke(branch));

    Leaf leaf = new Leaf("user", "000001000001000001");
    byte[] qualifier = leaf.columnQualifier();
    storage.addColumn(branch.compileBranchId(), Tree.TREE_FAMILY(),
        qualifier, (byte[])LeaftoStorageJson.invoke(leaf));

    leaf = new Leaf("nice", "000002000002000002");
    qualifier = leaf.columnQualifier();
    storage.addColumn(branch.compileBranchId(), Tree.TREE_FAMILY(),
        qualifier, (byte[])LeaftoStorageJson.invoke(leaf));

    // child branch
    branch = new Branch(1);
    path.put(3, "mboard");
    branch.prependParentPath(path);
    branch.setDisplayName("mboard");
    storage.addColumn(branch.compileBranchId(), Tree.TREE_FAMILY(),
        "branch".getBytes(MockBase.ASCII()),
        (byte[])toStorageJson.invoke(branch));

    leaf = new Leaf("Asus", "000003000003000003");
    qualifier = leaf.columnQualifier();
    storage.addColumn(branch.compileBranchId(), Tree.TREE_FAMILY(),
        qualifier, (byte[])LeaftoStorageJson.invoke(leaf));
  }
}


text:
#pragma once

#include <google/protobuf/stubs/common.h>

#include <vector>

#include "modules/perception/lib/thread/concurrent_queue.h"
#include "modules/perception/lib/thread/mutex.h"
#include "modules/perception/lib/thread/thread.h"

namespace apollo {
namespace perception {
namespace lib {

class ThreadPoolWorker;

class ThreadPool {
 public:
  explicit ThreadPool(int num_workers);

  ~ThreadPool();

  void Start();

  void Add(google::protobuf::Closure *closure);
  void Add(const std::vector<google::protobuf::Closure *> &closures);

  int num_workers() const { return num_workers_; }

  int num_available_workers() const { return num_available_workers_; }

  ThreadPool(const ThreadPool &) = delete;
  ThreadPool &operator=(const ThreadPool &) = delete;

 private:
  friend class ThreadPoolWorker;

  std::vector<ThreadPoolWorker *> workers_;
  int num_workers_;
  int num_available_workers_;
  Mutex mutex_;

  FixedSizeConQueue<google::protobuf::Closure *> task_queue_;
  bool started_;
};

class ThreadPoolWorker : public Thread {
 public:
  explicit ThreadPoolWorker(ThreadPool *thread_pool)
      : Thread(true, "ThreadPoolWorker"), thread_pool_(thread_pool) {}

  virtual ~ThreadPoolWorker() {}

  ThreadPoolWorker(const ThreadPoolWorker &) = delete;
  ThreadPoolWorker &operator=(const ThreadPoolWorker &) = delete;

 protected:
  void Run() override;

 private:
  ThreadPool *thread_pool_;
};

}  // namespace lib
}  // namespace perception
}  // namespace apollo


text:
from django.forms import BaseForm
from django.forms.forms import BoundField
from django.forms.widgets import TextInput, CheckboxInput, CheckboxSelectMultiple, RadioSelect
from django.template import Context
from django.template.loader import get_template
from django import template
from django.conf import settings

BOOTSTRAP_BASE_URL = getattr(settings, 'BOOTSTRAP_BASE_URL',
    'http://twitter.github.com/bootstrap/assets/'
)

BOOTSTRAP_JS_BASE_URL = getattr(settings, 'BOOTSTRAP_JS_BASE_URL',
    BOOTSTRAP_BASE_URL + 'js/'
)

BOOTSTRAP_JS_URL = getattr(settings, 'BOOTSTRAP_JS_URL',
    None
)

BOOTSTRAP_CSS_BASE_URL = getattr(settings, 'BOOTSTRAP_CSS_BASE_URL',
    BOOTSTRAP_BASE_URL + 'css/'
)

BOOTSTRAP_CSS_URL = getattr(settings, 'BOOTSTRAP_CSS_URL',
    BOOTSTRAP_CSS_BASE_URL + 'bootstrap.css'
)

BOOTSTRAP_RESPONSIVE_CSS_URL = getattr(settings, 'BOOTSTRAP_RESPONSIVE_CSS_URL',
                                       BOOTSTRAP_CSS_BASE_URL + 'bootstrap-responsive.css')

register = template.Library()

@register.simple_tag
def bootstrap_stylesheet_url():
    """
    URL to Bootstrap Stylesheet (CSS)
    """
    return BOOTSTRAP_CSS_URL

@register.simple_tag
def bootstrap_responsive_stylesheet_url():
    """
    URL to Bootstrap responsive Stylesheet(CSS)
    """
    return BOOTSTRAP_RESPONSIVE_CSS_URL

@register.simple_tag
def bootstrap_responsive_stylesheet_tag():
    """
    HTML tag to insert Bootstrap responsive stylesheet
    """
    return u'<link rel="stylesheet" href="%s">' % bootstrap_responsive_stylesheet_url()

@register.simple_tag
def bootstrap_stylesheet_tag():
    """
    HTML tag to insert Bootstrap stylesheet
    """
    return u'<link rel="stylesheet" href="%s">' % bootstrap_stylesheet_url()

@register.simple_tag
def bootstrap_javascript_url(name):
    """
    URL to Bootstrap javascript file
    """
    if BOOTSTRAP_JS_URL:
        return BOOTSTRAP_JS_URL
    return BOOTSTRAP_JS_BASE_URL + 'bootstrap-' + name + '.js'

@register.simple_tag
def bootstrap_javascript_tag(name):
    """
    HTML tag to insert bootstrap_toolkit javascript file
    """

    return u'<script src="%s"></script>' % bootstrap_javascript_url(name)

@register.filter
def as_bootstrap(form_or_field, layout='vertical,false'):
    """
    Render a field or a form according to Bootstrap guidelines
    """
    params = split(layout, ",")
    layout = str(params[0]).lower()

    try:
        float = str(params[1]).lower() == "float"
    except IndexError:
        float = False

    if isinstance(form_or_field, BaseForm):
        return get_template("bootstrap_toolkit/form.html").render(
            Context({
                'form': form_or_field,
                'layout': layout,
                'float': float,
            })
        )
    elif isinstance(form_or_field, BoundField):
        return get_template("bootstrap_toolkit/field.html").render(
            Context({
                'field': form_or_field,
                'layout': layout,
                'float': float,
            })
        )
    else:
        # Display the default
        return settings.TEMPLATE_STRING_IF_INVALID

@register.filter
def is_disabled(field):
    """
    Returns True if fields is disabled, readonly or not marked as editable, False otherwise
    """
    if not getattr(field.field, 'editable', True):
        return True
    if getattr(field.field.widget.attrs, 'readonly', False):
        return True
    if getattr(field.field.widget.attrs, 'disabled', False):
        return True
    return False

@register.filter
def is_enabled(field):
    """
    Shortcut to return the logical negative of is_disabled
    """
    return not is_disabled(field)

@register.filter
def bootstrap_input_type(field):
    """
    Return input type to use for field
    """
    try:
        widget = field.field.widget
    except:
        raise ValueError("Expected a Field, got a %s" % type(field))
    input_type = getattr(widget, 'bootstrap_input_type', None)
    if input_type:
        return unicode(input_type)
    if isinstance(widget, TextInput):
        return u'text'
    if isinstance(widget, CheckboxInput):
        return u'checkbox'
    if isinstance(widget, CheckboxSelectMultiple):
        return u'multicheckbox'
    if isinstance(widget, RadioSelect):
        return u'radioset'
    return u'default'

@register.simple_tag
def active_url(request, url, output=u'active'):
    # Tag that outputs text if the given url is active for the request
    if url == request.path:
        return output
    return ''

@register.filter
def pagination(page, range=5):
    """
    Generate Bootstrap pagination links from a page object
    """
    num_pages = page.paginator.num_pages
    current_page = page.number
    range_min = max(current_page - range, 1)
    range_max = min(current_page + range, num_pages)
    return get_template("bootstrap_toolkit/pagination.html").render(
        Context({
            'page': page,
            'num_pages': num_pages,
            'current_page': current_page,
            'range_min': range_min,
            'range_max': range_max,
        })
    )

@register.filter
def split(str, splitter):
    """
    Split a string
    """
    return str.split(splitter)


text:
import fs from "fs";
import crypto from "crypto";

export function sortMigrationsAsc(a, b) {
  if (a.version < b.version) {
    return -1;
  }
  if (a.version > b.version) {
    return 1;
  }
  return 0;
}

export function sortMigrationsDesc(a, b) {
  if (a.version < b.version) {
    return 1;
  }
  if (a.version > b.version) {
    return -1;
  }
  return 0;
}

/**
 * Calculate checksum of file to detect changes to migrations that have already run.
 * @param {string} filename
 * @param {string} lineEnding - newline setting string for newline lib
 */
export function fileChecksum(filename, lineEnding) {
  const content = fs.readFileSync(filename, "utf8");
  return checksum(content, lineEnding);
}

/**
 *
 * @param {string} content - Content to checksum
 * @param {string} lineEnding - newline setting string for newline lib
 */
export function checksum(content, lineEnding) {
  if (lineEnding) {
    content = convertLineEnding(content, lineEnding);
  }
  return crypto.createHash("md5").update(content, "utf8").digest("hex");
}

export function convertLineEnding(content, lineEnding) {
  const lineEndingMap = {
    LF: "\n",
    CR: "\r",
    CRLF: "\r\n",
  };
  if (!lineEndingMap[lineEnding]) {
    throw new Error(
      `newline must be one of: ${Object.keys(lineEndingMap).join(", ")}`
    );
  }
  return content.replace(/\r\n|\r|\n/g, lineEndingMap[lineEnding]);
}

export default {
  fileChecksum,
  sortMigrationsAsc,
  sortMigrationsDesc,
  convertLineEnding,
};


text:
@interface IBICImageSetInspector : IBICAbstractMultipartImageInspector
{
}

+ (Class)imageSetClass;
+ (id)slotSuggestionSets;
- (id)sliceElement;

@end