text:
package elastic

import (
	"context"
	"net"
	"sync"
	"sync/atomic"
	"time"
)

// BulkProcessorService allows to easily process bulk requests. It allows setting
// policies when to flush new bulk requests, e.g. based on a number of actions,
// on the size of the actions, and/or to flush periodically. It also allows
// to control the number of concurrent bulk requests allowed to be executed
// in parallel.
//
// BulkProcessorService, by default, commits either every 1000 requests or when the
// (estimated) size of the bulk requests exceeds 5 MB. However, it does not
// commit periodically. BulkProcessorService also does retry by default, using
// an exponential backoff algorithm.
//
// The caller is responsible for setting the index and type on every
// bulk request added to BulkProcessorService.
//
// BulkProcessorService takes ideas from the BulkProcessor of the
// Elasticsearch Java API as documented in
// https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-bulk-processor.html.
type BulkProcessorService struct {
	c             *Client
	beforeFn      BulkBeforeFunc
	afterFn       BulkAfterFunc
	name          string        // name of processor
	numWorkers    int           // # of workers (>= 1)
	bulkActions   int           // # of requests after which to commit
	bulkSize      int           // # of bytes after which to commit
	flushInterval time.Duration // periodic flush interval
	wantStats     bool          // indicates whether to gather statistics
	backoff       Backoff       // a custom Backoff to use for errors
}

// NewBulkProcessorService creates a new BulkProcessorService.
func NewBulkProcessorService(client *Client) *BulkProcessorService {
	return &BulkProcessorService{
		c:           client,
		numWorkers:  1,
		bulkActions: 1000,
		bulkSize:    5 << 20, // 5 MB
		backoff: NewExponentialBackoff(
			time.Duration(200)*time.Millisecond,
			time.Duration(10000)*time.Millisecond,
		),
	}
}

// BulkBeforeFunc defines the signature of callbacks that are executed
// before a commit to Elasticsearch.
type BulkBeforeFunc func(executionId int64, requests []BulkableRequest)

// BulkAfterFunc defines the signature of callbacks that are executed
// after a commit to Elasticsearch. The err parameter signals an error.
type BulkAfterFunc func(executionId int64, requests []BulkableRequest, response *BulkResponse, err error)

// Before specifies a function to be executed before bulk requests get comitted
// to Elasticsearch.
func (s *BulkProcessorService) Before(fn BulkBeforeFunc) *BulkProcessorService {
	s.beforeFn = fn
	return s
}

// After specifies a function to be executed when bulk requests have been
// comitted to Elasticsearch. The After callback executes both when the
// commit was successful as well as on failures.
func (s *BulkProcessorService) After(fn BulkAfterFunc) *BulkProcessorService {
	s.afterFn = fn
	return s
}

// Name is an optional name to identify this bulk processor.
func (s *BulkProcessorService) Name(name string) *BulkProcessorService {
	s.name = name
	return s
}

// Workers is the number of concurrent workers allowed to be
// executed. Defaults to 1 and must be greater or equal to 1.
func (s *BulkProcessorService) Workers(num int) *BulkProcessorService {
	s.numWorkers = num
	return s
}

// BulkActions specifies when to flush based on the number of actions
// currently added. Defaults to 1000 and can be set to -1 to be disabled.
func (s *BulkProcessorService) BulkActions(bulkActions int) *BulkProcessorService {
	s.bulkActions = bulkActions
	return s
}

// BulkSize specifies when to flush based on the size (in bytes) of the actions
// currently added. Defaults to 5 MB and can be set to -1 to be disabled.
func (s *BulkProcessorService) BulkSize(bulkSize int) *BulkProcessorService {
	s.bulkSize = bulkSize
	return s
}

// FlushInterval specifies when to flush at the end of the given interval.
// This is disabled by default. If you want the bulk processor to
// operate completely asynchronously, set both BulkActions and BulkSize to
// -1 and set the FlushInterval to a meaningful interval.
func (s *BulkProcessorService) FlushInterval(interval time.Duration) *BulkProcessorService {
	s.flushInterval = interval
	return s
}

// Stats tells bulk processor to gather stats while running.
// Use Stats to return the stats. This is disabled by default.
func (s *BulkProcessorService) Stats(wantStats bool) *BulkProcessorService {
	s.wantStats = wantStats
	return s
}

// Backoff sets the backoff strategy to use for errors
func (s *BulkProcessorService) Backoff(backoff Backoff) *BulkProcessorService {
	s.backoff = backoff
	return s
}

// Do creates a new BulkProcessor and starts it.
// Consider the BulkProcessor as a running instance that accepts bulk requests
// and commits them to Elasticsearch, spreading the work across one or more
// workers.
//
// You can interoperate with the BulkProcessor returned by Do, e.g. Start and
// Stop (or Close) it.
//
// Context is an optional context that is passed into the bulk request
// service calls. In contrast to other operations, this context is used in
// a long running process. You could use it to pass e.g. loggers, but you
// shouldn't use it for cancellation.
//
// Calling Do several times returns new BulkProcessors. You probably don't
// want to do this. BulkProcessorService implements just a builder pattern.
func (s *BulkProcessorService) Do(ctx context.Context) (*BulkProcessor, error) {
	p := newBulkProcessor(
		s.c,
		s.beforeFn,
		s.afterFn,
		s.name,
		s.numWorkers,
		s.bulkActions,
		s.bulkSize,
		s.flushInterval,
		s.wantStats,
		s.backoff)

	err := p.Start(ctx)
	if err != nil {
		return nil, err
	}
	return p, nil
}

// -- Bulk Processor Statistics --

// BulkProcessorStats contains various statistics of a bulk processor
// while it is running. Use the Stats func to return it while running.
type BulkProcessorStats struct {
	Flushed   int64 // number of times the flush interval has been invoked
	Committed int64 // # of times workers committed bulk requests
	Indexed   int64 // # of requests indexed
	Created   int64 // # of requests that ES reported as creates (201)
	Updated   int64 // # of requests that ES reported as updates
	Deleted   int64 // # of requests that ES reported as deletes
	Succeeded int64 // # of requests that ES reported as successful
	Failed    int64 // # of requests that ES reported as failed

	Workers []*BulkProcessorWorkerStats // stats for each worker
}

// BulkProcessorWorkerStats represents per-worker statistics.
type BulkProcessorWorkerStats struct {
	Queued       int64         // # of requests queued in this worker
	LastDuration time.Duration // duration of last commit
}

// newBulkProcessorStats initializes and returns a BulkProcessorStats struct.
func newBulkProcessorStats(workers int) *BulkProcessorStats {
	stats := &BulkProcessorStats{
		Workers: make([]*BulkProcessorWorkerStats, workers),
	}
	for i := 0; i < workers; i++ {
		stats.Workers[i] = &BulkProcessorWorkerStats{}
	}
	return stats
}

func (st *BulkProcessorStats) dup() *BulkProcessorStats {
	dst := new(BulkProcessorStats)
	dst.Flushed = st.Flushed
	dst.Committed = st.Committed
	dst.Indexed = st.Indexed
	dst.Created = st.Created
	dst.Updated = st.Updated
	dst.Deleted = st.Deleted
	dst.Succeeded = st.Succeeded
	dst.Failed = st.Failed
	for _, src := range st.Workers {
		dst.Workers = append(dst.Workers, src.dup())
	}
	return dst
}

func (st *BulkProcessorWorkerStats) dup() *BulkProcessorWorkerStats {
	dst := new(BulkProcessorWorkerStats)
	dst.Queued = st.Queued
	dst.LastDuration = st.LastDuration
	return dst
}

// -- Bulk Processor --

// BulkProcessor encapsulates a task that accepts bulk requests and
// orchestrates committing them to Elasticsearch via one or more workers.
//
// BulkProcessor is returned by setting up a BulkProcessorService and
// calling the Do method.
type BulkProcessor struct {
	c             *Client
	beforeFn      BulkBeforeFunc
	afterFn       BulkAfterFunc
	name          string
	bulkActions   int
	bulkSize      int
	numWorkers    int
	executionId   int64
	requestsC     chan BulkableRequest
	workerWg      sync.WaitGroup
	workers       []*bulkWorker
	flushInterval time.Duration
	flusherStopC  chan struct{}
	wantStats     bool
	backoff       Backoff

	startedMu sync.Mutex // guards the following block
	started   bool

	statsMu sync.Mutex // guards the following block
	stats   *BulkProcessorStats

	stopReconnC chan struct{} // channel to signal stop reconnection attempts
}

func newBulkProcessor(
	client *Client,
	beforeFn BulkBeforeFunc,
	afterFn BulkAfterFunc,
	name string,
	numWorkers int,
	bulkActions int,
	bulkSize int,
	flushInterval time.Duration,
	wantStats bool,
	backoff Backoff) *BulkProcessor {
	return &BulkProcessor{
		c:             client,
		beforeFn:      beforeFn,
		afterFn:       afterFn,
		name:          name,
		numWorkers:    numWorkers,
		bulkActions:   bulkActions,
		bulkSize:      bulkSize,
		flushInterval: flushInterval,
		wantStats:     wantStats,
		backoff:       backoff,
	}
}

// Start starts the bulk processor. If the processor is already started,
// nil is returned.
func (p *BulkProcessor) Start(ctx context.Context) error {
	p.startedMu.Lock()
	defer p.startedMu.Unlock()

	if p.started {
		return nil
	}

	// We must have at least one worker.
	if p.numWorkers < 1 {
		p.numWorkers = 1
	}

	p.requestsC = make(chan BulkableRequest)
	p.executionId = 0
	p.stats = newBulkProcessorStats(p.numWorkers)
	p.stopReconnC = make(chan struct{})

	// Create and start up workers.
	p.workers = make([]*bulkWorker, p.numWorkers)
	for i := 0; i < p.numWorkers; i++ {
		p.workerWg.Add(1)
		p.workers[i] = newBulkWorker(p, i)
		go p.workers[i].work(ctx)
	}

	// Start the ticker for flush (if enabled)
	if int64(p.flushInterval) > 0 {
		p.flusherStopC = make(chan struct{})
		go p.flusher(p.flushInterval)
	}

	p.started = true

	return nil
}

// Stop is an alias for Close.
func (p *BulkProcessor) Stop() error {
	return p.Close()
}

// Close stops the bulk processor previously started with Do.
// If it is already stopped, this is a no-op and nil is returned.
//
// By implementing Close, BulkProcessor implements the io.Closer interface.
func (p *BulkProcessor) Close() error {
	p.startedMu.Lock()
	defer p.startedMu.Unlock()

	// Already stopped? Do nothing.
	if !p.started {
		return nil
	}

	// Tell connection checkers to stop
	if p.stopReconnC != nil {
		close(p.stopReconnC)
		p.stopReconnC = nil
	}

	// Stop flusher (if enabled)
	if p.flusherStopC != nil {
		p.flusherStopC <- struct{}{}
		<-p.flusherStopC
		close(p.flusherStopC)
		p.flusherStopC = nil
	}

	// Stop all workers.
	close(p.requestsC)
	p.workerWg.Wait()

	p.started = false

	return nil
}

// Stats returns the latest bulk processor statistics.
// Collecting stats must be enabled first by calling Stats(true) on
// the service that created this processor.
func (p *BulkProcessor) Stats() BulkProcessorStats {
	p.statsMu.Lock()
	defer p.statsMu.Unlock()
	return *p.stats.dup()
}

// Add adds a single request to commit by the BulkProcessorService.
//
// The caller is responsible for setting the index and type on the request.
func (p *BulkProcessor) Add(request BulkableRequest) {
	p.requestsC <- request
}

// Flush manually asks all workers to commit their outstanding requests.
// It returns only when all workers acknowledge completion.
func (p *BulkProcessor) Flush() error {
	p.statsMu.Lock()
	p.stats.Flushed++
	p.statsMu.Unlock()

	for _, w := range p.workers {
		w.flushC <- struct{}{}
		<-w.flushAckC // wait for completion
	}
	return nil
}

// flusher is a single goroutine that periodically asks all workers to
// commit their outstanding bulk requests. It is only started if
// FlushInterval is greater than 0.
func (p *BulkProcessor) flusher(interval time.Duration) {
	ticker := time.NewTicker(interval)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C: // Periodic flush
			p.Flush() // TODO swallow errors here?

		case <-p.flusherStopC:
			p.flusherStopC <- struct{}{}
			return
		}
	}
}

// -- Bulk Worker --

// bulkWorker encapsulates a single worker, running in a goroutine,
// receiving bulk requests and eventually committing them to Elasticsearch.
// It is strongly bound to a BulkProcessor.
type bulkWorker struct {
	p           *BulkProcessor
	i           int
	bulkActions int
	bulkSize    int
	service     *BulkService
	flushC      chan struct{}
	flushAckC   chan struct{}
}

// newBulkWorker creates a new bulkWorker instance.
func newBulkWorker(p *BulkProcessor, i int) *bulkWorker {
	return &bulkWorker{
		p:           p,
		i:           i,
		bulkActions: p.bulkActions,
		bulkSize:    p.bulkSize,
		service:     NewBulkService(p.c),
		flushC:      make(chan struct{}),
		flushAckC:   make(chan struct{}),
	}
}

// work waits for bulk requests and manual flush calls on the respective
// channels and is invoked as a goroutine when the bulk processor is started.
func (w *bulkWorker) work(ctx context.Context) {
	defer func() {
		w.p.workerWg.Done()
		close(w.flushAckC)
		close(w.flushC)
	}()

	var stop bool
	for !stop {
		var err error
		select {
		case req, open := <-w.p.requestsC:
			if open {
				// Received a new request
				w.service.Add(req)
				if w.commitRequired() {
					err = w.commit(ctx)
				}
			} else {
				// Channel closed: Stop.
				stop = true
				if w.service.NumberOfActions() > 0 {
					err = w.commit(ctx)
				}
			}
		case <-w.flushC:
			// Commit outstanding requests
			if w.service.NumberOfActions() > 0 {
				err = w.commit(ctx)
			}
			w.flushAckC <- struct{}{}
		}
		if !stop && err != nil {
			waitForActive := func() {
				// Add back pressure to prevent Add calls from filling up the request queue
				ready := make(chan struct{})
				go w.waitForActiveConnection(ready)
				<-ready
			}
			if _, ok := err.(net.Error); ok {
				waitForActive()
			} else if IsConnErr(err) {
				waitForActive()
			}
		}
	}
}

// commit commits the bulk requests in the given service,
// invoking callbacks as specified.
func (w *bulkWorker) commit(ctx context.Context) error {
	var res *BulkResponse

	// commitFunc will commit bulk requests and, on failure, be retried
	// via exponential backoff
	commitFunc := func() error {
		var err error
		res, err = w.service.Do(ctx)
		return err
	}
	// notifyFunc will be called if retry fails
	notifyFunc := func(err error) {
		w.p.c.errorf("elastic: bulk processor %q failed but may retry: %v", w.p.name, err)
	}

	id := atomic.AddInt64(&w.p.executionId, 1)

	// Update # documents in queue before eventual retries
	w.p.statsMu.Lock()
	if w.p.wantStats {
		w.p.stats.Workers[w.i].Queued = int64(len(w.service.requests))
	}
	w.p.statsMu.Unlock()

	// Save requests because they will be reset in commitFunc
	reqs := w.service.requests

	// Invoke before callback
	if w.p.beforeFn != nil {
		w.p.beforeFn(id, reqs)
	}

	// Commit bulk requests
	err := RetryNotify(commitFunc, w.p.backoff, notifyFunc)
	w.updateStats(res)
	if err != nil {
		w.p.c.errorf("elastic: bulk processor %q failed: %v", w.p.name, err)
	}

	// Invoke after callback
	if w.p.afterFn != nil {
		w.p.afterFn(id, reqs, res, err)
	}

	return err
}

func (w *bulkWorker) waitForActiveConnection(ready chan<- struct{}) {
	defer close(ready)

	t := time.NewTicker(5 * time.Second)
	defer t.Stop()

	client := w.p.c
	stopReconnC := w.p.stopReconnC
	w.p.c.errorf("elastic: bulk processor %q is waiting for an active connection", w.p.name)

	// loop until a health check finds at least 1 active connection or the reconnection channel is closed
	for {
		select {
		case _, ok := <-stopReconnC:
			if !ok {
				w.p.c.errorf("elastic: bulk processor %q active connection check interrupted", w.p.name)
				return
			}
		case <-t.C:
			client.healthcheck(time.Duration(3)*time.Second, true)
			if client.mustActiveConn() == nil {
				// found an active connection
				// exit and signal done to the WaitGroup
				return
			}
		}
	}
}

func (w *bulkWorker) updateStats(res *BulkResponse) {
	// Update stats
	if res != nil {
		w.p.statsMu.Lock()
		if w.p.wantStats {
			w.p.stats.Committed++
			if res != nil {
				w.p.stats.Indexed += int64(len(res.Indexed()))
				w.p.stats.Created += int64(len(res.Created()))
				w.p.stats.Updated += int64(len(res.Updated()))
				w.p.stats.Deleted += int64(len(res.Deleted()))
				w.p.stats.Succeeded += int64(len(res.Succeeded()))
				w.p.stats.Failed += int64(len(res.Failed()))
			}
			w.p.stats.Workers[w.i].Queued = int64(len(w.service.requests))
			w.p.stats.Workers[w.i].LastDuration = time.Duration(int64(res.Took)) * time.Millisecond
		}
		w.p.statsMu.Unlock()
	}
}

// commitRequired returns true if the service has to commit its
// bulk requests. This can be either because the number of actions
// or the estimated size in bytes is larger than specified in the
// BulkProcessorService.
func (w *bulkWorker) commitRequired() bool {
	if w.bulkActions >= 0 && w.service.NumberOfActions() >= w.bulkActions {
		return true
	}
	if w.bulkSize >= 0 && w.service.EstimatedSizeInBytes() >= int64(w.bulkSize) {
		return true
	}
	return false
}


text:
@interface SRClassArgumentTest : XCTestCase

@end

@implementation SRClassArgumentTest

- (void)testSuccesfullModelParsing{
    NSDictionary* intput = @{
                              @"class": @"NSURL",
                              @"properties": @[
                                      @{@"name":@"absoluteString", @"returnValue":@"https://github.com/andrewBatutin/SilentRunner"}
                                      ],
                              @"methods": @[
                                      @{@"name":@"isFileReferenceURL", @"returnValue":@YES},
                                      ]
                             };
    NSError* parseError = nil;
    SRClassArgument* realResult = [MTLJSONAdapter modelOfClass:SRClassArgument.class fromJSONDictionary:intput error:&parseError];
    XCTAssertEqualObjects(realResult.className, intput[@"class"]);
    XCTAssertEqualObjects(realResult.properties, intput[@"properties"]);
    XCTAssertEqualObjects(realResult.methods, intput[@"methods"]);
}

- (void)testArgumentCreation{
    NSDictionary* intput = @{
                              @"class": @"NSURL",
                              @"properties": @[
                                      @{@"name":@"absoluteString", @"returnValue":@"https://github.com/andrewBatutin/SilentRunner"}
                                      ],
                              @"methods": @[
                                      @{@"name":@"isFileReferenceURL", @"returnValue":@YES},
                                      ]
                              };
    NSError* parseError = nil;
    SRClassArgument* realResult = [MTLJSONAdapter modelOfClass:SRClassArgument.class fromJSONDictionary:intput error:&parseError];
    NSURL* result = realResult.argumentValue;
    XCTAssertEqual(YES, [result isFileReferenceURL]);
    XCTAssertEqualObjects(@"https://github.com/andrewBatutin/SilentRunner", [result absoluteString]);
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Destiny\Definitions\Progression;

use Destiny\Definitions\Common\DisplayProperties;
use Destiny\Definitions\Definition;

/**
 * Class Mapping.
 *
 * @property DisplayProperties $displayProperties
 * @property string            $displayUnits
 * @property string            $hash
 * @property int               $index
 * @property bool              $redacted
 */
class Mapping extends Definition
{
    protected $appends = [
        'displayProperties',
    ];
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_item_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:drawableLeft="@drawable/news_cate_arr"
        android:drawablePadding="5dp"
        android:layout_gravity="center_horizontal"
        />

</LinearLayout>


text:
package net.daw.dao.implementation;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import net.daw.bean.implementation.CargoBean;
import net.daw.bean.implementation.DiagnosticoBean;
import net.daw.bean.implementation.UsuarioBean;
import net.daw.dao.publicinterface.TableDaoInterface;
import net.daw.dao.publicinterface.ViewDaoInterface;
import net.daw.data.implementation.MysqlData;
import net.daw.helper.statics.FilterBeanHelper;
import net.daw.helper.statics.Log4j;
import net.daw.helper.statics.SqlBuilder;

public class CargoDao implements ViewDaoInterface<CargoBean>, TableDaoInterface<CargoBean> {

    private String strTable = "cargo";
    private String strSQL = "select * from " + strTable + " where 1=1 ";
    private MysqlData oMysql = null;
    private Connection oConnection = null;
    private UsuarioBean oPuserSecurity = null;

    public CargoDao(Connection oPooledConnection, UsuarioBean oPusuarioBean_security, String strWhere) throws Exception {
        try {
            oConnection = oPooledConnection;
            oMysql = new MysqlData(oConnection);
            oPuserSecurity = oPusuarioBean_security;
            if (strWhere != null) {
                strSQL += strWhere;
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
    }

    @Override
    public Long getCount(ArrayList<FilterBeanHelper> hmFilter) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(hmFilter);
        Long pages = 0L;
        try {
            pages = oMysql.getCount(strSQL);
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return pages;
    }

    @Override
    public ArrayList<CargoBean> getPage(int intRegsPerPag, int intPage, ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(alFilter);
        strSQL += SqlBuilder.buildSqlOrder(hmOrder);
        strSQL += SqlBuilder.buildSqlLimit(oMysql.getCount(strSQL), intRegsPerPag, intPage);
        ArrayList<CargoBean> arrCargo = new ArrayList<>();
        ResultSet oResultSet = null;
        try {
            oResultSet = oMysql.getAllSQL(strSQL);
            while (oResultSet.next()) {
                CargoBean oCargoBean = new CargoBean();
                arrCargo.add(oCargoBean.fill(oResultSet, oConnection, oPuserSecurity, expand));
            }
            if (oResultSet != null) {
                oResultSet.close();
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        } finally {
            if (oResultSet != null) {
                oResultSet.close();
            }
        }
        return arrCargo;
    }

    @Override
    public ArrayList<CargoBean> getAll(ArrayList<FilterBeanHelper> alFilter, HashMap<String, String> hmOrder, Integer expand) throws Exception {
        strSQL += SqlBuilder.buildSqlWhere(alFilter);
        strSQL += SqlBuilder.buildSqlOrder(hmOrder);
        ArrayList<CargoBean> arrCargo = new ArrayList<>();
        ResultSet oResultSet = null;
        try {
            oResultSet = oMysql.getAllSQL(strSQL);
            while (oResultSet.next()) {
                CargoBean oCargoBean = new CargoBean();
                arrCargo.add(oCargoBean.fill(oResultSet, oConnection, oPuserSecurity, expand));
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        } finally {
            if (oResultSet != null) {
                oResultSet.close();
            }
        }
        return arrCargo;
    }

    @Override
    public CargoBean get(CargoBean oCargoBean, Integer expand) throws Exception {
        if (oCargoBean.getId() > 0) {
            ResultSet oResultSet = null;
            try {
                oResultSet = oMysql.getAllSQL(strSQL + " And id= " + oCargoBean.getId() + " ");
                Boolean empty = true;
                while (oResultSet.next()) {
                    oCargoBean = oCargoBean.fill(oResultSet, oConnection, oPuserSecurity, expand);
                    empty = false;
                }
                if (empty) {
                    oCargoBean.setId(0);
                }
            } catch (Exception ex) {
                Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
                throw new Exception();
            } finally {
                if (oResultSet != null) {
                    oResultSet.close();
                }
            }
        } else {
            oCargoBean.setId(0);
        }
        return oCargoBean;
    }

    @Override
    public Integer set(CargoBean oCargoBean) throws Exception {
        Integer iResult = null;
        try {
            if (oCargoBean.getId() == 0) {
                strSQL = "INSERT INTO " + strTable + " ";
                strSQL += "(" + oCargoBean.getColumns() + ")";
                strSQL += "VALUES(" + oCargoBean.getValues() + ")";
                iResult = oMysql.executeInsertSQL(strSQL);
            } else {
                strSQL = "UPDATE " + strTable + " ";
                strSQL += " SET " + oCargoBean.toPairs();
                strSQL += " WHERE id=" + oCargoBean.getId();
                iResult = oMysql.executeUpdateSQL(strSQL);
            }
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return iResult;
    }

    @Override
    public Integer remove(Integer id) throws Exception {
        int result = 0;
        try {
            result = oMysql.removeOne(id, strTable);
        } catch (Exception ex) {
            Log4j.errorLog(this.getClass().getName() + ":" + (ex.getStackTrace()[0]).getMethodName(), ex);
            throw new Exception();
        }
        return result;
    }

}


text:
class UsernamesController < ApplicationController
  skip_before_filter :require_registration

  def show
    if User.with_username(params[:id]) || User::RESERVED.include?(params[:id].downcase)
      head :forbidden
    else
      head :ok
    end
  end
end


text:
package com.mapsindoors.stdapp.ui.components.mapfloorselector;

import androidx.annotation.NonNull;

import com.mapsindoors.mapssdk.Floor;

interface MapFloorSelectorAdapterListener {
    void onFloorSelectionChanged(@NonNull Floor newFloor);
}


text:
package MachineLearning;

import java.util.*;

import java.awt.Color;
import java.util.Random;
import java.io.IOException;

import java.awt.geom.*;
import javax.swing.*;

class GradientDescent  {
   private List<PlotPoint> points;

   class linearHypothesis {
      // h(x) = mx + b
      public double m, b;

      public linearHypothesis (double a, double b) {
         this.m = a;
         this.b = b;
      }

      public double evalAt(double x) {
         return this.m * x + this.b;
      }
   }

   class CostFunction {
      double theta1, theta2;

      public CostFunction() {
         this.theta1 = 0;
         this.theta2 = 0;
      }

      public void minimizeParams() {
         //TODO: find min value for which we get a line of best fit
      }
   }

   public GradientDescent (List<PlotPoint> points) {
      this.points = points;
   }

   //y = mx + b abbr = mxb, returns the derivative of the cost function
   //evaluated at J( theta1, theta2)s
   public double CostFunctionLeastSquares(
      List<PlotPoint> points,
      linearHypothesis mxb,
      int derivativeParams
   ){
      double sum = 0;
      int numTrainingExamples = points.size();

      for ( int i = 0 ; i < numTrainingExamples; i ++ ) {
         double yprime, x, y;
         x = points.get(i).x;
         y = points.get(i).y;

         switch( derivativeParams ) {
            case 1:
               yprime = (mxb.evalAt(x) - y) ;
               sum += yprime;
               break;
            case 2:
               yprime = (mxb.evalAt(x) - y)*x;
               sum+= yprime;
               break;
            default:
               yprime = mxb.evalAt(x) - y;
               sum += yprime*yprime;
         }
      }

      sum = sum/(2*numTrainingExamples);

      // if case 1 or 2, fomula for derivaive calculations is 1/m instead of 1/2m
      return ( derivativeParams != 0 ) ? sum*2 : sum ;
   }

   public void MultipleVariableGradientDescent() {
      //TODO
   }

   public linearHypothesis getLineOfBestFit(double theta1, double theta2) {

      double alpha = 0.3; //rate of convergence
      double theta1new = 4000, theta2new = 4000;
      boolean skipFirst = true;

      while (!skipFirst && theta1new - theta1 < 0.0005){
         if(skipFirst) {
            skipFirst = false;
         }

         linearHypothesis mxb = new linearHypothesis( theta1, theta2);

         double derivativeCostFunctionO1 = CostFunctionLeastSquares(this.points,mxb, 1);
         double derivativeCostFunctionO2 = CostFunctionLeastSquares(this.points,mxb, 2);

         theta1new = theta1 - alpha*derivativeCostFunctionO1;
         theta2new = theta2 - alpha*derivativeCostFunctionO2;

         //update linear hypothesis parameters and cost function minimization
         theta1 = theta1new;
         theta2 = theta2new;
      }

      return new linearHypothesis(theta1new, theta2new) ;
   }

   public static void main( String [] args) {
        int n = 20;

        Random ran = new Random( 1455 ) ;
        List<PlotPoint> temppoints = new ArrayList<PlotPoint>();
        for ( int i = 0 ; i < n ; i++ ) {
            temppoints.add (new PlotPoint( i, i*i));
        }
        PlotPoint[] arr = temppoints.toArray(new PlotPoint[temppoints.size()]);

        //run the default java applet
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new GraphingData(arr));
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
   }
}


text:
package snap

import (
	"errors"
	"fmt"
	"hash/crc32"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"time"

	pioutil "github.com/coreos/etcd/pkg/ioutil"
	"github.com/coreos/etcd/pkg/pbutil"
	"github.com/coreos/etcd/raft"
	"github.com/coreos/etcd/raft/raftpb"
	"github.com/coreos/etcd/snap/snappb"
	"github.com/coreos/etcd/wal/walpb"
	"github.com/coreos/pkg/capnslog"
)

const (
	snapSuffix = ".snap"
)

var (
	plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "snap")

	ErrNoSnapshot    = errors.New("snap: no available snapshot")
	ErrEmptySnapshot = errors.New("snap: empty snapshot")
	ErrCRCMismatch   = errors.New("snap: crc mismatch")
	crcTable         = crc32.MakeTable(crc32.Castagnoli)

	// A map of valid files that can be present in the snap folder.
	validFiles = map[string]bool{
		"db": true,
	}
)

type Snapshotter struct {
	dir string
}

func New(dir string) *Snapshotter {
	return &Snapshotter{
		dir: dir,
	}
}

func (s *Snapshotter) SaveSnap(snapshot raftpb.Snapshot) error {
	if raft.IsEmptySnap(snapshot) {
		return nil
	}
	return s.save(&snapshot)
}

func (s *Snapshotter) save(snapshot *raftpb.Snapshot) error {
	start := time.Now()

	fname := fmt.Sprintf("%016x-%016x%s", snapshot.Metadata.Term, snapshot.Metadata.Index, snapSuffix)
	b := pbutil.MustMarshal(snapshot)
	crc := crc32.Update(0, crcTable, b)
	snap := snappb.Snapshot{Crc: crc, Data: b}
	d, err := snap.Marshal()
	if err != nil {
		return err
	}
	marshallingDurations.Observe(float64(time.Since(start)) / float64(time.Second))

	err = pioutil.WriteAndSyncFile(filepath.Join(s.dir, fname), d, 0666)
	if err == nil {
		saveDurations.Observe(float64(time.Since(start)) / float64(time.Second))
	} else {
		err1 := os.Remove(filepath.Join(s.dir, fname))
		if err1 != nil {
			plog.Errorf("failed to remove broken snapshot file %s", filepath.Join(s.dir, fname))
		}
	}
	return err
}

func (s *Snapshotter) Load() (*raftpb.Snapshot, error) {
	return s.loadMatching(func(*raftpb.Snapshot) bool { return true })
}

// LoadNewestAvailable loads the newest snapshot available that is in walSnaps.
func (s *Snapshotter) LoadNewestAvailable(walSnaps []walpb.Snapshot) (*raftpb.Snapshot, error) {
	return s.loadMatching(func(snapshot *raftpb.Snapshot) bool {
		m := snapshot.Metadata
		for i := len(walSnaps) - 1; i >= 0; i-- {
			if m.Term == walSnaps[i].Term && m.Index == walSnaps[i].Index {
				return true
			}
		}
		return false
	})
}

// loadMatching returns the newest snapshot where matchFn returns true.
func (s *Snapshotter) loadMatching(matchFn func(*raftpb.Snapshot) bool) (*raftpb.Snapshot, error) {
	names, err := s.snapNames()
	if err != nil {
		return nil, err
	}
	var snap *raftpb.Snapshot
	for _, name := range names {
		if snap, err = loadSnap(s.dir, name); err == nil && matchFn(snap) {
			return snap, nil
		}
	}
	return nil, ErrNoSnapshot
}

func loadSnap(dir, name string) (*raftpb.Snapshot, error) {
	fpath := filepath.Join(dir, name)
	snap, err := Read(fpath)
	if err != nil {
		renameBroken(fpath)
	}
	return snap, err
}

// Read reads the snapshot named by snapname and returns the snapshot.
func Read(snapname string) (*raftpb.Snapshot, error) {
	b, err := ioutil.ReadFile(snapname)
	if err != nil {
		plog.Errorf("cannot read file %v: %v", snapname, err)
		return nil, err
	}

	if len(b) == 0 {
		plog.Errorf("unexpected empty snapshot")
		return nil, ErrEmptySnapshot
	}

	var serializedSnap snappb.Snapshot
	if err = serializedSnap.Unmarshal(b); err != nil {
		plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
		return nil, err
	}

	if len(serializedSnap.Data) == 0 || serializedSnap.Crc == 0 {
		plog.Errorf("unexpected empty snapshot")
		return nil, ErrEmptySnapshot
	}

	crc := crc32.Update(0, crcTable, serializedSnap.Data)
	if crc != serializedSnap.Crc {
		plog.Errorf("corrupted snapshot file %v: crc mismatch", snapname)
		return nil, ErrCRCMismatch
	}

	var snap raftpb.Snapshot
	if err = snap.Unmarshal(serializedSnap.Data); err != nil {
		plog.Errorf("corrupted snapshot file %v: %v", snapname, err)
		return nil, err
	}
	return &snap, nil
}

// snapNames returns the filename of the snapshots in logical time order (from newest to oldest).
// If there is no available snapshots, an ErrNoSnapshot will be returned.
func (s *Snapshotter) snapNames() ([]string, error) {
	dir, err := os.Open(s.dir)
	if err != nil {
		return nil, err
	}
	defer dir.Close()
	names, err := dir.Readdirnames(-1)
	if err != nil {
		return nil, err
	}
	names, err = s.cleanupSnapdir(names)
	if err != nil {
		return nil, err
	}
	snaps := checkSuffix(names)
	if len(snaps) == 0 {
		return nil, ErrNoSnapshot
	}
	sort.Sort(sort.Reverse(sort.StringSlice(snaps)))
	return snaps, nil
}

func checkSuffix(names []string) []string {
	snaps := []string{}
	for i := range names {
		if strings.HasSuffix(names[i], snapSuffix) {
			snaps = append(snaps, names[i])
		} else {
			// If we find a file which is not a snapshot then check if it's
			// a vaild file. If not throw out a warning.
			if _, ok := validFiles[names[i]]; !ok {
				plog.Warningf("skipped unexpected non snapshot file %v", names[i])
			}
		}
	}
	return snaps
}

func renameBroken(path string) {
	brokenPath := path + ".broken"
	if err := os.Rename(path, brokenPath); err != nil {
		plog.Warningf("cannot rename broken snapshot file %v to %v: %v", path, brokenPath, err)
	}
}

// cleanupSnapdir removes any files that should not be in the snapshot directory:
// - db.tmp prefixed files that can be orphaned by defragmentation
func (s *Snapshotter) cleanupSnapdir(filenames []string) (names []string, err error) {
	for _, filename := range filenames {
		if strings.HasPrefix(filename, "db.tmp") {
			plog.Infof("found orphaned defragmentation file; deleting: %s", filename)
			if rmErr := os.Remove(filepath.Join(s.dir, filename)); rmErr != nil && !os.IsNotExist(rmErr) {
				return nil, fmt.Errorf("failed to remove orphaned defragmentation file %s: %v", filename, rmErr)
			}
			continue
		}
		names = append(names, filename)
	}
	return names, nil
}

func (s *Snapshotter) ReleaseSnapDBs(snap raftpb.Snapshot) error {
	dir, err := os.Open(s.dir)
	if err != nil {
		return err
	}
	defer dir.Close()
	filenames, err := dir.Readdirnames(-1)
	if err != nil {
		return err
	}
	for _, filename := range filenames {
		if strings.HasSuffix(filename, ".snap.db") {
			hexIndex := strings.TrimSuffix(filepath.Base(filename), ".snap.db")
			index, err := strconv.ParseUint(hexIndex, 16, 64)
			if err != nil {
				plog.Warningf("failed to parse index from filename: %s (%v)", filename, err)
				continue
			}
			if index < snap.Metadata.Index {
				plog.Infof("found orphaned .snap.db file; deleting %q", filename)
				if rmErr := os.Remove(filepath.Join(s.dir, filename)); rmErr != nil && !os.IsNotExist(rmErr) {
					plog.Warningf("failed to remove orphaned .snap.db file: %s (%v)", filename, rmErr)
				}
			}
		}
	}
	return nil
}


text:
package de.hub.cs.dbis.lrb.types.internal;

import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
import de.hub.cs.dbis.lrb.queries.utils.TopologyControl;
import de.hub.cs.dbis.lrb.types.util.IPositionIdentifier;
import de.hub.cs.dbis.lrb.util.Constants;
import de.hub.cs.dbis.lrb.util.Time;

/**
 * {@link StoppedCarTuple} represents an intermediate result tuple; it reports a stopped car for a specific time, xway,
 * lane, position, and direction. If VID is negative, it reports the first car movement for a stopped car.

 *

 * It has the following attributes: VID, MINUTE, XWAY, LANE, POSITON, DIR
 *

 *
VID: the vehicle id

 *
TIME: the time when the vehicle stopped

 *
XWAY: the expressway in which the vehicle stopped

 *
LANE: the lane in which the vehicle stopped

 *
POSITON: the position in which the vehicle stopped

 *
DIR: the driving direction of the stopped vehicle

 *

 *
 * @author mjsax
 */
public final class StoppedCarTuple extends Values implements IPositionIdentifier {
	private static final long serialVersionUID = -7555340520758056252L;

	// attribute indexes
	/** The index of the VID attribute. */
	public final static int VID_IDX = 0;

	/** The index of the TIME attribute. */
	public final static int TIME_IDX = 1;

	/** The index of the XWAY attribute. */
	public final static int XWAY_IDX = 2;

	/** The index of the LANE attribute. */
	public final static int LANE_IDX = 3;

	/** The index of the POSITION attribute. */
	public final static int POS_IDX = 4;

	/** The index of the DIR attribute. */
	public final static int DIR_IDX = 5;

	public StoppedCarTuple() {}

	/**
	 * Instantiates a new {@link StoppedCarTuple} for the given attributes.
	 *
	 * @param vid
	 *            the id of the stopped vehicle
	 * @param time
	 *            the time when the car stopped
	 * @param xway
	 *            the expressway the vehicle is on
	 * @param lane
	 *            the lane the vehicle is in
	 * @param position
	 *            the position of the vehicle
	 * @param direction
	 *            the vehicle's driving direction
	 */
	public StoppedCarTuple(Integer vid, Short time, Integer xway, Short lane, Integer position, Short direction) {
		assert (vid != null);
		assert (time != null);
		assert (xway != null);
		assert (lane != null);
		assert (position != null);
		assert (direction != null);

		super.add(VID_IDX, vid);
		super.add(TIME_IDX, time);
		super.add(XWAY_IDX, xway);
		super.add(LANE_IDX, lane);
		super.add(POS_IDX, position);
		super.add(DIR_IDX, direction);

		assert (super.size() == 6);
	}

	/**
	 * Returns the the vehicle ID of this {@link StoppedCarTuple}.
	 *
	 * @return the VID of this tuple
	 */
	public final Integer getVid() {
		return (Integer)super.get(VID_IDX);
	}

	/**
	 * Returns the time of this {@link StoppedCarTuple}.
	 *
	 * @return the time of this tuple
	 */
	public final Short getTime() {
		return (Short)super.get(TIME_IDX);
	}

	/**
	 * Returns the expressway ID of this {@link StoppedCarTuple}.
	 *
	 * @return the expressway of this tuple
	 */
	@Override
	public final Integer getXWay() {
		return (Integer)super.get(XWAY_IDX);
	}

	/**
	 * Returns the lane of this {@link StoppedCarTuple}.
	 *
	 * @return the lane of this tuple
	 */
	@Override
	public final Short getLane() {
		return (Short)super.get(LANE_IDX);
	}

	/**
	 * Returns the position of this {@link StoppedCarTuple}.
	 *
	 * @return the position of this tuple
	 */
	@Override
	public final Integer getPosition() {
		return (Integer)super.get(POS_IDX);
	}

	/**
	 * Returns the segment of this {@link StoppedCarTuple}.
	 *
	 * @return the segment of this tuple
	 */
	public final Short getSegment() {
		return new Short(
			(short)(((Integer)super.get(POS_IDX)).intValue() / (Constants.NUMBER_OF_POSITIONS / Constants.NUMBER_OF_SEGMENT)));
	}

	/**
	 * Returns the vehicle's direction of this {@link StoppedCarTuple}.
	 *
	 * @return the direction of this tuple
	 */
	@Override
	public final Short getDirection() {
		return (Short)super.get(DIR_IDX);
	}

	/**
	 * Returns the 'minute number' of this {@link StoppedCarTuple}.
	 *
	 * @return the 'minute number' of this {@link StoppedCarTuple}
	 */
	public final short getMinuteNumber() {
		return Time.getMinute(this.getTime().shortValue());
	}

	/**
	 * Returns the schema of a {@link StoppedCarTuple}.
	 *
	 * @return the schema of a {@link StoppedCarTuple}
	 */
	public static Fields getSchema() {
		return new Fields(TopologyControl.VEHICLE_ID_FIELD_NAME, TopologyControl.TIMESTAMP_FIELD_NAME,
			TopologyControl.XWAY_FIELD_NAME, TopologyControl.LANE_FIELD_NAME, TopologyControl.POSITION_FIELD_NAME,
			TopologyControl.DIRECTION_FIELD_NAME);
	}

}


text:
package tdb.ddg

import tdb._
import tdb.Constants.{ModId, TaskId}
import tdb.list.ListInput

object Node {
  var id = 0

  def getId(): Int = {
    id = id + 1
    id
  }
}

sealed trait Node {
  var currentModId: ModId = -1

  var currentModId2: ModId = -1

  var updated = false
}

sealed trait ReexecutableNode extends Node

class MemoNode
    (val signature: Seq[Any],
     val memoizer: Memoizer[_]) extends Node {

  var value: Any = null
}

class ModNode
    (val modId1: ModId,
     val modId2: ModId) extends Node

class ParNode
    (val taskId1: TaskId,
     val taskId2: TaskId) extends Node {
  var pebble1 = false
  var pebble2 = false
}

class PutNode
    (val input: ListInput[Any, Any],
     val key: Any,
     val value: Any) extends Node

class PutAllNode
    (val input: ListInput[Any, Any],
     val values: Iterable[(Any, Any)]) extends Node

class PutInNode
    (val traceable: Traceable[Any, Any, Any],
     val parameters: Any) extends Node

class GetNode
    (val input: ListInput[Any, Any],
     val key: Any,
     val getter: Any => Unit) extends ReexecutableNode

class GetFromNode
    (val traceable: Traceable[Any, Any, Any],
     val parameters: Any,
     val getter: Any => Unit) extends ReexecutableNode

class ReadNode
    (val modId: ModId,
     val reader: Any => Changeable[Any])
  extends ReexecutableNode

class Read2Node
    (val modId1: ModId,
     val modId2: ModId,
     val reader: (Any, Any) => Changeable[Any]) extends ReexecutableNode

class Read3Node
    (val modId1: ModId,
     val modId2: ModId,
     val modId3: ModId,
     val reader: (Any, Any, Any) => Changeable[Any]) extends ReexecutableNode

class RootNode extends Node

class WriteNode(val modId: ModId, val modId2: ModId) extends Node


text:
#include "stdafx.h"

#include <d3d9.h>
#include <d3dx9.h>

#include "TrackDescription.h"

using namespace System;

namespace SlimDX
{
namespace Direct3D9
{
	bool TrackDescription::operator == ( TrackDescription left, TrackDescription right )
	{
		return TrackDescription::Equals( left, right );
	}

	bool TrackDescription::operator != ( TrackDescription left, TrackDescription right )
	{
		return !TrackDescription::Equals( left, right );
	}

	int TrackDescription::GetHashCode()
	{
		return Priority.GetHashCode() + Weight.GetHashCode() + Speed.GetHashCode()
			 + Position.GetHashCode() + Enabled.GetHashCode();
	}

	bool TrackDescription::Equals( Object^ value )
	{
		if( value == nullptr )
			return false;

		if( value->GetType() != GetType() )
			return false;

		return Equals( safe_cast<TrackDescription>( value ) );
	}

	bool TrackDescription::Equals( TrackDescription value )
	{
		return ( Priority == value.Priority && Weight == value.Weight && Speed == value.Speed
			 && Position == value.Position && Enabled == value.Enabled );
	}

	bool TrackDescription::Equals( TrackDescription% value1, TrackDescription% value2 )
	{
		return ( value1.Priority == value2.Priority && value1.Weight == value2.Weight && value1.Speed == value2.Speed
			 && value1.Position == value2.Position && value1.Enabled == value2.Enabled );
	}
}
}


text:
<!DOCTYPE HTML>

  <meta charset="UTF-8">
  <title></title>

select-narrowing-down.jsのデモ

  結婚相手に求めるものを3つ選んでください

    <select>
      <option value="">--</option>
      <option value="1">お金</option>
      <option value="2">年齢</option>
      <option value="3">容姿</option>
      <option value="4">相性</option>
      <option value="5">性格</option>
    </select>

    <select>
      <option value="">--</option>
      <option value="1">お金</option>
      <option value="2">年齢</option>
      <option value="3">容姿</option>
      <option value="4">相性</option>
      <option value="5">性格</option>
    </select>

    <select>
      <option value="">--</option>
      <option value="1">お金</option>
      <option value="2">年齢</option>
      <option value="3">容姿</option>
      <option value="4">相性</option>
      <option value="5">性格</option>
    </select>


text:
const DIE = /(\d+)?d(\d+)([+|-]\d+)?/;

const isMocked = (mock, funcName) => mock[funcName].returnValues.length > 0;

const mockedValue = (mock, funcName) => mock[funcName].returnValues.shift();

const diceRollDetails = (die) => {
  if (!DIE.test(die))
    throw new Error("Invalid die specifier, try one of these: d6, d3, 2d4");
  const rolls = [];
  const [, count = 1, size, modifier = 0] = DIE.exec(die);
  for (let i = 0; i < count; i++) {
    rolls.push(randm.int.between(1, size));
  }
  const unmodifiedTotal = rolls.reduce((sum, roll) => sum + roll);
  return {
    rolls,
    unmodifiedTotal,
    modifier,
    total: unmodifiedTotal + parseInt(modifier),
  };
};

const randm = {
  any: () => Math.random(),
  bool: () => !!randm.int.between(0, 1),
  coinFlip: () => (randm.bool() ? "heads" : "tails"),
  diceRoll: (die) =>
    die ? randm.customDiceRoll(die) : randm.int.between(1, 6),
  diceRollBeats: (target) => randm.diceRoll() >= target,
  diceRollOf: (die) => ({
    beats: (target) => randm.diceRollOf(die).isGreaterThanOrEqual(target),
    isGreaterThan: (target) => randm.diceRoll(die) > target,
    isGreaterThanOrEqual: (target) => randm.diceRoll(die) >= target,
    isLessThan: (target) => randm.diceRoll(die) < target,
    isLessThanOrEqual: (target) => randm.diceRoll(die) <= target,
    rolls: () => diceRollDetails(die),
    roll: () => randm.diceRollOf(die).rolls(),
  }),
  artilleryDie: () => randm.from([2, 4, 6, 8, 10, randm.artilleryDie.MISS]),
  scatterDie: () => ({
    direction: randm.between(0, 359),
    isHit: randm.oneIn(3),
  }),
  between: (x, y) => randm.any() * (y - x) + x,
  oneIn: (n) => randm.int.between(1, n) === n,
  from: (arry) => arry[randm.int.between(0, arry.length - 1)],
  happens: (times) => ({
    outOf: (total) =>
      Array.from(Array(times).keys()).includes(randm.int.between(0, total - 1)),
  }),
  percentageChance: (percentage) =>
    randm.happens(Math.abs(percentage)).outOf(100),
  customDiceRoll: (die) => randm.diceRollOf(die).rolls().total,
};

randm.int = {
  between: (x, y) => Math.round(randm.any() * (y - x)) + x,
};

const resetMockedReturnValues = (mock) =>
  Object.keys(mock).forEach((prop) => (mock[prop].returnValues = []));

randm.next = {
  int: {},
  reset: () => {
    resetMockedReturnValues(randm.next);
    resetMockedReturnValues(randm.next.int);
  },
};

const addMockingToFunctions = (obj, mock) => {
  Object.keys(obj).forEach((prop) => {
    if (typeof obj[prop] === "function") {
      const originalFunc = obj[prop];
      mock[prop] = {
        returnValues: [],
        returns: (...vals) => (mock[prop].returnValues = [...vals]),
      };
      obj[prop] = (...args) =>
        isMocked(mock, prop) ? mockedValue(mock, prop) : originalFunc(...args);
    }
  });
};

addMockingToFunctions(randm, randm.next);
addMockingToFunctions(randm.int, randm.next.int);

randm.artilleryDie.MISS = "MISS";

module.exports = randm;


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:textAllCaps">false</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="windowActionModeOverlay">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="FullscreenTheme" parent="AppTheme">
        <item name="android:actionBarStyle">@style/FullscreenActionBarStyle</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowBackground">@null</item>
        <item name="metaButtonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="metaButtonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
    </style>

    <style name="FullscreenActionBarStyle" parent="Widget.AppCompat.ActionBar">
        <item name="android:background">@color/black_overlay</item>
    </style>

    <style name="WiFiDialogTheme" parent="Base.Theme.AppCompat.Dialog">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="windowFixedHeightMajor">90%</item>
        <item name="windowFixedHeightMinor">95%</item>
        <item name="windowFixedWidthMajor">80%</item>
        <item name="windowFixedWidthMinor">95%</item>
    </style>

    <style name="SimpleDialogTheme" parent="Theme.AppCompat.Light.Dialog">
        <item name="buttonBarButtonStyle">@style/DialogButtonStyle</item>
        <item name="android:textColorLink">@color/colorBloomRed</item>
    </style>

    <style name="DialogButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
        <item name="android:textColor">@color/colorBloomRed</item>
    </style>

    <style name="MainButton" parent="Widget.AppCompat.Button">
        <item name="android:textAllCaps">false</item>
        <item name="android:radius">10dp</item>
        <item name="android:textColor">@android:color/white</item>
        <item name="android:colorBackground">@color/colorBloomRed</item>
    </style>

    <style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
        <!-- By default it uses our default accent color, which doesn't contrast enough.-->
        <item name="colorAccent">@color/alert_buttons</item>
    </style>
</resources>


text:
function libapt_foundation_init($, window)
{
  'use strict';

  var $doc = $(document),
      Modernizr = window.Modernizr;

  $.fn.foundationAlerts           ? $doc.foundationAlerts() : null;
  $.fn.foundationAccordion        ? $doc.foundationAccordion() : null;
  $.fn.foundationTooltips         ? $doc.foundationTooltips() : null;
  $('input, textarea').placeholder();

  $.fn.foundationButtons          ? $doc.foundationButtons() : null;

  $.fn.foundationNavigation       ? $doc.foundationNavigation() : null;

  $.fn.foundationTopBar           ? $doc.foundationTopBar() : null;

  $.fn.foundationCustomForms      ? $doc.foundationCustomForms() : null;
  $.fn.foundationMediaQueryViewer ? $doc.foundationMediaQueryViewer() : null;

    $.fn.foundationTabs             ? $doc.foundationTabs() : null;

    $("#featured").orbit();

  // UNCOMMENT THE LINE YOU WANT BELOW IF YOU WANT IE8 SUPPORT AND ARE USING .block-grids
  // $('.block-grid.two-up>li:nth-child(2n+1)').css({clear: 'both'});
  // $('.block-grid.three-up>li:nth-child(3n+1)').css({clear: 'both'});
  // $('.block-grid.four-up>li:nth-child(4n+1)').css({clear: 'both'});
  // $('.block-grid.five-up>li:nth-child(5n+1)').css({clear: 'both'});

  // Hide address bar on mobile devices
  if (Modernizr.touch) {
    $(window).load(function () {
      setTimeout(function () {
        window.scrollTo(0, 1);
      }, 0);
    });
  }

  $('input.datepicker').datepicker(
		{
			dateFormat: "yy-mm-dd"
		}
	);

  $('input.timepicker').timepicker(
		{
			timeFormat: "hh:mm:ss"
		}
	);

  $('input.datetimepicker').datetimepicker(
		{
			dateFormat: "yy-mm-dd",
			timeFormat: "hh:mm:ss",
			hourGrid: 4,
			minuteGrid: 10
		}
	);
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('invoice', '0019_auto_20180107_0118'),
    ]

    operations = [
        migrations.AlterField(
            model_name='invoice',
            name='phone',
            field=models.CharField(blank=True, max_length=15, null=True),
        ),
    ]


text:
.. _extension-static:

=============================
Static site builder
=============================

.. automodule:: lux.extensions.static


text:
'use strict';

Connector.getArtist = () => {
	return getIframeElement('#player-artist').first().text();
};

Connector.getTrack = () => {
	return getIframeElement('#player-title').first().text();
};

Connector.getDuration = () => {
	const duration = getIframeElement('#player-time-left').text();
	return Util.stringToSeconds(duration);
};

Connector.getCurrentTime = () => {
	const currentTime = getIframeElement('#player-time-played').text();
	return Util.stringToSeconds(currentTime);
};

Connector.isPlaying = () => {
	const playButton = getIframeElement('#player-play-button');
	return playButton.css('display') === 'none';
};

Connector.getTrackArt = () => {
	const imageSrc = getIframeElement('#player-badge-image').attr('src');
	const url = `${window.location.protocol}//${window.location.host}${imageSrc}`;
	return url;
};

Connector.getUniqueID = () => {
	const trackUrl = getIframeElement('#player').attr('src');
	if (trackUrl) {
		return trackUrl.split('/').pop();
	}
	return null;
};

Connector.applyFilter(MetadataFilter.getRemasteredFilter());

/**
 * Find element in player iframe content.
 * @param  {String} selector CSS selector
 * @return {Object} Found element
 */
function getIframeElement(selector) {
	return $('#playerFrame').contents().find(selector);
}

/**
 * Manually set up observer on player markup inside iframe
 */
function onPlayerLoaded() {
	Util.debugLog('Player loaded, setting up observer');

	const observer = new MutationObserver(Connector.onStateChanged);
	const observeTarget = $('#playerFrame').get(0).contentDocument.getElementById('player-section');
	const config = {
		childList: true,
		subtree: true,
		attributes: true,
		characterData: true,
	};
	observer.observe(observeTarget, config);
}

/**
 * Crudely poll for readyState to hook up observer
 * due to no onload event firing on iframe
 */
const timer = setInterval(() => {
	const iframe = document.getElementById('playerFrame');
	const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
	if (iframeDoc.readyState === 'complete' || iframeDoc.readyState === 'interactive') {
		onPlayerLoaded();
		clearInterval(timer);
	}
}, 2000);


text:
module Docomoru
  module DialogueMethods
    PATH = "/dialogue/v1/dialogue"

    def create_dialogue(message, params = {}, headers = {})
      post(
        "#{PATH}?#{default_query_string}",
        params.merge(utt: message),
        headers,
      )
    end
  end
end


text:
<?php
namespace Embed\Providers\OEmbed;

class YFrog extends \Embed\Providers\OEmbedImplementationAbstract
{
	/**
	 * {@inheritDoc}
	 */
    public static function getEndPoint()
    {
        return 'http://www.yfrog.com/api/oembed';
    }

    /**
	 * {@inheritDoc}
	 */
    public static function getPatterns()
    {
        return array('http://twitter.yfrog.com/*','http://www.yfrog.com/*');
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>SQLite Release 3.8.7.1 On 2014-10-29</title>

Small. Fast. Reliable.
Choose any three.

    About
    Documentation
    Download
    License
    Support
    Purchase

    <form name=f method="GET" action="https://www.sqlite.org/search">
      <input id=q name=q type=text
       onfocus="entersearch()" onblur="leavesearch()" style="width:24ex;padding:1px 1ex; border:solid white 1px; font-size:0.9em ; font-style:italic;color:#044a64;" value="Search SQLite Docs...">
      <input type=submit value="Go" style="border:solid white 1px;background-color:#044a64;color:white;font-size:0.9em;padding:0 1ex">
    </form>

SQLite Release 3.8.7.1 On 2014-10-29

In PRAGMA journal_mode=TRUNCATE mode, call fsync() immediately after truncating
    the journal file to ensure that the transaction is durable across a power loss.

Fix an assertion fault that can occur when updating the NULL value of a field
    at the end of a table that was added using ALTER TABLE ADD COLUMN.

Do not attempt to use the strchrnul() function from the standard C library unless
    the HAVE_STRCHRNULL compile-time option is set.

Fix a couple of problems associated with running an UPDATE or DELETE on a
    VIEW with a rowid in the WHERE clause.

SQLITE_SOURCE_ID: "2014-10-29 13:59:56 3b7b72c4685aa5cf5e675c2c47ebec10d9704221"

SHA1 for sqlite3.c: 2d25bd1a73dc40f538f3a81c28e6efa5999bdf0c

A complete list of SQLite releases
      in a single page and a chronology are both also available.
      A detailed history of every
      check-in is available at

      SQLite version control site.


text:
title: Decommission Bookies
---

In case the user wants to decommission a bookie, the following process is useful to follow in order to verify if the
decommissioning was safely done.

### Before we decommission
1. Ensure state of your cluster can support the decommissioning of the target bookie.
Check if `EnsembleSize >= Write Quorum >= Ack Quorum` stays true with one less bookie

2. Ensure target bookie shows up in the listbookies command.

3. Ensure that there is no other process ongoing (upgrade etc).

### Process of Decommissioning
1. Log on to the bookie node, check if there are underreplicated ledgers.

If there are, the decommission command will force them to be replicated.
`$ bin/bookkeeper shell listunderreplicated`

2. Stop the bookie
`$ bin/bookkeeper-daemon.sh stop bookie`

3. Run the decommission command.
If you have logged onto the node you wish to decommission, you don't need to provide `-bookieid`
If you are running the decommission command for target bookie node from another bookie node you should mention
the target bookie id in the arguments for `-bookieid`
`$ bin/bookkeeper shell decommissionbookie`
or
`$ bin/bookkeeper shell decommissionbookie -bookieid <target bookieid>`

4. Validate that there are no ledgers on decommissioned bookie
`$ bin/bookkeeper shell listledgers -bookieid <target bookieid>`

Last step to verify is you could run this command to check if the bookie you decommissioned doesn't show up in list bookies:

```bash
./bookkeeper shell listbookies -rw -h
./bookkeeper shell listbookies -ro -h
```


text:
<Addin namespace="TextEditor" id="Core" version="1.0" isroot="true">

	<Runtime>
		<Import assembly="TextEditor.exe"/>
		<Import assembly="TextEditorLib.dll"/>
	</Runtime>

	<ConditionType id="OpenFile" type="TextEditor.OpenFileCondition" />

	<ExtensionPoint path = "/TextEditor/ToolbarButtons">
		<ExtensionNode name="ToolButton" type="TextEditor.ToolButtonNode"/>
		<ExtensionNode name="ToolSeparator" type="TextEditor.ToolSeparatorNode"/>
	</ExtensionPoint>

	<ExtensionPoint path = "/TextEditor/MainMenu">
		<ExtensionNode type="TextEditor.SubmenuNode"/>
	</ExtensionPoint>

	<ExtensionPoint path = "/TextEditor/Templates">
		<ExtensionNode name="Category" type="TextEditor.TemplateCategoryNode">
			<ExtensionNode name="FileTemplate" type="TextEditor.FileTemplateNode" />
		</ExtensionNode>
		<ExtensionNode name="FileTemplate" type="TextEditor.FileTemplateNode" />
	</ExtensionPoint>

	<Extension path = "/TextEditor/ToolbarButtons">
		<ToolButton icon="gtk-new" commandType="TextEditor.NewCommand" />
		<ToolButton icon="gtk-open" commandType="TextEditor.OpenCommand" />
		<ToolButton icon="gtk-save" commandType="TextEditor.SaveCommand" />
		<ToolSeparator />
		<ToolButton icon="gtk-cut" commandType="TextEditor.CutCommand" />
		<ToolButton icon="gtk-copy" commandType="TextEditor.CopyCommand" />
		<ToolButton icon="gtk-paste" commandType="TextEditor.PasteCommand" />
	</Extension>

	<Extension path = "/TextEditor/MainMenu">
		<Menu id="File" label="File">
			<MenuItem id="New" icon="gtk-new" commandType="TextEditor.NewCommand" />
			<MenuItem id="Open" icon="gtk-open" commandType="TextEditor.OpenCommand" />
			<MenuItem id="Save" icon="gtk-save" commandType="TextEditor.SaveCommand" />
			<MenuSeparator />
			<MenuItem id="Quit" icon="gtk-quit" commandType="TextEditor.ExitCommand" />
		</Menu>
		<Menu id="Edit" label="Edit">
			<MenuItem id="Cut" icon="gtk-cut" commandType="TextEditor.CutCommand" />
			<MenuItem id="Copy" icon="gtk-copy" commandType="TextEditor.CopyCommand" />
			<MenuItem id="Paste" icon="gtk-paste" commandType="TextEditor.PasteCommand" />
		</Menu>
		<Menu id="Tools" label="Tools">
			<MenuItem id="Setup" label="Add-in Manager" commandType="TextEditor.SetupCommand" />
		</Menu>
	</Extension>

	<Extension path = "/TextEditor/Templates">
		<Category id="Development" >
			<FileTemplate name="ChangeLog" resource="ChangeLogTemplate.txt" />
			<FileTemplate name=".config file" resource="DotConfigTemplate.txt" />
			<FileTemplate name="Work report" resource="WorkReport.txt" />
		</Category>
	</Extension>

</Addin>


text:
OC_NS_BG;

String LogLevelUtil::LogLeveltoString(LogLevel level)
{
    switch (level)
    {
    case LogLevel::Debug:
        return "Debug";
    case LogLevel::Info:
        return "Info";
    case LogLevel::Warn:
        return "Warn";
    case LogLevel::Error:
        return "Error";
    case LogLevel::Always:
        return "Always";
    default:
        {
        }
        return "";
    }
}

OC_NS_END;


text:
<?php

namespace Google\AdsApi\AdWords\v201705\cm;

/**
 * This file was generated from WSDL. DO NOT EDIT.
 */
class BidModifierSource
{
    const UNKNOWN = 'UNKNOWN';
    const CAMPAIGN = 'CAMPAIGN';
    const AD_GROUP = 'AD_GROUP';

}


text:
'use strict';

/**
 * @ngdoc function
 * @name mytodoAppApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the mytodoAppApp
 */
angular.module('mytodoAppApp')
  .controller('AboutCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });


text:
package ca.corefacility.bioinformatics.irida.ria.web.users;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import ca.corefacility.bioinformatics.irida.ria.web.services.UIUserStatisticsService;
import ca.corefacility.bioinformatics.irida.ria.web.users.dto.UserStatisticsResponse;

/**
 * Controller for user statistics
 */
@RestController
@RequestMapping("/ajax/user/statistics")
public class UserStatisticsAjaxController {

	private UIUserStatisticsService uiUserStatisticsService;

	@Autowired
	public UserStatisticsAjaxController(UIUserStatisticsService uiUserStatisticsService) {
		this.uiUserStatisticsService = uiUserStatisticsService;
	}

	/**
	 * Get basic user usage statistics for dashboard
	 *
	 * @param userId The identifier for the user
	 * @return dto with user usage stats
	 */
	@GetMapping("")
	public ResponseEntity<UserStatisticsResponse> getUserStatistics(@RequestParam Long userId) {
		return ResponseEntity.ok(uiUserStatisticsService.getUserStatistics(userId));
	}
}


text:
package org.georgie.validation;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
@Constraint(validatedBy = PasswordConstraintValidator.class)
@Target({TYPE, FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface ValidPassword
{

    String message() default "Invalid Password";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

}


text:
package main

// Import declaration declares library packages referenced in this file.
import "./calc" // a user defined package
import "fmt" // A package in the Go standard library.

func main() {
	x, y := 6, 3

	fmt.Printf("Sum of %d and %d is %d\n", x, y, calc.Add(x, y))
	fmt.Printf("Diffrence of %d and %d is %d\n", x, y, calc.Substract(x, y))
}


text:
'use strict';

angular.module('espaceClasse.calendar')

    .controller('CalendarController', function ($scope, $rootScope, $location, StorageService) {
        $rootScope.pageTitle = 'Calendar';

        // Get courses
        $scope.courses = StorageService.getItem('courses', []);

        $scope.$watch('courses', function () {
            StorageService.setItem('courses', $scope.courses);
        }, true);

        // Get events
        $scope.events = StorageService.getItem('events', [[]]);
        $scope.$watch('events', function () {
            StorageService.setItem('events', $scope.events);
        }, true);

        $scope.classrooms = StorageService.getItem('classrooms', []);
        $scope.indexedClassrooms = {};
        for (let i = 0; i < $scope.classrooms.length; i += 1) {
            $scope.indexedClassrooms[$scope.classrooms[i].id] = $scope.classrooms[i];
        }

        $scope.formCreateCourse = null;
        $scope.cancelCreateCourse = function () {
            $scope.formCreateCourse = null;
        };
        $scope.createCourse = function () {
            if ($scope.formCreateCourse.classroomId == null) {
                return;
            }

            let start = new Date($scope.formCreateCourse.date);
            start.setMinutes($scope.formCreateCourse.minutes);
            start.setHours($scope.formCreateCourse.hours + parseInt($scope.formCreateCourse.amOrPm) + 1);

            let end = new Date(start);
            end.setHours(start.getHours() + 1);

            let courseId = $scope.courses.length > 0 ? $scope.courses[$scope.courses.length - 1].id + 1 : 0;

            $scope.events[0].push({
                courseId,
                classroomId: parseInt($scope.formCreateCourse.classroomId),
                title: $scope.indexedClassrooms[$scope.formCreateCourse.classroomId].name,
                start: +start,
                end: +end
            });
            $scope.courses.push({
                id: courseId
            });
            $scope.formCreateCourse = null;
        };
        $scope.dayClickHandler = function (date) {
            $scope.formCreateCourse = {
                date: date,
                hours: date.hours() > 12 ? date.hours() - 12 : date.hours(),
                amOrPm: date.hours() > 12 ? '12' : '0',
                minutes: 0
            };
        };
        $scope.eventClickHandler = function (date) {
            $location.path('/course/' + date.classroomId + '/' + date.courseId);
        };
        $scope.uiConfig = {
            calendar: {
                height: 650,
                editable: true,
                firstDay: 1,
                dow: [1, 2, 3, 4, 5],
                header: {
                    left: 'agendaWeek,agendaDay,month',
                    center: 'title',
                    right: 'today prev,next'
                },
                dayClick: $scope.dayClickHandler,
                eventClick: $scope.eventClickHandler
            }
        };
    });


text:
package com.btmatthews.maven.plugins.inmemdb;

import javax.sql.DataSource;

/**
 * Describes the operations that are used by the Mojos to launch in-memory
 * databases, load data into, execute scripts against or shutdown the database.
 *
 * @author Brian Matthews
 * @version 1.0.0
 */
public interface SQLDatabase extends Database {

    /**
     * Get the data source that describes the connection to the in-memory
     * database.
     *
     * @return The data source.
     */
    DataSource getDataSource();
}


text:
package serve

import (
	"github.com/jacksinn/apifaker/route"
	"net/http"
	"fmt"
)

/*
|--------------------------------------------------------------------------
| Server
|--------------------------------------------------------------------------
|
| Here is where the HTTP Server is setup
|
*/
type Server struct {
	Address string
	Port    int
	Routes  route.Routes
}

func (server Server) getResponse(request *http.Request) route.Response {
	//getting our routes from JSON
	for _, route := range server.Routes {
		//if Path and Method Match
		if route.Request.Path == request.URL.Path && route.Request.Method == request.Method {
			//Respond with route response JSON
			return route.Response
		}
	}
	//else return bad response
	return route.Response{Code: 404, Body: "Not Found"}
}

func (server Server) Handle(writer http.ResponseWriter, request *http.Request) {
	response := server.getResponse(request)
	fmt.Fprintf(writer, response.Body)
}

func (server Server) Run() {
	//Handler Func Setup
	http.HandleFunc("/", server.Handle)
	//Setting up addr to listen & serve on, this feels a little crappy, cleanup s.c.s.a and s.c.s.p
	addr := fmt.Sprintf("%v:%v", server.Address, server.Port)
	panic(http.ListenAndServe(addr, nil))
}


text:
//This file is automatically rebuilt by the Cesium build process.
define(function() {
    'use strict';
    return "/**\n\
 * Calculates the specular intensity of reflected light.\n\
 *\n\
 * @name czm_getSpecular\n\
 * @glslFunction\n\
 *\n\
 * @param {vec3} lightDirectionEC Unit vector pointing to the light source in eye coordinates.\n\
 * @param {vec3} toEyeEC Unit vector pointing to the eye position in eye coordinates.\n\
 * @param {vec3} normalEC The surface normal in eye coordinates.\n\
 * @param {float} shininess The sharpness of the specular reflection.  Higher values create a smaller, more focused specular highlight.\n\
 *\n\
 * @returns {float} The intensity of the specular highlight.\n\
 *\n\
 * @see czm_phong\n\
 *\n\
 * @example\n\
 * float diffuseIntensity = czm_getLambertDiffuse(lightDirectionEC, normalEC);\n\
 * float specularIntensity = czm_getSpecular(lightDirectionEC, toEyeEC, normalEC, 200);\n\
 * vec3 color = (diffuseColor * diffuseIntensity) + (specularColor * specularIntensity);\n\
 */\n\
float czm_getSpecular(vec3 lightDirectionEC, vec3 toEyeEC, vec3 normalEC, float shininess)\n\
{\n\
    vec3 toReflectedLight = reflect(-lightDirectionEC, normalEC);\n\
    float specular = max(dot(toReflectedLight, toEyeEC), 0.0);\n\
\n\
    // pow has undefined behavior if both parameters <= 0.\n\
    // Prevent this by making sure shininess is at least czm_epsilon2.\n\
    return pow(specular, max(shininess, czm_epsilon2));\n\
}\n\
";
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DDsControlCollection
{
    class ProgressTextBox
    {
    }
}


text:
const ExternalAPI = {

	autocomplete: function(vocabulary, term, callback) {
		const url = '/autocomplete?vocab=' + vocabulary + '&term=' + term;
	    const xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function() {
			if (xhr.readyState == XMLHttpRequest.DONE) {
				if(xhr.status == 200) {
					callback(JSON.parse(xhr.responseText));
				} else {
					callback(null);
				}
			}
		}
		xhr.open("GET", url);
		xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
		xhr.send(null);
		return xhr;
	},

	search: function(api, searchTerm, callback) {
		const url = '/link/' + api + '/search?q=' + searchTerm;
	    const xhr = new XMLHttpRequest();
		xhr.onreadystatechange = function() {
			if (xhr.readyState == XMLHttpRequest.DONE) {
				if(xhr.status == 200) {
					callback(JSON.parse(xhr.responseText));
				} else {
					callback(null);
				}
			}
		}
		xhr.open("GET", url);
		xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
		xhr.send(null);
		return xhr;
	}
}

export default ExternalAPI;


text:
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    MPRISWatcher watcher;
    watcher.start();

    return a.exec();
}