text:
package core

import (
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/util/texttree"
)

// FlatPhysicalPlan provides an easier structure to traverse a plan and collect needed information.
// Note: Although it's named FlatPhysicalPlan, there also could be Insert, Delete and Update at the beginning of Main.
type FlatPhysicalPlan struct {
	Main FlatPlanTree
	CTEs []FlatPlanTree

	// InExecute and InExplain are expected to handle some special cases. Usually you don't need to use them.

	// InExecute means if the original plan tree contains Execute operator.
	//
	// Be careful when trying to use this, InExecute is true doesn't mean we are handling an EXECUTE statement.
	// When collecting information from the plan in an EXECUTE statement, usually we directly use the plan
	// in Execute.Plan, not Execute itself, so InExecute will be false.
	//
	// When will InExecute be true? When you're using "EXPLAIN FOR CONNECTION" to get the last plan of
	// a connection (usually we will record Explain.TargetPlan for an EXPLAIN statement) and that plan
	// is from an EXECUTE statement, we will collect from Execute itself, not directly from Execute.Plan,
	// then InExecute will be true.
	InExecute bool

	// InExplain means if the original plan tree contains Explain operator.
	InExplain bool

	// The fields below are only used when building the FlatPhysicalPlan.
	buildSideFirst bool
	ctesToFlatten  []*PhysicalCTE
}

// FlatPlanTree is a simplified plan tree.
// It arranges all operators in the tree as a slice, ordered by the order of traversing the tree, which means a
// depth-first traversal plus some special rule for some operators.
type FlatPlanTree []*FlatOperator

// GetSelectPlan skips Insert, Delete and Update at the beginning of the FlatPlanTree.
// Note:
//     It returns a reference to the original FlatPlanTree, please avoid modifying the returned value.
//     Since you get a part of the original slice, you need to adjust the FlatOperator.Depth and FlatOperator.ChildrenIdx when using them.
func (e FlatPlanTree) GetSelectPlan() FlatPlanTree {
	if len(e) == 0 {
		return nil
	}
	for i, op := range e {
		switch op.Origin.(type) {
		case *Insert, *Delete, *Update:
		default:
			return e[i:]
		}
	}
	return nil
}

// FlatOperator is a simplified operator.
// It contains a reference to the original operator and some usually needed information.
type FlatOperator struct {
	// A reference to the original operator.
	Origin Plan

	ChildrenIdx []int

	// NeedReverseDriverSide means if we need to reverse the order of children to keep build side before probe side.
	//
	// Specifically, it means if the below are all true:
	// 1. this operator has two children
	// 2. the first child's Label is the probe side and the second's is the build side.
	//
	// If you call FlattenPhysicalPlan with buildSideFirst true, NeedReverseDriverSide will be useless.
	NeedReverseDriverSide bool

	Depth     uint32
	Label     OperatorLabel
	IsRoot    bool
	StoreType kv.StoreType
	// ReqType is only meaningful when IsRoot is false.
	ReqType ReadReqType

	// The below two fields are mainly for text tree formatting. See texttree.PrettyIdentifier().
	TextTreeIndent string
	IsLastChild    bool

	IsPhysicalPlan bool
}

// OperatorLabel acts as some additional information to the name, usually it means its relationship with its parent.
// It's useful for index join, apply, index lookup, cte and so on.
type OperatorLabel uint8

const (
	// Empty means OperatorLabel is meaningless for this operator.
	Empty OperatorLabel = iota
	// BuildSide means this operator is at the build side of its parent
	BuildSide
	// ProbeSide means this operator is at the probe side of its parent
	ProbeSide
	// SeedPart means this operator is the seed part of its parent (a cte)
	SeedPart
	// RecursivePart means this operator is the recursive part of its parent (a cte)
	RecursivePart
)

func (d OperatorLabel) String() string {
	switch d {
	case Empty:
		return ""
	case BuildSide:
		return "(Build)"
	case ProbeSide:
		return "(Probe)"
	case SeedPart:
		return "(Seed Part)"
	case RecursivePart:
		return "(Recursive Part)"
	}
	return ""
}

type operatorCtx struct {
	depth       uint32
	label       OperatorLabel
	isRoot      bool
	storeType   kv.StoreType
	reqType     ReadReqType
	indent      string
	isLastChild bool
}

// FlattenPhysicalPlan generates a FlatPhysicalPlan from a PhysicalPlan, Insert, Delete, Update, Explain or Execute.
func FlattenPhysicalPlan(p Plan, buildSideFirst bool) *FlatPhysicalPlan {
	if p == nil {
		return nil
	}
	res := &FlatPhysicalPlan{
		buildSideFirst: buildSideFirst,
	}
	initInfo := &operatorCtx{
		depth:       0,
		label:       Empty,
		isRoot:      true,
		storeType:   kv.TiDB,
		indent:      "",
		isLastChild: true,
	}
	res.Main, _ = res.flattenRecursively(p, initInfo, nil)

	flattenedCTEPlan := make(map[int]struct{}, len(res.ctesToFlatten))

	// Note that ctesToFlatten may be modified during the loop, so we manually loop over it instead of using for...range.
	for i := 0; i < len(res.ctesToFlatten); i++ {
		cte := res.ctesToFlatten[i]
		cteDef := (*CTEDefinition)(cte)
		if _, ok := flattenedCTEPlan[cteDef.CTE.IDForStorage]; ok {
			continue
		}
		cteExplained := res.flattenCTERecursively(cteDef, initInfo, nil)
		res.CTEs = append(res.CTEs, cteExplained)
		flattenedCTEPlan[cteDef.CTE.IDForStorage] = struct{}{}
	}
	return res
}

func (f *FlatPhysicalPlan) flattenSingle(p Plan, info *operatorCtx) *FlatOperator {
	// Some operators are not initialized and given an ExplainID. So their explain IDs are "_0"
	// (when in EXPLAIN FORMAT = 'brief' it will be ""), we skip such operators.
	// Examples: Explain, Execute
	if len(p.TP()) == 0 && p.ID() == 0 {
		return nil
	}
	res := &FlatOperator{
		Origin:         p,
		Label:          info.label,
		IsRoot:         info.isRoot,
		StoreType:      info.storeType,
		Depth:          info.depth,
		ReqType:        info.reqType,
		TextTreeIndent: info.indent,
		IsLastChild:    info.isLastChild,
	}

	if _, ok := p.(PhysicalPlan); ok {
		res.IsPhysicalPlan = true
	}
	return res
}

// Note that info should not be modified in this method.
func (f *FlatPhysicalPlan) flattenRecursively(p Plan, info *operatorCtx, target FlatPlanTree) (res FlatPlanTree, idx int) {
	idx = -1
	flat := f.flattenSingle(p, info)
	if flat != nil {
		target = append(target, flat)
		idx = len(target) - 1
	}
	childIdxs := make([]int, 0)
	var childIdx int
	childCtx := &operatorCtx{
		depth:     info.depth + 1,
		isRoot:    info.isRoot,
		storeType: info.storeType,
		reqType:   info.reqType,
		indent:    texttree.Indent4Child(info.indent, info.isLastChild),
	}
	// For physical operators, we just enumerate their children and collect their information.
	// Note that some physical operators are special, and they are handled below this part.
	if physPlan, ok := p.(PhysicalPlan); ok {
		label := make([]OperatorLabel, len(physPlan.Children()))

		switch plan := physPlan.(type) {
		case *PhysicalApply:
			label[plan.InnerChildIdx] = ProbeSide
			label[1-plan.InnerChildIdx] = BuildSide
		case *PhysicalHashJoin:
			if plan.UseOuterToBuild {
				label[plan.InnerChildIdx] = ProbeSide
				label[1-plan.InnerChildIdx] = BuildSide
			} else {
				label[plan.InnerChildIdx] = BuildSide
				label[1-plan.InnerChildIdx] = ProbeSide
			}
		case *PhysicalMergeJoin:
			if plan.JoinType == RightOuterJoin {
				label[0] = BuildSide
				label[1] = ProbeSide
			} else {
				label[0] = ProbeSide
				label[1] = BuildSide
			}
		case *PhysicalIndexJoin:
			label[plan.InnerChildIdx] = ProbeSide
			label[1-plan.InnerChildIdx] = BuildSide
		case *PhysicalIndexMergeJoin:
			label[plan.InnerChildIdx] = ProbeSide
			label[1-plan.InnerChildIdx] = BuildSide
		case *PhysicalIndexHashJoin:
			label[plan.InnerChildIdx] = ProbeSide
			label[1-plan.InnerChildIdx] = BuildSide
		}

		children := make([]PhysicalPlan, len(physPlan.Children()))
		copy(children, physPlan.Children())
		if len(label) == 2 &&
			label[0] == ProbeSide &&
			label[1] == BuildSide {
			if f.buildSideFirst {
				// Put the build side before the probe side if buildSideFirst is true.
				label[0], label[1] = label[1], label[0]
				children[0], children[1] = children[1], children[0]
			} else if flat != nil {
				// Set NeedReverseDriverSide to true if buildSideFirst is false.
				flat.NeedReverseDriverSide = true
			}
		}

		for i := range children {
			childCtx.label = label[i]
			childCtx.isLastChild = i == len(children)-1
			target, childIdx = f.flattenRecursively(children[i], childCtx, target)
			childIdxs = append(childIdxs, childIdx)
		}
	}

	// For part of physical operators and some special operators, we need some special logic to get their "children".
	// For PhysicalCTE, we need to add the plan tree into flatTree.ctesToFlatten.
	switch plan := p.(type) {
	case *PhysicalTableReader:
		childCtx.isRoot = false
		childCtx.storeType = plan.StoreType
		childCtx.reqType = plan.ReadReqType
		childCtx.label = Empty
		childCtx.isLastChild = true
		target, childIdx = f.flattenRecursively(plan.tablePlan, childCtx, target)
		childIdxs = append(childIdxs, childIdx)
	case *PhysicalIndexReader:
		childCtx.isRoot = false
		childCtx.reqType = Cop
		childCtx.storeType = kv.TiKV
		childCtx.label = Empty
		childCtx.isLastChild = true
		target, childIdx = f.flattenRecursively(plan.indexPlan, childCtx, target)
		childIdxs = append(childIdxs, childIdx)
	case *PhysicalIndexLookUpReader:
		childCtx.isRoot = false
		childCtx.reqType = Cop
		childCtx.storeType = kv.TiKV
		childCtx.label = BuildSide
		childCtx.isLastChild = false
		target, childIdx = f.flattenRecursively(plan.indexPlan, childCtx, target)
		childIdxs = append(childIdxs, childIdx)
		childCtx.label = ProbeSide
		childCtx.isLastChild = true
		target, childIdx = f.flattenRecursively(plan.tablePlan, childCtx, target)
		childIdxs = append(childIdxs, childIdx)
	case *PhysicalIndexMergeReader:
		childCtx.isRoot = false
		childCtx.reqType = Cop
		childCtx.storeType = kv.TiKV
		for _, pchild := range plan.partialPlans {
			childCtx.label = BuildSide
			childCtx.isLastChild = false
			target, childIdx = f.flattenRecursively(pchild, childCtx, target)
			childIdxs = append(childIdxs, childIdx)
		}
		childCtx.label = ProbeSide
		childCtx.isLastChild = true
		target, childIdx = f.flattenRecursively(plan.tablePlan, childCtx, target)
		childIdxs = append(childIdxs, childIdx)
	case *PhysicalShuffleReceiverStub:
		childCtx.isRoot = true
		childCtx.label = Empty
		childCtx.isLastChild = true
		target, childIdx = f.flattenRecursively(plan.DataSource, childCtx, target)
		childIdxs = append(childIdxs, childIdx)
	case *PhysicalCTE:
		f.ctesToFlatten = append(f.ctesToFlatten, plan)
	case *Insert:
		if plan.SelectPlan != nil {
			childCtx.isRoot = true
			childCtx.label = Empty
			childCtx.isLastChild = true
			target, childIdx = f.flattenRecursively(plan.SelectPlan, childCtx, target)
			childIdxs = append(childIdxs, childIdx)
		}
	case *Update:
		if plan.SelectPlan != nil {
			childCtx.isRoot = true
			childCtx.label = Empty
			childCtx.isLastChild = true
			target, childIdx = f.flattenRecursively(plan.SelectPlan, childCtx, target)
			childIdxs = append(childIdxs, childIdx)
		}
	case *Delete:
		if plan.SelectPlan != nil {
			childCtx.isRoot = true
			childCtx.label = Empty
			childCtx.isLastChild = true
			target, childIdx = f.flattenRecursively(plan.SelectPlan, childCtx, target)
			childIdxs = append(childIdxs, childIdx)
		}
	case *Execute:
		f.InExecute = true
		if plan.Plan != nil {
			childCtx.isRoot = true
			childCtx.indent = info.indent
			childCtx.label = Empty
			childCtx.isLastChild = true
			target, childIdx = f.flattenRecursively(plan.Plan, childCtx, target)
			childIdxs = append(childIdxs, childIdx)
		}
	case *Explain:
		f.InExplain = true
		// Explain is ignored in flattenSingle(). We start to explain its TargetPlan from a new operatorCtx.
		if plan.TargetPlan != nil {
			initInfo := &operatorCtx{
				depth:       0,
				label:       Empty,
				isRoot:      true,
				storeType:   kv.TiDB,
				indent:      "",
				isLastChild: true,
			}
			target, childIdx = f.flattenRecursively(plan.TargetPlan, initInfo, target)
			childIdxs = append(childIdxs, childIdx)
		}
	}
	if flat != nil {
		flat.ChildrenIdx = childIdxs
	}
	return target, idx
}

func (f *FlatPhysicalPlan) flattenCTERecursively(cteDef *CTEDefinition, info *operatorCtx, target FlatPlanTree) FlatPlanTree {
	flat := f.flattenSingle(cteDef, info)
	if flat != nil {
		target = append(target, flat)
	}
	childIdxs := make([]int, 0)
	var childIdx int
	childInfo := &operatorCtx{
		depth:       info.depth + 1,
		label:       SeedPart,
		isRoot:      true,
		storeType:   kv.TiDB,
		indent:      texttree.Indent4Child(info.indent, info.isLastChild),
		isLastChild: cteDef.RecurPlan == nil,
	}
	target, childIdx = f.flattenRecursively(cteDef.SeedPlan, childInfo, target)
	childIdxs = append(childIdxs, childIdx)
	if cteDef.RecurPlan != nil {
		childInfo.label = RecursivePart
		childInfo.isLastChild = true
		target, childIdx = f.flattenRecursively(cteDef.RecurPlan, childInfo, target)
		childIdxs = append(childIdxs, childIdx)
	}
	if flat != nil {
		flat.ChildrenIdx = childIdxs
	}
	return target
}


text:
import { Square } from './square';
import { Tape } from './tape';
import { MachineStatus } from './machine-status';
import { TapeSymbol } from './tape-symbol';

describe('MachineStatus', () => {

  const configurationName = 'configuration name';
  const squares: Array<Square> = [new Square(1, new TapeSymbol(TapeSymbol.ONE)), new Square(2, new TapeSymbol(TapeSymbol.X))];
  const tape: Tape = new Tape(squares);
  const index = 1;

  let machineStatus: MachineStatus;

  beforeEach(() => {
    machineStatus = new MachineStatus(configurationName, tape, index);
  });

  it('should get the configuration name', () => {
    expect(machineStatus.configurationName).toEqual(configurationName);
  });

  it('should get the tape', () => {
    expect(machineStatus.tape).toEqual(tape);
  });

  it('should get the index', () => {
    expect(machineStatus.index).toEqual(index);
  });

  describe('symbol', () => {

    it('should get the actual tape symbol', () => {
      expect(machineStatus.symbol.value).toEqual(TapeSymbol.X);
    });

    it('should throw Error if cannot read symbol on actual tape square', () => {
      machineStatus.index = 5;

      const symbol = function () {
        return machineStatus.symbol;
      };

      expect(symbol).toThrow(new Error('Cannot read symbol on square with index 6'));
    });

    it('should set the actual tape symbol', () => {
      machineStatus.symbol = new TapeSymbol(TapeSymbol.SCHWA);

      expect(machineStatus.symbol.value).toEqual(TapeSymbol.SCHWA);
      machineStatus.symbol = new TapeSymbol(TapeSymbol.X);
    });

  });

  describe('maxSquareCount', () => {

    it('should return false if index is less than the tape squares count', () => {
      machineStatus.index = 1;

      expect(machineStatus.maxSquareCount()).toBeFalsy();
    });

    it('should return true if index is equal to the tape squares count', () => {
      machineStatus.index = 2;

      expect(machineStatus.maxSquareCount()).toBeTruthy();
    });

    it('should return true if index is more than the tape squares count', () => {
      machineStatus.index = 3;

      expect(machineStatus.maxSquareCount()).toBeTruthy();
    });

  });

});

redpajama_set_name: RedPajamaGithub


text:
			Define step, min and max

			<input id="default" type="text" pui-spinner="{step: 0.25, min: 0.0, max: 5.0}" ng-model="value" />

			Scope value {{value}}

		<fieldset id="Source" pui-fieldset style="margin-bottom:20px">
			<legend>Source</legend>

<input id="default" type="text" pui-spinner="{step: 0.25, min: 0.0, max: 5.0}" ng-model="value" />

Scope value {{value}}

$scope.value = null;

		</fieldset>


text:
require 'bundler/setup'

Bundler.require

full_file_name = ARGV[0]
file_name = ARGV[0].split(/\./)[0]
data = Roo::Spreadsheet.open(full_file_name)
data.sheets.each do |sheet_name|
	fp = open("#{file_name}_#{sheet_name}.csv","w")
	data.sheet(sheet_name).each do |row|
		fp.puts row.join(",")
	end
	fp.close()
end


text:
module RSpec::Matchers::BuiltIn
  describe Compound do
    RSpec::Matchers.define :custom_include do |*args|
      match { |actual| expect(actual).to include(*args) }
    end

    shared_examples "making a copy" do |compound_method, copy_method|
      context "when making a copy via `#{copy_method}`" do
        it "uses a copy of the base matchers" do
          matcher_1 = include(3)
          matcher_2 = include(4)
          compound  = matcher_1.__send__(compound_method, matcher_2)
          copy = compound.__send__(copy_method)

          expect(copy).not_to equal(compound)
          expect(copy.matcher_1).not_to equal(matcher_1)
          expect(copy.matcher_1).to be_a(RSpec::Matchers::BuiltIn::Include)
          expect(copy.matcher_1.expected).to eq([3])

          expect(copy.matcher_2).not_to equal(matcher_2)
          expect(copy.matcher_2).to be_a(RSpec::Matchers::BuiltIn::Include)
          expect(copy.matcher_2.expected).to eq([4])
        end

        it "copies custom matchers properly so they can work even though they have singleton behavior" do
          matcher_1 = custom_include(3)
          matcher_2 = custom_include(3)
          compound  = matcher_1.__send__(compound_method, matcher_2)
          copy = compound.__send__(copy_method)

          expect(copy).not_to equal(compound)
          expect(copy.matcher_1).not_to equal(matcher_1)
          expect(copy.matcher_2).not_to equal(matcher_2)

          expect([3]).to copy

          expect { expect([4]).to copy }.to fail_matching("expected [4]")
        end
      end
    end

    context "when used as a composable matcher" do
      it 'can pass' do
        expect(["food", "barn"]).to include(
          a_string_starting_with("f").and(ending_with("d")),
          a_string_starting_with("b").and(ending_with("n"))
        )
      end

      it 'can fail' do
        expect {
          expect(["foo", "bar"]).to include(
            a_string_starting_with("f").and(ending_with("d")),
            a_string_starting_with("b").and(ending_with("n"))
          )
        }.to fail_matching('expected ["foo", "bar"] to include (a string starting with "f" and ending with "d") and (a string starting with "b" and ending with "n")')
      end

      it 'provides a description' do
        matcher = include(
          a_string_starting_with("f").and(ending_with("d")),
          a_string_starting_with("b").and(ending_with("n"))
        )

        expect(matcher.description).to eq('include (a string starting with "f" and ending with "d") and (a string starting with "b" and ending with "n")')
      end
    end

    describe "expect(...).to matcher.and(other_matcher)" do

      it_behaves_like "an RSpec matcher", :valid_value => 3, :invalid_value => 4 do
        let(:matcher) { eq(3).and be <= 3 }
      end

      include_examples "making a copy", :and, :dup
      include_examples "making a copy", :and, :clone

      context 'when both matchers pass' do
        it 'passes' do
          expect(3).to eq(3).and be >= 2
        end
      end

      it 'has a description composed of both matcher descriptions' do
        matcher = eq(3).and be >= 2
        expect(3).to matcher
        expect(matcher.description).to eq("eq 3 and be >= 2")
      end

      context 'when only the first matcher fails' do
        it "fails with the first matcher's failure message" do
          expect {
            expect(3).to eq(4).and be >= 2
          }.to fail_with(dedent <<-EOS)
            |
            |expected: 4
            |     got: 3
            |
            |(compared using ==)
            |
          EOS
        end
      end

      context 'when only the second matcher fails' do
        it "fails with the second matcher's failure message" do
          expect {
            expect(3).to be_kind_of(Integer).and eq(4)
          }.to fail_with(dedent <<-EOS)
            |
            |expected: 4
            |     got: 3
            |
            |(compared using ==)
            |
          EOS
        end
      end

      context "when both mathers fail" do
        context "when both matchers have multi-line failure messages" do
          it 'fails with a well formatted message containing both sub-messages' do
            expect {
              expect(3).to eq(4).and be >= 8
            }.to fail_with(dedent <<-EOS)
              |
              |   expected: 4
              |        got: 3
              |
              |   (compared using ==)
              |
              |...and:
              |
              |   expected: >= 8
              |        got:    3
            EOS
          end
        end

        context "when both matchers have single-line failure messages" do
          it 'fails with a single-line failure message' do
            expect {
              expect("foo").to start_with("a").and end_with("z")
            }.to fail_with('expected "foo" to start with "a" and expected "foo" to end with "z"')
          end
        end

        context "when the first matcher has a multi-line failure message" do
          it 'fails with a well formatted message containing both sub-messages' do
            expect {
              expect("foo").to eq(4).and end_with("z")
            }.to fail_with(dedent <<-EOS)
              |
              |   expected: 4
              |        got: "foo"
              |
              |   (compared using ==)
              |
              |...and:
              |
              |   expected "foo" to end with "z"
            EOS
          end
        end

        context "when the second matcher has a multi-line failure message" do
          it 'fails with a well formatted message containing both sub-messages' do
            expect {
              expect("foo").to end_with("z").and eq(4)
            }.to fail_with(dedent <<-EOS)
              |   expected "foo" to end with "z"
              |
              |...and:
              |
              |   expected: 4
              |        got: "foo"
              |
              |   (compared using ==)
              |
            EOS
          end
        end
      end
    end

    describe "expect(...).not_to matcher.and(other_matcher)" do
      it "is not supported" do
        expect {
          expect(3).not_to eq(2).and be > 2
        }.to raise_error(NotImplementedError, /matcher.and matcher` is not supported/)
      end
    end

    describe "expect(...).to matcher.or(other_matcher)" do
      it_behaves_like "an RSpec matcher", :valid_value => 3, :invalid_value => 5 do
        let(:matcher) { eq(3).or eq(4) }
      end

      include_examples "making a copy", :or, :dup
      include_examples "making a copy", :or, :clone

      it 'has a description composed of both matcher descriptions' do
        matcher = eq(3).or eq(4)
        expect(3).to matcher
        expect(matcher.description).to eq("eq 3 or eq 4")
      end

      context 'when both matchers pass' do
        it 'passes' do
          expect("foo").to start_with("f").or end_with("o")
        end
      end

      context 'when only the first matcher passes' do
        it 'passes' do
          expect("foo").to start_with("f").or end_with("z")
        end
      end

      context 'when only the last matcher passes' do
        it 'passes' do
          expect("foo").to start_with("a").or end_with("o")
        end
      end

      context 'when both matchers fail' do
        context "when both matchers have multi-line failure messages" do
          it 'fails with a well formatted message containing both sub-messages' do
            expect {
              expect(3).to eq(4).or be >= 8
            }.to fail_with(dedent <<-EOS)
              |
              |   expected: 4
              |        got: 3
              |
              |   (compared using ==)
              |
              |...or:
              |
              |   expected: >= 8
              |        got:    3
            EOS
          end
        end

        context "when both matchers have single-line failure messages" do
          it 'fails with a single-line failure message' do
            expect {
              expect("foo").to start_with("a").or end_with("z")
            }.to fail_with('expected "foo" to start with "a" or expected "foo" to end with "z"')
          end
        end

        context "when the first matcher has a multi-line failure message" do
          it 'fails with a well formatted message containing both sub-messages' do
            expect {
              expect("foo").to eq(4).or end_with("z")
            }.to fail_with(dedent <<-EOS)
              |
              |   expected: 4
              |        got: "foo"
              |
              |   (compared using ==)
              |
              |...or:
              |
              |   expected "foo" to end with "z"
            EOS
          end
        end

        context "when the second matcher has a multi-line failure message" do
          it 'fails with a well formatted message containing both sub-messages' do
            expect {
              expect("foo").to end_with("z").or eq(4)
            }.to fail_with(dedent <<-EOS)
              |   expected "foo" to end with "z"
              |
              |...or:
              |
              |   expected: 4
              |        got: "foo"
              |
              |   (compared using ==)
              |
            EOS
          end
        end
      end
    end

    context "when chaining many matchers together" do
      it 'can pass appropriately' do
        matcher = start_with("f").and end_with("z").or end_with("o")
        expect("foo").to matcher
        expect(matcher.description).to eq('start with "f" and end with "z" or end with "o"')
      end

      it 'fails with a complete message' do
        expect {
          expect(3).to eq(1).and eq(2).and eq(3).and eq(4)
        }.to fail_with(dedent <<-EOS)
          |
          |   expected: 1
          |        got: 3
          |
          |   (compared using ==)
          |
          |...and:
          |
          |      expected: 2
          |           got: 3
          |
          |      (compared using ==)
          |
          |   ...and:
          |
          |      expected: 4
          |           got: 3
          |
          |      (compared using ==)
          |
        EOS
      end
    end

    describe "expect(...).not_to matcher.or(other_matcher)" do
      it "is not supported" do
        expect {
          expect(3).not_to eq(2).or be > 2
        }.to raise_error(NotImplementedError, /matcher.or matcher` is not supported/)
      end
    end
  end
end


text:
EXISTS="$(docker ps -a|grep centos7ansible)"
if ! [[ -z "$EXISTS" ]]; then
  docker exec -it centos7ansible bash
else
  echo "Container centos7ansible not found ..."
fi


text:
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}

-- Incidental:
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}

module Main where

import Control.Monad
import Data.Hashable
import Data.List
import Data.Text (Text)
import Data.Traversable (for)
import Data.Typeable
import Haxl.Core
import System.Random

import qualified Data.Text as Text

main :: IO ()
main = do
  let stateStore = stateSet UserState{} stateEmpty
  env0 <- initEnv stateStore ()
  names <- runHaxl env0 getAllUsernames
  print names

-- Data source API.

getAllUsernames :: Haxl [Name]
getAllUsernames = do
  userIds <- getAllUserIds
  for userIds $ \userId -> do
    getUsernameById userId

getAllUserIds :: Haxl [Id]
getAllUserIds = dataFetch GetAllIds

getUsernameById :: Id -> Haxl Name
getUsernameById userId = dataFetch (GetNameById userId)

-- Aliases.

type Haxl = GenHaxl () ()
type Id = Int
type Name = Text

-- Data source implementation.

data UserReq a where
  GetAllIds   :: UserReq [Id]
  GetNameById :: Id -> UserReq Name
  deriving (Typeable)

deriving instance Eq (UserReq a)
instance Hashable (UserReq a) where
   hashWithSalt s GetAllIds       = hashWithSalt s (0::Int)
   hashWithSalt s (GetNameById a) = hashWithSalt s (1::Int, a)

deriving instance Show (UserReq a)
instance ShowP UserReq where showp = show

instance StateKey UserReq where
  data State UserReq = UserState {}

instance DataSourceName UserReq where
  dataSourceName _ = "UserDataSource"

instance DataSource u UserReq where
  fetch _state _flags _userEnv = SyncFetch $ \blockedFetches -> do
    let
      allIdVars :: [ResultVar [Id]]
      allIdVars = [r | BlockedFetch GetAllIds r <- blockedFetches]

      idStrings :: [String]
      idStrings = map show ids

      ids :: [Id]
      vars :: [ResultVar Name]
      (ids, vars) = unzip
        [(userId, r) | BlockedFetch (GetNameById userId) r <- blockedFetches]

    unless (null allIdVars) $ do
      allIds <- sql "select id from ids"
      mapM_ (\r -> putSuccess r allIds) allIdVars

    unless (null ids) $ do
      names <- sql $ unwords
        [ "select name from names where"
        , intercalate " or " $ map ("id = " ++) idStrings
        , "order by find_in_set(id, '" ++ intercalate "," idStrings ++ "')"
        ]
      mapM_ (uncurry putSuccess) (zip vars names)

-- Mock SQL API.

class SQLResult a where
  mockResult :: IO a

instance SQLResult a => SQLResult [a] where
  mockResult = replicateM 10 mockResult

instance SQLResult Name where
  -- An infinite number of employees, all named Jim.
  mockResult = ("Jim" `Text.append`) . Text.pack . show <$> randomRIO (1::Int, 100)

instance SQLResult Id where
  mockResult = randomRIO (1, 100)

sql :: SQLResult a => String -> IO a
sql query = print query >> mockResult


text:
<?xml version="1.0" encoding="UTF-8"?>
<GeocodeResponse>
 <status>OK</status>
 <result>
  <type>administrative_area_level_3</type>
  <type>political</type>
  <formatted_address>Gemeinde Micheldorf in Oberösterreich, Austria</formatted_address>
  <address_component>
   <long_name>Gemeinde Micheldorf in Oberösterreich</long_name>
   <short_name>Gemeinde Micheldorf in Oberösterreich</short_name>
   <type>administrative_area_level_3</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Kirchdorf an der Krems</long_name>
   <short_name>Kirchdorf an der Krems</short_name>
   <type>administrative_area_level_2</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Oberösterreich</long_name>
   <short_name>Oberösterreich</short_name>
   <type>administrative_area_level_1</type>
   <type>political</type>
  </address_component>
  <address_component>
   <long_name>Austria</long_name>
   <short_name>AT</short_name>
   <type>country</type>
   <type>political</type>
  </address_component>
  <geometry>
   <location>
    <lat>47.8750699</lat>
    <lng>14.1297151</lng>
   </location>
   <location_type>APPROXIMATE</location_type>
   <viewport>
    <southwest>
     <lat>47.8388100</lat>
     <lng>14.0794800</lng>
    </southwest>
    <northeast>
     <lat>47.9162300</lat>
     <lng>14.2020801</lng>
    </northeast>
   </viewport>
   <bounds>
    <southwest>
     <lat>47.8388100</lat>
     <lng>14.0794800</lng>
    </southwest>
    <northeast>
     <lat>47.9162300</lat>
     <lng>14.2020801</lng>
    </northeast>
   </bounds>
  </geometry>
  <place_id>ChIJq6CbNcvfc0cRPIV56V86Kxo</place_id>
 </result>
</GeocodeResponse>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, Main!</string>
    <string name="app_name">AndroLua</string>
    <string name="main_module">main</string>
</resources>


text:
#include <string.h>

#include "ns_types.h"
#include "ns_list.h"
#include "ns_trace.h"
#include "nsdynmemLIB.h"
#include "sn_nsdl.h"
#include "sn_coap_header.h"
#include "coap_service_api.h"
#include "coap_message_handler.h"
#include "eventOS_event.h"
#include "eventOS_scheduler.h"
#include "eventOS_event_timer.h"
#include "common_functions.h"
#include "coap_connection_handler.h"
#include "net_interface.h"
#include "coap_service_api_internal.h"
#include "coap_message_handler.h"

static int16_t coap_msg_process_callback(int8_t socket_id, sn_coap_hdr_s *coap_message, coap_transaction_t *transaction_ptr);

typedef struct uri_registration {
    char *uri_ptr;
    uint16_t uri_len;
    uint8_t allowed_method;
    coap_service_request_recv_cb *request_recv_cb;
    ns_list_link_t link;
} uri_registration_t;

typedef NS_LIST_HEAD(uri_registration_t, link) uri_registration_list_t;

typedef struct coap_service {
    coap_service_security_done_cb *coap_security_done_cb;
    coap_service_security_start_cb *security_start_cb;
    coap_service_virtual_socket_send_cb *virtual_socket_send_cb;
    uri_registration_list_t uri_list;
    coap_conn_handler_t *conn_handler;
    int8_t interface_id;
    int8_t service_id;
    int8_t listen_socket;
    uint8_t service_options;
    ns_list_link_t link;
} coap_service_t;

#define TRACE_GROUP "ThSA"

static NS_LIST_DEFINE(instance_list, coap_service_t, link);
static int8_t tasklet_id = -1;
coap_msg_handler_t *coap_service_handle = NULL;
static uint32_t coap_ticks = 1;

#define COAP_TICK_TIMER 0xf1

static uri_registration_t *uri_registration_find(coap_service_t *this, const void *uri_ptr, uint16_t uri_len)
{
    ns_list_foreach(uri_registration_t, cur_ptr, &this->uri_list) {
        if (cur_ptr->uri_len == uri_len && memcmp(cur_ptr->uri_ptr, uri_ptr, uri_len) == 0) {
            return cur_ptr;
        }
    }
    return NULL;
}
static coap_service_t *service_find(int8_t service_id)
{
    coap_service_t *this = NULL;
    ns_list_foreach(coap_service_t, cur_ptr, &instance_list) {
        if (cur_ptr->service_id == service_id) {
            this = cur_ptr;
            break;
        }
    }
    return this;
}

static coap_service_t *service_find_by_socket(int8_t socket_id)
{
    coap_service_t *this = NULL;
    ns_list_foreach(coap_service_t, cur_ptr, &instance_list) {
        if( coap_connection_handler_socket_belongs_to(cur_ptr->conn_handler, socket_id) ){
            this = cur_ptr;
            break;
        }
    }
    return this;
}

static coap_service_t *service_find_by_uri(uint8_t socket_id, uint8_t *uri_ptr, uint16_t uri_len)
{
    ns_list_foreach(coap_service_t, cur_ptr, &instance_list) {
        if (coap_connection_handler_socket_belongs_to(cur_ptr->conn_handler, socket_id) && uri_registration_find(cur_ptr, uri_ptr, uri_len)) {
            return cur_ptr;
        }
    }
    return NULL;
}

/**
 *  Coap handling functions
 */
static void *own_alloc(uint16_t size)
{
    if (size) {
        return ns_dyn_mem_temporary_alloc(size);
    } else {
        return 0;
    }
}

static void own_free(void *ptr)
{
    if (ptr) {
        ns_dyn_mem_free(ptr);
    }
}

static uint8_t coap_tx_function(uint8_t *data_ptr, uint16_t data_len, sn_nsdl_addr_s *address_ptr, void *param)
{
    coap_service_t *this;
    coap_transaction_t *transaction_ptr = coap_message_handler_transaction_valid(param);
    ns_address_t dest_addr;

    if (!transaction_ptr || !data_ptr) {
        return -1;
    }

    tr_debug("Service %d, CoAP TX Function - mid: %d", transaction_ptr->service_id, common_read_16_bit(data_ptr + 2));

    this = service_find(transaction_ptr->service_id);
    if (!this) {
        return -1;
    }

    memcpy(&(dest_addr.address), address_ptr->addr_ptr, 16);
    dest_addr.identifier = address_ptr->port;
    dest_addr.type = ADDRESS_IPV6;

    if (-2 == coap_connection_handler_send_data(this->conn_handler, &dest_addr, transaction_ptr->local_address,
            data_ptr, data_len, (this->service_options & COAP_SERVICE_OPTIONS_SECURE_BYPASS) == COAP_SERVICE_OPTIONS_SECURE_BYPASS)) {
        transaction_ptr->data_ptr = ns_dyn_mem_alloc(data_len);
        if (!transaction_ptr->data_ptr) {
            tr_debug("coap tx out of memory");
            return 0;

        }
        memcpy(transaction_ptr->data_ptr, data_ptr, data_len);
        transaction_ptr->data_len = data_len;
    } else if (transaction_ptr->resp_cb == NULL ) {
        transaction_delete(transaction_ptr);
    }

    return 0;
}

static void service_event_handler(arm_event_s *event)
{
    if (event->event_type == ARM_LIB_TASKLET_INIT_EVENT) {
        tr_debug("service tasklet initialised");
        /*initialize coap service and listen socket*/
    }
    if (event->event_type == ARM_LIB_SYSTEM_TIMER_EVENT && event->event_id == COAP_TICK_TIMER) {
        coap_message_handler_exec(coap_service_handle, coap_ticks++);
        if(coap_ticks && !coap_ticks % SECURE_SESSION_CLEAN_INTERVAL){
            coap_connection_handler_exec(coap_ticks);
        }
    }
    eventOS_event_timer_request((uint8_t)COAP_TICK_TIMER, ARM_LIB_SYSTEM_TIMER_EVENT, tasklet_id, 1000);
}

static int16_t coap_msg_process_callback(int8_t socket_id, sn_coap_hdr_s *coap_message, coap_transaction_t *transaction_ptr)
{
    coap_service_t *this;
    if (!coap_message || !transaction_ptr) {
        return -1;
    }

    // Message is request, find correct handle
    this = service_find_by_uri(socket_id, coap_message->uri_path_ptr, coap_message->uri_path_len);
    if (!this) {
        tr_debug("not registered uri %.*s", coap_message->uri_path_len, coap_message->uri_path_ptr);
        if (coap_message->msg_type == COAP_MSG_TYPE_CONFIRMABLE) {
            coap_message_handler_response_send(coap_service_handle, transaction_ptr->service_id, COAP_SERVICE_OPTIONS_NONE, coap_message,
                COAP_MSG_CODE_RESPONSE_NOT_FOUND, COAP_CT_NONE, NULL, 0);
            return 0;
        }
        return -1;
    }

    uri_registration_t *uri_reg_ptr = uri_registration_find(this, coap_message->uri_path_ptr, coap_message->uri_path_len);
    if (uri_reg_ptr && uri_reg_ptr->request_recv_cb) {
        tr_debug("Service %d, call request recv cb uri %.*s", this->service_id, coap_message->uri_path_len, coap_message->uri_path_ptr);

        if ((this->service_options & COAP_SERVICE_OPTIONS_SECURE_BYPASS) == COAP_SERVICE_OPTIONS_SECURE_BYPASS ) {//TODO Add secure bypass option
            // Service has secure bypass active TODO this is not defined in interface
            // this check can be removed I think
            transaction_ptr->options = COAP_REQUEST_OPTIONS_SECURE_BYPASS;
        }
        transaction_ptr->service_id = this->service_id;
        return uri_reg_ptr->request_recv_cb(this->service_id, transaction_ptr->remote_address, transaction_ptr->remote_port, coap_message);
    }
    return -1;
}

static int recv_cb(int8_t socket_id, uint8_t src_address[static 16], uint16_t port, const uint8_t dst_address[static 16], unsigned char *data, int len)
{
    uint8_t *data_ptr = NULL;
    uint16_t data_len = 0;

    if (!data || !len) {
        return -1;
    }

    data_ptr = own_alloc(len);

    if (!data_ptr) {
        return -1;
    }
    memcpy(data_ptr, data, len);
    data_len = len;
    tr_debug("service recv socket data len %d ", data_len);

    //parse coap message what CoAP to use
    int ret = coap_message_handler_coap_msg_process(coap_service_handle, socket_id, src_address, port, dst_address, data_ptr, data_len, &coap_msg_process_callback);
    own_free(data_ptr);
    return ret;
}

static int send_cb(int8_t socket_id, const uint8_t address[static 16], uint16_t port, const void *data_ptr, int data_len)
{
    coap_service_t *this = service_find_by_socket(socket_id);
    if (this && this->virtual_socket_send_cb) {
        tr_debug("send to virtual socket");
        return this->virtual_socket_send_cb(this->service_id, (uint8_t*)address, port, data_ptr, data_len);
    }
    return -1;
}

static void sec_done_cb(int8_t socket_id, uint8_t address[static 16], uint16_t port, uint8_t keyblock[static 40])
{
    //TODO: this is not enough if shared socket. Inform all!
    coap_service_t *this = service_find_by_socket(socket_id);
    if (this && this->coap_security_done_cb) { // secure done callback
        this->coap_security_done_cb(this->service_id, address, keyblock);
    }

    //TODO: send all unsend transactions if more than 1
    coap_transaction_t *transaction_ptr = coap_message_handler_find_transaction(address, port);
    if (transaction_ptr && transaction_ptr->data_ptr) {
        tr_debug("send delayed packet");
        ns_address_t dest_addr;
        memcpy(dest_addr.address, address, 16);
        dest_addr.identifier = port;
        dest_addr.type = ADDRESS_IPV6;

        coap_connection_handler_send_data(this->conn_handler, &dest_addr, transaction_ptr->local_address,
                transaction_ptr->data_ptr, transaction_ptr->data_len, (this->service_options & COAP_SERVICE_OPTIONS_SECURE_BYPASS) == COAP_SERVICE_OPTIONS_SECURE_BYPASS);
        ns_dyn_mem_free(transaction_ptr->data_ptr);
        transaction_ptr->data_ptr = NULL;
        transaction_ptr->data_len = 0;
        if (transaction_ptr->resp_cb == NULL) {
            transaction_delete(transaction_ptr);
        }
    }
}

static int get_passwd_cb(int8_t socket_id, uint8_t address[static 16], uint16_t port, uint8_t *pw_ptr, uint8_t *pw_len)
{
    coap_service_t *this = service_find_by_socket(socket_id);
    if (this && this->security_start_cb) {
        return this->security_start_cb(this->service_id, address, port, pw_ptr, pw_len);
    }
    return -1;
}

int8_t coap_service_initialize(int8_t interface_id, uint16_t listen_port, uint8_t service_options,
                                 coap_service_security_start_cb *start_ptr, coap_service_security_done_cb *coap_security_done_cb)
{
    (void) interface_id;

    coap_service_t *this = ns_dyn_mem_alloc(sizeof(coap_service_t));
    if (!this) {
        return -1;
    }
    memset(this, 0, sizeof(coap_service_t));
    tr_debug("service init interface %d, port %d, options %d", interface_id, listen_port, service_options);

    int8_t id = 1;// get unique id
    while (service_find(id) && id < 127) {
        id++;
    }
    this->service_id = id;
    this->service_options = service_options;

    this->security_start_cb = start_ptr;
    this->coap_security_done_cb = coap_security_done_cb;

    if (tasklet_id == -1) {
        tr_debug("service tasklet init");
        tasklet_id = eventOS_event_handler_create(&service_event_handler, ARM_LIB_TASKLET_INIT_EVENT);
    }

    this->conn_handler = connection_handler_create(recv_cb, send_cb, get_passwd_cb, sec_done_cb);
    if(!this->conn_handler){
        ns_dyn_mem_free(this);
        return -1;
    }

    if (0 > coap_connection_handler_open_connection(this->conn_handler, listen_port, ((this->service_options & COAP_SERVICE_OPTIONS_EPHEMERAL_PORT) == COAP_SERVICE_OPTIONS_EPHEMERAL_PORT),
                                              ((this->service_options & COAP_SERVICE_OPTIONS_SECURE) == COAP_SERVICE_OPTIONS_SECURE),
                                              ((this->service_options & COAP_SERVICE_OPTIONS_VIRTUAL_SOCKET) != COAP_SERVICE_OPTIONS_VIRTUAL_SOCKET),
                                              ((this->service_options & COAP_SERVICE_OPTIONS_SECURE_BYPASS) == COAP_SERVICE_OPTIONS_SECURE_BYPASS))){
        ns_dyn_mem_free(this->conn_handler);
        ns_dyn_mem_free(this);
        return -1;
    }

    if (!coap_service_handle) {
        coap_service_handle = coap_message_handler_init(&own_alloc, &own_free, &coap_tx_function);
    }
    if (!coap_service_handle) {
        tr_error("coap service alloc failed");
        //TODO proper handling
    }

    ns_list_add_to_start(&instance_list, this);

    return id;
}

void coap_service_delete(int8_t service_id)
{
    coap_service_t *this = service_find(service_id);
    if (!this) {
        return;
    }

    if (this->conn_handler){
        connection_handler_destroy(this->conn_handler);
    }

    //TODO clear all transactions
    ns_list_foreach_safe(uri_registration_t, cur_ptr, &this->uri_list) {
        ns_dyn_mem_free(cur_ptr->uri_ptr);
        ns_list_remove(&this->uri_list, cur_ptr);
        ns_dyn_mem_free(cur_ptr);
    }

    ns_list_remove(&instance_list, this);
    ns_dyn_mem_free(this);
    return;
}

extern void coap_service_close_secure_connection(int8_t service_id, uint8_t destination_addr_ptr[static 16], uint16_t port)
{
    coap_service_t *this = service_find(service_id);
    if (!this || !destination_addr_ptr) {
        return;
    }
    if (this->conn_handler){
        connection_handler_close_secure_connection(this->conn_handler, destination_addr_ptr, port);
    }
}

int16_t coap_service_virtual_socket_recv(int8_t service_id, uint8_t source_addr_ptr[static 16], uint16_t port, uint8_t *data_ptr, uint16_t data_len)
{
    coap_service_t *this = service_find(service_id);
    tr_debug("Service %d, virtual socket received", service_id);
    if (!this) {
        return -1;
    }
    return coap_connection_handler_virtual_recv(this->conn_handler, source_addr_ptr, port, data_ptr, data_len);
}

int16_t coap_service_virtual_socket_set_cb(int8_t service_id, coap_service_virtual_socket_send_cb *send_method_ptr)
{
    coap_service_t *this = service_find(service_id);
    tr_debug("register virtual socket cb");
    if (!this) {
        return -1;
    }
    this->virtual_socket_send_cb = send_method_ptr;
    return 0;
}

int8_t coap_service_register_uri(int8_t service_id, const char *uri, uint8_t allowed_method, coap_service_request_recv_cb *request_recv_cb)
{
    coap_service_t *this = service_find(service_id);
    uri_registration_t *uri_reg_ptr;
    char *uri_ptr = NULL;
    uint16_t uri_len;
    tr_debug("Service %d, Uri registration uri: %s", service_id, uri);
    if (!this || !uri) {
        return -1;
    }
    uri_len = strlen(uri);

    uri_reg_ptr = uri_registration_find(this, uri, uri_len);
    if (!uri_reg_ptr) {
        uri_reg_ptr = ns_dyn_mem_alloc(sizeof(uri_registration_t));
        if( !uri_reg_ptr ){
            tr_error("Uri registration failed, OOM");
            return -2;
        }
        uri_reg_ptr->uri_ptr = NULL;
    } else {
        ns_dyn_mem_free(uri_reg_ptr->uri_ptr);
        ns_list_remove(&this->uri_list, uri_reg_ptr);
    }

    uri_ptr = ns_dyn_mem_alloc(uri_len);
    if (!uri_ptr) {
        ns_dyn_mem_free(uri_reg_ptr);
        tr_error("Uri registration failed, OOM");
        return -2;
    }

    uri_reg_ptr->uri_ptr = memcpy(uri_ptr, uri, uri_len);
    uri_reg_ptr->uri_len = uri_len;
    uri_reg_ptr->request_recv_cb = request_recv_cb;
    uri_reg_ptr->allowed_method = allowed_method;
    ns_list_add_to_start(&this->uri_list, uri_reg_ptr);
    return 0;
}

int8_t coap_service_unregister_uri(int8_t service_id, const char *uri)
{
    coap_service_t *this = service_find(service_id);
    uri_registration_t *uri_reg_ptr;
    tr_debug("Service %d, Uri unregistration uri: %s", service_id, uri);
    if (!this || !uri) {
        return -1;
    }

    uri_reg_ptr = uri_registration_find(this, uri, strlen(uri));
    if (!uri_reg_ptr) {
        return -2;
    }

    ns_dyn_mem_free(uri_reg_ptr->uri_ptr);
    ns_list_remove(&this->uri_list, uri_reg_ptr);
    ns_dyn_mem_free(uri_reg_ptr);

    return 0;
}

uint16_t coap_service_request_send(int8_t service_id, uint8_t options, const uint8_t destination_addr[static 16], uint16_t destination_port, sn_coap_msg_type_e msg_type, sn_coap_msg_code_e msg_code, const char *uri,
        sn_coap_content_format_e cont_type, const uint8_t *payload_ptr, uint16_t payload_len, coap_service_response_recv *request_response_cb){
    //TODO: coap_service_response_recv is an ugly cast, this should be refactored away + sn_coap_hdr_s MUST NOT be exposed to users of coap-service!
    //Callback would be still needed, but where to store callback?
    return coap_message_handler_request_send(coap_service_handle, service_id, options, destination_addr, destination_port, msg_type, msg_code, uri, cont_type, payload_ptr, payload_len, request_response_cb);
}

int8_t coap_service_response_send(int8_t service_id, uint8_t options, sn_coap_hdr_s *request_ptr, sn_coap_msg_code_e message_code, sn_coap_content_format_e content_type, const uint8_t *payload_ptr,uint16_t payload_len){
    return coap_message_handler_response_send(coap_service_handle, service_id, options, request_ptr, message_code, content_type, payload_ptr, payload_len);
}

int8_t coap_service_set_handshake_timeout(int8_t service_id, uint32_t min, uint32_t max)
{
    coap_service_t *this = service_find(service_id);
    if(!this){
        return -1;
    }

    return coap_connection_handler_set_timeout(this->conn_handler, min, max);
}

uint32_t coap_service_get_internal_timer_ticks(void)
{
    return coap_ticks;
}

uint16_t coap_service_id_find_by_socket(int8_t socket_id)
{
    coap_service_t *this = service_find_by_socket(socket_id);

    return this ? this->service_id:0;
}


text:
#pragma once

#include <map>
#include <mavlink.h>
#include <memory>
#include <vector>

#include "CameraComponent.h"
#include "conf_file.h"
#include "rtsp_server.h"
#include "socket.h"
#include "stream.h"

typedef struct image_callback {
    int comp_id;             /* Component ID */
    struct sockaddr_in addr; /* Requester address */
} image_callback_t;

class MavlinkServer {
public:
    MavlinkServer(ConfFile &conf, std::vector<std::unique_ptr<Stream>> &streams, RTSPServer &rtsp);
    ~MavlinkServer();
    void start();
    void stop();
    int addCameraComponent(CameraComponent *camComp);
    void removeCameraComponent(CameraComponent *camComp);
    CameraComponent *getCameraComponent(int compID);

private:
    const std::vector<std::unique_ptr<Stream>> &_streams;
    bool _is_running;
    unsigned int _timeout_handler;
    UDPSocket _udp;
    struct sockaddr_in _broadcast_addr = {};
    int _system_id;
    int _comp_id;
    char *_rtsp_server_addr;
    RTSPServer &_rtsp;
    std::map<int, CameraComponent *> compIdToObj;

    void _message_received(const struct sockaddr_in &sockaddr, const struct buffer &buf);
    void _handle_mavlink_message(const struct sockaddr_in &addr, mavlink_message_t *msg);
    void _handle_request_camera_information(const struct sockaddr_in &addr,
                                            mavlink_command_long_t &cmd);
    void _handle_request_camera_settings(const struct sockaddr_in &addr,
                                         mavlink_command_long_t &cmd);
    void _handle_request_storage_information(const struct sockaddr_in &addr,
                                             mavlink_command_long_t &cmd);
    void _handle_set_camera_mode(const struct sockaddr_in &addr,
                                                        mavlink_command_long_t &cmd);
    void _handle_image_start_capture(const struct sockaddr_in &addr, mavlink_command_long_t &cmd);
    void _handle_image_stop_capture(const struct sockaddr_in &addr, mavlink_command_long_t &cmd);
    void _image_captured_cb(image_callback_t cb_data, int result, int seq_num);
    void _handle_request_camera_capture_status(const struct sockaddr_in &addr,
                                               mavlink_command_long_t &cmd);
    void _handle_camera_video_stream_request(const struct sockaddr_in &addr, int command,
                                             unsigned int camera_id, unsigned int action);
    void _handle_camera_set_video_stream_settings(const struct sockaddr_in &addr,
                                                  mavlink_message_t *msg);
    void _handle_param_ext_request_read(const struct sockaddr_in &addr, mavlink_message_t *msg);
    void _handle_param_ext_request_list(const struct sockaddr_in &addr, mavlink_message_t *msg);
    void _handle_param_ext_set(const struct sockaddr_in &addr, mavlink_message_t *msg);
    void _handle_reset_camera_settings(const struct sockaddr_in &addr, mavlink_command_long_t &cmd);
    void _handle_heartbeat(const struct sockaddr_in &addr, mavlink_message_t *msg);
    bool _send_mavlink_message(const struct sockaddr_in *addr, mavlink_message_t &msg);
    void _send_ack(const struct sockaddr_in &addr, int cmd, int comp_id, bool success);
    const Stream::FrameSize *_find_best_frame_size(Stream &s, uint32_t w, uint32_t v);
    friend bool _heartbeat_cb(void *data);
};


text:
<?php

namespace Sabberworm\CSS;

use Sabberworm\CSS\Rule\Rule;

/**
 * Parser settings class.
 *
 * Configure parser behaviour here.
 */
class Settings {
	/**
	* Multi-byte string support. If true (mbstring extension must be enabled), will use (slower) mb_strlen, mb_convert_case, mb_substr and mb_strpos functions. Otherwise, the normal (ASCII-Only) functions will be used.
	*/
	public $bMultibyteSupport;

	/**
	* The default charset for the CSS if no `@charset` rule is found. Defaults to utf-8.
	*/
	public $sDefaultCharset = 'utf-8';

	/**
	* Lenient parsing. When used (which is true by default), the parser will not choke on unexpected tokens but simply ignore them.
	*/
	public $bLenientParsing = true;

	private function __construct() {
		$this->bMultibyteSupport = extension_loaded('mbstring');
	}

	public static function create() {
		return new Settings();
	}

	public function withMultibyteSupport($bMultibyteSupport = true) {
		$this->bMultibyteSupport = $bMultibyteSupport;
		return $this;
	}

	public function withDefaultCharset($sDefaultCharset) {
		$this->sDefaultCharset = $sDefaultCharset;
		return $this;
	}

	public function withLenientParsing($bLenientParsing = true) {
		$this->bLenientParsing = $bLenientParsing;
		return $this;
	}

	public function beStrict() {
		return $this->withLenientParsing(false);
	}
}


text:
The 1.0 release of the Container Analysis client is a significant upgrade
based on a [next-gen code generator](https://github.com/googleapis/gapic-generator-ruby),
and includes substantial interface changes. Existing code written for earlier
versions of this library will likely require updates to use this version.
This document describes the changes that have been made, and what you need to
do to update your usage.

To summarize:

 *  The library has been broken out into two libraries. The new gem
    `google-cloud-container_analysis-v1` contains the actual client classes for version
    V1 of the Container Analysis service, and the gem `google-cloud-container_analysis` now
    simply provides a convenience wrapper. See
    [Library Structure](#library-structure) for more info.
 *  The library uses a new configuration mechanism giving you closer control
    over endpoint address, network timeouts, and retry. See
    [Client Configuration](#client-configuration) for more info. Furthermore,
    when creating a client object, you can customize its configuration in a
    block rather than passing arguments to the constructor.
    See [Creating Clients](#creating-clients) for more info.
 *  Previously, positional arguments were used to indicate required arguments.
    Now, all method arguments are keyword arguments, with documentation that
    specifies whether they are required or optional. Additionally, you can pass
    a proto request object instead of separate arguments. See
    [Passing Arguments](#passing-arguments) for more info.
 *  Previously, some client classes included helper methods for constructing
    resource paths. These methods now take keyword rather than positional
    arguments, and are also available in a separate paths module. See
    [Resource Path Helpers](#resource-path-helpers) for more info.
 *  Previously, clients reported RPC errors by raising instances of
    `Google::Gax::GaxError` and its subclasses. Now, RPC exceptions are of type
    `Google::Cloud::Error` and its subclasses. See
    [Handling Errors](#handling-errors) for more info.
 *  Some classes have moved into different namespaces. See
    [Class Namespaces](#class-namespaces) for more info.

### Library Structure

Older 0.x releases of the `google-cloud-container_analysis` gem were all-in-one gems
that included potentially multiple clients for multiple versions of the
Container Analysis service. The `Google::Cloud::ContainerAnalysis.new` factory method would
return you an instance of a `Google::Cloud::ContainerAnalysis::V1::ContainerAnalysisClient`
object for the V1 version of the service.

With the 1.0 release, the `google-cloud-container_analysis` gem still provides factory
methods for obtaining clients. (The method signatures will have changed. See
[Creating Clients](#creating-clients) for details.) However, the actual client
classes have been moved into separate gems, one per service version. Currently,
Container Analysis has one version, V1. The
`Google::Cloud::ContainerAnalysis::V1::ContainerAnalysis::Client` class, along with its
helpers and data types, is now part of the `google-cloud-container_analysis-v1` gem.
If additional versions of the Container Analysis service are released, additional gems
may be provided for their client classes.

For normal usage, you can continue to install the `google-cloud-container_analysis` gem
(which will bring in the versioned client gems as dependencies) and continue to
use factory methods to create clients. However, you may alternatively choose to
install only one of the versioned gems. For example, if you know you will only
use `V1` of the service, you can install `google-cloud-container_analysis-v1` by
itself, and construct instances of the
`Google::Cloud::ContainerAnalysis::V1::ContainerAnalysis::Client` client class directly.

### Client Configuration

In older releases, if you wanted to customize performance parameters or
low-level behavior of the client (such as credentials, timeouts, or
instrumentation), you would pass a variety of keyword arguments to the client
constructor. It was also extremely difficult to customize the default settings.

With the 1.0 release, a configuration interface provides control over these
parameters, including defaults for all instances of a client, and settings for
each specific client instance. For example, to set default credentials and
timeout for all ContainerAnalysis V1 clients:

```
Google::Cloud::ContainerAnalysis::V1::ContainerAnalysis::Client.configure do |config|
  config.credentials = "/path/to/credentials.json"
  config.timeout = 10.0
end
```

Individual RPCs can also be configured independently. For example, to set the
timeout for the `set_iam_policy` call:

```
Google::Cloud::ContainerAnalysis::V1::ContainerAnalysis::Client.configure do |config|
  config.rpcs.set_iam_policy.timeout = 20.0
end
```

Finally, you can override the configuration for each client instance. See the
section on [Creating Clients](#creating-clients) for details.

### Creating Clients

In older releases, to create a client object, you would use the
`Google::Cloud::ContainerAnalysis.new` class method. Keyword arguments were available to
select a service version and to configure parameters such as credentials and
timeouts.

With the 1.0 release, use the `Google::Cloud::ContainerAnalysis.container_analysis` class
method to create a client object. You may select a service version using the
`:version` keyword argument. However, other configuration parameters should be
set in a configuration block when you create the client.

As with older versions of this library, you can get the underlying Grafeas
client by calling the `grafeas_client` method on the Container Analysis client.

Old:
```
container_analysis = Google::Cloud::ContainerAnalysis.new \
  credentials: "/path/to/credentials.json"

grafeas_client = container_analysis.grafeas_client
```

New:
```
container_analysis = Google::Cloud::ContainerAnalysis.container_analysis do |config|
  config.credentials = "/path/to/credentials.json"
end

grafeas_client = container_analysis.grafeas_client
```

The configuration block is optional. If you do not provide it, or you do not
set some configuration parameters, then the default configuration is used. See
[Client Configuration](#client-configuration).

### Passing Arguments

In older releases, required arguments would be passed as positional method
arguments, while most optional arguments would be passed as keyword arguments.

With the 1.0 release, all RPC arguments are passed as keyword arguments,
regardless of whether they are required or optional. For example:

Old:
```
ca_client = Google::Cloud::ContainerAnalysis.new
client = ca_client.grafeas_client

parent = "projects/my-project"

# Parent is a positional argument, while page_size is a keyword argument.
response = client.list_occurrences parent, page_size: 10
```

New:
```
ca_client = Google::Cloud::ContainerAnalysis.container_analysis
client = ca_client.grafeas_client

parent = "projects/my-project"

# Parent and page_size are both keyword arguments
response = client.list_occurrences parent: parent, page_size: 10
```

In the 1.0 release, it is also possible to pass a request object, either
as a hash or as a protocol buffer.

New:
```
ca_client = Google::Cloud::ContainerAnalysis.container_analysis
client = ca_client.grafeas_client

request = Grafeas::V1::ListOccurrencesRequest.new(
  parent: "projects/my-project",
  page_size: 10
)

# Pass a request object as a positional argument:
response = client.list_occurrences request
```

Finally, in older releases, to provide call options, you would pass a
`Google::Gax::CallOptions` object with the `:options` keyword argument. In the
1.0 release, pass call options using a _second set_ of keyword arguments.

Old:
```
ca_client = Google::Cloud::ContainerAnalysis.new
client = ca_client.grafeas_client

parent = "projects/my-project"

options = Google::Gax::CallOptions.new timeout: 10.0

response = client.list_occurrences parent, page_size: 10, options: options
```

New:
```
ca_client = Google::Cloud::ContainerAnalysis.container_analysis
client = ca_client.grafeas_client

parent = "projects/my-project"

# Use a hash to wrap the normal call arguments (or pass a request object), and
# then add further keyword arguments for the call options.
response = client.list_occurrences(
  { parent: parent, page_size: 10 },
  timeout: 10.0
)
```

### Resource Path Helpers

The client library includes helper methods for generating the resource path
strings passed to many calls. These helpers have changed in two ways:

* In older releases, they are _class_ methods on the client class. In the 1.0
  release, they are _instance_ methods on the client. They are also available
  on a separate paths module that you can include elsewhere for convenience.
* In older releases, arguments to a resource path helper are passed as
  _positional_ arguments. In the 1.0 release, they are passed as named _keyword_
  arguments.

Following is an example involving using a resource path helper.

Old:
```
ca_client = Google::Cloud::ContainerAnalysis.new
client = ca_client.grafeas_client

# Call the helper on the client class
parent = Grafeas::V1::GrafeasClient.project_path "my-project"

response = client.list_occurrences parent
```

New:
```
ca_client = Google::Cloud::ContainerAnalysis.container_analysis
client = ca_client.grafeas_client

# Call the helper on the client instance, and use keyword arguments
parent = client.project_path project: "my-project"

response = client.list_occurrences parent: parent
```

In the 1.0 client, you can also use the paths module as a convenience module.

New:
```
# Bring the path helper methods into the current class
include Grafeas::V1::Grafeas::Paths

def foo
  ca_client = Google::Cloud::ContainerAnalysis.container_analysis
  client = ca_client.grafeas_client

  # Call the included helper method
  parent = project_path project: "my-project"

  response = client.list_occurrences parent: parent

  # Do something with response...
end
```

### Handling Errors

The client reports standard
[gRPC error codes](https://github.com/grpc/grpc/blob/master/doc/statuscodes.md)
by raising exceptions. In older releases, these exceptions were located in the
`Google::Gax` namespace and were subclasses of the `Google::Gax::GaxError` base
exception class, defined in the `google-gax` gem. However, these classes were
different from the standard exceptions (subclasses of `Google::Cloud::Error`)
thrown by other client libraries such as `google-cloud-storage`.

The 1.0 client library now uses the `Google::Cloud::Error` exception hierarchy,
for consistency across all the Google Cloud client libraries. In general, these
exceptions have the same name as their counterparts from older releases, but
are located in the `Google::Cloud` namespace rather than the `Google::Gax`
namespace.

Old:
```
ca_client = Google::Cloud::ContainerAnalysis.new
client = ca_client.grafeas_client

parent = "projects/my-project"

begin
  response = client.list_occurrences parent, page_size: 10
rescue Google::Gax::Error => e
  # Handle exceptions that subclass Google::Gax::Error
end
```

New:
```
ca_client = Google::Cloud::ContainerAnalysis.container_analysis
client = ca_client.grafeas_client

parent = "projects/my-project"

begin
  response = client.list_occurrences parent: parent, page_size: 10
rescue Google::Cloud::Error => e
  # Handle exceptions that subclass Google::Cloud::Error
end
```

### Class Namespaces

In older releases, the client object was of classes with names like:
`Google::Cloud::ContainerAnalysis::V1::ContainerAnalysisClient`.
In the 1.0 release, the client object is of a different class:
`Google::Cloud::ContainerAnalysis::V1::ContainerAnalysis::Client`.
Note that most users will use the factory methods such as
`Google::Cloud::ContainerAnalysis.container_analysis` to create instances of the client object,
so you may not need to reference the actual class directly.
See [Creating Clients](#creating-clients).

In older releases, the credentials object was of class
`Google::Cloud::ContainerAnalysis::V1::Credentials`.
In the 1.0 release, each service has its own credentials class, e.g.
`Google::Cloud::ContainerAnalysis::V1::ContainerAnalysis::Credentials`.
Again, most users will not need to reference this class directly.
See [Client Configuration](#client-configuration).


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>de.cdietze.ld37</groupId>
    <artifactId>ld37</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>ld37-assets</artifactId>
  <packaging>jar</packaging>
</project>


text:
<?php

/**
 * This api exposes the relationships between organizations and CiviCRM groups.
 *
 * @package CiviCRM_APIv3
 */

/**
 * Get group organization record/s.
 *
 * @param array $params
 *   Name value pair of contact information.
 *
 * @return array
 *   list of groups, given contact subscribed to
 */
function civicrm_api3_group_organization_get($params) {
  return _civicrm_api3_basic_get('CRM_Contact_DAO_GroupOrganization', $params);
}

/**
 * Create group organization record.
 *
 * @param array $params
 *   Array.
 *
 * @return array
 */
function civicrm_api3_group_organization_create($params) {

  $groupOrgBAO = CRM_Contact_BAO_GroupOrganization::add($params);

  if (is_null($groupOrgBAO)) {
    return civicrm_api3_create_error("group organization not created");
  }

  _civicrm_api3_object_to_array($groupOrgBAO, $values);
  return civicrm_api3_create_success($values, $params, 'GroupOrganization', 'get', $groupOrgBAO);
}

/**
 * Adjust Metadata for Create action.
 *
 * The metadata is used for setting defaults, documentation & validation.
 *
 * @param array $params
 *   Array of parameters determined by getfields.
 */
function _civicrm_api3_group_organization_create_spec(&$params) {
  $params['organization_id']['api.required'] = 1;
  $params['group_id']['api.required'] = 1;
}

/**
 * Deletes an existing Group Organization.
 *
 * This API is used for deleting a Group Organization
 *
 * @param array $params
 *   With 'id' = ID of the Group Organization to be deleted.
 *
 * @return array
 *   API Result
 */
function civicrm_api3_group_organization_delete($params) {

  $result = CRM_Contact_BAO_GroupOrganization::deleteGroupOrganization($params['id']);
  return $result ? civicrm_api3_create_success('Deleted Group Organization successfully') : civicrm_api3_create_error('Could not delete Group Organization');
}


text:
<?php

	function __autoload($className)
	{
		include_once $className.".php";
	}

	$authenticate = new authenticate();

	$authenticate->checkLoginStatus();

	if(isset($_POST['confirm_add_teacher']))
	{
		$teacher = new teacher();

		$teacher->addTeacher($_POST);

		echo '';

		header("Location:view_teacher.php");
	}

?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>DarulHuda - Add Teacher</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/sb-admin.css" rel="stylesheet">
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css">
	<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/themes/ui-darkness/jquery-ui.css" rel="stylesheet">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
            Toggle navigation

          </button>
          DarulHuda

       <?php include_once "menu.php"; ?>

Add Teacher

 Home

Teacher

Add Teacher

				<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

Teacher Details

Personal Details

            <form role="form" method="post" action="" onsubmit=" return validateTeacher();">

                First Name
                <input type="text" class="form-control" name="first_name" placeholder="Enter text">

                Middle Name
                <input type="text" class="form-control" name="middle_name" placeholder="Enter text">

                Last Name
                <input type="text" class="form-control" name="last_name" placeholder="Enter text">

                Date Of Birth
                <input type="text" class="form-control" name="dob_teacher" placeholder="Enter text" id="dob_teacher">

                Gender
                <select class="form-control" name="gender" placeholder="Enter text">
					<option>Please Select</option>
                   <option>Male</option>
                   <option>Female</option>
                </select>

                Qualification
                <select class="form-control" name="qualification" placeholder="Enter text">
					<option>Please Select</option>
                    <option>Hafeez</option>
                    <option>Aalim</option>
				    <option>Mufti</option>
                </select>

                Address
                 <textarea class="form-control" placeholder="Enter text" rows="3" name="address"></textarea>

                Contact No
                <input type="text" class="form-control" placeholder="Enter text" name="contact_no">

           <input type="submit" class="btn btn-success" name="confirm_add_teacher" value="Add Teacher">
              <button type="reset" class="btn btn-danger">Reset Button</button>


text:
import sys
import os
import shutil

me_filename = 'mediaelement'
mep_filename = 'mediaelementplayer'
combined_filename = 'mediaelement-and-player'

# BUILD MediaElement (single file)

print('building MediaElement.js')
me_files = []
me_files.append('me-header.js')
me_files.append('me-namespace.js')
me_files.append('me-utility.js')
me_files.append('me-plugindetector.js')
me_files.append('me-featuredetection.js')
me_files.append('me-mediaelements.js')
me_files.append('me-shim.js')
me_files.append('me-i18n.js')
me_files.append('me-i18n-locale-de.js')

code = ''

for item in me_files:
	src_file = open('js/' + item,'r')
	code += src_file.read() + "\n"

tmp_file = open('../build/' + me_filename + '.js','w')
tmp_file.write(code)
tmp_file.close()

# BUILD MediaElementPlayer (single file)
print('building MediaElementPlayer.js')
mep_files = []
mep_files.append('mep-header.js')
mep_files.append('mep-library.js')
mep_files.append('mep-player.js')
mep_files.append('mep-feature-playpause.js')
mep_files.append('mep-feature-stop.js')
mep_files.append('mep-feature-progress.js')
mep_files.append('mep-feature-time.js')
mep_files.append('mep-feature-volume.js')
mep_files.append('mep-feature-fullscreen.js')
mep_files.append('mep-feature-tracks.js')
mep_files.append('mep-feature-contextmenu.js')
mep_files.append('mep-feature-postroll.js')
# mep_files.append('mep-feature-sourcechooser.js')

code = ''

for item in mep_files:
        src_file = open('js/' + item,'r')
        code += src_file.read() + "\n"

tmp_file = open('../build/' + mep_filename + '.js','w')
tmp_file.write(code)
tmp_file.close()

# MINIFY both scripts

print('Minifying JavaScript')
# os.system("java -jar yuicompressor-2.4.2.jar ../build/" + me_filename + ".js -o ../build/" + me_filename + ".min.js --charset utf-8 -v")
# os.system("java -jar yuicompressor-2.4.2.jar ../build/" + mep_filename + ".js -o ../build/" + mep_filename + ".min.js --charset utf-8 -v")
os.system("java -jar compiler.jar --js ../build/" + me_filename + ".js --js_output_file ../build/" + me_filename + ".min.js")
os.system("java -jar compiler.jar --js ../build/" + mep_filename + ".js --js_output_file ../build/" + mep_filename + ".min.js")

# PREPEND intros
def addHeader(headerFilename, filename):

	# get the header text
	tmp_file = open(headerFilename)
	header_txt = tmp_file.read();
	tmp_file.close()

	# read the current contents of the file
	tmp_file = open(filename)
	file_txt = tmp_file.read()
	tmp_file.close()

	# open the file again for writing
	tmp_file = open(filename, 'w')
	tmp_file.write(header_txt)
	# write the original contents
	tmp_file.write(file_txt)
	tmp_file.close()

addHeader('js/me-header.js', '../build/' + me_filename + '.min.js')
addHeader('js/mep-header.js', '../build/' + mep_filename + '.min.js')

# COMBINE into single script
print('Combining scripts')
code = ''
src_file = open('../build/' + me_filename + '.js','r')
code += src_file.read() + "\n"
src_file = open('../build/' + mep_filename + '.js','r')
code += src_file.read() + "\n"

tmp_file = open('../build/' + combined_filename + '.js','w')
tmp_file.write(code)
tmp_file.close()

code = ''
src_file = open('../build/' + me_filename + '.min.js','r')
code += src_file.read() + "\n"
src_file = open('../build/' + mep_filename + '.min.js','r')
code += src_file.read() + "\n"

tmp_file = open('../build/' + combined_filename + '.min.js','w')
tmp_file.write(code)
tmp_file.close()

# MINIFY CSS
print('Minifying CSS')
src_file = open('css/mediaelementplayer.css','r')
tmp_file = open('../build/mediaelementplayer.css','w')
tmp_file.write(src_file.read())
tmp_file.close()
os.system("java -jar yuicompressor-2.4.2.jar ../build/mediaelementplayer.css -o ../build/mediaelementplayer.min.css --charset utf-8 -v")

#COPY skin files
print('Copying Skin Files')
shutil.copy2('css/controls.png','../build/controls.png')
shutil.copy2('css/controls.svg','../build/controls.svg')
shutil.copy2('css/bigplay.png','../build/bigplay.png')
shutil.copy2('css/bigplay.svg','../build/bigplay.svg')
shutil.copy2('css/loading.gif','../build/loading.gif')

shutil.copy2('css/mejs-skins.css','../build/mejs-skins.css')
shutil.copy2('css/controls-ted.png','../build/controls-ted.png')
shutil.copy2('css/controls-wmp.png','../build/controls-wmp.png')
shutil.copy2('css/controls-wmp-bg.png','../build/controls-wmp-bg.png')

print('DONE!')


text:
Installation

License Key

XAP Java Installation

Environment Variables

Setting Classpath

Setting JVM Location

C++

Maven Plugin

Advanced Configuration

Eclipse setup

Running and Debugging Within Your IDE

JUnit Testing

XAP as Windows Service

POJO Support

Overview

Dynamic Properties

Space Document

Document API

Extended Document

Interoperability

Modeling your Data

Space Object ID

Annotation based Metadata

Class Annotations

Property Annotations

XML based Metadata

Class Metadata

Properties Metadata

Grid Metadata

Storage Types

Custom Serialization

Routing In Partitioned Spaces

The Space Interface

Overview

Configuration

Operations

Change API

Overview

Custom Change

Advanced

Counters

Aggregators

Transactions

Notifications

Space Filters

Interceptors

Space Mode Context Loader

Lease Time

Querying the Space

Id Queries

Template Matching

SQLQuery

Free Text Search

Nested Properties

User Defined Classes

Paging Support

Paging Support - GSIterator

Projection

Indexing

Basic Index

Nested Property Index

Collection Index

Compound Index

Unique Index

Transactions

Transaction Management

Locking and Blocking

Read Modifiers

Optimistic Locking

Pessimistic Locking

Space Persistency

Overview

Direct Persistency

Hibernate Integration

Data Source

Synchronization Endpoint

Initial Load

Asynchronous Persistency - Write Behind

Advanced Configuration

Transient Entries

Advanced Topics

Migrating from Hibernate

Migrating From External Data Source API

Other Data Access APIs

JDBC Driver

JPA API

Overview

JPA Entity Id

JPA Relationships

Limitations

Map API

Memcached API

Client Side Caching

Local Cache

Local View

Caching over the WAN

Monitoring Client Side Cache

Task Execution

Overview

Dynamic Language Tasks

Metadata

Event Processing

Notify Container

Overview

Transaction Support

Session Based Messaging API

Durable Notifications

Custom Data Event Filters

Polling Container

Overview

Transaction Support

Concurrent Consumers

Data Event Listener

Event Exception Handler

FIFO Ordering

FIFO Support

FIFO Grouping

JMS Messaging Support

JMS Basics

JMS Messages in XAP

JMS-Space Interoperability

Example

XAP JNDI

Working with GSJMSAdmin

Advanced Options

JMS Failover

Transactions

Security

Browsing JMS Queues

Known Issues and Considerations

Using GigaSpaces JMS Without Changing the Classpath

Space Based Remoting

Overview

Executor Based Remoting

Event Driven Remoting

Metadata Summary

Mule ESB Integration

Event Container Transport

Processing Unit

Queue Provider

SEDA Model

Big Data Integration

Archive Container

Cassandra Integration

Cassandra Persistency

Data Source

Synchronization Endpoint

Hector Client

Archive Handler

MongoDB Integration

Mongo Persistency

Data Source

Synchronization Endpoint

Archive Handler

Admin API

Overview

Dump

Administrative Alerts

SNMP Alerts

The Processing Unit

Directory Structure

Configuration

Cluster Information

Reloading Business Logic

Custom Processing Unit

Deploying and Running

Overview

Standalone Mode

Deploying onto the Grid

Deployment Properties

Elastic Processing Unit

Overview

Deployment

Scale Triggers

Machine Provisioning

Configuration Properties

Example

Web Application Support

Web Application Support - Overview

Jetty Processing Unit Container

HTTP Session Management

Web Processing Unit Container

Apache Load Balancer Agent

Global HTTP Session Sharing

Overview

Configuration & Deployment

Apache Load-Balancer

Multi Site LAN Replication

Overview

Gateway Bootstrapping

Multi Site WAN Replication

Overview

Communication Filter

Gateway Components

Configuring Targets

Bootstrapping Process

Conflict Resolution

Changing Deployment during Runtime

Filtering  Data

Intercepting Replication Events

Limitations

Platform Interoperability

Overview

CPP

Overview

The CPP Space Interface

API Mapping File

Type Converter

CPP Processing Unit

API Code Generator

gsxml2cpp Utility

CPP Examples

Hello World

CPP API Usage

Processing Unit

Writing Existing Class to Space

The REST Service

Overview

REST API

Scala

Constructor Based Properties

Enhanced Scala REPL

Predicate Based Queries

Scripting Executor

Scala Task Execution


text:
/* stream_i.h */

#ifndef STREAM_I_H_FILE
#define STREAM_I_H_FILE

#include "common/buffer.h"
#include "ssh/cipher_i.h"
#include "ssh/mac_i.h"

#include <stdint.h>

enum SSH_STREAM_TYPE {
  SSH_STREAM_TYPE_READ,
  SSH_STREAM_TYPE_WRITE
};

struct SSH_STREAM_WRITE_DATA {
  struct SSH_BUFFER buf_enc;
};

struct SSH_STREAM_READ_DATA {
  struct SSH_BUFFER buf;
  struct SSH_BUFFER buf_enc;
};

struct SSH_STREAM {
  uint32_t seq_num;
  struct SSH_BUFFER pack;

  enum SSH_STREAM_TYPE type;
  union {
    struct SSH_STREAM_WRITE_DATA write;
    struct SSH_STREAM_READ_DATA read;
  } net;

  enum SSH_CIPHER_TYPE cipher_type;
  struct SSH_CIPHER_CTX *cipher_ctx;
  uint32_t cipher_block_len;

  enum SSH_MAC_TYPE mac_type;
  struct SSH_MAC_CTX *mac_ctx;
  uint32_t mac_len;
};

void ssh_stream_init(struct SSH_STREAM *stream, enum SSH_STREAM_TYPE type);
void ssh_stream_close(struct SSH_STREAM *stream);

int ssh_stream_set_cipher(struct SSH_STREAM *stream, enum SSH_CIPHER_TYPE type, enum SSH_CIPHER_DIRECTION dir, struct SSH_STRING *iv, struct SSH_STRING *key);
int ssh_stream_set_mac(struct SSH_STREAM *stream, enum SSH_MAC_TYPE type, struct SSH_STRING *key);

struct SSH_BUFFER *ssh_stream_new_packet(struct SSH_STREAM *stream);
int ssh_stream_send_packet(struct SSH_STREAM *stream, int sock);
int ssh_stream_send_is_pending(struct SSH_STREAM *stream);
int ssh_stream_send_flush(struct SSH_STREAM *stream, int sock);

int ssh_stream_recv_packet(struct SSH_STREAM *stream, int sock);

#endif /* STREAM_I_H_FILE */


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="org.cboard.dao.DatasetDao">

    <select id="getCategoryList" resultType="java.lang.String">
        SELECT DISTINCT(category_name) category FROM dashboard_dataset order by category
    </select>

    <select id="getDatasetList" resultType="org.cboard.pojo.DashboardDataset">
       SELECT dataset_id id,user_id userId,dataset_name name,data_json data,category_name categoryName FROM dashboard_dataset
       order by dataset_name
    </select>

    <select id="getDataset" resultType="org.cboard.pojo.DashboardDataset">
       SELECT dataset_id id,user_id userId,dataset_name name,data_json data,category_name categoryName FROM dashboard_dataset WHERE dataset_id = #{0}
    </select>

    <insert id="save" parameterType="org.cboard.pojo.DashboardDataset">
        <![CDATA[
        INSERT INTO dashboard_dataset(user_id,dataset_name,data_json,category_name) VALUES (#{userId},#{name},#{data},#{categoryName})
        ]]>
    </insert>

    <update id="update" parameterType="org.cboard.pojo.DashboardDataset">
        <![CDATA[
        UPDATE dashboard_dataset SET dataset_name = #{name},data_json = #{data},category_name = #{categoryName} where dataset_id = #{id}
        ]]>
    </update>

    <select id="countExistDatasetName" resultType="java.lang.Long">
        SELECT count(1) from dashboard_dataset where 1=1
        <if test="dataset_id != null" >
        <![CDATA[
            and dataset_id <> #{dataset_id}
            ]]>
        </if>
          and dataset_name = #{dataset_name}
    </select>

    <delete id="delete">
        delete from dashboard_dataset where dataset_id = #{0}
    </delete>
</mapper>


text:
ExtARDrone::ExtARDrone(std::string sessionId, std::string userId, std::string appId,
                       const std::string ardIp,
                       const unsigned short ardATCmdsPort,
                       const unsigned short ardNavdataPort,
                       const unsigned short ardVideoPort,
                       const unsigned short ardControlPort)
    : ARDrone(sessionId, userId, appId,
              ardIp, ardATCmdsPort, ardNavdataPort, ardVideoPort, ardControlPort,
              new ucapa::ARDroneConnections(ardIp, ardATCmdsPort, ardNavdataPort, ardVideoPort, ardControlPort),
              new ExtNavdata(),
              new ucapa::Video(ardIp, ardVideoPort))
{

}


text:
namespace swift {

class SILBasicBlock;
class SILModule;

inline SILArgumentConvention
SILFunctionType::getSILArgumentConvention(unsigned index) const {
  assert(index <= getNumSILArguments());
  auto numIndirectResults = getNumIndirectResults();
  if (index < numIndirectResults) {
    return SILArgumentConvention::Indirect_Out;
  } else {
    auto param = getParameters()[index - numIndirectResults];
    return SILArgumentConvention(param.getConvention());
  }
}

class SILArgument : public ValueBase {
  void operator=(const SILArgument &) = delete;
  void operator delete(void *Ptr, size_t) = delete;

  SILBasicBlock *ParentBB;
  const ValueDecl *Decl;

public:
  SILBasicBlock *getParent() { return ParentBB; }
  const SILBasicBlock *getParent() const { return ParentBB; }

  SILFunction *getFunction();
  const SILFunction *getFunction() const;

  SILModule &getModule() const;

  const ValueDecl *getDecl() const { return Decl; }

  static bool classof(const ValueBase *V) {
    return V->getKind() >= ValueKind::First_SILArgument &&
           V->getKind() <= ValueKind::Last_SILArgument;
  }

  unsigned getIndex() const {
    ArrayRef<SILArgument *> Args = getParent()->getArguments();
    for (unsigned i = 0, e = Args.size(); i != e; ++i)
      if (Args[i] == this)
        return i;
    llvm_unreachable("SILArgument not argument of its parent BB");
  }

  /// Returns the incoming SILValue from the \p BBIndex predecessor of this
  /// argument's parent BB. If the routine fails, it returns an empty SILValue.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  SILValue getIncomingValue(unsigned BBIndex);

  /// Returns the incoming SILValue for this argument from BB. If the routine
  /// fails, it returns an empty SILValue.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  SILValue getIncomingValue(SILBasicBlock *BB);

  /// Returns true if we were able to find incoming values for each predecessor
  /// of this arguments basic block. The found values are stored in OutArray.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  bool getIncomingValues(llvm::SmallVectorImpl<SILValue> &OutArray);

  /// Returns true if we were able to find incoming values for each predecessor
  /// of this arguments basic block. The found values are stored in OutArray.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  bool getIncomingValues(
      llvm::SmallVectorImpl<std::pair<SILBasicBlock *, SILValue>> &OutArray);

  /// If this SILArgument's parent block has one predecessor, return the
  /// incoming value from that predecessor. Returns SILValue() otherwise.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  SILValue getSingleIncomingValue() const;

protected:
  SILArgument(ValueKind SubClassKind, SILBasicBlock *ParentBB, SILType Ty,
              const ValueDecl *D = nullptr);
  SILArgument(ValueKind SubClassKind, SILBasicBlock *ParentBB,
              SILBasicBlock::arg_iterator Pos, SILType Ty,
              const ValueDecl *D = nullptr);

  // A special constructor, only intended for use in
  // SILBasicBlock::replaceBBArg.
  explicit SILArgument(ValueKind SubClassKind, SILType Ty,
                       const ValueDecl *D = nullptr)
      : ValueBase(SubClassKind, Ty), ParentBB(nullptr), Decl(D) {}
  void setParent(SILBasicBlock *P) { ParentBB = P; }

  friend SILBasicBlock;
};

class SILPHIArgument : public SILArgument {
  ValueOwnershipKind Kind;

public:
  /// Return the static ownership kind associated with this SILPHIArgument.
  ValueOwnershipKind getOwnershipKind() const { return Kind; }

  /// Returns the incoming SILValue from the \p BBIndex predecessor of this
  /// argument's parent BB. If the routine fails, it returns an empty SILValue.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  SILValue getIncomingValue(unsigned BBIndex);

  /// Returns the incoming SILValue for this argument from BB. If the routine
  /// fails, it returns an empty SILValue.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  SILValue getIncomingValue(SILBasicBlock *BB);

  /// Returns true if we were able to find incoming values for each predecessor
  /// of this arguments basic block. The found values are stored in OutArray.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  bool getIncomingValues(llvm::SmallVectorImpl<SILValue> &OutArray);

  /// Returns true if we were able to find incoming values for each predecessor
  /// of this arguments basic block. The found values are stored in OutArray.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  bool getIncomingValues(
      llvm::SmallVectorImpl<std::pair<SILBasicBlock *, SILValue>> &OutArray);

  /// If this SILArgument's parent block has one predecessor, return the
  /// incoming value from that predecessor. Returns SILValue() otherwise.
  /// Note that for some predecessor terminators the incoming value is not
  /// exactly the argument value. E.g. the incoming value for a switch_enum
  /// payload argument is the enum itself (the operand of the switch_enum).
  SILValue getSingleIncomingValue() const;

  static bool classof(const ValueBase *V) {
    return V->getKind() == ValueKind::SILPHIArgument;
  }

private:
  friend SILBasicBlock;
  SILPHIArgument(SILBasicBlock *ParentBB, SILType Ty, ValueOwnershipKind Kind,
                 const ValueDecl *D = nullptr)
      : SILArgument(ValueKind::SILPHIArgument, ParentBB, Ty, D), Kind(Kind) {}
  SILPHIArgument(SILBasicBlock *ParentBB, SILBasicBlock::arg_iterator Pos,
                 SILType Ty, ValueOwnershipKind Kind,
                 const ValueDecl *D = nullptr)
      : SILArgument(ValueKind::SILPHIArgument, ParentBB, Pos, Ty, D),
        Kind(Kind) {}

  // A special constructor, only intended for use in
  // SILBasicBlock::replaceBBArg.
  explicit SILPHIArgument(SILType Ty, ValueOwnershipKind Kind,
                          const ValueDecl *D = nullptr)
      : SILArgument(ValueKind::SILPHIArgument, Ty, D), Kind(Kind) {}
};

class SILFunctionArgument : public SILArgument {
public:
  bool isIndirectResult() const {
    auto numIndirectResults =
        getFunction()->getLoweredFunctionType()->getNumIndirectResults();
    return (getIndex() < numIndirectResults);
  }

  SILArgumentConvention getArgumentConvention() const {
    return getFunction()->getLoweredFunctionType()->getSILArgumentConvention(
        getIndex());
  }

  /// Given that this is an entry block argument, and given that it does
  /// not correspond to an indirect result, return the corresponding
  /// SILParameterInfo.
  SILParameterInfo getKnownParameterInfo() const {
    auto index = getIndex();
    auto fnType = getFunction()->getLoweredFunctionType();
    auto numIndirectResults = fnType->getNumIndirectResults();
    assert(index >= numIndirectResults && "Cannot be an indirect result");
    auto param = fnType->getParameters()[index - numIndirectResults];
    return param;
  }

  /// Returns true if this SILArgument is the self argument of its
  /// function. This means that this will return false always for SILArguments
  /// of SILFunctions that do not have self argument and for non-function
  /// argument SILArguments.
  bool isSelf() const;

  /// Returns true if this SILArgument is passed via the given convention.
  bool hasConvention(SILArgumentConvention P) const {
    return getArgumentConvention() == P;
  }

  static bool classof(const ValueBase *V) {
    return V->getKind() == ValueKind::SILFunctionArgument;
  }

private:
  friend SILBasicBlock;

  SILFunctionArgument(SILBasicBlock *ParentBB, SILType Ty,
                      const ValueDecl *D = nullptr)
      : SILArgument(ValueKind::SILFunctionArgument, ParentBB, Ty, D) {}
  SILFunctionArgument(SILBasicBlock *ParentBB, SILBasicBlock::arg_iterator Pos,
                      SILType Ty, const ValueDecl *D = nullptr)
      : SILArgument(ValueKind::SILFunctionArgument, ParentBB, Pos, Ty, D) {}

  // A special constructor, only intended for use in SILBasicBlock::replaceBBArg.
  explicit SILFunctionArgument(SILType Ty, const ValueDecl *D = nullptr)
      : SILArgument(ValueKind::SILFunctionArgument, Ty, D) {}
};

//===----------------------------------------------------------------------===//
// Out of line Definitions for SILArgument to avoid Forward Decl issues
//===----------------------------------------------------------------------===//

inline SILValue SILArgument::getIncomingValue(unsigned BBIndex) {
  if (isa<SILFunctionArgument>(this))
    return SILValue();
  return cast<SILPHIArgument>(this)->getIncomingValue(BBIndex);
}

inline SILValue SILArgument::getIncomingValue(SILBasicBlock *BB) {
  if (isa<SILFunctionArgument>(this))
    return SILValue();
  return cast<SILPHIArgument>(this)->getIncomingValue(BB);
}

inline bool
SILArgument::getIncomingValues(llvm::SmallVectorImpl<SILValue> &OutArray) {
  if (isa<SILFunctionArgument>(this))
    return false;
  return cast<SILPHIArgument>(this)->getIncomingValues(OutArray);
}

inline bool SILArgument::getIncomingValues(
    llvm::SmallVectorImpl<std::pair<SILBasicBlock *, SILValue>> &OutArray) {
  if (isa<SILFunctionArgument>(this))
    return false;
  return cast<SILPHIArgument>(this)->getIncomingValues(OutArray);
}

inline SILValue SILArgument::getSingleIncomingValue() const {
  if (isa<SILFunctionArgument>(this))
    return SILValue();
  return cast<SILPHIArgument>(this)->getSingleIncomingValue();
}

} // end swift namespace

#endif


text:
#ifndef PWMC_H
#define PWMC_H

//------------------------------------------------------------------------------
//         Global functions
//------------------------------------------------------------------------------

extern void PWMC_ConfigureChannel(
    unsigned char channel,
    unsigned int prescaler,
    unsigned int alignment,
    unsigned int polarity);

extern void PWMC_ConfigureClocks
    (unsigned int clka,
     unsigned int clkb,
     unsigned int mck);

extern void PWMC_SetPeriod(unsigned char channel, unsigned short period);

extern void PWMC_SetDutyCycle(unsigned char channel, unsigned short duty);

extern void PWMC_EnableChannel(unsigned char channel);

extern void PWMC_DisableChannel(unsigned char channel);

extern void PWMC_EnableChannelIt(unsigned char channel);

extern void PWMC_DisableChannelIt(unsigned char channel);

#endif //#ifndef PWMC_H


text:
using Lucene.Net.Index;
using Lucene.Net.Util;

namespace Lucene.Net.Codecs.Memory
{

    /// <summary>
    /// Tests MemoryPostingsFormat
    /// </summary>
    public class TestMemoryPostingsFormat : BasePostingsFormatTestCase
    {
        // TODO: randomize doPack
        private readonly Codec codec = TestUtil.AlwaysPostingsFormat(new MemoryPostingsFormat());

        protected override Codec GetCodec()
        {
            return codec;
        }
    }
}