text:
#ifndef MAP_H_
#define MAP_H_

#include"hashtable.h"

template<typename Key, typename Value>
struct _key_data {
    Key   m_key;
    Value m_value;
    _key_data() {
    }
    _key_data(Key const & k):
        m_key(k) {
    }
    _key_data(Key const & k, Value const & v):
        m_key(k),
        m_value(v) {
    }
};

template<typename Entry, typename HashProc, typename EqProc>
class table2map {
public:
    typedef Entry    entry;
    typedef typename Entry::key      key;
    typedef typename Entry::value    value;
    typedef typename Entry::key_data key_data;

    struct entry_hash_proc : private HashProc {
        entry_hash_proc(HashProc const & p):
            HashProc(p) {
        }

        unsigned operator()(key_data const & d) const {
            return HashProc::operator()(d.m_key);
        }
    };

    struct entry_eq_proc : private EqProc {
        entry_eq_proc(EqProc const & p):
            EqProc(p) {
        }

        bool operator()(key_data const & d1, key_data const & d2) const {
            return EqProc::operator()(d1.m_key, d2.m_key);
        }
    };

    typedef core_hashtable<entry, entry_hash_proc, entry_eq_proc> table;

    table m_table;

public:
    table2map(HashProc const & h = HashProc(), EqProc const & e = EqProc()):
        m_table(DEFAULT_HASHTABLE_INITIAL_CAPACITY, entry_hash_proc(h), entry_eq_proc(e)) {
    }

    typedef typename table::iterator iterator;

    void reset() {
        m_table.reset();
    }

    void finalize() {
        m_table.finalize();
    }

    bool empty() const {
        return m_table.empty();
    }

    unsigned size() const {
        return m_table.size();
    }

    unsigned capacity() const {
        return m_table.capacity();
    }

    iterator begin() const {
        return m_table.begin();
    }

    iterator end() const {
        return m_table.end();
    }

    void insert(key const & k, value const & v) {
        m_table.insert(key_data(k, v));
    }

    bool insert_if_not_there_core(key const & k, value const & v, entry *& et) {
        return m_table.insert_if_not_there_core(key_data(k,v), et);
    }

    key_data const & insert_if_not_there(key const & k, value const & v) {
        return m_table.insert_if_not_there(key_data(k, v));
    }

    entry * insert_if_not_there2(key const & k, value const & v) {
        return m_table.insert_if_not_there2(key_data(k, v));
    }

    entry * find_core(key const & k) const {
        return m_table.find_core(key_data(k));
    }

    bool find(key const & k, value & v) const {
        entry * e = find_core(k);
        if (e) {
            v = e->get_data().m_value;
        }
        return (0 != e);
    }

    value const& get(key const& k, value const& default_value) const {
        entry* e = find_core(k);
        if (e) {
	  return e->get_data().m_value;
        }
        else {
            return default_value;
        }
    }

    iterator find_iterator(key const & k) const {
        return m_table.find(key_data(k));
    }

    value const & find(key const& k) const {
        entry * e = find_core(k);
        SASSERT(e);
        return e->get_data().m_value;
    }

    value & find(key const& k)  {
        entry * e = find_core(k);
        SASSERT(e);
        return e->get_data().m_value;
    }

    value const& operator[](key const& k) const {  return find(k); }

    value& operator[](key const& k) { return find(k); }

    bool contains(key const & k) const {
        return find_core(k) != 0;
    }

    void remove(key const & k) {
        m_table.remove(key_data(k));
    }

    void erase(key const & k) {
        remove(k);
    }

    unsigned long long get_num_collision() const { return m_table.get_num_collision(); }

    void swap(table2map & other) {
        m_table.swap(other.m_table);
    }

#ifdef Z3DEBUG

    bool check_invariant() {
        return m_table.check_invariant();
    }

#endif
};

template<typename Key, typename Value>
class default_map_entry : public default_hash_entry<_key_data<Key, Value> > {
public:
    typedef Key   key;
    typedef Value value;
    typedef _key_data<Key, Value> key_data;
};

template<typename Key, typename Value, typename HashProc, typename EqProc>
class map : public table2map<default_map_entry<Key, Value>, HashProc, EqProc> {
public:
    map(HashProc const & h = HashProc(), EqProc const & e = EqProc()):
        table2map<default_map_entry<Key, Value>, HashProc, EqProc>(h, e) {
    }
};

template<typename Key, typename Value>
struct _key_ptr_data {
    Key * m_key;
    Value m_value;
    _key_ptr_data():
        m_key(0) {
    }
    _key_ptr_data(Key * k):
        m_key(k) {
    }
    _key_ptr_data(Key * k, Value const & v):
        m_key(k),
        m_value(v) {
    }
};

template<typename Key, typename Value>
class ptr_map_entry {
public:
    typedef _key_ptr_data<Key, Value> key_data;
    typedef _key_ptr_data<Key, Value> data;
private:
    unsigned m_hash; //!< cached hash code
    data     m_data;
public:
    typedef Key * key;
    typedef Value value;
    unsigned get_hash() const { return m_hash; }
    bool is_free() const { return m_data.m_key == 0; }
    bool is_deleted() const { return m_data.m_key == reinterpret_cast<Key *>(1); }
    bool is_used() const { return m_data.m_key != reinterpret_cast<Key *>(0) && m_data.m_key != reinterpret_cast<Key *>(1); }
    key_data const & get_data() const { return m_data; }
    key_data & get_data() { return m_data; }
    void set_data(key_data const & d) { m_data = d; }
    void set_hash(unsigned h) { m_hash = h; }
    void mark_as_deleted() { m_data.m_key = reinterpret_cast<Key *>(1); }
    void mark_as_free() { m_data.m_key = 0; }
};

template<typename Key, typename Value>
class ptr_addr_map_entry {
public:
    typedef _key_ptr_data<Key, Value> key_data;
    typedef _key_ptr_data<Key, Value> data;
private:
    data     m_data;
public:
    typedef Key * key;
    typedef Value value;
    unsigned get_hash() const { return get_ptr_hash(m_data.m_key); }
    bool is_free() const { return m_data.m_key == 0; }
    bool is_deleted() const { return m_data.m_key == reinterpret_cast<Key *>(1); }
    bool is_used() const { return m_data.m_key != reinterpret_cast<Key *>(0) && m_data.m_key != reinterpret_cast<Key *>(1); }
    key_data const & get_data() const { return m_data; }
    key_data & get_data() { return m_data; }
    void set_data(key_data const & d) { m_data = d; }
    void set_hash(unsigned h) { SASSERT(h == get_ptr_hash(m_data.m_key)); /* do nothing */ }
    void mark_as_deleted() { m_data.m_key = reinterpret_cast<Key *>(1); }
    void mark_as_free() { m_data.m_key = 0; }
};

template<typename Key, typename Value>
class ptr_addr_map : public table2map<ptr_addr_map_entry<Key, Value>, ptr_hash<Key>, ptr_eq<Key> > {
public:
};

struct u_hash { unsigned operator()(unsigned u) const { return u; } };

struct u_eq { bool operator()(unsigned u1, unsigned u2) const { return u1 == u2; } };

struct size_t_eq { bool operator()(size_t u1, size_t u2) const { return u1 == u2; } };

struct int_eq { bool operator()(int u1, int u2) const { return u1 == u2; } };

template<typename Value>
class u_map : public map<unsigned, Value, u_hash, u_eq> {};

template<typename Value>
class size_t_map : public map<size_t, Value, size_t_hash, size_t_eq> {};

#endif


text:
package experiment

import (
	"fmt"

	"github.com/lawrencewoodman/ddataset"
	"github.com/lawrencewoodman/dexpr"
	"github.com/vlifesystems/rhkit/aggregator"
	"github.com/vlifesystems/rhkit/assessment"
	"github.com/vlifesystems/rhkit/description"
	"github.com/vlifesystems/rhkit/goal"
	"github.com/vlifesystems/rhkit/rule"
	"github.com/vlifesystems/rulehunter/config"
	"github.com/vlifesystems/rulehunter/progress"
	"github.com/vlifesystems/rulehunter/quitter"
	"github.com/vlifesystems/rulehunter/report"
)

type TrainMode struct {
	dataset        ddataset.Dataset
	when           *dexpr.Expr
	ruleGeneration ruleGeneration
}

type ruleGenerationDesc struct {
	Fields            []string `yaml:"fields"`
	Arithmetic        bool     `yaml:"arithmetic"`
	CombinationLength int      `yaml:"combinationLength"`
}

type ruleGeneration struct {
	fields            []string
	arithmetic        bool
	combinationLength int
}

func (rg ruleGeneration) Fields() []string {
	return rg.fields
}

func (rg ruleGeneration) Arithmetic() bool {
	return rg.arithmetic
}

type trainModeDesc struct {
	Dataset *datasetDesc `yaml:"dataset"`
	// An expression that works out whether to run the experiment for this mode
	When           string             `yaml:"when"`
	RuleGeneration ruleGenerationDesc `yaml:"ruleGeneration"`
}

func newTrainMode(
	cfg *config.Config,
	desc *trainModeDesc,
	experimentFilename string,
	aggregators []aggregator.Spec,
	goals []*goal.Goal,
	sortOrder []assessment.SortOrder,
) (*TrainMode, error) {
	d, err := makeDataset(cfg, desc.Dataset)
	if err != nil {
		return nil, fmt.Errorf("dataset: %s", err)
	}
	when, err := makeWhenExpr(desc.When)
	if err != nil {
		return nil, InvalidWhenExprError(desc.When)
	}
	return &TrainMode{
		dataset: d,
		when:    when,
		ruleGeneration: ruleGeneration{
			fields:            desc.RuleGeneration.Fields,
			arithmetic:        desc.RuleGeneration.Arithmetic,
			combinationLength: desc.RuleGeneration.CombinationLength,
		},
	}, nil
}

func (m *TrainMode) Kind() report.ModeKind {
	return report.Train
}

func (m *TrainMode) Release() error {
	if m == nil {
		return nil
	}
	return m.dataset.Release()
}

func (m *TrainMode) Dataset() ddataset.Dataset {
	return m.dataset
}

func (m *TrainMode) NumAssessRulesStages() int {
	return 4 + m.ruleGeneration.combinationLength
}

func (m *TrainMode) Process(
	e *Experiment,
	cfg *config.Config,
	pm *progress.Monitor,
	q *quitter.Quitter,
	rules []rule.Rule,
) ([]rule.Rule, error) {
	reportProgress := func(msg string, percent float64) error {
		return pm.ReportProgress(e.File.Name(), report.Train, msg, percent)
	}
	quitReceived := func() bool {
		select {
		case <-q.C:
			return true
		default:
			return false
		}
	}
	noRules := []rule.Rule{}
	rt := newRuleTracker()

	if err := reportProgress("Describing train dataset", 0); err != nil {
		return noRules, err
	}

	if quitReceived() {
		return noRules, ErrQuitReceived
	}
	desc, err := description.DescribeDataset(m.Dataset())
	if err != nil {
		return noRules, fmt.Errorf("Couldn't describe train dataset: %s", err)
	}

	if quitReceived() {
		return noRules, ErrQuitReceived
	}
	rt.track(rules)
	userRules := append(rules, rule.NewTrue())
	ass, err := assessRules(e, m, 1, userRules, pm, q, cfg)
	if err != nil {
		return noRules, fmt.Errorf("Couldn't assess rules: %s", err)
	}

	assessRules := func(
		stage int,
		rules []rule.Rule,
	) (*assessment.Assessment, error) {
		newRules := rt.track(rules)
		newAss, err :=
			assessRules(e, m, stage, newRules, pm, q, cfg)
		if err != nil {
			return nil, fmt.Errorf("Couldn't assess rules: %s", err)
		}
		ass, err = ass.Merge(newAss)
		if err != nil {
			return nil, fmt.Errorf("Couldn't merge assessments: %s", err)
		}
		ass.Sort(e.SortOrder)
		ass.Refine()
		ass = ass.TruncateRuleAssessments(10000)
		return newAss, nil
	}

	if err := reportProgress("Generating rules", 0); err != nil {
		return noRules, err
	}
	generatedRules, err := rule.Generate(desc, m.ruleGeneration)
	if err != nil {
		return noRules, fmt.Errorf("Couldn't generate rules: %s", err)
	}

	if quitReceived() {
		return noRules, ErrQuitReceived
	}

	if _, err := assessRules(2, generatedRules); err != nil {
		return noRules, err
	}

	if quitReceived() {
		return noRules, ErrQuitReceived
	}

	if err := reportProgress("Tweaking rules", 0); err != nil {
		return noRules, err
	}
	tweakableRules := rule.Tweak(1, ass.Rules(), desc)

	if _, err := assessRules(3, tweakableRules); err != nil {
		return noRules, err
	}

	if quitReceived() {
		return noRules, ErrQuitReceived
	}

	if err := reportProgress("Reduce DP of rules", 0); err != nil {
		return noRules, err
	}
	reducedDPRules := rule.ReduceDP(ass.Rules())

	if _, err := assessRules(4, reducedDPRules); err != nil {
		return noRules, err
	}

	if quitReceived() {
		return noRules, ErrQuitReceived
	}

	ruleAssessments := []*assessment.RuleAssessment{ass.RuleAssessments[0]}
	for i := 0; i < m.ruleGeneration.combinationLength; i++ {
		if err := reportProgress("Combining rules", 0); err != nil {
			return noRules, err
		}
		combinedRules := rule.Combine(ass.Rules(), 10000)
		combinedAss, err := assessRules(5+i, combinedRules)
		if err != nil {
			return noRules, err
		}
		if quitReceived() {
			return noRules, ErrQuitReceived
		}
		combinedAss.Sort(e.SortOrder)
		combinedAss.Refine()

		// Add ruleAssessment for each combinationLength
		for _, ra := range combinedAss.RuleAssessments {
			if _, isTrueRule := ra.Rule.(rule.True); !isTrueRule {
				ruleAssessments = append(ruleAssessments, ra)
				break
			}
		}
	}

	// Add the true rule assessment if missing
	trueRuleAssessment := getTrueRuleAssessment(ruleAssessments)
	if trueRuleAssessment == nil {
		trueRuleAssessment = getTrueRuleAssessment(ass.RuleAssessments)
		if trueRuleAssessment == nil {
			panic("true rule missing from assessment")
		}
		ruleAssessments = append(ruleAssessments, trueRuleAssessment)
	}
	ass.RuleAssessments = ruleAssessments
	ass.Sort(e.SortOrder)
	ass.Refine()
	// TODO: Remove ruleAssessments that have longer combinationLength than
	// previous ruleAssessment?

	r := report.New(
		report.Train,
		e.Title,
		desc,
		ass,
		e.Aggregators,
		e.SortOrder,
		e.File.Name(),
		e.Tags,
		e.Category,
	)
	if err := r.WriteJSON(cfg); err != nil {
		return noRules, fmt.Errorf("Couldn't write JSON train report: %s", err)
	}
	return ass.Rules(), nil
}

func getTrueRuleAssessment(
	ruleAssessments []*assessment.RuleAssessment,
) *assessment.RuleAssessment {
	for _, ra := range ruleAssessments {
		if _, isTrueRule := ra.Rule.(rule.True); isTrueRule {
			return ra
		}
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
from core.himesis import Himesis
import uuid

class Hlayer1rule3(Himesis):
	def __init__(self):
		"""
		Creates the himesis graph representing the DSLTrans rule layer1rule3.
		"""
		# Flag this instance as compiled now
		self.is_compiled = True

		super(Hlayer1rule3, self).__init__(name='Hlayer1rule3', num_nodes=0, edges=[])

		# Set the graph attributes
		self["mm__"] = ['HimesisMM']
		self["name"] = """layer1rule3"""
		self["GUID__"] = uuid.uuid3(uuid.NAMESPACE_DNS,'layer1rule3')

		# match model. We only support one match model
		self.add_node()
		self.vs[0]["mm__"] = """MatchModel"""

		# apply model node
		self.add_node()
		self.vs[1]["mm__"] = """ApplyModel"""

		# paired with relation between match and apply models
		self.add_node()
		self.vs[2]["mm__"] = """paired_with"""
		self.vs[2]["attr1"] = """layer1rule3"""

		# match class Operation(layer1rule3class0Operation) node
		self.add_node()
		self.vs[3]["mm__"] = """Operation"""
		self.vs[3]["attr1"] = """+"""

		# match class StringType(layer1rule3class1StringType) node
		self.add_node()
		self.vs[4]["mm__"] = """StringType"""
		self.vs[4]["attr1"] = """+"""

		# apply class FunctionRefType(layer1rule3class2FunctionRefType) node
		self.add_node()
		self.vs[5]["mm__"] = """FunctionRefType"""
		self.vs[5]["attr1"] = """1"""

		# apply class StringType(layer1rule3class3StringType) node
		self.add_node()
		self.vs[6]["mm__"] = """StringType"""
		self.vs[6]["attr1"] = """1"""

		# match association Operation--type-->StringType node
		self.add_node()
		self.vs[7]["attr1"] = """type"""
		self.vs[7]["mm__"] = """directLink_S"""

		# apply association FunctionRefType--returnType-->StringType node
		self.add_node()
		self.vs[8]["attr1"] = """returnType"""
		self.vs[8]["mm__"] = """directLink_T"""

		# backward association StringType-->StringTypenode
		self.add_node()
		self.vs[9]["mm__"] = """backward_link"""

		# backward association FunctionRefType-->Operationnode
		self.add_node()
		self.vs[10]["mm__"] = """backward_link"""

		# Add the edges
		self.add_edges([
			(0,3), # matchmodel -> match_class Operation(layer1rule3class0Operation)
			(0,4), # matchmodel -> match_class StringType(layer1rule3class1StringType)
			(1,5), # applymodel -> apply_classFunctionRefType(layer1rule3class2FunctionRefType)
			(1,6), # applymodel -> apply_classStringType(layer1rule3class3StringType)
			(3,7), # match classOperation(layer1rule3class0Operation) -> association type
			(7,4), # associationtype -> match_classOperation(layer1rule3class1StringType)
			(5,8), # apply class FunctionRefType(layer1rule3class2FunctionRefType) -> association returnType
			(8,6), # associationreturnType -> apply_classStringType(layer1rule3class3StringType)
			(6,9), # apply class StringType(layer1rule3class1StringType) -> backward_association
			(9,4), # backward_associationStringType -> match_class StringType(layer1rule3class1StringType)
			(5,10), # apply class FunctionRefType(layer1rule3class0Operation) -> backward_association
			(10,3), # backward_associationOperation -> match_class Operation(layer1rule3class0Operation)
			(0,2), # matchmodel -> pairedwith
			(2,1) # pairedwith -> applyModel
		])

		self["equations"] = []


text:
namespace FastNehalem
{
   class CacheBase
   {
      public:
         virtual ~CacheBase() {}
         virtual SubsecondTime access(Core::mem_op_t mem_op_type, IntPtr tag) = 0;
   };

   class MemoryManager : public MemoryManagerFast
   {
      private:
         CacheBase *icache, *dcache, *l2cache;
         static CacheBase *l3cache, *dram;

      public:
         MemoryManager(Core* core, Network* network, ShmemPerfModel* shmem_perf_model);
         ~MemoryManager();

         SubsecondTime coreInitiateMemoryAccessFast(
               bool use_icache,
               Core::mem_op_t mem_op_type,
               IntPtr address)
         {
            IntPtr tag = address >> CACHE_LINE_BITS;
            return (use_icache ? icache : dcache)->access(mem_op_type, tag);
         }
   };
}

#endif // __FAST_NEHALEM_H


text:
class DevToolsHttpClient;

class ChromeAndroidImpl : public ChromeImpl {
 public:
  ChromeAndroidImpl(
      scoped_ptr<DevToolsHttpClient> client,
      const std::string& version,
      int build_no,
      const std::list<DevToolsEventLogger*>& devtools_event_loggers);
  virtual ~ChromeAndroidImpl();

  // Overridden from Chrome:
  virtual std::string GetOperatingSystemName() OVERRIDE;
  virtual Status Quit() OVERRIDE;
};

#endif  // CHROME_TEST_CHROMEDRIVER_CHROME_CHROME_ANDROID_IMPL_H_


text:
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace System.Threading.Channels.Tests
{
    public abstract class ChannelTestBase : TestBase
    {
        protected abstract Channel<int> CreateChannel();
        protected abstract Channel<int> CreateFullChannel();

        protected virtual bool RequiresSingleReader => false;
        protected virtual bool RequiresSingleWriter => false;
        protected virtual bool BuffersItems => true;

        [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Requires internal reflection on framework types.")]
        [Fact]
        public void ValidateDebuggerAttributes()
        {
            Channel<int> c = CreateChannel();
            for (int i = 1; i <= 10; i++)
            {
                c.Writer.WriteAsync(i);
            }
            DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
            DebuggerAttributes.InvokeDebuggerTypeProxyProperties(c);
        }

        [Fact]
        public void Cast_MatchesInOut()
        {
            Channel<int> c = CreateChannel();
            ChannelReader<int> rc = c;
            ChannelWriter<int> wc = c;
            Assert.Same(rc, c.Reader);
            Assert.Same(wc, c.Writer);
        }

        [Fact]
        public void Completion_Idempotent()
        {
            Channel<int> c = CreateChannel();

            Task completion = c.Reader.Completion;
            Assert.Equal(TaskStatus.WaitingForActivation, completion.Status);

            Assert.Same(completion, c.Reader.Completion);
            c.Writer.Complete();
            Assert.Same(completion, c.Reader.Completion);

            Assert.Equal(TaskStatus.RanToCompletion, completion.Status);
        }

        [Fact]
        public async Task Complete_AfterEmpty_NoWaiters_TriggersCompletion()
        {
            Channel<int> c = CreateChannel();
            c.Writer.Complete();
            await c.Reader.Completion;
        }

        [Fact]
        public async Task Complete_AfterEmpty_WaitingReader_TriggersCompletion()
        {
            Channel<int> c = CreateChannel();
            Task<int> r = c.Reader.ReadAsync().AsTask();
            c.Writer.Complete();
            await c.Reader.Completion;
            await Assert.ThrowsAnyAsync<InvalidOperationException>(() => r);
        }

        [Fact]
        public async Task Complete_BeforeEmpty_WaitingReaders_TriggersCompletion()
        {
            Channel<int> c = CreateChannel();
            Task<int> read = c.Reader.ReadAsync().AsTask();
            c.Writer.Complete();
            await c.Reader.Completion;
            await Assert.ThrowsAnyAsync<InvalidOperationException>(() => read);
        }

        [Fact]
        public void Complete_Twice_ThrowsInvalidOperationException()
        {
            Channel<int> c = CreateChannel();
            c.Writer.Complete();
            Assert.ThrowsAny<InvalidOperationException>(() => c.Writer.Complete());
        }

        [Fact]
        public void TryComplete_Twice_ReturnsTrueThenFalse()
        {
            Channel<int> c = CreateChannel();
            Assert.True(c.Writer.TryComplete());
            Assert.False(c.Writer.TryComplete());
            Assert.False(c.Writer.TryComplete());
        }

        [Fact]
        public async Task TryComplete_ErrorsPropage()
        {
            Channel<int> c;

            // Success
            c = CreateChannel();
            Assert.True(c.Writer.TryComplete());
            await c.Reader.Completion;

            // Error
            c = CreateChannel();
            Assert.True(c.Writer.TryComplete(new FormatException()));
            await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion);

            // Canceled
            c = CreateChannel();
            var cts = new CancellationTokenSource();
            cts.Cancel();
            Assert.True(c.Writer.TryComplete(new OperationCanceledException(cts.Token)));
            await AssertCanceled(c.Reader.Completion, cts.Token);
        }

        [Fact]
        public void SingleProducerConsumer_ConcurrentReadWrite_Success()
        {
            Channel<int> c = CreateChannel();

            const int NumItems = 100000;
            Task.WaitAll(
                Task.Run(async () =>
                {
                    for (int i = 0; i < NumItems; i++)
                    {
                        await c.Writer.WriteAsync(i);
                    }
                }),
                Task.Run(async () =>
                {
                    for (int i = 0; i < NumItems; i++)
                    {
                        Assert.Equal(i, await c.Reader.ReadAsync());
                    }
                }));
        }

        [Fact]
        public void SingleProducerConsumer_PingPong_Success()
        {
            Channel<int> c1 = CreateChannel();
            Channel<int> c2 = CreateChannel();

            const int NumItems = 100000;
            Task.WaitAll(
                Task.Run(async () =>
                {
                    for (int i = 0; i < NumItems; i++)
                    {
                        Assert.Equal(i, await c1.Reader.ReadAsync());
                        await c2.Writer.WriteAsync(i);
                    }
                }),
                Task.Run(async () =>
                {
                    for (int i = 0; i < NumItems; i++)
                    {
                        await c1.Writer.WriteAsync(i);
                        Assert.Equal(i, await c2.Reader.ReadAsync());
                    }
                }));
        }

        [Theory]
        [InlineData(1, 1)]
        [InlineData(1, 10)]
        [InlineData(10, 1)]
        [InlineData(10, 10)]
        public void ManyProducerConsumer_ConcurrentReadWrite_Success(int numReaders, int numWriters)
        {
            if (RequiresSingleReader && numReaders > 1)
            {
                return;
            }

            if (RequiresSingleWriter && numWriters > 1)
            {
                return;
            }

            Channel<int> c = CreateChannel();

            const int NumItems = 10000;

            long readTotal = 0;
            int remainingWriters = numWriters;
            int remainingItems = NumItems;

            Task[] tasks = new Task[numWriters + numReaders];

            for (int i = 0; i < numReaders; i++)
            {
                tasks[i] = Task.Run(async () =>
                {
                    try
                    {
                        while (await c.Reader.WaitToReadAsync())
                        {
                            if (c.Reader.TryRead(out int value))
                            {
                                Interlocked.Add(ref readTotal, value);
                            }
                        }
                    }
                    catch (ChannelClosedException) { }
                });
            }

            for (int i = 0; i < numWriters; i++)
            {
                tasks[numReaders + i] = Task.Run(async () =>
                {
                    while (true)
                    {
                        int value = Interlocked.Decrement(ref remainingItems);
                        if (value < 0)
                        {
                            break;
                        }
                        await c.Writer.WriteAsync(value + 1);
                    }
                    if (Interlocked.Decrement(ref remainingWriters) == 0)
                    {
                        c.Writer.Complete();
                    }
                });
            }

            Task.WaitAll(tasks);
            Assert.Equal((NumItems * (NumItems + 1L)) / 2, readTotal);
        }

        [Fact]
        public void WaitToReadAsync_DataAvailableBefore_CompletesSynchronously()
        {
            Channel<int> c = CreateChannel();
            Task write = c.Writer.WriteAsync(42);
            Task<bool> read = c.Reader.WaitToReadAsync();
            Assert.Equal(TaskStatus.RanToCompletion, read.Status);
        }

        [Fact]
        public void WaitToReadAsync_DataAvailableAfter_CompletesAsynchronously()
        {
            Channel<int> c = CreateChannel();
            Task<bool> read = c.Reader.WaitToReadAsync();
            Assert.False(read.IsCompleted);
            Task write = c.Writer.WriteAsync(42);
            Assert.True(read.Result);
        }

        [Fact]
        public void WaitToReadAsync_AfterComplete_SynchronouslyCompletes()
        {
            Channel<int> c = CreateChannel();
            c.Writer.Complete();
            Task<bool> read = c.Reader.WaitToReadAsync();
            Assert.Equal(TaskStatus.RanToCompletion, read.Status);
            Assert.False(read.Result);
        }

        [Fact]
        public void WaitToReadAsync_BeforeComplete_AsynchronouslyCompletes()
        {
            Channel<int> c = CreateChannel();
            Task<bool> read = c.Reader.WaitToReadAsync();
            Assert.False(read.IsCompleted);
            c.Writer.Complete();
            Assert.False(read.Result);
        }

        [Fact]
        public void WaitToWriteAsync_AfterComplete_SynchronouslyCompletes()
        {
            Channel<int> c = CreateChannel();
            c.Writer.Complete();
            Task<bool> write = c.Writer.WaitToWriteAsync();
            Assert.Equal(TaskStatus.RanToCompletion, write.Status);
            Assert.False(write.Result);
        }

        [Fact]
        public void WaitToWriteAsync_EmptyChannel_SynchronouslyCompletes()
        {
            if (!BuffersItems)
            {
                return;
            }

            Channel<int> c = CreateChannel();
            Task<bool> write = c.Writer.WaitToWriteAsync();
            Assert.Equal(TaskStatus.RanToCompletion, write.Status);
            Assert.True(write.Result);
        }

        [Fact]
        public async Task WaitToWriteAsync_ManyConcurrent_SatisifedByReaders()
        {
            if (RequiresSingleReader || RequiresSingleWriter)
            {
                return;
            }

            Channel<int> c = CreateChannel();

            Task[] writers = Enumerable.Range(0, 100).Select(_ => c.Writer.WaitToWriteAsync()).ToArray();
            Task[] readers = Enumerable.Range(0, 100).Select(_ => c.Reader.ReadAsync().AsTask()).ToArray();

            await Task.WhenAll(writers);
        }

        [Fact]
        public void WaitToWriteAsync_BlockedReader_ReturnsTrue()
        {
            Channel<int> c = CreateChannel();
            ValueTask<int> reader = c.Reader.ReadAsync();
            AssertSynchronousSuccess(c.Writer.WaitToWriteAsync());
        }

        [Fact]
        public void TryRead_DataAvailable_Success()
        {
            Channel<int> c = CreateChannel();
            Task write = c.Writer.WriteAsync(42);
            Assert.True(c.Reader.TryRead(out int result));
            Assert.Equal(42, result);
        }

        [Fact]
        public void TryRead_AfterComplete_ReturnsFalse()
        {
            Channel<int> c = CreateChannel();
            c.Writer.Complete();
            Assert.False(c.Reader.TryRead(out int result));
        }

        [Fact]
        public void TryWrite_AfterComplete_ReturnsFalse()
        {
            Channel<int> c = CreateChannel();
            c.Writer.Complete();
            Assert.False(c.Writer.TryWrite(42));
        }

        [Fact]
        public async Task WriteAsync_AfterComplete_ThrowsException()
        {
            Channel<int> c = CreateChannel();
            c.Writer.Complete();
            await Assert.ThrowsAnyAsync<InvalidOperationException>(() => c.Writer.WriteAsync(42));
        }

        [Fact]
        public async Task Complete_WithException_PropagatesToCompletion()
        {
            Channel<int> c = CreateChannel();
            var exc = new FormatException();
            c.Writer.Complete(exc);
            Assert.Same(exc, await Assert.ThrowsAsync<FormatException>(() => c.Reader.Completion));
        }

        [Fact]
        public async Task Complete_WithCancellationException_PropagatesToCompletion()
        {
            Channel<int> c = CreateChannel();
            var cts = new CancellationTokenSource();
            cts.Cancel();

            Exception exc = null;
            try { cts.Token.ThrowIfCancellationRequested(); }
            catch (Exception e) { exc = e; }

            c.Writer.Complete(exc);
            await AssertCanceled(c.Reader.Completion, cts.Token);
        }

        [Fact]
        public async Task Complete_WithException_PropagatesToExistingWriter()
        {
            Channel<int> c = CreateFullChannel();
            if (c != null)
            {
                Task write = c.Writer.WriteAsync(42);
                var exc = new FormatException();
                c.Writer.Complete(exc);
                Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(() => write)).InnerException);
            }
        }

        [Fact]
        public async Task Complete_WithException_PropagatesToNewWriter()
        {
            Channel<int> c = CreateChannel();
            var exc = new FormatException();
            c.Writer.Complete(exc);
            Task write = c.Writer.WriteAsync(42);
            Assert.Same(exc, (await Assert.ThrowsAsync<ChannelClosedException>(() => write)).InnerException);
        }

        [Fact]
        public async Task Complete_WithException_PropagatesToExistingWaitingReader()
        {
            Channel<int> c = CreateChannel();
            Task<bool> read = c.Reader.WaitToReadAsync();
            var exc = new FormatException();
            c.Writer.Complete(exc);
            await Assert.ThrowsAsync<FormatException>(() => read);
        }

        [Fact]
        public async Task Complete_WithException_PropagatesToNewWaitingReader()
        {
            Channel<int> c = CreateChannel();
            var exc = new FormatException();
            c.Writer.Complete(exc);
            Task<bool> read = c.Reader.WaitToReadAsync();
            await Assert.ThrowsAsync<FormatException>(() => read);
        }

        [Fact]
        public async Task Complete_WithException_PropagatesToNewWaitingWriter()
        {
            Channel<int> c = CreateChannel();
            var exc = new FormatException();
            c.Writer.Complete(exc);
            Task<bool> write = c.Writer.WaitToWriteAsync();
            await Assert.ThrowsAsync<FormatException>(() => write);
        }

        [Theory]
        [InlineData(0)]
        [InlineData(1)]
        public void ManyWriteAsync_ThenManyTryRead_Success(int readMode)
        {
            if (RequiresSingleReader || RequiresSingleWriter)
            {
                return;
            }

            Channel<int> c = CreateChannel();

            const int NumItems = 2000;

            Task[] writers = new Task[NumItems];
            for (int i = 0; i < writers.Length; i++)
            {
                writers[i] = c.Writer.WriteAsync(i);
            }

            Task<int>[] readers = new Task<int>[NumItems];
            for (int i = 0; i < readers.Length; i++)
            {
                int result;
                Assert.True(c.Reader.TryRead(out result));
                Assert.Equal(i, result);
            }

            Assert.All(writers, w => Assert.True(w.IsCompleted));
        }

        [Fact]
        public void Precancellation_Writing_ReturnsImmediately()
        {
            Channel<int> c = CreateChannel();

            Task writeTask = c.Writer.WriteAsync(42, new CancellationToken(true));
            Assert.Equal(TaskStatus.Canceled, writeTask.Status);

            Task<bool> waitTask = c.Writer.WaitToWriteAsync(new CancellationToken(true));
            Assert.Equal(TaskStatus.Canceled, waitTask.Status);
        }

        [Fact]
        public void Write_WaitToReadAsync_CompletesSynchronously()
        {
            Channel<int> c = CreateChannel();
            c.Writer.WriteAsync(42);
            AssertSynchronousTrue(c.Reader.WaitToReadAsync());
        }

        [Fact]
        public void Precancellation_WaitToReadAsync_ReturnsImmediately()
        {
            Channel<int> c = CreateChannel();

            Task writeTask = c.Reader.WaitToReadAsync(new CancellationToken(true));
            Assert.Equal(TaskStatus.Canceled, writeTask.Status);
        }

        [Theory]
        [InlineData(false)]
        [InlineData(true)]
        public async Task WaitToReadAsync_DataWritten_CompletesSuccessfully(bool cancelable)
        {
            Channel<int> c = CreateChannel();
            CancellationToken token = cancelable ? new CancellationTokenSource().Token : default;

            Task<bool> read = c.Reader.WaitToReadAsync(token);
            Assert.False(read.IsCompleted);

            Task write = c.Writer.WriteAsync(42, token);

            Assert.True(await read);
        }

        [Fact]
        public async Task WaitToReadAsync_NoDataWritten_Canceled_CompletesAsCanceled()
        {
            Channel<int> c = CreateChannel();
            var cts = new CancellationTokenSource();

            Task<bool> read = c.Reader.WaitToReadAsync(cts.Token);
            Assert.False(read.IsCompleted);
            cts.Cancel();
            await Assert.ThrowsAnyAsync<OperationCanceledException>(() => read);
        }

        [Fact]
        public async Task ReadAsync_ThenWriteAsync_Succeeds()
        {
            Channel<int> c = CreateChannel();

            ValueTask<int> r = c.Reader.ReadAsync();
            Assert.False(r.IsCompleted);

            Task w = c.Writer.WriteAsync(42);
            AssertSynchronousSuccess(w);

            Assert.Equal(42, await r);
        }

        [Fact]
        public async Task WriteAsync_ReadAsync_Succeeds()
        {
            Channel<int> c = CreateChannel();

            Task w = c.Writer.WriteAsync(42);
            ValueTask<int> r = c.Reader.ReadAsync();

            await Task.WhenAll(w, r.AsTask());

            Assert.Equal(42, await r);
        }

        [Fact]
        public void ReadAsync_Precanceled_CanceledSynchronously()
        {
            Channel<int> c = CreateChannel();
            var cts = new CancellationTokenSource();
            cts.Cancel();
            AssertSynchronouslyCanceled(c.Reader.ReadAsync(cts.Token).AsTask(), cts.Token);
        }

        [Fact]
        public async Task ReadAsync_Canceled_CanceledAsynchronously()
        {
            Channel<int> c = CreateChannel();
            var cts = new CancellationTokenSource();

            ValueTask<int> r = c.Reader.ReadAsync(cts.Token);
            Assert.False(r.IsCompleted);

            cts.Cancel();

            await AssertCanceled(r.AsTask(), cts.Token);

            if (c.Writer.TryWrite(42))
            {
                Assert.Equal(42, await c.Reader.ReadAsync());
            }
        }

        [Fact]
        public async Task ReadAsync_WriteAsync_ManyConcurrentReaders_SerializedWriters_Success()
        {
            if (RequiresSingleReader)
            {
                return;
            }

            Channel<int> c = CreateChannel();
            const int Items = 100;

            ValueTask<int>[] readers = (from i in Enumerable.Range(0, Items) select c.Reader.ReadAsync()).ToArray();
            for (int i = 0; i < Items; i++)
            {
                await c.Writer.WriteAsync(i);
            }

            Assert.Equal((Items * (Items - 1)) / 2, Enumerable.Sum(await Task.WhenAll(readers.Select(r => r.AsTask()))));
        }

        [Fact]
        public async Task ReadAsync_TryWrite_ManyConcurrentReaders_SerializedWriters_Success()
        {
            if (RequiresSingleReader)
            {
                return;
            }

            Channel<int> c = CreateChannel();
            const int Items = 100;

            ValueTask<int>[] readers = (from i in Enumerable.Range(0, Items) select c.Reader.ReadAsync()).ToArray();
            var remainingReaders = new List<Task<int>>(readers.Select(r => r.AsTask()));

            for (int i = 0; i < Items; i++)
            {
                Assert.True(c.Writer.TryWrite(i), $"Failed to write at {i}");
                Task<int> r = await Task.WhenAny(remainingReaders);
                await r;
                remainingReaders.Remove(r);
            }

            Assert.Equal((Items * (Items - 1)) / 2, Enumerable.Sum(await Task.WhenAll(readers.Select(r => r.AsTask()))));
        }

        [Fact]
        public async Task ReadAsync_AlreadyCompleted_Throws()
        {
            Channel<int> c = CreateChannel();
            c.Writer.Complete();
            await Assert.ThrowsAsync<ChannelClosedException>(() => c.Reader.ReadAsync().AsTask());
        }

        [Fact]
        public async Task ReadAsync_SubsequentlyCompleted_Throws()
        {
            Channel<int> c = CreateChannel();
            Task<int> r = c.Reader.ReadAsync().AsTask();
            Assert.False(r.IsCompleted);
            c.Writer.Complete();
            await Assert.ThrowsAsync<ChannelClosedException>(() => r);
        }

        [Fact]
        public async Task ReadAsync_AfterFaultedChannel_Throws()
        {
            Channel<int> c = CreateChannel();

            var e = new FormatException();
            c.Writer.Complete(e);
            Assert.True(c.Reader.Completion.IsFaulted);

            ChannelClosedException cce = await Assert.ThrowsAsync<ChannelClosedException>(() => c.Reader.ReadAsync().AsTask());
            Assert.Same(e, cce.InnerException);
        }

        [Fact]
        public async Task ReadAsync_AfterCanceledChannel_Throws()
        {
            Channel<int> c = CreateChannel();

            var e = new OperationCanceledException();
            c.Writer.Complete(e);
            Assert.True(c.Reader.Completion.IsCanceled);

            await Assert.ThrowsAnyAsync<OperationCanceledException>(() => c.Reader.ReadAsync().AsTask());
        }

        [Fact]
        public async Task ReadAsync_Canceled_WriteAsyncCompletesNextReader()
        {
            Channel<int> c = CreateChannel();

            for (int i = 0; i < 5; i++)
            {
                var cts = new CancellationTokenSource();
                ValueTask<int> r = c.Reader.ReadAsync(cts.Token);
                cts.Cancel();
                await AssertCanceled(r.AsTask(), cts.Token);
            }

            for (int i = 0; i < 7; i++)
            {
                ValueTask<int> r = c.Reader.ReadAsync();
                await c.Writer.WriteAsync(i);
                Assert.Equal(i, await r);
            }
        }
    }
}


text:
namespace {

// TODO(vtl): Remove.
class TestChildProcessHostDelegate
    : public mojo::shell::ChildProcessHost::Delegate {
 public:
  TestChildProcessHostDelegate() {}
  virtual ~TestChildProcessHostDelegate() {}
  virtual void WillStart() OVERRIDE {
    VLOG(2) << "TestChildProcessHostDelegate::WillStart()";
  }
  virtual void DidStart(bool success) OVERRIDE {
    VLOG(2) << "TestChildProcessHostDelegate::DidStart(" << success << ")";
    base::MessageLoop::current()->QuitWhenIdle();
  }
};

}  // namespace

int main(int argc, char** argv) {
  base::AtExitManager at_exit;
  CommandLine::Init(argc, argv);
  mojo::shell::InitializeLogging();

  // TODO(vtl): Move this a proper test (and remove includes marked "remove").
  if (CommandLine::ForCurrentProcess()->HasSwitch("run-test-child")) {
    base::MessageLoop message_loop(
        scoped_ptr<base::MessagePump>(new mojo::common::MessagePumpMojo()));

    mojo::shell::Context context;
    TestChildProcessHostDelegate child_process_host_delegate;
    mojo::shell::ChildProcessHost child_process_host(
        &context, &child_process_host_delegate,
        mojo::shell::ChildProcess::TYPE_TEST);
    child_process_host.Start();
    message_loop.Run();
    int exit_code = child_process_host.Join();
    VLOG(2) << "Joined child: exit_code = " << exit_code;
    return 0;
  }

  // TODO(vtl): Unify parent and child process cases to the extent possible.
  if (scoped_ptr<mojo::shell::ChildProcess> child_process =
          mojo::shell::ChildProcess::Create(
              *CommandLine::ForCurrentProcess())) {
    child_process->Main();
  } else {
    gfx::GLSurface::InitializeOneOff();

    base::MessageLoop message_loop;
    mojo::shell::Context context;
    message_loop.PostTask(FROM_HERE, base::Bind(mojo::shell::Run, &context));

    message_loop.Run();
  }

  return 0;
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.activiti.standalone.escapeclause;

import java.util.HashMap;
import java.util.Map;

import org.flowable.common.engine.impl.history.HistoryLevel;
import org.flowable.engine.repository.DeploymentProperties;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.variable.api.history.HistoricVariableInstance;

public class HistoricVariableInstanceEscapeClauseTest extends AbstractEscapeClauseTestCase {

    private String deploymentOneId;

    private String deploymentTwoId;

    private ProcessInstance processInstance1;

    private ProcessInstance processInstance2;

    @Override
    protected void setUp() throws Exception {
        deploymentOneId = repositoryService
                .createDeployment()
                .tenantId("One%")
                .addClasspathResource("org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml")
                .deploymentProperty(DeploymentProperties.DEPLOY_AS_FLOWABLE5_PROCESS_DEFINITION, Boolean.TRUE)
                .deploy()
                .getId();

        deploymentTwoId = repositoryService
                .createDeployment()
                .tenantId("Two_")
                .addClasspathResource("org/activiti/engine/test/api/oneTaskProcess.bpmn20.xml")
                .deploymentProperty(DeploymentProperties.DEPLOY_AS_FLOWABLE5_PROCESS_DEFINITION, Boolean.TRUE)
                .deploy()
                .getId();

        Map<String, Object> vars = new HashMap<String, Object>();
        vars.put("var%", "One%");
        processInstance1 = runtimeService.startProcessInstanceByKeyAndTenantId("oneTaskProcess", vars, "One%");
        runtimeService.setProcessInstanceName(processInstance1.getId(), "One%");

        vars = new HashMap<String, Object>();
        vars.put("var_", "Two_");
        processInstance2 = runtimeService.startProcessInstanceByKeyAndTenantId("oneTaskProcess", vars, "Two_");
        runtimeService.setProcessInstanceName(processInstance2.getId(), "Two_");

        org.flowable.task.api.Task task = taskService.createTaskQuery().processInstanceId(processInstance1.getId()).singleResult();
        taskService.complete(task.getId());

        task = taskService.createTaskQuery().processInstanceId(processInstance2.getId()).singleResult();
        taskService.complete(task.getId());

        super.setUp();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        repositoryService.deleteDeployment(deploymentOneId, true);
        repositoryService.deleteDeployment(deploymentTwoId, true);
    }

    public void testQueryByVariableNameLike() {
        if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
            HistoricVariableInstance historicVariable = historyService.createHistoricVariableInstanceQuery().variableNameLike("%|%%").singleResult();
            assertNotNull(historicVariable);
            assertEquals(processInstance1.getId(), historicVariable.getProcessInstanceId());
            assertEquals("One%", historicVariable.getValue());

            historicVariable = historyService.createHistoricVariableInstanceQuery().variableNameLike("%|_%").singleResult();
            assertNotNull(historicVariable);
            assertEquals(processInstance2.getId(), historicVariable.getProcessInstanceId());
            assertEquals("Two_", historicVariable.getValue());
        }
    }

    public void testQueryLikeByQueryVariableValue() {
        if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
            HistoricVariableInstance historicVariable = historyService.createHistoricVariableInstanceQuery().variableValueLike("var%", "%|%%").singleResult();
            assertNotNull(historicVariable);
            assertEquals(processInstance1.getId(), historicVariable.getProcessInstanceId());

            historicVariable = historyService.createHistoricVariableInstanceQuery().variableValueLike("var_", "%|_%").singleResult();
            assertNotNull(historicVariable);
            assertEquals(processInstance2.getId(), historicVariable.getProcessInstanceId());
        }
    }

    public void testQueryLikeByQueryVariableValueIgnoreCase() {
        if (processEngineConfiguration.getHistoryLevel().isAtLeast(HistoryLevel.ACTIVITY)) {
            HistoricVariableInstance historicVariable = historyService.createHistoricVariableInstanceQuery().variableValueLikeIgnoreCase("var%", "%|%%").singleResult();
            assertNotNull(historicVariable);
            assertEquals(processInstance1.getId(), historicVariable.getProcessInstanceId());

            historicVariable = historyService.createHistoricVariableInstanceQuery().variableValueLikeIgnoreCase("var_", "%|_%").singleResult();
            assertNotNull(historicVariable);
            assertEquals(processInstance2.getId(), historicVariable.getProcessInstanceId());
        }
    }
}


text:
using Xunit;
using System.Collections.Generic;
using System.Reflection.CustomAttributesTests.Data;

// Need to disable warning related to CLS Compliance as using Array as custom attribute is not CLS compliant
#pragma warning disable 3016

namespace System.Reflection.Tests
{
    public class FieldInfoTestClass
    {
        public FieldInfoTestClass()
        {
        }

        [Attr(77, name = "AttrSimple"),
        Int32Attr(77, name = "Int32AttrSimple"),
        Int64Attr(77, name = "Int64AttrSimple"),
        StringAttr("hello", name = "StringAttrSimple"),
        EnumAttr(MyColorEnum.RED, name = "EnumAttrSimple"),
        TypeAttr(typeof(object), name = "TypeAttrSimple")]
        public string MyField = "MyField";

        public int Prop
        {
            get { return 0; }
            set { }
        }
    }

    // Test class for Custom Attribute Test
    public class FieldInfoCustomAttributeTests
    {
        [Theory]
        [InlineData(typeof(Int32Attr), "[System.Reflection.CustomAttributesTests.Data.Int32Attr((Int32)77, name = \"Int32AttrSimple\")]")]
        [InlineData(typeof(Int64Attr), "[System.Reflection.CustomAttributesTests.Data.Int64Attr((Int64)77, name = \"Int64AttrSimple\")]")]
        [InlineData(typeof(StringAttr), "[System.Reflection.CustomAttributesTests.Data.StringAttr(\"hello\", name = \"StringAttrSimple\")]")]
        [InlineData(typeof(EnumAttr), "[System.Reflection.CustomAttributesTests.Data.EnumAttr((System.Reflection.CustomAttributesTests.Data.MyColorEnum)1, name = \"EnumAttrSimple\")]")]
        [InlineData(typeof(TypeAttr), "[System.Reflection.CustomAttributesTests.Data.TypeAttr(typeof(System.Object), name = \"TypeAttrSimple\")]")]
        [InlineData(typeof(Attr), "[System.Reflection.CustomAttributesTests.Data.Attr((Int32)77, name = \"AttrSimple\")]")]
        public static void TestCustomAttributeDetails(Type type, string attributeStr)
        {
            FieldInfo fi = GetField("MyField");
            Assert.Contains(fi.CustomAttributes, attr => attr.AttributeType.Equals(type) && attr.ToString().Equals(attributeStr));
        }

        // Helper method to get field from Type type
        private static FieldInfo GetField(string fieldName)
        {
            Type t = typeof(FieldInfoTestClass);
            TypeInfo ti = t.GetTypeInfo();
            IEnumerator<FieldInfo> alldefinedFields = ti.DeclaredFields.GetEnumerator();
            FieldInfo fi = null, found = null;

            while (alldefinedFields.MoveNext())
            {
                fi = alldefinedFields.Current;
                if (fi.Name.Equals(fieldName))
                {
                    //found type
                    found = fi;
                    break;
                }
            }
            return found;
        }
    }
}


text:
layout: post
title: "Programming A LED Matrix Display"
description: ""
headline:
modified: 2016-04-07
category: Electronics
tags: [jekyll]
imagefeature:
mathjax:
chart:
comments: true
featured: false
---

In this article, I talk about how we learnt to program a LED matrix whose protocol we did not know. [Nikhil](http://nikhilendra.com/) and I worked on this with the [Almabase](http://almabase.com/) team for building a digital dashboard named Abacus for them.

The LED dot matrix display that we were trying to program looked similar to this. It was a 96x16 dot matrix display.

![NGX-Display](/images/blog/dot-matrix-1.jpg)

The manufacturer provided us with a windows application to program this, and it's source code. The source code seemed very complicated at first, and I thought it'd be extremely hard to figure out the code. Here's a screenshot from the windows application.

![Screenshot](/images/blog/dot-matrix-6.jpg)

We had to integrate this with a Raspberry Pi which runs Linux. The present code was in C sharp. C sharp is properly supported only in windows. So we had to rewrite the whole code in another launguage that Linux supports if we had to get this to work.

![Nikhil](/images/blog/dot-matrix-5.jpg)

It seemed scary at first but thanks to Nikhil. His experience at debugging complicated codes in Qualcomm was very helpful. He executed the code in Visual Studio, debugged it, understood what the packet information was. Once we looked at what byte information of the packets that we being sent into the device we were able to figure out the protocol. This was not as complicated as it seemed.

![Surya](/images/blog/dot-matrix-4.jpg)

Then we were able to program the protocol in Python. The code was less than 100 lines, and not as complicated as we assumed it would be at first. Here's an image with the dot matrix display coded with our algorithm in Python.

![Full](/images/blog/dot-matrix-3.jpg)

This is a great learning lesson for me.

> Most of the codes that look very complicated are not so complicated once you understand the logic behind them.

From here, next time I encounter a complicated code, I will debug it, and try to figure out the logic instead of thinking that it's impossible to figure things out.

**Thanks Nikhil!**


text:
(function() {
  'use strict';

  angular
    .module('horizon.framework.widgets.wizard')
    .controller('ModalContainerController', ModalContainerController);

  ModalContainerController.$inject = ['$scope', '$modalInstance', 'launchContext'];

  /**
   * @ngdoc controller
   * @name horizon.framework.widgets.wizard.controller:ModalContainerController
   * @description
   * Extends the bootstrap-ui modal widget
   */
  function ModalContainerController($scope, $modalInstance, launchContext) {
    // $scope is used because the methods are shared between
    // wizard and modal-container controller
    /*eslint-disable angular/ng_controller_as */
    $scope.launchContext = launchContext;
    $scope.close = function(args) {
      $modalInstance.close(args);
    };
    $scope.cancel = function() {
      $modalInstance.dismiss();
    };
    /*eslint-enable angular/ng_controller_as */
  }
})();


text:
FROM brucepc/mapguide

ENV DEBIAN_FRONTEND noninteractive

# ---------
# MULTIVERSE
# ---------
RUN apt-get update
RUN apt-get install -y --no-install-recommends software-properties-common wget unzip curl
RUN apt-add-repository multiverse
RUN apt-get update

# ---------
# MS CORE FONTS
# ---------
# from http://askubuntu.com/a/25614
RUN echo "ttf-mscorefonts-installer msttcorefonts/accepted-mscorefonts-eula select true" | debconf-set-selections
RUN apt-get install -y --no-install-recommends fontconfig ttf-mscorefonts-installer
# ADD localfonts.conf /etc/fonts/local.conf
# RUN fc-cache -f -v

RUN wget https://github.com/jumpinjackie/mapguide-react-layout/releases/download/v0.13.1/viewer.zip -O /tmp/viewer.zip
RUN wget http://download.osgeo.org/mapguide/releases/3.0.0/extras/Sheboygan.mgp -O /usr/local/mapguideopensource-3.1.2/server/Packages/Sheboygan.mgp
RUN unzip /tmp/viewer.zip -d /usr/local/mapguideopensource-3.1.2/webserverextensions/www
ADD index.php /usr/local/mapguideopensource-3.1.2/webserverextensions/www


text:
is a RESTful JSON API built using [Eden V4](https://github.com/eden-php)

### requirements
- PHP 5.6+
- Apache 2
- composer

### setup
- point your VirtualHost to `/public`
- run `composer install`
- run `mkdir upload && chmod 777 upload` for files

### features
- JWT authentication
- Lazy CRUD
- RESTful Module
- File Upload
- Image Render
- CSV Tool
- Email

### structure

	-------- Modules --------
	|			|			|
	Resource -> Service -> Controller
	|			|			|
	|			|			- presentation
	|			- business logic
	- database objects


text:
//
//  THDatePickerViewController.h
//  THCalendarDatePicker
//
//  Created by chase wasden on 2/10/13.
//  Adapted by Hannes Tribus on 31/07/14.
//  Copyright (c) 2014 3Bus. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import <KNSemiModalViewController_hons82/UIViewController+KNSemiModal.h>

#import "THDateDay.h"

@class THDatePickerViewController;

@protocol THDatePickerDelegate <NSObject>

-(void)datePickerDonePressed:(THDatePickerViewController *)datePicker;
-(void)datePickerCancelPressed:(THDatePickerViewController *)datePicker;

@optional

-(void)datePicker:(THDatePickerViewController *)datePicker selectedDate:(NSDate *)selectedDate;
-(void)datePicker:(THDatePickerViewController *)datePicker deselectedDate:(NSDate *)deselectedDate;
-(void)datePickerDidHide:(THDatePickerViewController *)datePicker;
-(void)datePicker:(THDatePickerViewController *)datePicker changedMonth:(NSInteger)month year:(NSInteger)year;

@end

@interface THDatePickerViewController : UIViewController <THDateDayDelegate>

+(THDatePickerViewController *)datePicker;

@property (strong, nonatomic) NSDate * date;
@property (weak, nonatomic) id<THDatePickerDelegate> delegate;
@property (strong, nonatomic) UIColor *selectedBackgroundColor;
@property (strong, nonatomic) UIColor *currentDateColor;
@property (strong, nonatomic) UIColor *currentDateColorSelected;
@property (nonatomic) float autoCloseCancelDelay;
@property (strong, nonatomic) NSTimeZone *dateTimeZone;
@property (nonatomic, getter=isRounded) BOOL rounded;
@property (nonatomic, getter=isHistoryFutureBasedOnInternal) BOOL historyFutureBasedOnInternal;
@property (weak, nonatomic) IBOutlet UIView *toolbarBackgroundView;
@property (nonatomic) float slideAnimationDuration;
@property (strong, nonatomic) NSString* dateTitle;
@property (strong, nonatomic) NSArray * selectedDates;

- (void)setDateHasItemsCallback:(BOOL (^)(NSDate * date))callback;

/*! Enable Clear Date Button
 * \param allow should show "clear date" button
 */
- (void)setAllowClearDate:(BOOL)allow;

/*! Enable Multi Day Selection
 * \param allow selection of multiple days
 */
- (void)setAllowMultiDaySelection:(BOOL)allow;

/*! Enable Ok Button when selected Date has already been selected
 * \param allow should show ok button
 */
- (void)setAllowSelectionOfSelectedDate:(BOOL)allow;

/*! Use Clear Date Button as "got to Today"
 * \param beTodayButton should use "clear date" button as today
 */
- (void)setClearAsToday:(BOOL)beTodayButton;

/*! Should the view be closed on selection of a date
 * \param autoClose should close view on selection
 */
- (void)setAutoCloseOnSelectDate:(BOOL)autoClose;

/*! Should it be possible to select dates in history
 * \param disableHistorySelection should it be possible?
 */
- (void)setDisableHistorySelection:(BOOL)disableHistorySelection;

/*! Should it be possible to select dates in future
 * \param disableFutureSelection should it be possible?
 */
- (void)setDisableFutureSelection:(BOOL)disableFutureSelection;

/*! Should it be possible to select dates in history up to a number of days (including today) or 0 if any date
 * \param daysInHistory how many days?
 */
- (void)setDaysInHistorySelection:(NSUInteger)daysInHistory;

/*! Should it be possible to select dates in future up to a number of days (including today) or 0 if any date
 * \param daysInFuture how many days?
 */
- (void)setDaysInFutureSelection:(NSUInteger)daysInFuture;

/*! Set the timeZone by name to be used. Valid timezones can be retrieved using [NSTimeZone knownTimeZoneNames]
 * \param the name of the timezone to be used
 * \return successful?
 */
- (BOOL)setDateTimeZoneWithName:(NSString *)name;

/*! Should it be possible to fast switch the year
 * \param disableYearSwitch should it be possible?
 */
- (void)setDisableYearSwitch:(BOOL)disableYearSwitch;

/*! Set date range
 * \param fromDate      range from
 * \param toDate        range to
 */
- (void)setDateRangeFrom:(NSDate *)fromDate toDate:(NSDate *)toDate;

/*! Set calendar title
 * \param dateTitle     calendar title
 */
- (void)setDateTitle:(NSString*)dateTitle;

/*! Redraw the calendar to update the dot indicators
 */
- (void)redraw;
@end


text:
package cz.cuni.mff.spl.deploy.store;

import java.io.InputStream;
import java.io.OutputStream;

import cz.cuni.mff.spl.deploy.build.SampleIdentification;
import cz.cuni.mff.spl.deploy.store.exception.StoreException;

/**
 *
 * @author Frantisek Haas
 *
 */
public interface IStore extends IStoreReadonly {

    /**
     * Saves measurement from the stream into the store. There is a special
     * requirement on measurement files. They must contain their full
     * identification in the commentary on the first line. Commentary line
     * starts with character '#'.
     *
     * @param measurement
     * @param identification
     * @throws StoreException
     */
    public void saveMeasurement(InputStream measurement, SampleIdentification identification)
            throws StoreException;

    /**
     * Creates evaluation directory and returns object to control it.
     *
     * @param prefix
     * @return
     */
    public IStoreDirectory createEvaluationDirectory(String prefix)
            throws StoreException;

    /**
     * Interface to access store directory object.
     *
     *

     * {@link IStore} interface supports one level of directories. Therefore a
     * separate directory may be created per run (e.g. evaluation process) of
     * SPL framework.
     *

     *
     * @author Frantisek Haas
     *
     */
    public interface IStoreDirectory extends IStoreReadonlyDirectory {

        /**
         * Creates file with specified name in the directory.
         *
         * @param name
         *            Full name of the file to be created.
         * @return
         *         Object to access the file.
         *
         * @throws StoreException
         */
        public IStoreFile createFile(String name)
                throws StoreException;

        /**
         * Creates unique file with specified prefix and suffix in the
         * directory.
         *
         * @param prefix
         *            Mandatory prefix of the file.
         * @param suffix
         *            Mandatory suffix of the file.
         * @return
         *         Object to access the file.
         *
         * @throws StoreException
         */
        public IStoreFile createUniqueFile(String prefix, String suffix)
                throws StoreException;

        /**
         * Interface to access store file object.
         *
         * @author Frantisek Haas
         *
         */
        public interface IStoreFile extends IStoreReadonlyFile {

            /**
             * Gets the output stream to save content to.
             *
             * @return The output stream.
             * @throws StoreException
             *             The store exception.
             */
            public OutputStream getOutputStream()
                    throws StoreException;

            /**
             * Deletes file.
             *
             *

             * Note that this operation may not be supported and
             * {@link StoreException} will be thrown.
             *
             * @return True if and only if the file; false otherwise.
             * @throws StoreException
             *             The store exception.
             */
            public boolean delete()
                    throws StoreException;
        }
    }
}


text:
package com.granule;

/**
 * User: Dario Wunsch
 * Date: 23.06.2010
 * Time: 1:32:46
 */
public class JSCompileException extends Exception {

	private static final long serialVersionUID = -2323320364173426969L;

	public JSCompileException(Throwable cause) {
        super(cause);
    }

    public JSCompileException() {
        super();
    }

    public JSCompileException(String message) {
        super(message);
    }
}


text:
<?php
return array (
  '{userName} created task {task}.' => '{userName} ha creato il task {task}.',
);


text:
module spa.main.components {
    export class MyButton {
        // inject services here
        static $inject = [];

        name:string = 'my-button';
        color:string;

        constructor() {
            //place your initialize logic here
        }

        change() {
            this.color = 'green';
        }

        link(element: HTMLElement, homePage: pages.HomePage, transclude){
            //console.log(homePage);
        }
    }
}


text:
#include "main/VRMain.h"
#include <main/VREventHandler.h>
#include <main/VRRenderHandler.h>
#include <plugin/VRPlugin.h>

using namespace MinVR;

// Event and Render python callback functions
extern "C" {
	PLUGIN_API typedef int (*eventcallback_type)(const char* eventName, void* eventData);
	PLUGIN_API typedef int (*rendercallback_type)(void* renderState);
}

// Event handler callback wrapper
class VRPythonEventCallbackHandler : public VREventHandler {
public:
	PLUGIN_API VRPythonEventCallbackHandler(eventcallback_type eventCallback) : eventCallback(eventCallback) {}
	PLUGIN_API virtual ~VRPythonEventCallbackHandler() {}

	PLUGIN_API virtual void onVREvent(const VRDataIndex &event) {
		eventCallback(event.getName().c_str(), (void*)&event);
	}

private:
	eventcallback_type eventCallback;
};

// Render handler callback wrapper
class VRPythonRenderCallbackHandler : public VRRenderHandler {
public:
	PLUGIN_API VRPythonRenderCallbackHandler(rendercallback_type renderCallback, rendercallback_type renderContextCallback) : renderCallback(renderCallback), renderContextCallback(renderContextCallback) {}
	PLUGIN_API virtual ~VRPythonRenderCallbackHandler() {}

	PLUGIN_API virtual void onVRRenderScene(const VRDataIndex &renderState) {
		renderCallback((void*)&renderState);
	}
	PLUGIN_API virtual void onVRRenderContext(const VRDataIndex &renderState) {
		renderContextCallback((void*)&renderState);
	}

private:
	rendercallback_type renderCallback;
	rendercallback_type renderContextCallback;
};

// Python hooks
extern "C" {

	// Create VRMain
	PLUGIN_API VRMain* VRMain_init(char* searchPath, int argc, char** argv) {
		VRMain* vrmain = new VRMain();
		vrmain->addPluginSearchPath(std::string(searchPath));
		vrmain->initialize(argc, argv);
		std::cout << "Plugin directory: " << std::string(searchPath) << std::endl;
		return vrmain;
	}

	// Shutdown VRMain
	PLUGIN_API void VRMain_shutdown(VRMain* vrmain, VREventHandler* eventHandler, VRRenderHandler* renderHandler) {
		vrmain->shutdown();
		delete eventHandler;
		delete renderHandler;
		delete vrmain;
	}

	// Register event callback
	PLUGIN_API VREventHandler* VRMain_registerEventCallback(VRMain* vrmain, eventcallback_type eventCallback) {
		VREventHandler* handler = new VRPythonEventCallbackHandler(eventCallback);
		vrmain->addEventHandler(handler);
		return handler;
	}

	// Register render callback
	PLUGIN_API VRRenderHandler* VRMain_registerRenderCallback(VRMain* vrmain, rendercallback_type renderCallback, rendercallback_type renderContextCallback) {
		VRRenderHandler* handler = new VRPythonRenderCallbackHandler(renderCallback, renderContextCallback);
		vrmain->addRenderHandler(handler);
		return handler;
	}

	// Allow python specific plugins which calls the python modules specified
	PLUGIN_API bool setPluginList(VRMain* vrmain, char* pluginList) {
		if (vrmain->getConfig()->exists("PythonPlugins","/")) {
			std::string py = vrmain->getConfig()->getValue("PythonPlugins","/");
			strcpy(pluginList, py.c_str());

			return true;
		}

		return false;
	}

	// Runs main loop
	PLUGIN_API void VRMain_mainloop(VRMain* vrmain) {
		vrmain->mainloop();
	}
}


text:
module.exports = function(sector) {
	sector.factory('Blocks', function(DEFAULTS) {
		return {

		}
	});
};


text:
import React, {
  View,
  Text,
  StyleSheet,
  Component,
  TouchableHighlight,
  Alert
} from 'react-native';

import baseStyles from '../baseStyles';
import ScoreButton from './ScoreButton';
import UserList from './UserList';
import FirebaseRef from '../FirebaseRef';

export default class Game extends Component {
  constructor() {
    super();
    this.state = {
      score: {
        challenger: 0,
        opponent: 0
      }
    };
  }

  componentDidMount() {
    FirebaseRef.database().ref('games').on('child_changed', this._updateGame.bind(this));
  }

  componentWillUnmount() {
    FirebaseRef.database().ref('games').off('child_changed');
  }

  componentDidUpdate() {
    console.log('componentDidUpdate', this.state.score);
    if (this.state.score.challenger === 12) {
      this._isCurrentUser(this.props.game.challenger) ? this._showWinnerDialog() : this._showLoserDialog();
    } else if (this.state.score.opponent === 12) {
      this._isCurrentUser(this.props.game.opponent) ? this._showWinnerDialog() : this._showLoserDialog();
    }
  }

  _showLoserDialog() {
    Alert.alert(
      'Perdeu marreco!',
      'Perdeu hein, que tal uma revanche?',
      [
        { text: 'OK', style: 'cancel', onPress: this._openUserList.bind(this) }
      ]
    );
  }

  _showWinnerDialog() {
    Alert.alert(
      'Ganhou marreco!',
      'Tá facil ganhar desse pato hein, que tal desafiar outro?',
      [
        { text: 'OK', style: 'cancel', onPress: this._openUserList.bind(this) }
      ]
    );
  }

  _openUserList() {
    this.props.navigator.replace({
      title: 'UserList',
      component: UserList,
      passProps: { user: this.props.currentUser }
    });
  }

  _updateGame(data) {
    let game = Object.assign(data.val(), { uid: data.key });

    if (game.uid === this.props.game.uid && (game.score.challenger !== this.state.score.challenger || game.score.opponent !== this.state.score.opponent)) {
      this.setState({ score: game.score });
    }
  }

  _addScore(score) {
    var newScore;

    if (this._isCurrentUser(this.props.game.challenger)) {
      newScore = Object.assign(this.state.score, { challenger: this.state.score.challenger + score });
    } else {
      newScore = Object.assign(this.state.score, { opponent: this.state.score.opponent + score });
    }

    if (newScore.challenger > 12 || newScore.opponent > 12) {
      return;
    }

    this.setState({ score: newScore });
    FirebaseRef.database().ref('games/' + this.props.game.uid).update({ score: newScore });
  }

  _isCurrentUser(user) {
    return this.props.currentUser.uid === user.uid;
  }

  render() {
    return(
      <View style={baseStyles.container}>
        <View style={[baseStyles.container, styles.container, styles.scoreContainer]}>
          <Text style={[baseStyles.title, styles.title]}>{this.state.score.challenger}</Text>
          <Text style={baseStyles.title}>x</Text>
          <Text style={[baseStyles.title, styles.title]}>{this.state.score.opponent}</Text>
        </View>
        <View style={[baseStyles.container, styles.container, styles.usersContainer]}>
          <Text style={[baseStyles.title, styles.title]}>{this.props.game.challenger.username}</Text>
          <Text style={[baseStyles.title, styles.title]}>{this.props.game.opponent.username}</Text>
        </View>
        <View style={[baseStyles.container, styles.buttonsContainer]}>
          <ScoreButton score={'+1'} onClick={() => this._addScore(1)} />
          <ScoreButton score={'+3'} onClick={() => this._addScore(3)} />
          <ScoreButton score={'+6'} onClick={() => this._addScore(6)} />
          <ScoreButton score={'+9'} onClick={() => this._addScore(9)} />
          <ScoreButton score={'+12'} onClick={() => this._addScore(12)} />
        </View>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'flex-start',
    padding: 10
  },
  scoreContainer: {
    marginTop: 30,
    flex: .05,
    justifyContent: 'space-around'
  },
  usersContainer: {
    flex: .15,
    justifyContent: 'space-around'
  },
  buttonsContainer: {
    flex: .50,
    flexDirection: 'row',
    justifyContent: 'center',
    flexWrap: 'wrap'
  },
  title: {
    fontSize: 30,
  }
});


text:
/***********************************************************************
    created:    24/9/2004
    author:     Paul D Turner
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifndef _CEGuiD3D9BaseApplication_h_
#define _CEGuiD3D9BaseApplication_h_

#include "CEGuiBaseApplication.h"
#include "CEGUI/GeometryBuffer.h"

#if defined( __WIN32__ ) || defined( _WIN32 )
#   define WIN32_LEAN_AND_MEAN
#   include <windows.h>

// undefine Microsoft macro evilness
#   undef min
#   undef max
#endif

struct CEGuiBaseApplication9Impl;

class CEGuiD3D9BaseApplication : public CEGuiBaseApplication
{
public:
    //! Constructor.
    CEGuiD3D9BaseApplication();

    //! Destructor.
    ~CEGuiD3D9BaseApplication();

protected:
    /*************************************************************************
        Implementation Methods
    *************************************************************************/
    /*!
    \brief
        Initialises Direct3D system.
    */
    bool initialiseDirect3D(unsigned int width, unsigned int height, unsigned int adapter, bool windowed);

    /*!
    \brief
        Do reset of Direct3D device

    \return
        - true if the device was reset successfully
        - false if the device was not reset.
    */
    bool resetDirect3D(void);

    // Implementation of base class abstract methods.
    void run();
    void destroyWindow();
    void beginRendering(const float elapsed);
    void endRendering();

    /*************************************************************************
        Data fields
    *************************************************************************/
    CEGuiBaseApplication9Impl* pimpl;

    // counter used to track elapsed time
    DWORD d_lastFrameTime;
};

#endif  // end of guard _CEGuiD3D9BaseApplication_h_


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

namespace yycms.union.wechat
{
   public class Fans:SDK
    {
        public Fans(String _Accecc_Token)
        {
            base.Access_Token = _Accecc_Token;
        }

        #region 查询粉丝
        public FansModel Batch_Get(String next_openid)
        {
            var res = Get("https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + Access_Token + "&next_openid=" + next_openid);

            var result = JsonConvert.DeserializeObject<FansModel>(res);

            return result;
        }
        #endregion

        public FansInfo Detail(String OPENID)
        {
            var res = Get("https://api.weixin.qq.com/cgi-bin/user/info?access_token="+ Access_Token + "&openid="+ OPENID + "&lang=zh_CN");

            var result = JsonConvert.DeserializeObject<FansInfo>(res);

            return result;
        }

        public JObject SendMsg(String openID,String content)
        {
            var ReqStr = JsonConvert.SerializeObject(new
            {
                touser = openID,
                msgtype = "text",
                text = new
                {
                    content = content
                }
            });

            var res = Request("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_Token, ReqStr);

            return res;
        }

        public JObject SendByImage(String openID, String media_id)
        {
            var ReqStr = JsonConvert.SerializeObject(new
            {
                touser = openID,
                msgtype = "image",
                image = new
                {
                    media_id = media_id
                }
            });

            var res = Request("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_Token, ReqStr);

            return res;
        }

        public JObject SendByNews(String openID, Object _articles)
        {
            var ReqStr = JsonConvert.SerializeObject(new
            {
                touser = openID,
                msgtype = "news",
                news = new
                {
                    articles = _articles
                }
            });

            var res = Request("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + Access_Token, ReqStr);

            return res;
        }
    }
}


text:
"""
  equip.analysis.dataflow.lattice
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  The base lattice implementation (mostly used as semi-lattice).

  :copyright: (c) 2014 by Romain Gaucher (@rgaucher)
  :license: Apache 2, see LICENSE for more details.
"""

class Lattice(object):
  """
    Interface for a lattice element. Practically, we only use the semi-lattice
    with the join (V) operator.
  """
  def __init__(self):
    pass

  def init_state(self):
    """
      Returns a new initial state.
    """
    pass

  def join_all(self, *states):
    result_state = None
    for state in states:
      if result_state is None:
        result_state = state
      else:
        result_state = self.join(result_state, state)
    return result_state

  def join(self, state1, state2):
    """
      Returns the result of the V (supremum) between the two states.
    """
    pass

  def meet_all(self, *states):
    result_state = None
    for state in states:
      if result_state is None:
        result_state = state
      else:
        result_state = self.meet(result_state, state)
    return result_state

  def meet(self, state1, state2):
    """
      Returns the result of the meet \/ (infimum) between the two states.
    """
    pass

  def lte(self, state1, state2):
    """
      This is the <= operator between two lattice elements (states) as defined by:
        state1 <= state2 and state2 <= state1 <=> state1 == state2
    """
    pass

  def top(self):
    """
      The top of the lattice.
    """
    pass

  def bottom(self):
    """
      The bottom of the lattice.
    """
    pass


text:
package com.txusballesteros.mara.compiler.writer;

import java.io.BufferedWriter;

public abstract class JavaWriter {
    private BufferedWriter writer;

    public JavaWriter(BufferedWriter writer) {
        this.writer = writer;
    }
}


text:
from pywin.mfc import dialog
import win32api
import win32con
import win32ui
import copy
import string
from scintillacon import *

######################################################
# Property Page for syntax formatting options

# The standard 16 color VGA palette should always be possible
paletteVGA = ( ("Black",0,0,0), ("Navy",0,0,128), ("Green",0,128,0), ("Cyan",0,128,128),
	("Maroon",128,0,0), ("Purple",128,0,128), ("Olive",128,128,0), ("Gray",128,128,128),
	("Silver",192,192,192), ("Blue",0,0,255), ("Lime",0,255,0), ("Aqua",0,255,255),
	("Red",255,0,0), ("Fuchsia",255,0,255), ("Yellow",255,255,0), ("White",255,255,255),
# and a few others will generally be possible.
	("DarkGrey", 64,64,64 ), ("PurpleBlue",64,64,192), ("DarkGreen",0,96,0),
	("DarkOlive",128,128,64), ("MediumBlue",0,0,192), ("DarkNavy",0,0,96),
	("Magenta",96,0,96), ("OffWhite", 255,255,220 ), ("LightPurple",220,220,255),
)

def BGR(b,g,r):		# Colors in font definitions are integers made up of Blue, Green, and Red bytes
    return b*256*256 + g*256 + r

class ScintillaFormatPropertyPage(dialog.PropertyPage):
	def __init__(self, scintillaClass = None, caption = 0):
		self.scintillaClass = scintillaClass
		dialog.PropertyPage.__init__(self, win32ui.IDD_PP_FORMAT, caption=caption)

	def OnInitDialog(self):
		try:
			if self.scintillaClass is None:
				import control
				sc = control.CScintillaEdit
			else:
				sc = self.scintillaClass

			self.scintilla = sc()
			style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.ES_MULTILINE
			# Convert the rect size
			rect = self.MapDialogRect( (5, 5, 120, 75))
			self.scintilla.CreateWindow(style, rect, self, 111)
			self.HookNotify(self.OnBraceMatch, SCN_CHECKBRACE)
			self.scintilla.HookKeyStroke(self.OnEsc, 27)
			self.scintilla.SCISetViewWS(1)
			self.pos_bstart = self.pos_bend = self.pos_bbad = 0

			colorizer = self.scintilla._GetColorizer()
			text = colorizer.GetSampleText()
			items = string.split(text, '|', 2)
			pos = len(items[0])
			self.scintilla.SCIAddText(string.join(items,''))
			self.scintilla.SetSel(pos, pos)
			self.scintilla.ApplyFormattingStyles()
			self.styles = self.scintilla._GetColorizer().styles

			self.cbo = self.GetDlgItem(win32ui.IDC_COMBO1)
			for c in paletteVGA:
				self.cbo.AddString(c[0])

			self.cboBoldItalic = self.GetDlgItem(win32ui.IDC_COMBO2)
			for item in ["Bold Italic", "Bold", "Italic", "Regular"]:
				self.cboBoldItalic.InsertString(0, item)

			self.butIsDefault = self.GetDlgItem(win32ui.IDC_CHECK1)
			self.butIsDefaultBackground = self.GetDlgItem(win32ui.IDC_CHECK2)
			self.listbox = self.GetDlgItem(win32ui.IDC_LIST1)
			self.HookCommand(self.OnListCommand, win32ui.IDC_LIST1)
			names = self.styles.keys()
			names.sort()
			for name in names:
				if self.styles[name].aliased is None:
					self.listbox.AddString(name)
			self.listbox.SetCurSel(0)

			idc = win32ui.IDC_RADIO1
			if not self.scintilla._GetColorizer().bUseFixed: idc = win32ui.IDC_RADIO2
			self.GetDlgItem(idc).SetCheck(1)
			self.UpdateUIForStyle(self.styles[names[0]])

			self.scintilla.HookFormatter(self)
			self.HookCommand(self.OnButDefaultFixedFont, win32ui.IDC_BUTTON1)
			self.HookCommand(self.OnButDefaultPropFont, win32ui.IDC_BUTTON2)
			self.HookCommand(self.OnButThisFont, win32ui.IDC_BUTTON3)
			self.HookCommand(self.OnButUseDefaultFont, win32ui.IDC_CHECK1)
			self.HookCommand(self.OnButThisBackground, win32ui.IDC_BUTTON4)
			self.HookCommand(self.OnButUseDefaultBackground, win32ui.IDC_CHECK2)
			self.HookCommand(self.OnStyleUIChanged, win32ui.IDC_COMBO1)
			self.HookCommand(self.OnStyleUIChanged, win32ui.IDC_COMBO2)
			self.HookCommand(self.OnButFixedOrDefault, win32ui.IDC_RADIO1)
			self.HookCommand(self.OnButFixedOrDefault, win32ui.IDC_RADIO2)
		except:
			import traceback
			traceback.print_exc()

	def OnEsc(self, ch):
		self.GetParent().EndDialog(win32con.IDCANCEL)

	def OnBraceMatch(self, std, extra):
		import pywin.scintilla.view
		pywin.scintilla.view.DoBraceMatch(self.scintilla)

	def GetSelectedStyle(self):
		return self.styles[self.listbox.GetText(self.listbox.GetCurSel())]

	def _DoButDefaultFont(self, extra_flags, attr):
		baseFormat = getattr(self.scintilla._GetColorizer(), attr)
		flags = extra_flags | win32con.CF_SCREENFONTS | win32con.CF_EFFECTS | win32con.CF_FORCEFONTEXIST
		d=win32ui.CreateFontDialog(baseFormat, flags, None, self)
		if d.DoModal()==win32con.IDOK:
			setattr(self.scintilla._GetColorizer(), attr, d.GetCharFormat())
			self.OnStyleUIChanged(0, win32con.BN_CLICKED)

	def OnButDefaultFixedFont(self, id, code):
		if code==win32con.BN_CLICKED:
			self._DoButDefaultFont(win32con.CF_FIXEDPITCHONLY, "baseFormatFixed")
			return 1

	def OnButDefaultPropFont(self, id, code):
		if code==win32con.BN_CLICKED:
			self._DoButDefaultFont(win32con.CF_SCALABLEONLY, "baseFormatProp")
			return 1

	def OnButFixedOrDefault(self, id, code):
		if code==win32con.BN_CLICKED:
			bUseFixed = id == win32ui.IDC_RADIO1
			self.GetDlgItem(win32ui.IDC_RADIO1).GetCheck() != 0
			self.scintilla._GetColorizer().bUseFixed = bUseFixed
			self.scintilla.ApplyFormattingStyles(0)
			return 1

	def OnButThisFont(self, id, code):
		if code==win32con.BN_CLICKED:
			flags = win32con.CF_SCREENFONTS | win32con.CF_EFFECTS | win32con.CF_FORCEFONTEXIST
			style = self.GetSelectedStyle()
			# If the selected style is based on the default, we need to apply
			# the default to it.
			def_format = self.scintilla._GetColorizer().GetDefaultFormat()
			format = style.GetCompleteFormat(def_format)
			d=win32ui.CreateFontDialog(format, flags, None, self)
			if d.DoModal()==win32con.IDOK:
				style.format = d.GetCharFormat()
				self.scintilla.ApplyFormattingStyles(0)
			return 1

	def OnButUseDefaultFont(self, id, code):
		if code == win32con.BN_CLICKED:
			isDef = self.butIsDefault.GetCheck()
			self.GetDlgItem(win32ui.IDC_BUTTON3).EnableWindow(not isDef)
			if isDef: # Being reset to the default font.
				style = self.GetSelectedStyle()
				style.ForceAgainstDefault()
				self.UpdateUIForStyle(style)
				self.scintilla.ApplyFormattingStyles(0)
			else:
				# User wants to override default -
				# do nothing!
				pass

	def OnButThisBackground(self, id, code):
		if code==win32con.BN_CLICKED:
			style = self.GetSelectedStyle()
			bg = win32api.RGB(0xff, 0xff, 0xff)
			if style.background is not None:
				bg = style.background
			d=win32ui.CreateColorDialog(bg, 0, self)
			if d.DoModal()==win32con.IDOK:
				style.background = d.GetColor()
				self.scintilla.ApplyFormattingStyles(0)
			return 1

	def OnButUseDefaultBackground(self, id, code):
		if code == win32con.BN_CLICKED:
			isDef = self.butIsDefaultBackground.GetCheck()
			self.GetDlgItem(win32ui.IDC_BUTTON4).EnableWindow(not isDef)
			if isDef: # Being reset to the default color
				style = self.GetSelectedStyle()
				style.background = None
				self.UpdateUIForStyle(style)
				self.scintilla.ApplyFormattingStyles(0)
			else:
				# User wants to override default -
				# do nothing!
				pass

	def OnListCommand(self, id, code):
		if code==win32con.LBN_SELCHANGE:
			style = self.GetSelectedStyle()
			self.UpdateUIForStyle(style)
		return 1

	def UpdateUIForStyle(self, style ):
		format = style.format
		sel = 0
		for c in paletteVGA:
			if format[4] == BGR(c[3], c[2], c[1]):
#				print "Style", style.name, "is", c[0]
				break
			sel = sel + 1
		else:
			sel = -1
		self.cbo.SetCurSel(sel)
		self.butIsDefault.SetCheck(style.IsBasedOnDefault())
		self.GetDlgItem(win32ui.IDC_BUTTON3).EnableWindow(not style.IsBasedOnDefault())

		self.butIsDefaultBackground.SetCheck(style.background is None)
		self.GetDlgItem(win32ui.IDC_BUTTON4).EnableWindow(style.background is not None)

		bold = format[1] & win32con.CFE_BOLD != 0; italic = format[1] & win32con.CFE_ITALIC != 0
		self.cboBoldItalic.SetCurSel( bold*2 + italic )

	def OnStyleUIChanged(self, id, code):
		if code in [win32con.BN_CLICKED, win32con.CBN_SELCHANGE]:
			style = self.GetSelectedStyle()
			self.ApplyUIFormatToStyle(style)
			self.scintilla.ApplyFormattingStyles(0)
			return 0
		return 1

	def ApplyUIFormatToStyle(self, style):
		format = style.format
		color = paletteVGA[self.cbo.GetCurSel()]
		effect = 0
		sel = self.cboBoldItalic.GetCurSel()
		if sel==0:
			effect = 0
		elif sel==1:
			effect = win32con.CFE_ITALIC
		elif sel==2:
			effect = win32con.CFE_BOLD
		else:
			effect = win32con.CFE_BOLD | win32con.CFE_ITALIC
		maskFlags=format[0]|win32con.CFM_COLOR|win32con.CFM_BOLD|win32con.CFM_ITALIC
		style.format = (maskFlags, effect, style.format[2], style.format[3], BGR(color[3], color[2], color[1])) + style.format[5:]

	def OnOK(self):
		self.scintilla._GetColorizer().SavePreferences()
		return 1

def test():
	page = ColorEditorPropertyPage()
	sheet = pywin.mfc.dialog.PropertySheet("Test")
	sheet.AddPage(page)
	sheet.CreateWindow()


text:
<?php
session_start();
 include("includes/connect_db.php");

include("functions/function.php");

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>My Shopping Cart Website</title>
<link rel="stylesheet" href="style/style.css" media="all"/>

Home

All Product

Sign Up

Shopping Cart

Contact Us

My Account

Categories

<?php

getcat();      //categories function call
?>

Brand

<?php

 getbrand()
?>

<form action="search_product.php" method="get" enctype="multipart/form-data">
<input type="text" name="search" placeholder="Search a Product" size="30px">
<input type="submit" name="submit" value="Search">

</form>

<?php
if(isset($_SESSION['cust_email']))
{
echo $_SESSION['cust_email'];

}
else
{
echo "Welcome:Guest";
}
?>

<?php
if(!isset($_SESSION['cust_email']))
{

echo "Login";

}
else
{
echo "Logout";

}

?>

Item:   <?php total_items(); ?>

price: Rs.<?php total_price() ;?>

Back to Shopping

<?php
/*if(!isset($_SESSION['cust_email']))
{

echo "Login";

}
else
{
echo "Logout";

}
*/
?>

<?php cart(); ?>

<form action="go_to_cart_page.php" method="post" name="go_to_cart" enctype="multipart/form-data">

Your Cart

Remove
Products
Quantity
Price
Subtotal

<?php
$total=0;

$ip=getIP();

$price_product="select *from cart where ip_address='$ip'";

$price_run=mysql_query($price_product);

while($price_select=mysql_fetch_array($price_run))

{

$pro_id=$price_select['p_id'];
$price="select * from products where product_id='$pro_id'";

$item_price=mysql_query($price);

while($p_price=mysql_fetch_array($item_price))
{
$pro_single_price=$p_price['product_price'];
$pro_img1=$p_price['img1'];
$pro_title=$p_price['product_title'];

$price=array($p_price['product_price']);
$total_price=array_sum($price);

$total+=$total_price;

?>
<input type="checkbox" name="remove[]" value=<?php echo $pro_id; ?>/>
<?php echo $pro_title; ?>
<?php echo ""; ?>
<input type="text "name="quantity" value="1" size="5">
Rs: <?php echo $pro_single_price; ?>
abc
<input type="submit" name="qty_up" value="Update">

<?php }}?>

Total Price: <?php echo $total; ?>

<input type="submit" name="update_cart" value="Delete">
<input type="submit" name="continue" value="Continue Shoping">

<button>Checkout</button>

</form>

<?php

function update_qty()
{
                                      //script for update cart
if(isset($_POST['update_cart']))
{
$ip=getIp();

foreach($_POST['remove'] as $remove_id)
{

$delete_product="delete from cart where p_id='$remove_id' AND  ip_address='$ip'";

$run_delete=mysql_query($delete_product);

if($run_delete)
{
echo "";

}

}

}

if(isset($_POST['continue']))
{

echo "";

}

}

?>

<?php  @update_qty(); ?>


text:
function patches = sampleIMAGES_sp(imld,patchsize,numpatches)
% sampleIMAGES
% Returns 10000 patches for training

% % For the ASSIGMENT 1:
% load IMAGES;    % load images from disk
% patchsize = 8;  % we'll use 8x8 patches
% numpatches = 10000;

% For the ASSIGMENT 2:
% imld = loadMNISTImages('train-images.idx3-ubyte');
% numpatches = 10000;
% imm = imld(:,1:numpatches);
% patchsize = 28;

% Initialize patches with zeros.  Your code will fill in this matrix--one
% column per patch, 10000 columns.
patches = zeros(patchsize*patchsize, numpatches);

%% ---------- YOUR CODE HERE --------------------------------------
%  Instructions: Fill in the variable called "patches" using data
%  from IMAGES.
%
%  IMAGES is a 3D array containing 10 images
%  For instance, IMAGES(:,:,6) is a 512x512 array containing the 6th image,
%  and you can type "imagesc(IMAGES(:,:,6)), colormap gray;" to visualize
%  it. (The contrast on these images look a bit off because they have
%  been preprocessed using using "whitening."  See the lecture notes for
%  more details.) As a second example, IMAGES(21:30,21:30,1) is an image
%  patch corresponding to the pixels in the block (21,21) to (30,30) of
%  Image 1

% We start by getting the dimensions. We know the images are squared, if
% it's rectangular, just changed it.

%====================================
% For the ASSIGMENT 1:
ii = imld(:,:,6);
[m n] = size(ii);

% Select the number of specified patches:
for i = 1:numpatches
    % We first sample uniformy an images out of the ten:
    randp = unidrnd(10);
%     imsel = IMAGES(:,:,randp);

    % We pick the upper left corner of the image:
    ycord = unidrnd(m - patchsize + 1);
    xcord = unidrnd(n - patchsize + 1);
    % We now select the random patch:
%     patchsel = imsel(ycord:ycord + patchsize - 1, xcord:xcord + patchsize - 1);

    patchsel = imld(ycord:ycord + patchsize - 1, xcord:xcord + patchsize - 1, randp);

    patches(:,i) = patchsel(:);
end
%====================================

%====================================
% % For the ASSIGMENT 2:
% patches = imm;
%====================================

%% ---------------------------------------------------------------
% For the autoencoder to work well we need to normalize the data
% Specifically, since the output of the network is bounded between [0,1]
% (due to the sigmoid activation function), we have to make sure
% the range of pixel values is also bounded between [0,1]
% ONLY FOR ASSIGMENT 1:
% patches = normalizeData(patches);

end

%% ---------------------------------------------------------------
function patches = normalizeData(patches)

% Squash data to [0.1, 0.9] since we use sigmoid as the activation
% function in the output layer

% Remove DC (mean of images).
patches = bsxfun(@minus, patches, mean(patches));

% Truncate to +/-3 standard deviations and scale to -1 to 1
pstd = 3 * std(patches(:));
patches = max(min(patches, pstd), -pstd) / pstd;

% Rescale from [-1,1] to [0.1,0.9]
patches = (patches + 1) * 0.4 + 0.1;

end


text:
using Spring.Core.CDH.Autowire;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Spring.Core.CDH
{
    /// <summary>
    /// Autowire 대상 속성을 판별하여, <see cref="AutowireTargetPropertyInfo"/> 열거하여 가져 옵니다.
    /// </summary>
    internal static class AutowireTargetPropertyGetter
    {
        /// <summary>
        /// Autowie 대상 정보를 가져 옵니다.
        /// </summary>
        /// <param name="type"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public static IEnumerable<AutowireTargetPropertyInfo> GetAutowireTargetPropertiesInfo(Type type, AutowireTargetPropertyInfo parent)
        {
            return type.GetProperties()
                .Where(prop => prop.IsAttributeDefined<AutowireAttribute>())
                .Select(prop => new AutowireTargetPropertyInfo(prop, parent));
        }
    }
}


text:
import * as ts from 'typescript/lib/tsserverlibrary';
import {NgLanguageService, PluginConfig} from './api';

export * from './api';

interface PluginModule extends ts.server.PluginModule {
  create(createInfo: ts.server.PluginCreateInfo): NgLanguageService;
  onConfigurationChanged?(config: PluginConfig): void;
}

const factory: ts.server.PluginModuleFactory = (tsModule): PluginModule => {
  let plugin: PluginModule;

  return {
    create(info: ts.server.PluginCreateInfo): NgLanguageService {
      const config: PluginConfig = info.config;
      const bundleName = config.ivy ? 'ivy.js' : 'language-service.js';
      plugin = require(`./bundles/${bundleName}`)(tsModule);
      return plugin.create(info);
    },
    getExternalFiles(project: ts.server.Project): string[] {
      return plugin?.getExternalFiles?.(project) ?? [];
    },
    onConfigurationChanged(config: PluginConfig): void {
      plugin?.onConfigurationChanged?.(config);
    },
  };
};

module.exports = factory;


text:
#Tutoriais, plugins, snippets e outros recursos

Esse é um projeto que foi utilizado como aprendizado em Node.js, libraries, módulos e afins. Não teria sido possível sem o material desenvolvido por muita gente e compartilhado na Web.

Separamos aqui uma "bibliografia" de recursos utilizados:

/*
Artigos que estamos usando como referência para configuração inicial:
http://www.peachpit.com/articles/article.aspx?p=2252193&seqNum=4
https://scalegrid.io/blog/getting-started-with-mongodb-and-mongoose/
https://scotch.io/tutorials/easy-node-authentication-setup-and-local
http://mongoosejs.com/docs/models.html
*/

//setup Routes --> http://billpatrianakos.me/blog/2015/12/01/organizing-express-routes/

//reset password
//Using base http://sahatyalkabov.com/how-to-implement-password-reset-in-nodejs/

//adicionar arquivos
//https://www.terlici.com/2015/05/16/uploading-files-locally.html
//http://stackoverflow.com/questions/15772394/how-to-upload-display-and-save-images-using-node-js-and-express
//http://stackoverflow.com/questions/5294470/writing-image-to-local-server
//http://stackoverflow.com/questions/16860334/how-to-load-and-save-image-using-node-js