text:
package embedded

import (
	"context"
	"errors"
	"fmt"
	"net/url"
	"strings"
	"time"

	"github.com/apache/servicecomb-service-center/datasource/etcd"
	"github.com/apache/servicecomb-service-center/datasource/etcd/client"
	errorsEx "github.com/apache/servicecomb-service-center/pkg/errors"
	"github.com/apache/servicecomb-service-center/pkg/gopool"
	"github.com/apache/servicecomb-service-center/pkg/log"
	"github.com/apache/servicecomb-service-center/pkg/util"
	"github.com/coreos/etcd/compactor"
	"github.com/coreos/etcd/embed"
	"github.com/coreos/etcd/etcdserver"
	"github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
	"github.com/coreos/etcd/etcdserver/etcdserverpb"
	"github.com/coreos/etcd/lease"
	"github.com/coreos/etcd/mvcc/mvccpb"
)

func init() {
	client.Install("embeded_etcd", getEmbedInstance)
}

type EtcdEmbed struct {
	Embed     *embed.Etcd
	err       chan error
	ready     chan struct{}
	goroutine *gopool.Pool
}

func (s *EtcdEmbed) Err() <-chan error {
	return s.err
}

func (s *EtcdEmbed) Ready() <-chan struct{} {
	return s.ready
}

func (s *EtcdEmbed) Close() {
	if s.Embed != nil {
		s.Embed.Close()
	}
	s.goroutine.Close(true)
	log.Debugf("embedded etcd client stopped")
}

func (s *EtcdEmbed) getPrefixEndKey(prefix []byte) []byte {
	l := len(prefix)
	endBytes := make([]byte, l+1)
	copy(endBytes, prefix)
	if endBytes[l-1] == 0xff {
		endBytes[l] = 1
		return endBytes
	}
	endBytes[l-1]++
	return endBytes[:l]
}

func (s *EtcdEmbed) toGetRequest(op client.PluginOp) *etcdserverpb.RangeRequest {
	endBytes := op.EndKey
	if op.Prefix {
		endBytes = s.getPrefixEndKey(op.Key)
	}
	sortTarget := etcdserverpb.RangeRequest_KEY
	switch op.OrderBy {
	case client.OrderByKey:
		sortTarget = etcdserverpb.RangeRequest_KEY
	case client.OrderByCreate:
		sortTarget = etcdserverpb.RangeRequest_CREATE
	}
	order := etcdserverpb.RangeRequest_NONE
	switch op.SortOrder {
	case client.SortAscend:
		order = etcdserverpb.RangeRequest_ASCEND
	case client.SortDescend:
		order = etcdserverpb.RangeRequest_DESCEND
	}
	return &etcdserverpb.RangeRequest{
		Key:        op.Key,
		RangeEnd:   endBytes,
		KeysOnly:   op.KeyOnly,
		CountOnly:  op.CountOnly,
		SortOrder:  order,
		SortTarget: sortTarget,
		Revision:   op.Revision,
	}
}

func (s *EtcdEmbed) toPutRequest(op client.PluginOp) *etcdserverpb.PutRequest {
	var valueBytes []byte
	if len(op.Value) > 0 {
		valueBytes = op.Value
	}
	return &etcdserverpb.PutRequest{
		Key:         op.Key,
		Value:       valueBytes,
		PrevKv:      op.PrevKV,
		Lease:       op.Lease,
		IgnoreLease: op.IgnoreLease,
	}
}

func (s *EtcdEmbed) toDeleteRequest(op client.PluginOp) *etcdserverpb.DeleteRangeRequest {
	endBytes := op.EndKey
	if op.Prefix {
		endBytes = s.getPrefixEndKey(op.Key)
	}
	return &etcdserverpb.DeleteRangeRequest{
		Key:      op.Key,
		RangeEnd: endBytes,
		PrevKv:   op.PrevKV,
	}
}

func (s *EtcdEmbed) toTxnRequest(opts []client.PluginOp) []*etcdserverpb.RequestOp {
	etcdOps := []*etcdserverpb.RequestOp{}
	for _, op := range opts {
		switch op.Action {
		case client.ActionGet:
			etcdOps = append(etcdOps, &etcdserverpb.RequestOp{
				Request: &etcdserverpb.RequestOp_RequestRange{
					RequestRange: s.toGetRequest(op),
				},
			})
		case client.ActionPut:
			etcdOps = append(etcdOps, &etcdserverpb.RequestOp{
				Request: &etcdserverpb.RequestOp_RequestPut{
					RequestPut: s.toPutRequest(op),
				},
			})
		case client.ActionDelete:
			etcdOps = append(etcdOps, &etcdserverpb.RequestOp{
				Request: &etcdserverpb.RequestOp_RequestDeleteRange{
					RequestDeleteRange: s.toDeleteRequest(op),
				},
			})
		}
	}
	return etcdOps
}

func (s *EtcdEmbed) toCompares(cmps []client.CompareOp) []*etcdserverpb.Compare {
	etcdCmps := []*etcdserverpb.Compare{}
	for _, cmp := range cmps {
		compare := &etcdserverpb.Compare{
			Key: cmp.Key,
		}
		switch cmp.Type {
		case client.CmpVersion:
			var version int64
			if cmp.Value != nil {
				if v, ok := cmp.Value.(int64); ok {
					version = v
				}
			}
			compare.Target = etcdserverpb.Compare_VERSION
			compare.TargetUnion = &etcdserverpb.Compare_Version{
				Version: version,
			}
		case client.CmpCreate:
			var revision int64
			if cmp.Value != nil {
				if v, ok := cmp.Value.(int64); ok {
					revision = v
				}
			}
			compare.Target = etcdserverpb.Compare_CREATE
			compare.TargetUnion = &etcdserverpb.Compare_CreateRevision{
				CreateRevision: revision,
			}
		case client.CmpMod:
			var revision int64
			if cmp.Value != nil {
				if v, ok := cmp.Value.(int64); ok {
					revision = v
				}
			}
			compare.Target = etcdserverpb.Compare_MOD
			compare.TargetUnion = &etcdserverpb.Compare_ModRevision{
				ModRevision: revision,
			}
		case client.CmpValue:
			var value []byte
			if cmp.Value != nil {
				if v, ok := cmp.Value.([]byte); ok {
					value = v
				}
			}
			compare.Target = etcdserverpb.Compare_VALUE
			compare.TargetUnion = &etcdserverpb.Compare_Value{
				Value: value,
			}
		}
		switch cmp.Result {
		case client.CmpEqual:
			compare.Result = etcdserverpb.Compare_EQUAL
		case client.CmpGreater:
			compare.Result = etcdserverpb.Compare_GREATER
		case client.CmpLess:
			compare.Result = etcdserverpb.Compare_LESS
		case client.CmpNotEqual:
			compare.Result = etcdserverpb.Compare_NOT_EQUAL
		}
		etcdCmps = append(etcdCmps, compare)
	}
	return etcdCmps
}

func (s *EtcdEmbed) Compact(ctx context.Context, reserve int64) error {
	curRev := s.getLeaderCurrentRevision(ctx)
	revToCompact := max(0, curRev-reserve)
	if revToCompact <= 0 {
		log.Infof("revision is %d, <=%d, no nead to compact", curRev, reserve)
		return nil
	}

	log.Infof("compacting... revision is %d(current: %d, reserve %d)", revToCompact, curRev, reserve)
	_, err := s.Embed.Server.Compact(ctx, &etcdserverpb.CompactionRequest{
		Revision: revToCompact,
		Physical: true,
	})
	if err != nil {
		log.Errorf(err, "compact locally failed, revision is %d(current: %d, reserve %d)",
			revToCompact, curRev, reserve)
		return err
	}
	log.Infof("compacted locally, revision is %d(current: %d, reserve %d)", revToCompact, curRev, reserve)

	// TODO defragment
	log.Infof("defraged locally")

	return nil
}

func (s *EtcdEmbed) getLeaderCurrentRevision(ctx context.Context) int64 {
	return s.Embed.Server.KV().Rev()
}

func (s *EtcdEmbed) PutNoOverride(ctx context.Context, opts ...client.PluginOpOption) (bool, error) {
	op := client.OpPut(opts...)
	resp, err := s.TxnWithCmp(ctx, []client.PluginOp{op}, []client.CompareOp{
		client.OpCmp(client.CmpCreateRev(op.Key), client.CmpEqual, 0),
	}, nil)
	log.Debugf("response %s %v %v", op.Key, resp.Succeeded, resp.Revision)
	if err != nil {
		return false, err
	}
	return resp.Succeeded, nil
}

func (s *EtcdEmbed) Do(ctx context.Context, opts ...client.PluginOpOption) (*client.PluginResponse, error) {
	op := client.OptionsToOp(opts...)

	otCtx, cancel := etcd.WithTimeout(ctx)
	defer cancel()
	var err error
	var resp *client.PluginResponse
	switch op.Action {
	case client.ActionGet:
		var etcdResp *etcdserverpb.RangeResponse
		etcdResp, err = s.Embed.Server.Range(otCtx, s.toGetRequest(op))
		if err != nil {
			break
		}
		resp = &client.PluginResponse{
			Kvs:      etcdResp.Kvs,
			Count:    etcdResp.Count,
			Revision: etcdResp.Header.Revision,
		}
	case client.ActionPut:
		var etcdResp *etcdserverpb.PutResponse
		etcdResp, err = s.Embed.Server.Put(otCtx, s.toPutRequest(op))
		if err != nil {
			break
		}
		resp = &client.PluginResponse{
			Revision: etcdResp.Header.Revision,
		}
	case client.ActionDelete:
		var etcdResp *etcdserverpb.DeleteRangeResponse
		etcdResp, err = s.Embed.Server.DeleteRange(otCtx, s.toDeleteRequest(op))
		if err != nil {
			break
		}
		resp = &client.PluginResponse{
			Revision: etcdResp.Header.Revision,
		}
	}
	if err != nil {
		return nil, err
	}
	resp.Succeeded = true
	return resp, nil
}

// TODO EMBED支持KV().TxnBegin()->TxnID,可惜PROXY模式暂时不支持
func (s *EtcdEmbed) Txn(ctx context.Context, opts []client.PluginOp) (*client.PluginResponse, error) {
	resp, err := s.TxnWithCmp(ctx, opts, nil, nil)
	if err != nil {
		return nil, err
	}
	return &client.PluginResponse{
		Succeeded: resp.Succeeded,
		Revision:  resp.Revision,
	}, nil
}

func (s *EtcdEmbed) TxnWithCmp(ctx context.Context, success []client.PluginOp, cmps []client.CompareOp, fail []client.PluginOp) (*client.PluginResponse, error) {
	otCtx, cancel := etcd.WithTimeout(ctx)
	defer cancel()

	etcdCmps := s.toCompares(cmps)
	etcdSuccessOps := s.toTxnRequest(success)
	etcdFailOps := s.toTxnRequest(fail)
	txnRequest := &etcdserverpb.TxnRequest{
		Success: etcdSuccessOps,
	}
	if len(etcdCmps) > 0 {
		txnRequest.Compare = etcdCmps
	}
	if len(etcdFailOps) > 0 {
		txnRequest.Failure = etcdFailOps
	}
	resp, err := s.Embed.Server.Txn(otCtx, txnRequest)
	if err != nil {
		if err.Error() == rpctypes.ErrKeyNotFound.Error() {
			// etcd return ErrKeyNotFound if key does not exist and
			// the PUT options contain WithIgnoreLease
			return &client.PluginResponse{Succeeded: false}, nil
		}
		return nil, err
	}

	var rangeResponse etcdserverpb.RangeResponse
	for _, itf := range resp.Responses {
		if rr, ok := itf.Response.(*etcdserverpb.ResponseOp_ResponseRange); ok {
			// plz request the same type range kv in txn success/fail options
			rangeResponse.Kvs = append(rangeResponse.Kvs, rr.ResponseRange.Kvs...)
			rangeResponse.Count += rr.ResponseRange.Count
		}
	}

	return &client.PluginResponse{
		Succeeded: resp.Succeeded,
		Revision:  resp.Header.Revision,
		Kvs:       rangeResponse.Kvs,
		Count:     rangeResponse.Count,
	}, nil
}

func (s *EtcdEmbed) LeaseGrant(ctx context.Context, TTL int64) (int64, error) {
	otCtx, cancel := etcd.WithTimeout(ctx)
	defer cancel()
	etcdResp, err := s.Embed.Server.LeaseGrant(otCtx, &etcdserverpb.LeaseGrantRequest{
		TTL: TTL,
	})
	if err != nil {
		return 0, err
	}
	return etcdResp.ID, nil
}

func (s *EtcdEmbed) LeaseRenew(ctx context.Context, leaseID int64) (int64, error) {
	otCtx, cancel := etcd.WithTimeout(ctx)
	defer cancel()
	ttl, err := s.Embed.Server.LeaseRenew(otCtx, lease.LeaseID(leaseID))
	if err != nil {
		if err.Error() == rpctypes.ErrLeaseNotFound.Error() {
			return 0, err
		}
		return 0, errorsEx.RaiseError(err)
	}
	return ttl, nil
}

func (s *EtcdEmbed) LeaseRevoke(ctx context.Context, leaseID int64) error {
	otCtx, cancel := etcd.WithTimeout(ctx)
	defer cancel()
	_, err := s.Embed.Server.LeaseRevoke(otCtx, &etcdserverpb.LeaseRevokeRequest{
		ID: leaseID,
	})
	if err != nil {
		if err.Error() == rpctypes.ErrLeaseNotFound.Error() {
			return err
		}
		return errorsEx.RaiseError(err)
	}
	return nil
}

func (s *EtcdEmbed) Watch(ctx context.Context, opts ...client.PluginOpOption) (err error) {
	op := client.OpGet(opts...)

	if len(op.Key) > 0 {
		watchable := s.Embed.Server.Watchable()
		ws := watchable.NewWatchStream()
		defer ws.Close()

		key := util.BytesToStringWithNoCopy(op.Key)
		var keyBytes []byte
		if op.Prefix {
			if key[len(key)-1] != '/' {
				key += "/"
			}
			keyBytes = s.getPrefixEndKey(util.StringToBytesWithNoCopy(key))
		}
		watchID := ws.Watch(op.Key, keyBytes, op.Revision)
		defer func() {
			if err := ws.Cancel(watchID); err != nil {
				log.Error("", err)
			}
		}()
		responses := ws.Chan()
		for {
			select {
			case <-ctx.Done():
				return
			case resp, ok := <-responses:
				if !ok {
					err = errors.New("channel is closed")
					return
				}

				err = dispatch(resp.Events, op.WatchCallback)
				if err != nil {
					return
				}
			}
		}
	}
	err = fmt.Errorf("no key has been watched")
	return
}

func (s *EtcdEmbed) readyNotify() {
	timeout := etcd.Configuration().DialTimeout
	select {
	case <-s.Embed.Server.ReadyNotify():
		close(s.ready)
		s.goroutine.Do(func(ctx context.Context) {
			select {
			case <-ctx.Done():
				return
			case err := <-s.Embed.Err():
				s.err <- err
			}
		})
	case <-time.After(timeout):
		err := fmt.Errorf("timed out(%s)", timeout)
		log.Errorf(err, "read notify failed")

		s.Embed.Server.Stop()

		s.err <- err
	}
}

func dispatch(evts []mvccpb.Event, cb client.WatchCallback) error {
	l := len(evts)
	kvs := make([]*mvccpb.KeyValue, l)
	sIdx, eIdx, rev := 0, 0, int64(0)
	action, prevEvtType := client.ActionPut, mvccpb.PUT

	for _, evt := range evts {
		if prevEvtType != evt.Type {
			if eIdx > 0 {
				err := callback(action, rev, kvs[sIdx:eIdx], cb)
				if err != nil {
					return err
				}
				sIdx = eIdx
			}
			prevEvtType = evt.Type
		}

		if rev < evt.Kv.ModRevision {
			rev = evt.Kv.ModRevision
		}
		action = setKvsAndConvertAction(kvs, eIdx, evt)

		eIdx++
	}

	if eIdx > 0 {
		return callback(action, rev, kvs[sIdx:eIdx], cb)
	}
	return nil
}

func setKvsAndConvertAction(kvs []*mvccpb.KeyValue, pIdx int, evt mvccpb.Event) client.ActionType {
	switch evt.Type {
	case mvccpb.DELETE:
		kv := evt.PrevKv
		if kv == nil {
			kv = evt.Kv
		}
		kvs[pIdx] = kv
		return client.ActionDelete
	default:
		kvs[pIdx] = evt.Kv
		return client.ActionPut
	}
}

func callback(action client.ActionType, rev int64, kvs []*mvccpb.KeyValue, cb client.WatchCallback) error {
	return cb("key information changed", &client.PluginResponse{
		Action:    action,
		Kvs:       kvs,
		Count:     int64(len(kvs)),
		Revision:  rev,
		Succeeded: true,
	})
}

func getEmbedInstance(opts client.Options) client.Registry {
	log.Warnf("enable embedded registry mode")

	hostName := "sc-0"
	if len(etcd.Configuration().ClusterName) > 0 {
		hostName = etcd.Configuration().ClusterName
	}
	mgrAddrs := "http://127.0.0.1:2380"
	if len(etcd.Configuration().ManagerAddress) > 0 {
		mgrAddrs = etcd.Configuration().ManagerAddress
	}

	inst := &EtcdEmbed{
		err:       make(chan error, 1),
		ready:     make(chan struct{}),
		goroutine: gopool.New(context.Background()),
	}

	if etcd.Configuration().SslEnabled {
		log.Info("config no use for embedded etcd")
	}

	serverCfg := embed.NewConfig()
	serverCfg.EnableV2 = false
	serverCfg.EnablePprof = false
	serverCfg.QuotaBackendBytes = etcdserver.MaxQuotaBytes
	// TODO 不支持使用TLS通信
	// 存储目录,相对于工作目录
	serverCfg.Dir = "data"
	// 集群支持
	serverCfg.Name = hostName
	serverCfg.InitialCluster = etcd.Configuration().ClusterAddresses
	// 1. 管理端口
	urls, err := parseURL(mgrAddrs)
	if err != nil {
		log.Error(`"manager_addr" field configure error`, err)
		inst.err <- err
		return inst
	}
	serverCfg.LPUrls = urls
	serverCfg.APUrls = urls
	// 2. 业务端口,关闭默认2379端口
	serverCfg.LCUrls = nil
	serverCfg.ACUrls = nil
	// 自动压缩历史, 1 hour
	serverCfg.AutoCompactionMode = compactor.ModePeriodic
	serverCfg.AutoCompactionRetention = "1h"

	log.Debugf("--initial-cluster %s --initial-advertise-peer-urls %s --listen-peer-urls %s",
		serverCfg.InitialCluster, mgrAddrs, mgrAddrs)

	etcd, err := embed.StartEtcd(serverCfg)
	if err != nil {
		log.Error("error to start etcd server", err)
		inst.err <- err
		return inst
	}
	inst.Embed = etcd

	inst.readyNotify()
	return inst
}

func parseURL(addrs string) ([]url.URL, error) {
	var urls []url.URL
	ips := strings.Split(addrs, ",")
	for _, ip := range ips {
		addr, err := url.Parse(ip)
		if err != nil {
			log.Error("Error to parse ip address string", err)
			return nil, err
		}
		urls = append(urls, *addr)
	}
	return urls, nil
}

func max(n1, n2 int64) int64 {
	if n1 > n2 {
		return n1
	}
	return n2
}


text:
/**
 * @file frac.h
 * @brief implementation of frac storage
 * @author Oleg Borschuk
 * @version
 * @date 2011-07-29
 */
#ifndef FRAC_YSG17OI0

#define FRAC_YSG17OI0

#include <string>
#include <sstream>
#include <vector>
#include <fstream>

#include "frac_iface.h"

namespace blue_sky
{

  class BS_API_PLUGIN frac : public frac_iface
    {

    public:

      typedef BS_SP (prop_iface)                      sp_prop_t;

      // ------------------------------------
      // METHODS
      // ------------------------------------
    public:
      // destructor
      virtual ~frac ()
        {}
      // ------------------------------------
      // INTERFACE METHODS
      // ------------------------------------

      /**
       * @brief return SP to the property
       */
      virtual sp_prop_t get_prop ()
        {
          return sp_prop;
        }

    public:
#ifdef BSPY_EXPORTING_PLUGIN
      /**
       * @brief python print wrapper
       *
       * @return return table description
       */
      virtual std::string py_str () const;

#endif //BSPY_EXPORTING_PLUGIN

    protected:
      void init_prop ();

      // ------------------------------
      // VARIABLES
      // ------------------------------
    protected:
      sp_prop_t sp_prop;        //!< ptoperties pointer

      BLUE_SKY_TYPE_DECL (frac);
    };

}; //end of blue_sky namespace

#endif /* end of include guard: FRAC_YSG17OI0 */

redpajama_set_name: RedPajamaGithub


text:
from .stage03_quantification_dG_f_io import stage03_quantification_dG_f_io
from .stage03_quantification_otherData_query import stage03_quantification_otherData_query
from .stage03_quantification_metid2keggid_query import stage03_quantification_metid2keggid_query
from .stage03_quantification_simulation_query import stage03_quantification_simulation_query
# Dependencies from thermodynamics
from thermodynamics.thermodynamics_dG_f_data import thermodynamics_dG_f_data
from thermodynamics.thermodynamics_otherData import thermodynamics_otherData

class stage03_quantification_dG_f_execute(stage03_quantification_dG_f_io,
                                          stage03_quantification_otherData_query,
                                          stage03_quantification_metid2keggid_query,
                                          stage03_quantification_simulation_query):
    def execute_adjust_dG_f(self,experiment_id_I,models_I,model_ids_I = [],time_points_I=[],sample_name_abbreviations_I=[]):
        '''adjust dG0_f to specified temperature, pH, and ionic strength'''

        dGf_O = [];
        # query dG0f data
        id2kegg = {};
        id2kegg = self.get_rowsDict_dataStage03QuantificationMetid2keggid();
        dG0_f = {};
        dG0_f = self.get_rowsDict_dataStage03QuantificationDG0f();
        # get the model ids:
        if model_ids_I:
            model_ids = model_ids_I;
        else:
            model_ids = [];
            model_ids = self.get_modelID_experimentID_dataStage03QuantificationSimulation(experiment_id_I);
        for model_id in model_ids:
            # get the cobra model
            cobra_model = models_I[model_id];
            # get the time-points
            if time_points_I:
                time_points = time_points_I;
            else:
                time_points = [];
                time_points = self.get_timePoints_experimentIDAndModelID_dataStage03QuantificationSimulation(experiment_id_I,model_id);
            for tp in time_points:
                # get sample_name_abbreviations
                if sample_name_abbreviations_I:
                    sample_name_abbreviations = sample_name_abbreviations_I;
                else:
                    sample_name_abbreviations = [];
                    sample_name_abbreviations = self.get_sampleNameAbbreviations_experimentIDAndModelIDAndTimePoint_dataStage03QuantificationSimulation(experiment_id_I,model_id,tp);
                for sna in sample_name_abbreviations:
                    # get otherData
                    pH,temperature,ionic_strength = {},{},{}
                    pH,temperature,ionic_strength = self.get_rowsFormatted_experimentIDAndTimePointAndSampleNameAbbreviation_dataStage03QuantificationOtherData(experiment_id_I,tp,sna);
                    # load pH, ionic_strength, and temperature parameters
                    other_data = thermodynamics_otherData(pH_I=pH,temperature_I=temperature,ionic_strength_I=ionic_strength);
                    #other_data.load_defaultData();
                    other_data.check_data();
                    # adjust dG0f to environmental conditions
                    dG_f_data = thermodynamics_dG_f_data(id2KEGGID_I=id2kegg);
                    dG_f_data.get_transformed_dG_f(dG0_f,cobra_model,other_data.pH,other_data.temperature,other_data.ionic_strength); # adjust the non-transformed dG0_f data to physiological pH, temperature, and ionic strength (this step has already been completed)
                    # upload to database for later use
                    for k,v in dG_f_data.dG_f.items():
                        compartment = k.split('_')[-1]; #compartment id is appended to the met_id
                        data_tmp={'experiment_id':experiment_id_I,
                            'model_id':model_id,
                            'sample_name_abbreviation':sna,
                            'time_point':tp,
                            'met_name':None,
                            'met_id':k,
                            'dG_f':v['dG_f'],
                            'dG_f_var':v['dG_f_var'],
                            'dG_f_units':v['dG_f_units'],
                            'dG_f_lb':None,
                            'dG_f_ub':None,
                            'temperature':temperature[compartment]['temperature'],
                            'temperature_units':temperature[compartment]['temperature_units'],
                            'ionic_strength':ionic_strength[compartment]['ionic_strength'],
                            'ionic_strength_units':ionic_strength[compartment]['ionic_strength_units'],
                            'pH':pH[compartment]['pH'],
                            'pH_units':None,
                            'measured':True,
                            'used_':True,
                            'comment_':None};
                        dGf_O.append(data_tmp);
                        #row = None;
                        #row = data_stage03_quantification_dG_f(experiment_id_I,
                        #    model_id,
                        #    sna,
                        #    tp,
                        #    None,
                        #    k,
                        #    v['dG_f'],
                        #    v['dG_f_var'],
                        #    v['dG_f_units'],
                        #    None,
                        #    None,
                        #    temperature[compartment]['temperature'],
                        #    temperature[compartment]['temperature_units'],
                        #    ionic_strength[compartment]['ionic_strength'],
                        #    ionic_strength[compartment]['ionic_strength_units'],
                        #    pH[compartment]['pH'],
                        #    None,
                        #    True,
                        #    True,
                        #    None);
                        #self.session.add(row);
        #add data to to the DB
        self.add_dataStage03QuantificationDGf(dGf_O);
        #self.session.commit();


text:
void f(void*, int); // expected-note{{candidate function}}
template<typename T>
  void f(T*, long); // expected-note{{candidate function}}

void test_f(int *ip, int i) {
  f(ip, i); // expected-error{{ambiguous}}
}


text:
package com.example.android_0100_selfimproveproject.activities;

import com.example.android_0100_selfimproveproject.Constant;
import com.example.android_0100_selfimproveproject.utils.LogUtils;

import android.app.Activity;
import android.os.Bundle;

public class BaseActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LogUtils.d(Constant.BASE_ACTIVITY_TAG, getClass().getSimpleName());
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

}


text:
void WebsiteSettingsInfoBarDelegate::Create(InfoBarService* infobar_service) {
  infobar_service->AddInfoBar(
      infobar_service->CreateConfirmInfoBar(scoped_ptr<ConfirmInfoBarDelegate>(
          new WebsiteSettingsInfoBarDelegate())));
}

WebsiteSettingsInfoBarDelegate::WebsiteSettingsInfoBarDelegate()
    : ConfirmInfoBarDelegate() {
}

WebsiteSettingsInfoBarDelegate::~WebsiteSettingsInfoBarDelegate() {
}

int WebsiteSettingsInfoBarDelegate::GetIconID() const {
  return IDR_INFOBAR_ALT_NAV_URL;
}

infobars::InfoBarDelegate::Type WebsiteSettingsInfoBarDelegate::GetInfoBarType()
    const {
  return PAGE_ACTION_TYPE;
}

base::string16 WebsiteSettingsInfoBarDelegate::GetMessageText() const {
  return l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_INFOBAR_TEXT);
}

int WebsiteSettingsInfoBarDelegate::GetButtons() const {
  return BUTTON_OK;
}

base::string16 WebsiteSettingsInfoBarDelegate::GetButtonLabel(
    InfoBarButton button) const {
  DCHECK_EQ(BUTTON_OK, button);
  return l10n_util::GetStringUTF16(IDS_WEBSITE_SETTINGS_INFOBAR_BUTTON);
}

bool WebsiteSettingsInfoBarDelegate::Accept() {
  content::WebContents* web_contents =
      InfoBarService::WebContentsFromInfoBar(infobar());
  web_contents->GetController().Reload(true);
  return true;
}


text:
package main

import (
	"flag"
	"os"

	"k8s.io/klog"

	genericapiserver "k8s.io/apiserver/pkg/server"
	"k8s.io/component-base/logs"
	"k8s.io/sample-apiserver/pkg/cmd/server"
)

func main() {
	logs.InitLogs()
	defer logs.FlushLogs()

	stopCh := genericapiserver.SetupSignalHandler()
	options := server.NewWardleServerOptions(os.Stdout, os.Stderr)
	cmd := server.NewCommandStartWardleServer(options, stopCh)
	cmd.Flags().AddGoFlagSet(flag.CommandLine)
	if err := cmd.Execute(); err != nil {
		klog.Fatal(err)
	}
}


text:
const chai           = require('chai');
const chaiAsPromised = require('chai-as-promised');

const lightscript    = require('../');

const expect         = chai.expect;

chai.use(chaiAsPromised);

describe('Functions', () => {

  describe('Standard', () => {

    describe('Declaration', () => {

      it('should produce a function with no arguments that returns', () => {
        const string = 'foo = -> 1';
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = function (it?:any) {
  return 1;
};
`);
          })
        ;
      });

      it('should produce a function with no arguments that dont returns', () => {
        const string = 'foo = !-> 1';
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = function (it?:any) {
  1;
};
`);
          })
        ;
      });
      it('should produce a function with one argument and returns it', () => {
        const string = 'foo = (a) -> a';
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = function (a) {
  return a;
};
`);
          })
        ;
      });

      it('should produce a function with multiple arguments and dont returns', () => {
        const string = 'foo = (a, b) !-> a';
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = function (a, b) {
  a;
};
`);
          })
        ;
      });

      it('should produce a function with multiple arguments returns last', () => {
        const string = `foo = (a, b) ->
  a
  b
`;
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = function (a, b) {
  a;
  return b;
};
`);
          })
        ;
      });

    });

    describe('Call', () => {

      describe('Parenthesis', () => {

        it('should produce and call for no arguments', () => {
          const string = `foo = -> 1
foo()`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = function (it?:any) {
  return 1;
};
foo();
`);
            })
          ;
        });

        it('should produce and call for one argument', () => {
          const string = `foo = (a) -> a
foo(1)`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = function (a) {
  return a;
};
foo(1);
`);
            })
          ;
        });

        it('should produce and call for multiple arguments', () => {
          const string = `foo = (a, b) -> a
foo(1, 2)`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = function (a, b) {
  return a;
};
foo(1, 2);
`);
            })
          ;
        });

      });

      describe('Spaces', () => {

        it('should produce and call for one argument', () => {
          const string = `foo = (a) -> a
foo 1`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = function (a) {
  return a;
};
foo(1);
`);
            })
          ;
        });

        it('should produce and call for multiple arguments', () => {
          const string = `foo = (a, b) -> a
foo 1, 2`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = function (a, b) {
  return a;
};
foo(1, 2);
`);
            })
          ;
        });

      });

      describe('Bang (!)', () => {

        it('should produce and call with no arguments', () => {
          const string = `foo = -> 1
foo!`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = function (it?:any) {
  return 1;
};
foo();
`);
            })
          ;
        });

      });

    });

  });

  describe('Arrow', () => {

    describe('Declaration', () => {

      it('should produce a function with no arguments that returns', () => {
        const string = 'foo = ~> 1';
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = (it?:any) => {
  return 1;
};
`);
          })
        ;
      });

      it('should produce a function with no arguments that dont returns', () => {
        const string = 'foo = !~> 1';
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = (it?:any) => {
  1;
};
`);
          })
        ;
      });
      it('should produce a function with one argument and returns it', () => {
        const string = 'foo = (a) ~> a';
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = (a) => {
  return a;
};
`);
          })
        ;
      });

      it('should produce a function with multiple arguments and dont returns', () => {
        const string = 'foo = (a, b) !~> a';
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = (a, b) => {
  a;
};
`);
          })
        ;
      });

      it('should produce a function with multiple arguments returns last', () => {
        const string = `foo = (a, b) ~>
  c = 1
  b
`;
        const promise = lightscript._transpileStringToTs(string);

        return expect(promise).to.be.fulfilled
          .then(res => {
            expect(res).to.eq(`let foo = (a, b) => {
  let c = 1;
  return b;
};
`);
          })
        ;
      });

    });

    describe('Call', () => {

      describe('Parenthesis', () => {

        it('should produce and call for no arguments', () => {
          const string = `foo = ~> 1
foo()`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = (it?:any) => {
  return 1;
};
foo();
`);
            })
          ;
        });

        it('should produce and call for one argument', () => {
          const string = `foo = (a) ~> a
foo(1)`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = (a) => {
  return a;
};
foo(1);
`);
            })
          ;
        });

        it('should produce and call for multiple arguments', () => {
          const string = `foo = (a, b) ~> a
foo(1, 2)`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = (a, b) => {
  return a;
};
foo(1, 2);
`);
            })
          ;
        });

      });

      describe('Spaces', () => {

        it('should produce and call for one argument', () => {
          const string = `foo = (a) ~> a
foo 1`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = (a) => {
  return a;
};
foo(1);
`);
            })
          ;
        });

        it('should produce and call for multiple arguments', () => {
          const string = `foo = (a, b) ~> a
foo 1, 2`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = (a, b) => {
  return a;
};
foo(1, 2);
`);
            })
          ;
        });

      });

      describe('Bang (!)', () => {

        it('should produce and call with no arguments', () => {
          const string = `foo = ~> 1
foo!`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = (it?:any) => {
  return 1;
};
foo();
`);
            })
          ;
        });

      });

    });

  });

  describe('Curry', () => {

    const curryFunc = `function curry$(f: any, bound?: any){ let context: any, _curry: any = function(args?: any){ return f.length > 1 ? function(){ var params = args ? args.concat() :[]; context = bound ? context || this : this; return params.push.apply(params, arguments) < f.length && arguments.length ? _curry.call(context, params) : f.apply(context, params); } : f; }; return _curry(); }`;

    describe('Declaration', () => {

        it('should produce a currified function', () => {
          const string = `foo = (a, b) --> 1
`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = curry$(function (a, b) {
  return 1;
});
${curryFunc}`);
            })
          ;
        });

        it('should produce a currified arrow function', () => {
          const string = `foo = (a, b) ~~> 1
`;
          const promise = lightscript._transpileStringToTs(string);

          return expect(promise).to.be.fulfilled
            .then(res => {
              expect(res).to.eq(`let foo = curry$((a, b) => {
  return 1;
});
${curryFunc}`);
            })
          ;
        });

    });

  });

});


text:
Pattern: Empty statement

Issue: -

## Description

Checks against two semi-colons with no executable code in between. Also checks against an empty PHP open - close tag combination.

## Further Reading

* [PHP_CodeSniffer - Generic.CodeAnalysis.EmptyPHPStatement](https://github.com/squizlabs/PHP_CodeSniffer/blob/master/src/Standards/Generic/Sniffs/CodeAnalysis/EmptyPHPStatementSniff.php)


text:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from ramjet.settings import (MAIL_FROM_ADDR, MAIL_HOST, MAIL_PASSWD, MAIL_PORT,
                             MAIL_USERNAME)

def send_alert(*, to_addrs, subject, content, from_addr=MAIL_FROM_ADDR):
    # FIXME: change to telegram
    return

def send_mail(*, to_addrs, subject, content, from_addr=MAIL_FROM_ADDR):
    """Send email

    Args:
        fr (string):
        to (list): receivers' addresses
    """
    smtp = smtplib.SMTP(host=MAIL_HOST, port=MAIL_PORT)
    smtp.starttls()
    smtp.login(MAIL_USERNAME, MAIL_PASSWD)

    msg = MIMEMultipart("alternative")
    msg.set_charset("utf-8")
    msg["From"] = from_addr
    msg["To"] = ", ".join(to_addrs[0].split(";"))
    msg["Subject"] = subject
    msg.attach(MIMEText(content, "plain"))
    try:
        smtp.sendmail(from_addr, to_addrs, msg.as_string())
    except Exception:
        smtp.close()
        raise

if __name__ == "__main__":
    send_alert(to_addrs=["ppcelery@gmail.com"], subject="test", content="yooo")


text:
  <form class="form-horizontal">
    <fieldset>

      <legend>Create a New Segment</legend>

        Date

          <input id="textinput" name="textinput" type="text" placeholder="ex: 1/1/2017" class="form-control input-md" ng-model="date">

        Origin

          <input id="textinput" name="textinput" type="text" placeholder="ex: Seattle, WA" class="form-control input-md" ng-model="origin">

        Destination

          <input id="textinput" name="textinput" type="text" placeholder="ex: Portland, OR" class="form-control input-md" ng-model="destination">

        Total Distance

          <input id="textinput" name="textinput" type="text" placeholder="ex: 73" class="form-control input-md" ng-model="totalDistance">

          Submit »

    </fieldset>
  </form>


text:
package net.genesishub.gFeatures.Feature.gWarsSuite.Connection;

public class Enabling {
	public void start(){
		Connection c = new Connection();
		CheckConfig cc = new CheckConfig();
		String Address, Port, Tablename, Username, Password;
		Address = cc.getAddress();
		Port = cc.getPort();
		Tablename = cc.getTablename();
		Username = cc.getUsername();
		Password = cc.getPassword();
		String URL = c.toURL(Port, Address, Tablename);
		c.checkOnline(URL, Username, Password);
		c.Connect(URL, Username, Password, "CREATE TABLE IF NOT EXISTS Kills(Name VARCHAR(200), Kills FLOAT) ENGINE=InnoDB;");
		c.Connect(URL, Username, Password, "CREATE TABLE IF NOT EXISTS Deaths(Name VARCHAR(200), Deaths FLOAT) ENGINE=InnoDB;");
	}
}


text:
// Copyright Sascha Ochsenknecht 2009.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/program_options/parsers.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/cmdline.hpp>
using namespace boost::program_options;

#include <iostream>
#include <sstream>
#include <vector>
#include <cassert>
using namespace std;

#include "minitest.hpp"

void test_ambiguous()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,c", value<string>()->multitoken(), "the config file")
        ("output,c", value<string>(), "the output file")
        ("output,o", value<string>(), "the output file")
    ;

    const char* cmdline[] = {"program", "-c", "file", "-o", "anotherfile"};

    variables_map vm;
    try {
       store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
    }
    catch (ambiguous_option& e)
    {
        BOOST_CHECK_EQUAL(e.alternatives().size(), 2);
        BOOST_CHECK_EQUAL(e.get_option_name(), "-c");
        BOOST_CHECK_EQUAL(e.alternatives()[0], "cfgfile");
        BOOST_CHECK_EQUAL(e.alternatives()[1], "output");
    }
}

void test_ambiguous_long()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,c", value<string>()->multitoken(), "the config file")
        ("output,c", value<string>(), "the output file")
        ("output,o", value<string>(), "the output file")
    ;

    const char* cmdline[] = {"program", "--cfgfile", "file", "--output", "anotherfile"};

    variables_map vm;
    try {
       store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
    }
    catch (ambiguous_option& e)
    {
        BOOST_CHECK_EQUAL(e.alternatives().size(), 2);
        BOOST_CHECK_EQUAL(e.get_option_name(), "--output");
        BOOST_CHECK_EQUAL(e.alternatives()[0], "output");
        BOOST_CHECK_EQUAL(e.alternatives()[1], "output");
    }
}

void test_ambiguous_multiple_long_names()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,foo,c", value<string>()->multitoken(), "the config file")
        ("output,foo,o", value<string>(), "the output file")
    ;

    const char* cmdline[] = {"program", "--foo", "file"};

    variables_map vm;
    try {
       store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
    }
    catch (ambiguous_option& e)
    {
        BOOST_CHECK_EQUAL(e.alternatives().size(), 2);
        BOOST_CHECK_EQUAL(e.get_option_name(), "--foo");
        BOOST_CHECK_EQUAL(e.alternatives()[0], "cfgfile");
        BOOST_CHECK_EQUAL(e.alternatives()[1], "output");
    }
}

void test_unknown_option()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,c", value<string>(), "the configfile")
      ;

   const char* cmdline[] = {"program", "-c", "file", "-f", "anotherfile"};

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
   }
   catch (unknown_option& e)
   {
      BOOST_CHECK_EQUAL(e.get_option_name(), "-f");
      BOOST_CHECK_EQUAL(string(e.what()), "unrecognised option '-f'");
   }
}

void test_multiple_values()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,c", value<string>()->multitoken(), "the config file")
        ("output,o", value<string>(), "the output file")
      ;

   const char* cmdline[] = { "program", "-o", "fritz", "hugo", "--cfgfile", "file", "c", "-o", "text.out" };

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (validation_error& e)
   {
      // TODO: this is currently validation_error, shouldn't it be multiple_values ???
      //
      //   multiple_values is thrown only at one place untyped_value::xparse(),
      //    but I think this can never be reached
      //   because: untyped_value always has one value and this is filtered before reach specific
      //   validation and parsing
      //
      BOOST_CHECK_EQUAL(e.get_option_name(), "--cfgfile");
      BOOST_CHECK_EQUAL(string(e.what()), "option '--cfgfile' only takes a single argument");
   }
}

void test_multiple_occurrences()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,c", value<string>(), "the configfile")
      ;

   const char* cmdline[] = {"program", "--cfgfile", "file", "-c", "anotherfile"};

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (multiple_occurrences& e)
   {
      BOOST_CHECK_EQUAL(e.get_option_name(), "--cfgfile");
      BOOST_CHECK_EQUAL(string(e.what()), "option '--cfgfile' cannot be specified more than once");
   }
}

void test_multiple_occurrences_with_different_names()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,config-file,c", value<string>(), "the configfile")
      ;

   const char* cmdline[] = {"program", "--config-file", "file", "--cfgfile", "anotherfile"};

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (multiple_occurrences& e)
   {
      BOOST_CHECK( (e.get_option_name() == "--cfgfile") || (e.get_option_name() == "--config-file"));
      BOOST_CHECK(
         (string(e.what()) == "option '--cfgfile' cannot be specified more than once") ||
         (string(e.what()) == "option '--config-file' cannot be specified more than once")
      );
   }
}

void test_multiple_occurrences_with_non_key_names()
{
   options_description desc;
   desc.add_options()
        ("cfgfile,config-file,c", value<string>(), "the configfile")
      ;

   const char* cmdline[] = {"program", "--config-file", "file", "-c", "anotherfile"};

   variables_map vm;
   try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                    const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (multiple_occurrences& e)
   {
       BOOST_CHECK_EQUAL(e.get_option_name(), "--cfgfile");
       BOOST_CHECK_EQUAL(string(e.what()), "option '--cfgfile' cannot be specified more than once");
   }
}

void test_missing_value()
{
    options_description desc;
    desc.add_options()
        ("cfgfile,c", value<string>()->multitoken(), "the config file")
        ("output,o", value<string>(), "the output file")
    ;
    // missing value for option '-c'
    const char* cmdline[] = { "program", "-c", "-c", "output.txt"};

    variables_map vm;

    try {
      store(parse_command_line(sizeof(cmdline)/sizeof(const char*),
                                       const_cast<char**>(cmdline), desc), vm);
      notify(vm);
   }
   catch (invalid_command_line_syntax& e)
   {
      BOOST_CHECK_EQUAL(e.kind(), invalid_syntax::missing_parameter);
      BOOST_CHECK_EQUAL(e.tokens(), "--cfgfile");
   }
}

int main(int /*ac*/, char** /*av*/)
{
   test_ambiguous();
   test_ambiguous_long();
   test_ambiguous_multiple_long_names();
   test_unknown_option();
   test_multiple_values();
   test_multiple_occurrences();
   test_multiple_occurrences_with_different_names();
   test_multiple_occurrences_with_non_key_names();
   test_missing_value();

   return 0;
}


text:
package sk.sorien.silexplugin.tests.pimple;

import com.intellij.openapi.project.Project;
import com.jetbrains.php.lang.PhpFileType;
import com.jetbrains.php.lang.psi.elements.*;
import org.jetbrains.annotations.NotNull;
import sk.sorien.silexplugin.pimple.*;
import sk.sorien.silexplugin.pimple.Parameter;
import sk.sorien.silexplugin.tests.SilexCodeInsightFixtureTestCase;

import java.io.File;

/**
 * @author Stanislav Turza
 */
public class PimplePhpTypeProviderTest extends SilexCodeInsightFixtureTestCase {

    @Override
    public void setUp() throws Exception {

        super.setUp();
        Project project = myFixture.getProject();

        // Create virtual container
        Container container = new Container(project);
        container.put(new Container("container1", project).put(new Container("container2", project).put(new Service("service1", "\\Sorien\\Service1"))));
        container.put(new Parameter("service2_class", ParameterType.STRING, "\\Sorien\\Service2"));
        container.put(new Service("service2", "\\Sorien\\Service2"));

        ContainerResolver.put(myFixture.getProject(), container);

        // Add Fixtures
        myFixture.configureFromExistingVirtualFile(myFixture.copyFileToProject("classes.php"));
    }

    @Override
    public void tearDown() throws Exception {

        ContainerResolver.remove(myFixture.getProject());
        super.tearDown();
    }

    @NotNull
    protected String getTestDataPath() {
        return new File(this.getClass().getResource("fixtures").getFile()).getAbsolutePath();
    }

    public void testTypeForArrayAccessContainer() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, ArrayAccessExpression.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$a<caret>pp['service1'];",
                "#Š#C\\Silex\\Application[service1]"
        );
    }

    public void testTypeForArrayAccessMultiContainer() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, ArrayAccessExpression.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$app['service1']['ser<caret>vice2'];",
                "#Š#C\\Silex\\Application[service1][service2]"
        );
    }

    public void testTypeForArrayAccessContainerConstantKey() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, ArrayAccessExpression.class,
                "<?php " +
                        "class Test {" +
                        "    const c = \"container1\";" +
                        "}" +
                        "$app = new \\Silex\\Application();" +
                        "$app[Test::c]['service1<caret>']",
                "#Š#C\\Silex\\Application[#K#C\\Test.c][service1]"
        );
    }

    public void testTypeForArrayAccessContainerPropertyKey() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, ArrayAccessExpression.class,
                "<?php " +
                        "class Test {" +
                        "    public $property = \"container1\";" +
                        "}" +
                        "$app = new \\Silex\\Application();" +
                        "$class = new Test();" +
                        "$app[$class->property]['service1<caret>']",
                "#Š#C\\Silex\\Application[#P#C\\Test.property][service1]"
        );
    }

    public void testTypeForArrayAccessReferencedContainer() throws Exception {

        assertPhpReferenceSignatureEquals(PhpFileType.INSTANCE, Variable.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$a = $app['container1']; " +
                        "$se<caret>rvice = $a['service1']",
                "#Š#Š#C\\Silex\\Application[container1][service1]"
        );
    }

    public void testTypeForArrayNewExpressionSignature() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, NewExpression.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$abc = new $a<caret>pp['service2_class']();",
                "#Š#C\\Silex\\Application[@service2_class]"
        );
    }

    public void testTypeForParameterFactoryMethod() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Parameter.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$app[''] = $app->factory(function ($<caret>class) {});",
                "#Š#C\\Silex\\Application"
        );
    }

    public void testTypeForParameterShareMethod() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Parameter.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$app[''] = $app->share(function ($<caret>class) {});",
                "#Š#C\\Silex\\Application"
        );
    }

    public void testTypeForParameterAnonymousFunction() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Parameter.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$app['service2'] = function ($<caret>app) {};",
                "#Š#C\\Silex\\Application"
        );
    }

    public void testTypeForParameterExtendMethodOneParameter() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Parameter.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$app[''] = $app->extend('service2', function ($<caret>class) {});",
                "#Š#C\\Silex\\Application[service2]"
        );
    }

    public void testTypeForParameterExtendMethodTwoParameters() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Parameter.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$app[''] = $app->extend('service2', function ($class, $a<caret>pplication) {});",
                "#Š#C\\Silex\\Application"
        );
    }

    public void testTypeForParameterExtendMethodSubContainer() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Parameter.class,
                "<?php " +
                        "$app = new \\Silex\\Application(); " +
                        "$app['container1']['container2']->extend('service1', function ($<caret>class) {});",
                "#Š#C\\Silex\\Application[container1][container2][service1]"
        );
    }

    public void testTypeForParameterConstKey() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Parameter.class,
                "<?php " +
                        "$app = new \\Silex\\Application();" +
                        "$app['container1']['container2']->extend(\\Sorien\\Service1::name, function ($<caret>class) {});",
                "#Š#C\\Silex\\Application[container1][container2][#K#C\\Sorien\\Service1.name]"
        );
    }

    public void testTypeForParameterPropertyKey() throws Exception {

        assertSignatureEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Parameter.class,
                "<?php " +
                        "$app = new \\Silex\\Application();" +
                        "$service2 = new \\Sorien\\Service2();" +
                        "$app->extend($service2->name, function ($<caret>class) {});",
                "#Š#C\\Silex\\Application[#P#C\\Sorien\\Service2.name]"
        );
    }

    public void testProperArrayValueTypeIfServiceCantBeResolved() throws Exception {

        assertTypeEquals(PhpFileType.INSTANCE, com.jetbrains.php.lang.psi.elements.Variable.class,
                "<?php " +
                        "class Publication  {};" +
                        "class Foo {" +
                        "    /** @var Publication[] */" +
                        "    public $publications;" +
                        "    public function collect() {" +
                        "        $<caret>a = $this->publications['test'];" +
                        "    }" +
                        "};",
                "\\Publication"
        );
    }

    public void testResolveSignatureToPhpClass() throws Exception {

//        assertSignatureEqualsType("#Š#C\\Silex\\Application[c1]", "\\Pimple");
//        assertSignatureEqualsType("#Š#C\\Silex\\Application[c1][c2]", "\\Pimple");
        assertSignatureEqualsType("#Š#C\\Silex\\Application[@service2_class]", "\\Sorien\\Service2");
        assertSignatureEqualsType("#Š#C\\Silex\\Application[container1][container2][service1]", "\\Sorien\\Service1");
        assertSignatureEqualsType("#Š#C\\Silex\\Application[container1][container2][#K#C\\Sorien\\Service1.name]", "\\Sorien\\Service1");
        assertSignatureEqualsType("#Š#C\\Silex\\Application[#P#C\\Sorien\\Service2.name]", "\\Sorien\\Service2");
    }
}


text:
using MZBlog.Core;
using MZBlog.Core.Cache;
using MZBlog.Core.ViewProjections.Home;
using MZBlog.Web.Features;
using MZBlog.Web.Responses;
using System;

namespace MZBlog.Web.Modules
{
    public class RssModule : BaseNancyModule
    {
        private readonly IViewProjectionFactory _viewProjectionFactory;

        private readonly ICache _cache;

        public RssModule(IViewProjectionFactory viewProjectionFactory, ICache cache)
        {
            _viewProjectionFactory = viewProjectionFactory;
            _cache = cache;

            Get["/rss"] = _ => GetRecentPostsRss();
        }

        private dynamic GetRecentPostsRss()
        {
            var cacheKey = "rss";
            var rss = _cache.Get<RssResponse>(cacheKey);
            if (rss == null)
            {
                var recentPosts = _viewProjectionFactory.Get<RecentBlogPostsBindingModel, RecentBlogPostsViewModel>(new RecentBlogPostsBindingModel()
                {
                    Page = 1,
                    Take = 30
                });

                rss = new RssResponse(recentPosts.Posts, Settings.WebsiteName, new Uri(AppConfiguration.Current.SiteUrl));
                _cache.Add(cacheKey, rss, 60 * 5);
            }
            return rss;
        }
    }
}


text:
% Contact ythomas@csail.mit.edu or msabuncu@csail.mit.edu for bugs or questions
%
%=========================================================================
%
%  Copyright (c) 2008 Thomas Yeo and Mert Sabuncu
%  All rights reserved.
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions are met:
%
%    * Redistributions of source code must retain the above copyright notice,
%      this list of conditions and the following disclaimer.
%
%    * Redistributions in binary form must reproduce the above copyright notice,
%      this list of conditions and the following disclaimer in the documentation
%      and/or other materials provided with the distribution.
%
%    * Neither the names of the copyright holders nor the names of future
%      contributors may be used to endorse or promote products derived from this
%      software without specific prior written permission.
%
%THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
%ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
%WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
%DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
%ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
%(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
%LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
%ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
%SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%
%=========================================================================
function averaged_data = MARS_simpleAverageData(mesh, data, sigma_sq)
%function averaged_data = MARS_simpleAverageData(mesh, data, sigma_sq)

my_flag = 0;
if (ndims(data) == 3)
    [k l m] = size(data);
    data = reshape(data, [k*l, m]);
    my_flag = 1;
end

if (size(sigma_sq,1) ~= 1)
    sigma_sq = sigma_sq(1);
end

averaged_data = MARS_simpleAverageDataAux(mesh.vertices, mesh.vertexNbors, single(data), single(sigma_sq));

if (my_flag == 1)
    averaged_data = reshape(averaged_data, [k l m]);
end

return;


text:
"""

    This file defines the LSTM layer of the neural network.

"""

import theano
from theano import tensor
from util import numpy_floatX

def lstm_unmasked_layer(tparams, state_below, options, prefix='lstm', mult=1, go_backwards=False):
    """

    :param tparams:
    :param state_below:
    :param options:
    :param prefix:
    :return:
    """
    nsteps = state_below.shape[0]
    if state_below.ndim == 3:
        n_samples = state_below.shape[1]
    else:
        n_samples = 1

    def _slice(_x, n, dim):
        if _x.ndim == 3:
            return _x[:, :, n * dim:(n + 1) * dim]
        return _x[:, n * dim:(n + 1) * dim]

    def _p(pp, name):
        return '%s_%s' % (pp, name)

    def _step(x_, h_, c_):

        preact = tensor.dot(h_, tparams[_p(prefix, 'U')])
        preact += x_

        i = tensor.nnet.sigmoid(_slice(preact, 0, options['dim_proj']*mult))
        f = tensor.nnet.sigmoid(_slice(preact, 1, options['dim_proj']*mult))
        o = tensor.nnet.sigmoid(_slice(preact, 2, options['dim_proj']*mult))
        c = tensor.tanh(_slice(preact, 3, options['dim_proj']*mult))

        c = f * c_ + i * c

        h = o * tensor.tanh(c)

        return h, c

    state_below = (tensor.dot(state_below, tparams[_p(prefix, 'W')]) +
                   tparams[_p(prefix, 'b')])

    dim_proj = options['dim_proj']*mult
    rval, updates = theano.scan(_step,
                                sequences=[state_below],
                                outputs_info=[tensor.cast(tensor.alloc(numpy_floatX(0.),
                                                           n_samples,
                                                           dim_proj), theano.config.floatX),
                                              tensor.cast(tensor.alloc(numpy_floatX(0.),
                                                           n_samples,
                                                           dim_proj), theano.config.floatX)],
                                name=_p(prefix, '_layers'),
                                n_steps=nsteps,
                                go_backwards=go_backwards)
    return rval[0]

def lstm_layer(tparams, state_below, options, prefix='lstm', mask=None, go_backwards=False, mult=1):
    """

    :param tparams:
    :param state_below:
    :param options:
    :param prefix:
    :param mask:
    :return:
    """
    nsteps = state_below.shape[0]
    if state_below.ndim == 3:
        n_samples = state_below.shape[1]
    else:
        n_samples = 1

    assert mask is not None

    def _slice(_x, n, dim):
        if _x.ndim == 3:
            return _x[:, :, n * dim:(n + 1) * dim]
        return _x[:, n * dim:(n + 1) * dim]

    def _p(pp, name):
        return '%s_%s' % (pp, name)

    def _step(m_, x_, h_, c_):

        preact = tensor.dot(h_, tparams[_p(prefix, 'U')])
        preact += x_

        i = tensor.nnet.sigmoid(_slice(preact, 0, options['dim_proj']))
        f = tensor.nnet.sigmoid(_slice(preact, 1, options['dim_proj']))
        o = tensor.nnet.sigmoid(_slice(preact, 2, options['dim_proj']))
        c = tensor.tanh(_slice(preact, 3, options['dim_proj']))

        c = f * c_ + i * c
        c = m_[:, None] * c + (1. - m_)[:, None] * c_

        h = o * tensor.tanh(c)
        h = m_[:, None] * h + (1. - m_)[:, None] * h_

        return h, c

    state_below = (tensor.dot(state_below, tparams[_p(prefix, 'W')]) +
                   tparams[_p(prefix, 'b')])

    dim_proj = options['dim_proj'] * mult
    rval, updates = theano.scan(_step,
                                sequences=[mask, state_below],
                                outputs_info=[tensor.alloc(numpy_floatX(0.),
                                                           n_samples,
                                                           dim_proj),
                                              tensor.alloc(numpy_floatX(0.),
                                                           n_samples,
                                                           dim_proj)],
                                name=_p(prefix, '_layers'),
                                n_steps=nsteps, go_backwards=go_backwards)
    return rval[0]

def bidirectional_lstm_layer(tparams, state_below, options, prefix='lstm', mask=None, mult=1):

    def _p(pp, name):
        return '%s_%s' % (pp, name)

    prefix_forwards = '%s_forwards' % (prefix,)
    prefix_backwards = '%s_backwards' % (prefix,)

    if mask is not None:
        forwards = lstm_layer(tparams, state_below, options, prefix=prefix_forwards, mask=mask, go_backwards=False, mult=mult)
        backwards = lstm_layer(tparams, state_below, options, prefix=prefix_backwards, mask=mask, go_backwards=True, mult=mult)
    else:
        forwards = lstm_unmasked_layer(tparams, state_below, options, prefix=prefix_forwards, mult=mult, go_backwards=False)
        backwards = lstm_unmasked_layer(tparams, state_below, options, prefix=prefix_backwards, mult=mult, go_backwards=True)

    #forwards = theano.printing.Print(prefix_forwards, attrs=["shape"])(forwards)
    #backwards = theano.printing.Print(prefix_forwards, attrs=["shape"])(backwards)

    return forwards + backwards


text:
package ca.uwaterloo.Lab4_204_08;

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

import mapper.InterceptPoint;
import mapper.LineGraphView;
import mapper.MapLoader;
import mapper.MapView;
import mapper.NavigationalMap;
import mapper.PositionListener;
import android.R.interpolator;
import android.annotation.TargetApi;
import android.graphics.PointF;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends ActionBarActivity {

	public static AccelerationSensor aSensor;
	public static float storedAccel[] = new float[3];
	public static MagneticSensor mSensor;
	public static CalculateDisplacement getDisplacement;
	public static int count = 0;
	public static int azimuth = 0;
	public static LineGraphView graph;
	public static MapView mapView;
	static State state = State.WAIT;
	public static PointF setStartPoint = new PointF();
	public static PointF setEndPoint = new PointF();
	public static NavigationalMap map;
	public static List<InterceptPoint> intersectionList = new ArrayList<InterceptPoint>();
	public static List<PointF> pathList = new ArrayList<PointF>();
	public static PositionListener listener;
	public static PathFinding pathFinder;
	public String fileName = "Lab-room-unconnected.svg";
	public static Compass myCompass;

	public enum State {
		WAIT, RISING, PEAK, FALLING, NEGFALLING, TROUGH, NEGRISING
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		mapView.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		return super.onContextItemSelected(item)
				|| mapView.onContextItemSelected(item);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		graph = new LineGraphView(getApplicationContext(), 100, Arrays.asList(
				"PITCH", "ROLL", "AZIMUTH"));
		graph.setVisibility(View.VISIBLE);

		mapView = new MapView(getApplicationContext(), 1000, 1000, 55, 55);
		registerForContextMenu(mapView);

		map = MapLoader.loadMap(getExternalFilesDir(null), this.fileName);
		mapView.setMap(map);
		if (fileName == "Lab-room-peninsula.svg") {
			mapView.setWayPoint1((float) 3.5, (float) 9.5);
			mapView.setWayPoint2((float) 7.5, (float) 9.5);
			mapView.setWayPoint3((float) 11.5, (float) 9.5);
			mapView.setWayPoint4((float) 15.75, (float) 9.5);
		} else if (fileName == "Lab-room-unconnected.svg") {
			mapView.setWayPoint1((float) 3.5, (float) 9.5);
			mapView.setWayPoint2((float) 7.5, (float) 9.5);
			mapView.setWayPoint3((float) 11.5, (float) 9.5);
			mapView.setWayPoint4((float) 15.75, (float) 9.5);
			mapView.setWayPoint5((float) 3.5, (float) 5.5);
			mapView.setWayPoint6((float) 7.5, (float) 5.5);
			mapView.setWayPoint7((float) 11.5, (float) 5.5);
			mapView.setWayPoint8((float) 15.75, (float) 5.5);
		}
		myCompass = new Compass(getApplicationContext());
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
					.add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			getDisplacement.xDisplacement = 0;
			getDisplacement.yDisplacement = 0;
			getDisplacement.newX = 0;
			getDisplacement.newY = 0;
			getDisplacement.count = 0;
			getDisplacement.totalDegree = 0;
			getDisplacement.totalDisplacement = 0;
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {

			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);

			LinearLayout layout = (LinearLayout) rootView
					.findViewById(R.id.layout);
			TextView accelerationReading = new TextView(rootView.getContext());
			TextView magneticReading = new TextView(rootView.getContext());
			TextView orientationReading = new TextView(rootView.getContext());
			TextView stepReading = new TextView(rootView.getContext());
			TextView stepDetail = new TextView(rootView.getContext());
			TextView test = new TextView(rootView.getContext());
			TextView pointView = new TextView(rootView.getContext());
			TextView pathInfo = new TextView(rootView.getContext());
			CharSequence text = "You have hit the wall";
			int duration = Toast.LENGTH_SHORT;
			Toast wallHit = Toast.makeText(rootView.getContext(), text,
					duration);
			layout.addView(orientationReading);
			layout.addView(stepReading);
			// layout.addView(stepDetail);
			// layout.addView(test);
			// layout.addView(pointView);
			layout.addView(pathInfo);
			layout.addView(mapView);
			layout.addView(myCompass);

			SensorManager sensorManager = (SensorManager) rootView.getContext()
					.getSystemService(SENSOR_SERVICE);

			Sensor accelerationSensor = sensorManager
					.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

			Sensor magneticSensor = sensorManager
					.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

			Sensor linearAccelerationSensor = sensorManager
					.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);

			aSensor = new AccelerationSensor(accelerationReading);

			mSensor = new MagneticSensor(magneticReading);

			getDisplacement = new CalculateDisplacement(storedAccel,
					stepReading, state, aSensor.valuesAcceleration,
					mSensor.valuesMagneticField, orientationReading, test,
					mapView, map, wallHit, myCompass);

			getDisplacement.setStepListener(new StepListener() {
				@Override
				public void onStepMade(PointF userPoint) {
					mapView.setUserPoint(userPoint);
					pathFinder.findPath();
				}
			});

			sensorManager.registerListener(getDisplacement, accelerationSensor,
					SensorManager.SENSOR_DELAY_NORMAL);

			sensorManager.registerListener(getDisplacement, magneticSensor,
					SensorManager.SENSOR_DELAY_NORMAL);

			sensorManager.registerListener(getDisplacement,
					linearAccelerationSensor,
					SensorManager.SENSOR_DELAY_FASTEST);

			mapView.setUserPoint((float) getDisplacement.xDisplacement,
					(float) getDisplacement.yDisplacement);

			pathFinder = new PathFinding(pathList, mapView, map, pathInfo,
					wallHit);

			return rootView;
		}

	}
}


text:
package org.apereo.cas.authentication.principal;

/**
 * This is {@link ClientCustomPropertyConstants}.
 *
 * @author Misagh Moayyed
 * @since 6.0.0
 */
public interface ClientCustomPropertyConstants {
    /**
     * Property to indicate the principal attribute used for profile creation.
     */
    String CLIENT_CUSTOM_PROPERTY_PRINCIPAL_ATTRIBUTE_ID = "principalAttributeId";

    /**
     * Property to indicate whether auto-redirect should execute for this client.
     */
    String CLIENT_CUSTOM_PROPERTY_AUTO_REDIRECT = "autoRedirect";
}


text:
<!doctype html>

		<title>Test page - Sprites</title>
		<link rel="stylesheet" href="./stylesheets/style.css" />

				<button data-icon="accept">Accept</button>
				<button data-icon="add">Add</button>
				<button data-icon="anchor">Anchor</button>
				<button data-icon="application">Application</button>
				<button data-icon="application_form">Application Form</button>
				<button data-icon="application_lightning">Application Lightning</button>


text:
package manager

import (
	"strings"
	"testing"

	"github.com/docker/cli/cli/config"
	"github.com/docker/cli/cli/config/configfile"
	"github.com/docker/cli/internal/test"
	"github.com/spf13/cobra"
	"gotest.tools/v3/assert"
	"gotest.tools/v3/fs"
)

func TestListPluginCandidates(t *testing.T) {
	// Populate a selection of directories with various shadowed and bogus/obscure plugin candidates.
	// For the purposes of this test no contents is required and permissions are irrelevant.
	dir := fs.NewDir(t, t.Name(),
		fs.WithDir(
			"plugins1",
			fs.WithFile("docker-plugin1", ""),                        // This appears in each directory
			fs.WithFile("not-a-plugin", ""),                          // Should be ignored
			fs.WithFile("docker-symlinked1", ""),                     // This and ...
			fs.WithSymlink("docker-symlinked2", "docker-symlinked1"), // ... this should both appear
			fs.WithDir("ignored1"),                                   // A directory should be ignored
		),
		fs.WithDir(
			"plugins2",
			fs.WithFile("docker-plugin1", ""),
			fs.WithFile("also-not-a-plugin", ""),
			fs.WithFile("docker-hardlink1", ""),                     // This and ...
			fs.WithHardlink("docker-hardlink2", "docker-hardlink1"), // ... this should both appear
			fs.WithDir("ignored2"),
		),
		fs.WithDir(
			"plugins3-target", // Will be referenced as a symlink from below
			fs.WithFile("docker-plugin1", ""),
			fs.WithDir("ignored3"),
			fs.WithSymlink("docker-brokensymlink", "broken"),           // A broken symlink is still a candidate (but would fail tests later)
			fs.WithFile("non-plugin-symlinked", ""),                    // This shouldn't appear, but ...
			fs.WithSymlink("docker-symlinked", "non-plugin-symlinked"), // ... this link to it should.
		),
		fs.WithSymlink("plugins3", "plugins3-target"),
		fs.WithFile("/plugins4", ""),
		fs.WithSymlink("plugins5", "plugins5-nonexistent-target"),
	)
	defer dir.Remove()

	var dirs []string
	for _, d := range []string{"plugins1", "nonexistent", "plugins2", "plugins3", "plugins4", "plugins5"} {
		dirs = append(dirs, dir.Join(d))
	}

	candidates, err := listPluginCandidates(dirs)
	assert.NilError(t, err)
	exp := map[string][]string{
		"plugin1": {
			dir.Join("plugins1", "docker-plugin1"),
			dir.Join("plugins2", "docker-plugin1"),
			dir.Join("plugins3", "docker-plugin1"),
		},
		"symlinked1": {
			dir.Join("plugins1", "docker-symlinked1"),
		},
		"symlinked2": {
			dir.Join("plugins1", "docker-symlinked2"),
		},
		"hardlink1": {
			dir.Join("plugins2", "docker-hardlink1"),
		},
		"hardlink2": {
			dir.Join("plugins2", "docker-hardlink2"),
		},
		"brokensymlink": {
			dir.Join("plugins3", "docker-brokensymlink"),
		},
		"symlinked": {
			dir.Join("plugins3", "docker-symlinked"),
		},
	}

	assert.DeepEqual(t, candidates, exp)
}

func TestGetPlugin(t *testing.T) {
	dir := fs.NewDir(t, t.Name(),
		fs.WithFile("docker-bbb", `
#!/bin/sh
echo '{"SchemaVersion":"0.1.0"}'`, fs.WithMode(0o777)),
		fs.WithFile("docker-aaa", `
#!/bin/sh
echo '{"SchemaVersion":"0.1.0"}'`, fs.WithMode(0o777)),
	)
	defer dir.Remove()

	cli := test.NewFakeCli(nil)
	cli.SetConfigFile(&configfile.ConfigFile{CLIPluginsExtraDirs: []string{dir.Path()}})

	plugin, err := GetPlugin("bbb", cli, &cobra.Command{})
	assert.NilError(t, err)
	assert.Equal(t, plugin.Name, "bbb")

	_, err = GetPlugin("ccc", cli, &cobra.Command{})
	assert.Error(t, err, "Error: No such CLI plugin: ccc")
	assert.Assert(t, IsNotFound(err))
}

func TestListPluginsIsSorted(t *testing.T) {
	dir := fs.NewDir(t, t.Name(),
		fs.WithFile("docker-bbb", `
#!/bin/sh
echo '{"SchemaVersion":"0.1.0"}'`, fs.WithMode(0o777)),
		fs.WithFile("docker-aaa", `
#!/bin/sh
echo '{"SchemaVersion":"0.1.0"}'`, fs.WithMode(0o777)),
	)
	defer dir.Remove()

	cli := test.NewFakeCli(nil)
	cli.SetConfigFile(&configfile.ConfigFile{CLIPluginsExtraDirs: []string{dir.Path()}})

	plugins, err := ListPlugins(cli, &cobra.Command{})
	assert.NilError(t, err)

	// We're only interested in the plugins we created for testing this, and only
	// if they appear in the expected order
	var names []string
	for _, p := range plugins {
		if p.Name == "aaa" || p.Name == "bbb" {
			names = append(names, p.Name)
		}
	}
	assert.DeepEqual(t, names, []string{"aaa", "bbb"})
}

func TestErrPluginNotFound(t *testing.T) {
	var err error = errPluginNotFound("test")
	err.(errPluginNotFound).NotFound()
	assert.Error(t, err, "Error: No such CLI plugin: test")
	assert.Assert(t, IsNotFound(err))
	assert.Assert(t, !IsNotFound(nil))
}

func TestGetPluginDirs(t *testing.T) {
	cli := test.NewFakeCli(nil)

	pluginDir, err := config.Path("cli-plugins")
	assert.NilError(t, err)
	expected := append([]string{pluginDir}, defaultSystemPluginDirs...)

	var pluginDirs []string
	pluginDirs, err = getPluginDirs(cli)
	assert.Equal(t, strings.Join(expected, ":"), strings.Join(pluginDirs, ":"))
	assert.NilError(t, err)

	extras := []string{
		"foo", "bar", "baz",
	}
	expected = append(extras, expected...)
	cli.SetConfigFile(&configfile.ConfigFile{
		CLIPluginsExtraDirs: extras,
	})
	pluginDirs, err = getPluginDirs(cli)
	assert.DeepEqual(t, expected, pluginDirs)
	assert.NilError(t, err)
}


text:
[![Travis status](https://secure.travis-ci.org/smartlogic/raddocs.png)](https://secure.travis-ci.org/smartlogic/raddocs)

# Raddocs

Raddocs is a browser for JSON outputted by the [rspec_api_documentation](http://github.com/zipmark/rspec_api_documentation) gem.

## Install

`Gemfile`
```ruby
gem 'raddocs'
```

`config/routes.rb`

```ruby
  mount Raddocs::App => "/docs"
```

Make sure RspecApiDocumentation is generating JSON:

`spec/spec_helper.rb`

```ruby
RspecApiDocumentation.configure do |config|
  config.format = :json
end
```

## Configuration
* `api_name` - Name of the API on the example index page
* `docs_dir` - where the JSON output from rspec_api_documentation is located
* `docs_mime_type` - if you use the middleware, what mime type are you serving your docs as, must be a regex. eg: `/text\/vnd.org.oestrich.raddocs\+plain/`
* `include_bootstrap` - Boolean to disable including bootstrap if you are using your own css
* `external_css` - Array of css files to include, with a full URL to them

### Custom CSS

You can include extra css by the config option `external_css` or add a directory to the docs dir named `styles`. Every css file in the styles dir will be included as a link element on all pages.


text:
import React, {Component} from 'react';
import TextField from 'material-ui/TextField';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

class SearchField extends Component {
    render() {
        return (
            <form>
                <TextField placeholder="Search for video"/>
            </form>
        );
    }
}

class Search extends Component {
    render() {
        return (
<MuiThemeProvider><SearchField/></MuiThemeProvider>
)
    }
}

export default Search;


text: Web Application for listing the ward wise voters includes listing, search, etc.


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Script filterSeizeDistribution.m
%
% Description: Filter the seizure distribution during seizure dynamics of
% each of the seizure. Then create plots to allow for computing it
%
% Then plot histogram over time
%
% Output:   no output returned.
%
% Author: Adam Li
%
% Ver.: 1.0 - Date: 09/22/2015
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all
clear
%% 01: Create Settings
Patient = 'PY05N004';
FreqBand = 'high';
FreqBands = {'alpha', 'beta', 'gamma', 'high'};
% szindices = [70 73 77 79];
% szindices = [61 74 81]; %PY04N007
szindices = {'124A', '124B', '125'}; %PY05N004
% szindices = {'762' '767' '777' '780' '783' '801'}; %PY04N013
% szindices = {'8', '20'}; %PY04N008

szclusters = 6;
distanceFunc = 'cosine'; %or cityblock, correlation, sqeuclidean
options = statset('MaxIter', 3000);

mattype = 'q'; % q, or pwr_q
if strcmp(mattype, 'pwr_q')
    mat = 'pwr_'
else
    mat = ''
end

eval(['Subject = ' 'Patient;'])

%% 02: Add Directory Paths and load related Mat files
% addpath('/home/adamli/MATLAB/code_adam/burns_adapted/MatFiles')
% addpath(strcat('/home/adamli/MATLAB/code_adam/burns_adapted/cluster/', FreqBand))
% addpath(strcat('/home/adamli/MATLAB/code_adam/burns_adapted/EVC/', FreqBand))

% addpath(strcat('/Users/adam2392/Documents/MATLAB/Johns Hopkins/epilepsy/code_adam/burns_adapted/EVC/', FreqBand))
% addpath(strcat('/Users/adam2392/Documents/MATLAB/Johns Hopkins/epilepsy/code_adam/burns_adapted/cluster/', FreqBand))
% addpath('/Users/adam2392/Documents/MATLAB/Johns Hopkins/epilepsy/code_adam/burns_adapted/MatFiles')

disp('Manually code in the index of the seizure centroids!')
disp('Look at 2nd for loop "load in centroids and idx values of seizure"')

%% 03: Load in Clu7ster data to do ictal analysis
% loop through FreqBands
for j=1:length(FreqBands)
    FreqBand = FreqBands{j}
    addpath(strcat('/home/adamli/MATLAB/code_adam/burns_adapted/cluster'))
%     addpath(strcat('/Users/adam2392/Documents/MATLAB/Johns Hopkins/epilepsy/code_adam/burns_adapted/cluster/', FreqBand))
    for i=1:length(szindices)
        seizurenum = szindices{i};
        window = '600';
        %%%%% Load in preictal cluster files from GapStat.m
        eval(['load ', 'cluster', seizurenum, '_', Patient, '_', FreqBand, window])

        % load in the centriods and idx values of seizure
        szcents = clusterAllCents;%clusterAllCents(2:2+5,:); % get the 2nd -> 7th column in centroid matrix
        szidx = clusterAllIDX; %clusterAllIDX(601:end-600);

        % rescale szidx to uniform length
        clusterdursz = size(szidx, 1);

        % create evenly spacedintervals
        totallen = 250; % total length of the area of analysis (e.g. 500 seconds)
        intervalsz = transpose(linspace(1, clusterdursz, totallen));   % create an interval of 500 points

        %%% scale the seizure
        if clusterdursz ~= totallen %%%% Scale up and interpolate
           newszidx = (round(interp1(1:clusterdursz, szidx, intervalsz, 'linear')));
        end

        A = figure(j);
        a = subplot(length(szindices), 2, 2*i-1);
        plot(newszidx)
        title([FreqBand ' band | time scaled seizure states for seizure#: ' seizurenum])
        ylim([0 9]);
        ax = gca;
        ax.YTick = [0 1 2 3 4 5 6 7 8 9];
        xlabel('seconds')
        ylabel('seizure states')

        %% 03b: Filter when the states change
        if strcmp(Patient, 'PY04N013')
            if strcmp(FreqBand, 'alpha')
                medfilteredidx = medfilt1(newszidx, 50);
            else
                medfilteredidx = medfilt1(newszidx, 40);
            end
        else
            medfilteredidx = medfilt1(newszidx, 40);
        end

        figure(j)
%         B = figure(length(FreqBands)+j);
        b = subplot(length(szindices),2,2*i);
        fig = gcf;
        plot(medfilteredidx)
        title([FreqBand ' band | median filtered states for seizure#: ' seizurenum])
        ylim([0 9]);
        ax = gca;
        ax.YTick = [0 1 2 3 4 5 6 7 8 9];
        xlabel('seconds')
        ylabel('seizure states')

        % store median filtered seizure distrib. in a struct
        field = strcat('seizure_', seizurenum);
        freq.(field).filteredidx = medfilteredidx;
        freq.(field).originalidx = newszidx;
        freq.(field).szcents = szcents;
    end
    % save figure as .fig
    saveas(A, strcat(Patient, '_', FreqBand, '.fig'))

    % store this corresponding frequency band's struct
    eval([FreqBand ' = freq;']);
end

filename = strcat(Patient, '_seizureDistribution');
save(filename, FreqBands{:});

%% Optional
% for i=1:length(szindices)
%     % load in the preictal centroids from the +/- 10 min
%     window = '600';
%     %%%%% Load in preictal EVC files from MakeQ2.m
%     eval(['load ', mat, 'q' num2str(szindices(i)) 'sz_', Patient, '_', window])
%     eval(['szdata = q' num2str(szindices(i)) 'sz;'])
%
%     disp('Loaded ictal EVC')
%
%     szclusters = 5; % 5 seizure states
%     [szidx, szcents] = kmeans(szdata, szclusters, 'Distance', distanceFunc, 'Options', options);
%     szdistances = pdist(szcents, 'cosine');
%     szdistances = squareform(szdistances);
%
%     %%% Get the most different state from the rest
%     [ii,jj] = sort(szdistances,2,'descend');
%     v = ii(:,1);    % get the most different state's distance
%     idx = jj(:,1);  % get the row/column it is in (state)
%     iter = 0;
%     % loop k-means alg. to make sure there is 1 "very" different state
%     while length(unique(idx)) > 2
%         iter = iter+1;
%         [preidx, szcents] = kmeans(predata, 5, 'Distance', distanceFunc, 'Options', options);
%         szdistances = pdist(szcents, 'cosine');
%         szdistances = squareform(szdistances);
%
%         [ii,jj] = sort(szdistances,2,'descend');
%         v = ii(:,1);
%         idx = jj(:,1);
%     end
%     unique(idx)
% %
%     figure(length(szindices)+i);
%     imagesc(szdistances)
%
%     %% 04: Determine which state corresponds to the most different state
%     % load in the preictal EVC's of 7200
%     % qpre
%     eval(['load ', mat, 'q' num2str(szindices(i)) 'pre_', Patient, '_', '7200;'])
%     eval(['predata = q' num2str(szindices(i)) 'pre;'])
%
% %     predata = predata(end-3600:end,:);
%
%     %%% Build a KD-tree to perform nearest neighbor search based on the
%     %%% Unsupervised PreCentroids
%     mdl = createns(szcents, 'NSMethod', 'kdtree', 'Distance', 'minkowski', 'BucketSize', 80);
%     newprecluster = knnsearch(mdl, predata, 'K', 1);
%
%     % Create the spike train based on that
%     hypostate = mode(idx); % store the state that is most different
%     spiketrain = newprecluster == hypostate;
%     step = 7200/200;
%     for j=1:length(spiketrain)/step
%        firingrate(j) = sum(spiketrain(j:j+step))/step;
%     end
%
%     A = figure(i);
%     a = subplot(4, 1, 1);
%     plot(preidx)
%     title(['the original unsupervised clusters of preictal state seizure: ', num2str(szindices(i))])
%
%     b = subplot(4, 1, 2);
%     plot(newprecluster)
%     title(['the new clusters of preictal state 7200 seconds out'])
%
%     c = subplot(4, 1, 3);
%     plot(spiketrain)
%     title(['The spike train (How often "most different" state occurs) '])
%
%     d = subplot(4, 1, 4);
%     plot(firingrate)
%     title(['the firing rate over window of 30 seconds '])
%
%     saveas(A, [num2str(szindices(i)) 'spikeTrainCluster_' FreqBand '.bmp'])
%
%     clear firingrate spiketrain hypostate newprecluster preidx
% end


text:
"""
    This package contains SQLAlchemy model classes
"""

from .genre import Genre
from .image import Image
from .record import Record, RecordFlag
from .scan import Scan, scan_records
from .export import Export
from setting import Setting

# This allows `from models import *` for simple create_all/drop_all
__all__ = ['Genre', 'Image', 'Record', 'RecordFlag', 'Scan', 'scan_records',
           'Export', 'Setting']


text:
import smtplib, platform,os
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from config import Config

class MailType:
    NOTIFY = 1
    REPORT = 2

class MailBuilder:
    """MailBuilder build and send email"""
    def __init__(self, type = MailType.NOTIFY):
        self.config = Config.get_mailconfig()
        self.send_from = 'root@tur.tancoder.com'
        self.send_to = self.config["recipients"]
        self.type = type
        self.build_subject()
        self.is_body_built = False

    def build_subject(self):
        """Put email subject according to email type, usually don't need to directly execute"""
        if self.type == MailType.NOTIFY:
            self.subject = 'EMERGENCY Infomation From LocalBitcoin'
        elif self.type == MailType.REPORT:
            self.subject = 'Daily Report From LocalBitcoin'

    def build_body(self, text = ''):
        """Build context and attachment according to input text and mail type"""
        self.attachment = []
        if self.type == MailType.NOTIFY:
            self.body_text = 'Hi,\n\nYou need to take care of the following infomation:\n\n' + text
        elif self.type == MailType.REPORT:
            self.body_text = 'Hi,\n\nThis is the daily report from LocalBitcoin.com.'
            self.attachment.append(Config.configs['xlsx']['filename'])
        self.is_body_built = True

    def build_body_by():
        pass # TODO

    def send(self):
        """Send email if this program running on Linux or print a message"""
        if self.is_body_built:
            for recipient in self.send_to:
                if platform.system() == "Windows":
                    print 'send mail: ', self.send_from, recipient, self.subject, self.body_text, self.attachment
                else:
                    self.send_mail(self.send_from, recipient, self.subject, self.body_text, self.attachment)
            return True
        else:
            return False

    def send_mail(self, send_from, send_to, subject, text, files=None, server="localhost"):
        """Use smtp to send email"""
        msg = MIMEMultipart()
        msg['From'] = send_from
        msg['To'] = send_to
        msg['Date'] = formatdate(localtime=True)
        msg['Subject'] = subject

        msg.attach(MIMEText(text))

        for fbasename in files or []:
            filepath = os.path.join(self.config['path'],'doc',fbasename)
            with open(filepath, "rb") as fil:
                part = MIMEApplication(
                    fil.read(),
                    Name=fbasename
                )
            # After the file is closed
            part['Content-Disposition'] = 'attachment; filename="%s"' % fbasename
            msg.attach(part)

        smtp = smtplib.SMTP(server)
        smtp.sendmail(send_from, send_to, msg.as_string())
        smtp.close()


text:
using System;

namespace LibGit2Sharp.Core.Handles
{
    internal class NullRepositorySafeHandle : SafeHandleBase
    {
        public NullRepositorySafeHandle()
        {
            handle = IntPtr.Zero;
        }

        protected override bool ReleaseHandleImpl()
        {
            // Nothing to release
            return true;
        }
    }
}


text:
#include "test_precomp.hpp"

using namespace cv;
using namespace std;

class Core_ConcatenationTest : public cvtest::BaseTest
{
public:
    Core_ConcatenationTest(bool horizontal, bool firstEmpty, bool secondEmpty);
protected:
    int prepare_test_case( int );
    void run_func();
    int validate_test_results( int );

    Mat mat0x5;
    Mat mat10x5;
    Mat mat20x5;

    Mat mat5x0;
    Mat mat5x10;
    Mat mat5x20;

    Mat result;

    bool horizontal;
    bool firstEmpty;
    bool secondEmpty;

private:
    static bool areEqual(const Mat& m1, const Mat& m2);

};

Core_ConcatenationTest::Core_ConcatenationTest(bool horizontal_, bool firstEmpty_, bool secondEmpty_)
    : horizontal(horizontal_)
    , firstEmpty(firstEmpty_)
    , secondEmpty(secondEmpty_)
{
    test_case_count = 1;

    mat0x5 = Mat::ones(0,5, CV_8U);
    mat10x5 = Mat::ones(10,5, CV_8U);
    mat20x5 = Mat::ones(20,5, CV_8U);

    mat5x0 = Mat::ones(5,0, CV_8U);
    mat5x10 = Mat::ones(5,10, CV_8U);
    mat5x20 = Mat::ones(5,20, CV_8U);
}

int Core_ConcatenationTest::prepare_test_case( int test_case_idx )
{
    cvtest::BaseTest::prepare_test_case( test_case_idx );
    return 1;
}

void Core_ConcatenationTest::run_func()
{
    if (horizontal)
    {
        cv::hconcat((firstEmpty ? mat5x0 : mat5x10),
                    (secondEmpty ? mat5x0 : mat5x10),
                    result);
    } else {
        cv::vconcat((firstEmpty ? mat0x5 : mat10x5),
                    (secondEmpty ? mat0x5 : mat10x5),
                    result);
    }
}

int Core_ConcatenationTest::validate_test_results( int )
{
    Mat expected;

    if (firstEmpty && secondEmpty)
        expected = (horizontal ? mat5x0 : mat0x5);
    else if ((firstEmpty && !secondEmpty) || (!firstEmpty && secondEmpty))
        expected = (horizontal ? mat5x10 : mat10x5);
    else
        expected = (horizontal ? mat5x20 : mat20x5);

    if (areEqual(expected, result))
    {
        return cvtest::TS::OK;
    } else
    {
        ts->printf( cvtest::TS::LOG, "Concatenation failed");
        ts->set_failed_test_info( cvtest::TS::FAIL_MISMATCH );
    }

    return cvtest::TS::OK;
}

bool Core_ConcatenationTest::areEqual(const Mat &m1, const Mat &m2)
{
    return m1.size() == m2.size()
            && m1.type() == m2.type()
            && countNonZero(m1 != m2) == 0;
}

TEST(Core_Concatenation, hconcat_empty_nonempty) { Core_ConcatenationTest test(true, true, false); test.safe_run(); }
TEST(Core_Concatenation, hconcat_nonempty_empty) { Core_ConcatenationTest test(true, false, true); test.safe_run(); }
TEST(Core_Concatenation, hconcat_empty_empty) { Core_ConcatenationTest test(true, true, true); test.safe_run(); }

TEST(Core_Concatenation, vconcat_empty_nonempty) { Core_ConcatenationTest test(false, true, false); test.safe_run(); }
TEST(Core_Concatenation, vconcat_nonempty_empty) { Core_ConcatenationTest test(false, false, true); test.safe_run(); }
TEST(Core_Concatenation, vconcat_empty_empty) { Core_ConcatenationTest test(false, true, true); test.safe_run(); }


text:
"use strict";

var config = require("config");
var logger = require("../common/logger");
var request = require('superagent');
var Character = require('../models/Character.model.js');

function addCharacter(character, callback) {
  console.log(character)
  new Character(character).save(function(err, newCharacter){
    if (err) return callback(err);
    console.log('new item');
    return callback(null, newCharacter);
  })
}

function getCharacter(characterid, callback) {
  if (!characterid) {
    var blankCharacter = Character();
    return callback(null, blankCharacter);
  }
  Character.findOne({_id: characterid}, function(err, character){
    if (err) return callback(err)

    return callback(null, character);
   })

}

function getCharacters(callback) {
  Character.find({}, function(err, characters) {
    if (err) return callback(err);

    return callback(null, characters);
  });
}

function removeCharacter(characterid, callback) {
  console.log(characterid);
  Character.remove({_id: characterid}, function(err){

      return callback(null, {success: true});
  });
}

function updateCharacter(character, callback) {
  var id = character._id;
  delete character._id;
  Character.findByIdAndUpdate(id, character, function(err, newCharacter) {
    if (err) return callback(err);

    return callback(null, {success: true});
  });

}

module.exports = {
  addCharacter: addCharacter,
  getCharacter: getCharacter,
  getCharacters: getCharacters,
  removeCharacter: removeCharacter,
  updateCharacter: updateCharacter
};