text:
Remove a Vaccination Record

    <a href="<?=site_url();?>editanimal/<?=$animal[0]['chart_num']?>">Go Back to Edit page

    <?php if(!empty($this->session->flashdata('results'))){ ?>
        <?php echo $this->session->flashdata('results'); ?>
    <?php } ?>
    <?php echo validation_errors(); ?>
    <?php echo form_open('removevaccination' .'/'.$animal[0]['chart_num']);?>

           Chart Number:
           <input readonly type="text" size="20" id="chart_num" name="chart_num" class="form-control" value="<?=$animal[0]['chart_num']?>"/>

           Name:
           <input readonly type="text" size="20" id="name" name="name" class="form-control" value="<?=$animal[0]['name']?>"/>

        Vaccination:
        <select name="id" id="id" class="form-control">
          <option value="">Select a Vaccination record</option>
          <?php
            foreach($vaccinations as $vaccination) { ?>
              <option  value="<?= $vaccination['id'] ?>"><?= $vaccination['date_given'] ?> - <?=$vaccination['name']?></option>
          <?php
            } ?>
        </select>

     <input class="btn btn-success" type="submit" value="Remove Vaccination"/>
   </form>

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by yangguo on 14-12-15.
 */

object JsonTest {
  def main(args:Array[String]): Unit ={
    val g: PartialFunction[List[Int], String] = {
      case Nil =>"one"
      case x :: rest =>
        rest match {
          case Nil => " two "
          case y::z if z.isInstanceOf[List[Int]]=> {
            if (z.isInstanceOf[List[Int]] ){println("sdasdas")
            }
            println(z.getClass.getName);
            "t"
          }
        }
    }
    println(g.isDefinedAt(List(1,2,3,4)))
    println(g(List(1,2,3)))
  }
  def createJsonObj={
    JObj(Map(
      "firstName"->JString("John"),
      "lastName"->JString("smith"),
      "address"->JObj(Map(
        "streetAddress"->JString("长虹"),
         "state"->JString("SC"),
        "postalCode"->JDouble(10021)
      )),
      "phoneNumber"->JSeq(List(
        JObj(Map("type"->JString("home"),"number"->JString("212 555-1234"))),
        JObj(Map("type"->JString("fax"),"number"->JString("646 555-4567")))
        ))
    ))
  }
  def decoder(json:JSON):String=json match{
    case JSeq(elems)=>
      "["+(elems map decoder mkString ",")+"]"
    case JObj(binds)=>
      val assocs=binds map{
        case (key,value)=>"\""+key+"\": "+ decoder(value)
      }
      "{"+(assocs mkString ",")+"}"
    case JDouble(num)=>num.toString
    case JString(str)=>"\""+str+"\""
    case JBool(b)=>b.toString
    case JNull=>"null"
  }
}
abstract class JSON
case class JSeq(elems:List[JSON]) extends JSON
case class JString(str:String) extends JSON
case class JDouble(num:Double) extends JSON
case class JBool(b:Boolean) extends JSON
case class JObj(bindings:Map[String,JSON]) extends JSON
case object JNull extends JSON
trait dd {
  val value:String
  val length:Int
  def getValue=value
  val f:PartialFunction[String,String]
}


text:
"""
test_fake.py

By Paul Malmsten, 2010
pmalmsten@gmail.com

Tests fake device objects for proper functionality.
"""
import unittest
from xbee.tests.Fake import Serial

class TestFakeSerialRead(unittest.TestCase):
    """
    Fake Serial class should work as intended to emluate reading from a serial port.
    """

    def setUp(self):
        """
        Create a fake read device for each test.
        """
        self.device = Serial()
        self.device.set_read_data("test")

    def test_read_single_byte(self):
        """
        Reading one byte at a time should work as expected.
        """
        self.assertEqual(self.device.read(), 't')
        self.assertEqual(self.device.read(), 'e')
        self.assertEqual(self.device.read(), 's')
        self.assertEqual(self.device.read(), 't')

    def test_read_multiple_bytes(self):
        """
        Reading multiple bytes at a time should work as expected.
        """
        self.assertEqual(self.device.read(3), 'tes')
        self.assertEqual(self.device.read(), 't')

    def test_write(self):
        """
        Test serial write function.
        """
        self.device.write("Hello World")
        self.assertEqual(self.device.get_data_written(), "Hello World")


text:
package strategicpatch

import (
	"fmt"
	"reflect"
	"sort"
	"strings"

	"k8s.io/apimachinery/pkg/util/json"
	"k8s.io/apimachinery/pkg/util/mergepatch"
	forkedjson "k8s.io/apimachinery/third_party/forked/golang/json"
)

// An alternate implementation of JSON Merge Patch
// (https://tools.ietf.org/html/rfc7386) which supports the ability to annotate
// certain fields with metadata that indicates whether the elements of JSON
// lists should be merged or replaced.
//
// For more information, see the PATCH section of docs/devel/api-conventions.md.
//
// Some of the content of this package was borrowed with minor adaptations from
// evanphx/json-patch and openshift/origin.

const (
	directiveMarker  = "$patch"
	deleteDirective  = "delete"
	replaceDirective = "replace"
	mergeDirective   = "merge"

	deleteFromPrimitiveListDirectivePrefix = "$deleteFromPrimitiveList"
)

// JSONMap is a representations of JSON object encoded as map[string]interface{}
// where the children can be either map[string]interface{}, []interface{} or
// primitive type).
// Operating on JSONMap representation is much faster as it doesn't require any
// json marshaling and/or unmarshaling operations.
type JSONMap map[string]interface{}

type DiffOptions struct {
	// IgnoreChangesAndAdditions indicates if we keep the changes and additions in the patch.
	IgnoreChangesAndAdditions bool
	// IgnoreDeletions indicates if we keep the deletions in the patch.
	IgnoreDeletions bool
}

type MergeOptions struct {
	// MergeDeleteList indicates if we are merging the delete parallel list.
	MergeDeleteList bool
	// IgnoreUnmatchedNulls indicates if we should process the unmatched nulls.
	IgnoreUnmatchedNulls bool
}

// The following code is adapted from github.com/openshift/origin/pkg/util/jsonmerge.
// Instead of defining a Delta that holds an original, a patch and a set of preconditions,
// the reconcile method accepts a set of preconditions as an argument.

// CreateTwoWayMergePatch creates a patch that can be passed to StrategicMergePatch from an original
// document and a modified document, which are passed to the method as json encoded content. It will
// return a patch that yields the modified document when applied to the original document, or an error
// if either of the two documents is invalid.
func CreateTwoWayMergePatch(original, modified []byte, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error) {
	originalMap := map[string]interface{}{}
	if len(original) > 0 {
		if err := json.Unmarshal(original, &originalMap); err != nil {
			return nil, mergepatch.ErrBadJSONDoc
		}
	}

	modifiedMap := map[string]interface{}{}
	if len(modified) > 0 {
		if err := json.Unmarshal(modified, &modifiedMap); err != nil {
			return nil, mergepatch.ErrBadJSONDoc
		}
	}

	patchMap, err := CreateTwoWayMergeMapPatch(originalMap, modifiedMap, dataStruct, fns...)
	if err != nil {
		return nil, err
	}

	return json.Marshal(patchMap)
}

// CreateTwoWayMergeMapPatch creates a patch from an original and modified JSON objects,
// encoded JSONMap.
// The serialized version of the map can then be passed to StrategicMergeMapPatch.
func CreateTwoWayMergeMapPatch(original, modified JSONMap, dataStruct interface{}, fns ...mergepatch.PreconditionFunc) (JSONMap, error) {
	t, err := getTagStructType(dataStruct)
	if err != nil {
		return nil, err
	}

	diffOptions := DiffOptions{
		IgnoreChangesAndAdditions: false,
		IgnoreDeletions:           false,
	}
	patchMap, err := diffMaps(original, modified, t, diffOptions)
	if err != nil {
		return nil, err
	}

	// Apply the preconditions to the patch, and return an error if any of them fail.
	for _, fn := range fns {
		if !fn(patchMap) {
			return nil, mergepatch.NewErrPreconditionFailed(patchMap)
		}
	}

	return patchMap, nil
}

// Returns a (recursive) strategic merge patch that yields modified when applied to original.
func diffMaps(original, modified map[string]interface{}, t reflect.Type, diffOptions DiffOptions) (map[string]interface{}, error) {
	patch := map[string]interface{}{}
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	for key, modifiedValue := range modified {
		originalValue, ok := original[key]
		if !ok {
			// Key was added, so add to patch
			if !diffOptions.IgnoreChangesAndAdditions {
				patch[key] = modifiedValue
			}
			continue
		}

		// The patch may have a patch directive
		foundDirectiveMarker, err := handleDirectiveMarker(key, originalValue, modifiedValue, patch)
		if err != nil {
			return nil, err
		}
		if foundDirectiveMarker {
			continue
		}

		if reflect.TypeOf(originalValue) != reflect.TypeOf(modifiedValue) {
			// Types have changed, so add to patch
			if !diffOptions.IgnoreChangesAndAdditions {
				patch[key] = modifiedValue
			}
			continue
		}

		// Types are the same, so compare values
		switch originalValueTyped := originalValue.(type) {
		case map[string]interface{}:
			modifiedValueTyped := modifiedValue.(map[string]interface{})
			err = handleMapDiff(key, originalValueTyped, modifiedValueTyped, patch, t, diffOptions)
		case []interface{}:
			modifiedValueTyped := modifiedValue.([]interface{})
			err = handleSliceDiff(key, originalValueTyped, modifiedValueTyped, patch, t, diffOptions)
		default:
			replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)
		}
		if err != nil {
			return nil, err
		}
	}

	updatePatchIfMissing(original, modified, patch, diffOptions)
	return patch, nil
}

// handleDirectiveMarker handles how to diff directive marker between 2 objects
func handleDirectiveMarker(key string, originalValue, modifiedValue interface{}, patch map[string]interface{}) (bool, error) {
	if key == directiveMarker {
		originalString, ok := originalValue.(string)
		if !ok {
			return false, fmt.Errorf("invalid value for special key: %s", directiveMarker)
		}
		modifiedString, ok := modifiedValue.(string)
		if !ok {
			return false, fmt.Errorf("invalid value for special key: %s", directiveMarker)
		}
		if modifiedString != originalString {
			patch[directiveMarker] = modifiedValue
		}
		return true, nil
	}
	return false, nil
}

// handleMapDiff diff between 2 maps `originalValueTyped` and `modifiedValue`,
// puts the diff in the `patch` associated with `key`
// key is the key associated with originalValue and modifiedValue.
// originalValue, modifiedValue are the old and new value respectively.They are both maps
// patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue
// diffOptions contains multiple options to control how we do the diff.
func handleMapDiff(key string, originalValue, modifiedValue, patch map[string]interface{},
	t reflect.Type, diffOptions DiffOptions) error {
	fieldType, fieldPatchStrategy, _, err := forkedjson.LookupPatchMetadata(t, key)
	if err != nil {
		// We couldn't look up metadata for the field
		// If the values are identical, this doesn't matter, no patch is needed
		if reflect.DeepEqual(originalValue, modifiedValue) {
			return nil
		}
		// Otherwise, return the error
		return err
	}
	switch fieldPatchStrategy {
	// The patch strategic from metadata tells us to replace the entire object instead of diffing it
	case replaceDirective:
		if !diffOptions.IgnoreChangesAndAdditions {
			patch[key] = modifiedValue
		}
	default:
		patchValue, err := diffMaps(originalValue, modifiedValue, fieldType, diffOptions)
		if err != nil {
			return err
		}
		// Maps were not identical, use provided patch value
		if len(patchValue) > 0 {
			patch[key] = patchValue
		}
	}
	return nil
}

// handleSliceDiff diff between 2 slices `originalValueTyped` and `modifiedValue`,
// puts the diff in the `patch` associated with `key`
// key is the key associated with originalValue and modifiedValue.
// originalValue, modifiedValue are the old and new value respectively.They are both slices
// patch is the patch map that contains key and the updated value, and it is the parent of originalValue, modifiedValue
// diffOptions contains multiple options to control how we do the diff.
func handleSliceDiff(key string, originalValue, modifiedValue []interface{}, patch map[string]interface{},
	t reflect.Type, diffOptions DiffOptions) error {
	fieldType, fieldPatchStrategy, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadata(t, key)
	if err != nil {
		// We couldn't look up metadata for the field
		// If the values are identical, this doesn't matter, no patch is needed
		if reflect.DeepEqual(originalValue, modifiedValue) {
			return nil
		}
		// Otherwise, return the error
		return err
	}

	switch fieldPatchStrategy {
	// Merge the 2 slices using mergePatchKey
	case mergeDirective:
		addList, deletionList, err := diffLists(originalValue, modifiedValue, fieldType.Elem(), fieldPatchMergeKey, diffOptions)
		if err != nil {
			return err
		}
		if len(addList) > 0 {
			patch[key] = addList
		}
		// generate a parallel list for deletion
		if len(deletionList) > 0 {
			parallelDeletionListKey := fmt.Sprintf("%s/%s", deleteFromPrimitiveListDirectivePrefix, key)
			patch[parallelDeletionListKey] = deletionList
		}
	default:
		replacePatchFieldIfNotEqual(key, originalValue, modifiedValue, patch, diffOptions)
	}
	return nil
}

// replacePatchFieldIfNotEqual updates the patch if original and modified are not deep equal
// if diffOptions.IgnoreChangesAndAdditions is false.
// original is the old value, maybe either the live cluster object or the last applied configuration
// modified is the new value, is always the users new config
func replacePatchFieldIfNotEqual(key string, original, modified interface{},
	patch map[string]interface{}, diffOptions DiffOptions) {
	if diffOptions.IgnoreChangesAndAdditions {
		// Ignoring changes - do nothing
		return
	}
	if reflect.DeepEqual(original, modified) {
		// Contents are identical - do nothing
		return
	}
	// Create a patch to replace the old value with the new one
	patch[key] = modified
}

// updatePatchIfMissing iterates over `original` when ignoreDeletions is false.
// Clear the field whose key is not present in `modified`.
// original is the old value, maybe either the live cluster object or the last applied configuration
// modified is the new value, is always the users new config
func updatePatchIfMissing(original, modified, patch map[string]interface{}, diffOptions DiffOptions) {
	if diffOptions.IgnoreDeletions {
		// Ignoring deletion - do nothing
		return
	}
	// Add nils for deleted values
	for key := range original {
		if _, found := modified[key]; !found {
			patch[key] = nil
		}
	}
}

// Returns a (recursive) strategic merge patch and a parallel deletion list if necessary.
// Only list of primitives with merge strategy will generate a parallel deletion list.
// These two lists should yield modified when applied to original, for lists with merge semantics.
func diffLists(original, modified []interface{}, t reflect.Type, mergeKey string, diffOptions DiffOptions) ([]interface{}, []interface{}, error) {
	if len(original) == 0 {
		// Both slices are empty - do nothing
		if len(modified) == 0 || diffOptions.IgnoreChangesAndAdditions {
			return nil, nil, nil
		}

		// Old slice was empty - add all elements from the new slice
		return modified, nil, nil
	}

	elementType, err := sliceElementType(original, modified)
	if err != nil {
		return nil, nil, err
	}

	switch elementType.Kind() {
	case reflect.Map:
		patchList, err := diffListsOfMaps(original, modified, t, mergeKey, diffOptions)
		return patchList, nil, err
	case reflect.Slice:
		// Lists of Lists are not permitted by the api
		return nil, nil, mergepatch.ErrNoListOfLists
	default:
		return diffListsOfScalars(original, modified, diffOptions)
	}
}

// diffListsOfScalars returns 2 lists, the first one is addList and the second one is deletionList.
// Argument diffOptions.IgnoreChangesAndAdditions controls if calculate addList. true means not calculate.
// Argument diffOptions.IgnoreDeletions controls if calculate deletionList. true means not calculate.
func diffListsOfScalars(original, modified []interface{}, diffOptions DiffOptions) ([]interface{}, []interface{}, error) {
	// Sort the scalars for easier calculating the diff
	originalScalars := sortScalars(original)
	modifiedScalars := sortScalars(modified)

	originalIndex, modifiedIndex := 0, 0
	addList := []interface{}{}
	deletionList := []interface{}{}

	for {
		originalInBounds := originalIndex < len(originalScalars)
		modifiedInBounds := modifiedIndex < len(modifiedScalars)
		if !originalInBounds && !modifiedInBounds {
			break
		}
		// we need to compare the string representation of the scalar,
		// because the scalar is an interface which doesn't support either < or >
		// And that's how func sortScalars compare scalars.
		var originalString, modifiedString string
		var originalValue, modifiedValue interface{}
		if originalInBounds {
			originalValue = originalScalars[originalIndex]
			originalString = fmt.Sprintf("%v", originalValue)
		}
		if modifiedInBounds {
			modifiedValue = modifiedScalars[modifiedIndex]
			modifiedString = fmt.Sprintf("%v", modifiedValue)
		}

		originalV, modifiedV := compareListValuesAtIndex(originalInBounds, modifiedInBounds, originalString, modifiedString)
		switch {
		case originalV == nil && modifiedV == nil:
			originalIndex++
			modifiedIndex++
		case originalV != nil && modifiedV == nil:
			if !diffOptions.IgnoreDeletions {
				deletionList = append(deletionList, originalValue)
			}
			originalIndex++
		case originalV == nil && modifiedV != nil:
			if !diffOptions.IgnoreChangesAndAdditions {
				addList = append(addList, modifiedValue)
			}
			modifiedIndex++
		default:
			return nil, nil, fmt.Errorf("Unexpected returned value from compareListValuesAtIndex: %v and %v", originalV, modifiedV)
		}
	}

	return addList, deletionList, nil
}

// If first return value is non-nil, list1 contains an element not present in list2
// If second return value is non-nil, list2 contains an element not present in list1
func compareListValuesAtIndex(list1Inbounds, list2Inbounds bool, list1Value, list2Value string) (interface{}, interface{}) {
	bothInBounds := list1Inbounds && list2Inbounds
	switch {
	// scalars are identical
	case bothInBounds && list1Value == list2Value:
		return nil, nil
	// only list2 is in bound
	case !list1Inbounds:
		fallthrough
	// list2 has additional scalar
	case bothInBounds && list1Value > list2Value:
		return nil, list2Value
	// only original is in bound
	case !list2Inbounds:
		fallthrough
	// original has additional scalar
	case bothInBounds && list1Value < list2Value:
		return list1Value, nil
	default:
		return nil, nil
	}
}

// Returns a (recursive) strategic merge patch that yields modified when applied to original,
// for a pair of lists of maps with merge semantics.
func diffListsOfMaps(original, modified []interface{}, t reflect.Type, mergeKey string, diffOptions DiffOptions) ([]interface{}, error) {
	patch := make([]interface{}, 0)

	originalSorted, err := sortMergeListsByNameArray(original, t, mergeKey, false)
	if err != nil {
		return nil, err
	}
	modifiedSorted, err := sortMergeListsByNameArray(modified, t, mergeKey, false)
	if err != nil {
		return nil, err
	}

	originalIndex, modifiedIndex := 0, 0
	for {
		originalInBounds := originalIndex < len(originalSorted)
		modifiedInBounds := modifiedIndex < len(modifiedSorted)
		bothInBounds := originalInBounds && modifiedInBounds
		if !originalInBounds && !modifiedInBounds {
			break
		}

		var originalElementMergeKeyValueString, modifiedElementMergeKeyValueString string
		var originalElementMergeKeyValue, modifiedElementMergeKeyValue interface{}
		var originalElement, modifiedElement map[string]interface{}
		if originalInBounds {
			originalElement, originalElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(originalIndex, mergeKey, originalSorted)
			if err != nil {
				return nil, err
			}
			originalElementMergeKeyValueString = fmt.Sprintf("%v", originalElementMergeKeyValue)
		}
		if modifiedInBounds {
			modifiedElement, modifiedElementMergeKeyValue, err = getMapAndMergeKeyValueByIndex(modifiedIndex, mergeKey, modifiedSorted)
			if err != nil {
				return nil, err
			}
			modifiedElementMergeKeyValueString = fmt.Sprintf("%v", modifiedElementMergeKeyValue)
		}

		switch {
		case bothInBounds && ItemMatchesOriginalAndModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
			// Merge key values are equal, so recurse
			patchValue, err := diffMaps(originalElement, modifiedElement, t, diffOptions)
			if err != nil {
				return nil, err
			}
			if len(patchValue) > 0 {
				patchValue[mergeKey] = modifiedElementMergeKeyValue
				patch = append(patch, patchValue)
			}
			originalIndex++
			modifiedIndex++
		// only modified is in bound
		case !originalInBounds:
			fallthrough
		// modified has additional map
		case bothInBounds && ItemAddedToModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
			if !diffOptions.IgnoreChangesAndAdditions {
				patch = append(patch, modifiedElement)
			}
			modifiedIndex++
		// only original is in bound
		case !modifiedInBounds:
			fallthrough
		// original has additional map
		case bothInBounds && ItemRemovedFromModifiedSlice(originalElementMergeKeyValueString, modifiedElementMergeKeyValueString):
			if !diffOptions.IgnoreDeletions {
				// Item was deleted, so add delete directive
				patch = append(patch, CreateDeleteDirective(mergeKey, originalElementMergeKeyValue))
			}
			originalIndex++
		}
	}

	return patch, nil
}

// getMapAndMergeKeyValueByIndex return a map in the list and its merge key value given the index of the map.
func getMapAndMergeKeyValueByIndex(index int, mergeKey string, listOfMaps []interface{}) (map[string]interface{}, interface{}, error) {
	m, ok := listOfMaps[index].(map[string]interface{})
	if !ok {
		return nil, nil, mergepatch.ErrBadArgType(m, listOfMaps[index])
	}

	val, ok := m[mergeKey]
	if !ok {
		return nil, nil, mergepatch.ErrNoMergeKey(m, mergeKey)
	}
	return m, val, nil
}

// StrategicMergePatch applies a strategic merge patch. The patch and the original document
// must be json encoded content. A patch can be created from an original and a modified document
// by calling CreateStrategicMergePatch.
func StrategicMergePatch(original, patch []byte, dataStruct interface{}) ([]byte, error) {
	originalMap, err := handleUnmarshal(original)
	if err != nil {
		return nil, err
	}
	patchMap, err := handleUnmarshal(patch)
	if err != nil {
		return nil, err
	}

	result, err := StrategicMergeMapPatch(originalMap, patchMap, dataStruct)
	if err != nil {
		return nil, err
	}

	return json.Marshal(result)
}

func handleUnmarshal(j []byte) (map[string]interface{}, error) {
	if j == nil {
		j = []byte("{}")
	}

	m := map[string]interface{}{}
	err := json.Unmarshal(j, &m)
	if err != nil {
		return nil, mergepatch.ErrBadJSONDoc
	}
	return m, nil
}

// StrategicMergePatch applies a strategic merge patch. The original and patch documents
// must be JSONMap. A patch can be created from an original and modified document by
// calling CreateTwoWayMergeMapPatch.
// Warning: the original and patch JSONMap objects are mutated by this function and should not be reused.
func StrategicMergeMapPatch(original, patch JSONMap, dataStruct interface{}) (JSONMap, error) {
	t, err := getTagStructType(dataStruct)
	if err != nil {
		return nil, err
	}
	mergeOptions := MergeOptions{
		MergeDeleteList:      true,
		IgnoreUnmatchedNulls: true,
	}
	return mergeMap(original, patch, t, mergeOptions)
}

func getTagStructType(dataStruct interface{}) (reflect.Type, error) {
	if dataStruct == nil {
		return nil, mergepatch.ErrBadArgKind(struct{}{}, nil)
	}

	t := reflect.TypeOf(dataStruct)
	if t.Kind() == reflect.Ptr {
		t = t.Elem()
	}

	if t.Kind() != reflect.Struct {
		return nil, mergepatch.ErrBadArgKind(struct{}{}, dataStruct)
	}

	return t, nil
}

// handleDirectiveInMergeMap handles the patch directive when merging 2 maps.
func handleDirectiveInMergeMap(directive interface{}, patch map[string]interface{}) (map[string]interface{}, error) {
	if directive == replaceDirective {
		// If the patch contains "$patch: replace", don't merge it, just use the
		// patch directly. Later on, we can add a single level replace that only
		// affects the map that the $patch is in.
		delete(patch, directiveMarker)
		return patch, nil
	}

	if directive == deleteDirective {
		// If the patch contains "$patch: delete", don't merge it, just return
		//  an empty map.
		return map[string]interface{}{}, nil
	}

	return nil, mergepatch.ErrBadPatchType(directive, patch)
}

// preprocessDeletionListForMerging preprocesses the deletion list.
// it returns shouldContinue, isDeletionList, noPrefixKey
func preprocessDeletionListForMerging(key string, original map[string]interface{},
	patchVal interface{}, mergeDeletionList bool) (bool, bool, string, error) {
	// If found a parallel list for deletion and we are going to merge the list,
	// overwrite the key to the original key and set flag isDeleteList
	foundParallelListPrefix := strings.HasPrefix(key, deleteFromPrimitiveListDirectivePrefix)
	if foundParallelListPrefix {
		if !mergeDeletionList {
			original[key] = patchVal
			return true, false, "", nil
		}
		substrings := strings.SplitN(key, "/", 2)
		if len(substrings) <= 1 {
			return false, false, "", mergepatch.ErrBadPatchFormatForPrimitiveList
		}
		return false, true, substrings[1], nil
	}
	return false, false, "", nil
}

// Merge fields from a patch map into the original map. Note: This may modify
// both the original map and the patch because getting a deep copy of a map in
// golang is highly non-trivial.
// flag mergeOptions.MergeDeleteList controls if using the parallel list to delete or keeping the list.
// If patch contains any null field (e.g. field_1: null) that is not
// present in original, then to propagate it to the end result use
// mergeOptions.IgnoreUnmatchedNulls == false.
func mergeMap(original, patch map[string]interface{}, t reflect.Type, mergeOptions MergeOptions) (map[string]interface{}, error) {
	if v, ok := patch[directiveMarker]; ok {
		return handleDirectiveInMergeMap(v, patch)
	}

	// nil is an accepted value for original to simplify logic in other places.
	// If original is nil, replace it with an empty map and then apply the patch.
	if original == nil {
		original = map[string]interface{}{}
	}

	// Start merging the patch into the original.
	for k, patchV := range patch {
		skipProcessing, isDeleteList, noPrefixKey, err := preprocessDeletionListForMerging(k, original, patchV, mergeOptions.MergeDeleteList)
		if err != nil {
			return nil, err
		}
		if skipProcessing {
			continue
		}
		if len(noPrefixKey) > 0 {
			k = noPrefixKey
		}

		// If the value of this key is null, delete the key if it exists in the
		// original. Otherwise, check if we want to preserve it or skip it.
		// Preserving the null value is useful when we want to send an explicit
		// delete to the API server.
		if patchV == nil {
			if _, ok := original[k]; ok {
				delete(original, k)
			}
			if mergeOptions.IgnoreUnmatchedNulls {
				continue
			}
		}

		_, ok := original[k]
		if !ok {
			// If it's not in the original document, just take the patch value.
			original[k] = patchV
			continue
		}

		// If the data type is a pointer, resolve the element.
		if t.Kind() == reflect.Ptr {
			t = t.Elem()
		}

		originalType := reflect.TypeOf(original[k])
		patchType := reflect.TypeOf(patchV)
		if originalType != patchType {
			original[k] = patchV
			continue
		}
		// If they're both maps or lists, recurse into the value.
		// First find the fieldPatchStrategy and fieldPatchMergeKey.
		fieldType, fieldPatchStrategy, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadata(t, k)
		if err != nil {
			return nil, err
		}
		switch originalType.Kind() {
		case reflect.Map:

			original[k], err = mergeMapHandler(original[k], patchV, fieldType, fieldPatchStrategy, mergeOptions)
		case reflect.Slice:
			original[k], err = mergeSliceHandler(original[k], patchV, fieldType, fieldPatchStrategy, fieldPatchMergeKey, isDeleteList, mergeOptions)
		default:
			original[k] = patchV
		}
		if err != nil {
			return nil, err
		}
	}
	return original, nil
}

// mergeMapHandler handles how to merge `patchV` whose key is `key` with `original` respecting
// fieldPatchStrategy and mergeOptions.
func mergeMapHandler(original, patch interface{}, fieldType reflect.Type,
	fieldPatchStrategy string, mergeOptions MergeOptions) (map[string]interface{}, error) {
	typedOriginal, typedPatch, err := mapTypeAssertion(original, patch)
	if err != nil {
		return nil, err
	}

	if fieldPatchStrategy != replaceDirective {
		return mergeMap(typedOriginal, typedPatch, fieldType, mergeOptions)
	} else {
		return typedPatch, nil
	}
}

// mergeSliceHandler handles how to merge `patchV` whose key is `key` with `original` respecting
// fieldPatchStrategy, fieldPatchMergeKey, isDeleteList and mergeOptions.
func mergeSliceHandler(original, patch interface{}, fieldType reflect.Type,
	fieldPatchStrategy, fieldPatchMergeKey string, isDeleteList bool, mergeOptions MergeOptions) ([]interface{}, error) {
	typedOriginal, typedPatch, err := sliceTypeAssertion(original, patch)
	if err != nil {
		return nil, err
	}

	if fieldPatchStrategy == mergeDirective {
		elemType := fieldType.Elem()
		return mergeSlice(typedOriginal, typedPatch, elemType, fieldPatchMergeKey, mergeOptions, isDeleteList)
	} else {
		return typedPatch, nil
	}
}

// Merge two slices together. Note: This may modify both the original slice and
// the patch because getting a deep copy of a slice in golang is highly
// non-trivial.
func mergeSlice(original, patch []interface{}, elemType reflect.Type, mergeKey string, mergeOptions MergeOptions, isDeleteList bool) ([]interface{}, error) {
	if len(original) == 0 && len(patch) == 0 {
		return original, nil
	}

	// All the values must be of the same type, but not a list.
	t, err := sliceElementType(original, patch)
	if err != nil {
		return nil, err
	}

	// If the elements are not maps, merge the slices of scalars.
	if t.Kind() != reflect.Map {
		if mergeOptions.MergeDeleteList && isDeleteList {
			return deleteFromSlice(original, patch), nil
		}
		// Maybe in the future add a "concat" mode that doesn't
		// uniqify.
		both := append(original, patch...)
		return uniqifyScalars(both), nil
	}

	if mergeKey == "" {
		return nil, fmt.Errorf("cannot merge lists without merge key for type %s", elemType.Kind().String())
	}

	original, patch, err = mergeSliceWithSpecialElements(original, patch, mergeKey)
	if err != nil {
		return nil, err
	}

	return mergeSliceWithoutSpecialElements(original, patch, mergeKey, elemType, mergeOptions)
}

// mergeSliceWithSpecialElements handles special elements with directiveMarker
// before merging the slices. It returns a updated `original` and a patch without special elements.
// original and patch must be slices of maps, they should be checked before calling this function.
func mergeSliceWithSpecialElements(original, patch []interface{}, mergeKey string) ([]interface{}, []interface{}, error) {
	patchWithoutSpecialElements := []interface{}{}
	replace := false
	for _, v := range patch {
		typedV := v.(map[string]interface{})
		patchType, ok := typedV[directiveMarker]
		if !ok {
			patchWithoutSpecialElements = append(patchWithoutSpecialElements, v)
		} else {
			switch patchType {
			case deleteDirective:
				mergeValue, ok := typedV[mergeKey]
				if ok {
					var err error
					original, err = deleteMatchingEntries(original, mergeKey, mergeValue)
					if err != nil {
						return nil, nil, err
					}
				} else {
					return nil, nil, fmt.Errorf("delete patch type with no merge key defined")
				}
			case replaceDirective:
				replace = true
				// Continue iterating through the array to prune any other $patch elements.
			case mergeDirective:
				return nil, nil, fmt.Errorf("merging lists cannot yet be specified in the patch")
			default:
				return nil, nil, mergepatch.ErrBadPatchType(patchType, typedV)
			}
		}
	}
	if replace {
		return patchWithoutSpecialElements, nil, nil
	}
	return original, patchWithoutSpecialElements, nil
}

// delete all matching entries (based on merge key) from a merging list
func deleteMatchingEntries(original []interface{}, mergeKey string, mergeValue interface{}) ([]interface{}, error) {
	for {
		_, originalKey, found, err := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)
		if err != nil {
			return nil, err
		}

		if !found {
			break
		}
		// Delete the element at originalKey.
		original = append(original[:originalKey], original[originalKey+1:]...)
	}
	return original, nil
}

// mergeSliceWithoutSpecialElements merges slices with non-special elements.
// original and patch must be slices of maps, they should be checked before calling this function.
func mergeSliceWithoutSpecialElements(original, patch []interface{}, mergeKey string, elemType reflect.Type, mergeOptions MergeOptions) ([]interface{}, error) {
	for _, v := range patch {
		typedV := v.(map[string]interface{})
		mergeValue, ok := typedV[mergeKey]
		if !ok {
			return nil, mergepatch.ErrNoMergeKey(typedV, mergeKey)
		}

		// If we find a value with this merge key value in original, merge the
		// maps. Otherwise append onto original.
		originalMap, originalKey, found, err := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)
		if err != nil {
			return nil, err
		}

		if found {
			var mergedMaps interface{}
			var err error
			// Merge into original.
			mergedMaps, err = mergeMap(originalMap, typedV, elemType, mergeOptions)
			if err != nil {
				return nil, err
			}

			original[originalKey] = mergedMaps
		} else {
			original = append(original, v)
		}
	}
	return original, nil
}

// deleteFromSlice uses the parallel list to delete the items in a list of scalars
func deleteFromSlice(current, toDelete []interface{}) []interface{} {
	currentScalars := uniqifyAndSortScalars(current)
	toDeleteScalars := uniqifyAndSortScalars(toDelete)

	currentIndex, toDeleteIndex := 0, 0
	mergedList := []interface{}{}

	for currentIndex < len(currentScalars) && toDeleteIndex < len(toDeleteScalars) {
		originalString := fmt.Sprintf("%v", currentScalars[currentIndex])
		modifiedString := fmt.Sprintf("%v", toDeleteScalars[toDeleteIndex])

		switch {
		// found an item to delete
		case originalString == modifiedString:
			currentIndex++
		// Request to delete an item that was not found in the current list
		case originalString > modifiedString:
			toDeleteIndex++
		// Found an item that was not part of the deletion list, keep it
		case originalString < modifiedString:
			mergedList = append(mergedList, currentScalars[currentIndex])
			currentIndex++
		}
	}
	return append(mergedList, currentScalars[currentIndex:]...)
}

// This method no longer panics if any element of the slice is not a map.
func findMapInSliceBasedOnKeyValue(m []interface{}, key string, value interface{}) (map[string]interface{}, int, bool, error) {
	for k, v := range m {
		typedV, ok := v.(map[string]interface{})
		if !ok {
			return nil, 0, false, fmt.Errorf("value for key %v is not a map.", k)
		}

		valueToMatch, ok := typedV[key]
		if ok && valueToMatch == value {
			return typedV, k, true, nil
		}
	}

	return nil, 0, false, nil
}

// This function takes a JSON map and sorts all the lists that should be merged
// by key. This is needed by tests because in JSON, list order is significant,
// but in Strategic Merge Patch, merge lists do not have significant order.
// Sorting the lists allows for order-insensitive comparison of patched maps.
func sortMergeListsByName(mapJSON []byte, dataStruct interface{}) ([]byte, error) {
	var m map[string]interface{}
	err := json.Unmarshal(mapJSON, &m)
	if err != nil {
		return nil, err
	}

	newM, err := sortMergeListsByNameMap(m, reflect.TypeOf(dataStruct))
	if err != nil {
		return nil, err
	}

	return json.Marshal(newM)
}

// Function sortMergeListsByNameMap recursively sorts the merge lists by its mergeKey in a map.
func sortMergeListsByNameMap(s map[string]interface{}, t reflect.Type) (map[string]interface{}, error) {
	newS := map[string]interface{}{}
	for k, v := range s {
		if strings.HasPrefix(k, deleteFromPrimitiveListDirectivePrefix) {
			typedV, ok := v.([]interface{})
			if !ok {
				return nil, mergepatch.ErrBadPatchFormatForPrimitiveList
			}
			v = uniqifyAndSortScalars(typedV)
		} else if k != directiveMarker {
			fieldType, fieldPatchStrategy, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadata(t, k)
			if err != nil {
				return nil, err
			}

			// If v is a map or a merge slice, recurse.
			if typedV, ok := v.(map[string]interface{}); ok {
				var err error
				v, err = sortMergeListsByNameMap(typedV, fieldType)
				if err != nil {
					return nil, err
				}
			} else if typedV, ok := v.([]interface{}); ok {
				if fieldPatchStrategy == mergeDirective {
					var err error
					v, err = sortMergeListsByNameArray(typedV, fieldType.Elem(), fieldPatchMergeKey, true)
					if err != nil {
						return nil, err
					}
				}
			}
		}

		newS[k] = v
	}

	return newS, nil
}

// Function sortMergeListsByNameMap recursively sorts the merge lists by its mergeKey in an array.
func sortMergeListsByNameArray(s []interface{}, elemType reflect.Type, mergeKey string, recurse bool) ([]interface{}, error) {
	if len(s) == 0 {
		return s, nil
	}

	// We don't support lists of lists yet.
	t, err := sliceElementType(s)
	if err != nil {
		return nil, err
	}

	// If the elements are not maps...
	if t.Kind() != reflect.Map {
		// Sort the elements, because they may have been merged out of order.
		return uniqifyAndSortScalars(s), nil
	}

	// Elements are maps - if one of the keys of the map is a map or a
	// list, we may need to recurse into it.
	newS := []interface{}{}
	for _, elem := range s {
		if recurse {
			typedElem := elem.(map[string]interface{})
			newElem, err := sortMergeListsByNameMap(typedElem, elemType)
			if err != nil {
				return nil, err
			}

			newS = append(newS, newElem)
		} else {
			newS = append(newS, elem)
		}
	}

	// Sort the maps.
	newS = sortMapsBasedOnField(newS, mergeKey)
	return newS, nil
}

func sortMapsBasedOnField(m []interface{}, fieldName string) []interface{} {
	mapM := mapSliceFromSlice(m)
	ss := SortableSliceOfMaps{mapM, fieldName}
	sort.Sort(ss)
	newS := sliceFromMapSlice(ss.s)
	return newS
}

func mapSliceFromSlice(m []interface{}) []map[string]interface{} {
	newM := []map[string]interface{}{}
	for _, v := range m {
		vt := v.(map[string]interface{})
		newM = append(newM, vt)
	}

	return newM
}

func sliceFromMapSlice(s []map[string]interface{}) []interface{} {
	newS := []interface{}{}
	for _, v := range s {
		newS = append(newS, v)
	}

	return newS
}

type SortableSliceOfMaps struct {
	s []map[string]interface{}
	k string // key to sort on
}

func (ss SortableSliceOfMaps) Len() int {
	return len(ss.s)
}

func (ss SortableSliceOfMaps) Less(i, j int) bool {
	iStr := fmt.Sprintf("%v", ss.s[i][ss.k])
	jStr := fmt.Sprintf("%v", ss.s[j][ss.k])
	return sort.StringsAreSorted([]string{iStr, jStr})
}

func (ss SortableSliceOfMaps) Swap(i, j int) {
	tmp := ss.s[i]
	ss.s[i] = ss.s[j]
	ss.s[j] = tmp
}

func uniqifyAndSortScalars(s []interface{}) []interface{} {
	s = uniqifyScalars(s)
	return sortScalars(s)
}

func sortScalars(s []interface{}) []interface{} {
	ss := SortableSliceOfScalars{s}
	sort.Sort(ss)
	return ss.s
}

func uniqifyScalars(s []interface{}) []interface{} {
	// Clever algorithm to uniqify.
	length := len(s) - 1
	for i := 0; i < length; i++ {
		for j := i + 1; j <= length; j++ {
			if s[i] == s[j] {
				s[j] = s[length]
				s = s[0:length]
				length--
				j--
			}
		}
	}

	return s
}

type SortableSliceOfScalars struct {
	s []interface{}
}

func (ss SortableSliceOfScalars) Len() int {
	return len(ss.s)
}

func (ss SortableSliceOfScalars) Less(i, j int) bool {
	iStr := fmt.Sprintf("%v", ss.s[i])
	jStr := fmt.Sprintf("%v", ss.s[j])
	return sort.StringsAreSorted([]string{iStr, jStr})
}

func (ss SortableSliceOfScalars) Swap(i, j int) {
	tmp := ss.s[i]
	ss.s[i] = ss.s[j]
	ss.s[j] = tmp
}

// Returns the type of the elements of N slice(s). If the type is different,
// another slice or undefined, returns an error.
func sliceElementType(slices ...[]interface{}) (reflect.Type, error) {
	var prevType reflect.Type
	for _, s := range slices {
		// Go through elements of all given slices and make sure they are all the same type.
		for _, v := range s {
			currentType := reflect.TypeOf(v)
			if prevType == nil {
				prevType = currentType
				// We don't support lists of lists yet.
				if prevType.Kind() == reflect.Slice {
					return nil, mergepatch.ErrNoListOfLists
				}
			} else {
				if prevType != currentType {
					return nil, fmt.Errorf("list element types are not identical: %v", fmt.Sprint(slices))
				}
				prevType = currentType
			}
		}
	}

	if prevType == nil {
		return nil, fmt.Errorf("no elements in any of the given slices")
	}

	return prevType, nil
}

// MergingMapsHaveConflicts returns true if the left and right JSON interface
// objects overlap with different values in any key. All keys are required to be
// strings. Since patches of the same Type have congruent keys, this is valid
// for multiple patch types. This method supports strategic merge patch semantics.
func MergingMapsHaveConflicts(left, right map[string]interface{}, dataStruct interface{}) (bool, error) {
	t, err := getTagStructType(dataStruct)
	if err != nil {
		return true, err
	}

	return mergingMapFieldsHaveConflicts(left, right, t, "", "")
}

func mergingMapFieldsHaveConflicts(
	left, right interface{},
	fieldType reflect.Type,
	fieldPatchStrategy, fieldPatchMergeKey string,
) (bool, error) {
	switch leftType := left.(type) {
	case map[string]interface{}:
		rightType, ok := right.(map[string]interface{})
		if !ok {
			return true, nil
		}
		leftMarker, okLeft := leftType[directiveMarker]
		rightMarker, okRight := rightType[directiveMarker]
		// if one or the other has a directive marker,
		// then we need to consider that before looking at the individual keys,
		// since a directive operates on the whole map.
		if okLeft || okRight {
			// if one has a directive marker and the other doesn't,
			// then we have a conflict, since one is deleting or replacing the whole map,
			// and the other is doing things to individual keys.
			if okLeft != okRight {
				return true, nil
			}
			// if they both have markers, but they are not the same directive,
			// then we have a conflict because they're doing different things to the map.
			if leftMarker != rightMarker {
				return true, nil
			}
		}
		if fieldPatchStrategy == replaceDirective {
			return false, nil
		}
		// Check the individual keys.
		return mapsHaveConflicts(leftType, rightType, fieldType)

	case []interface{}:
		rightType, ok := right.([]interface{})
		if !ok {
			return true, nil
		}
		return slicesHaveConflicts(leftType, rightType, fieldType, fieldPatchStrategy, fieldPatchMergeKey)

	case string, float64, bool, int, int64, nil:
		return !reflect.DeepEqual(left, right), nil
	default:
		return true, fmt.Errorf("unknown type: %v", reflect.TypeOf(left))
	}
}

func mapsHaveConflicts(typedLeft, typedRight map[string]interface{}, structType reflect.Type) (bool, error) {
	for key, leftValue := range typedLeft {
		if key != directiveMarker {
			if rightValue, ok := typedRight[key]; ok {
				fieldType, fieldPatchStrategy, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadata(structType, key)
				if err != nil {
					return true, err
				}

				if hasConflicts, err := mergingMapFieldsHaveConflicts(leftValue, rightValue,
					fieldType, fieldPatchStrategy, fieldPatchMergeKey); hasConflicts {
					return true, err
				}
			}
		}
	}

	return false, nil
}

func slicesHaveConflicts(
	typedLeft, typedRight []interface{},
	fieldType reflect.Type,
	fieldPatchStrategy, fieldPatchMergeKey string,
) (bool, error) {
	elementType, err := sliceElementType(typedLeft, typedRight)
	if err != nil {
		return true, err
	}

	valueType := fieldType.Elem()
	if fieldPatchStrategy == mergeDirective {
		// Merging lists of scalars have no conflicts by definition
		// So we only need to check further if the elements are maps
		if elementType.Kind() != reflect.Map {
			return false, nil
		}

		// Build a map for each slice and then compare the two maps
		leftMap, err := sliceOfMapsToMapOfMaps(typedLeft, fieldPatchMergeKey)
		if err != nil {
			return true, err
		}

		rightMap, err := sliceOfMapsToMapOfMaps(typedRight, fieldPatchMergeKey)
		if err != nil {
			return true, err
		}

		return mapsOfMapsHaveConflicts(leftMap, rightMap, valueType)
	}

	// Either we don't have type information, or these are non-merging lists
	if len(typedLeft) != len(typedRight) {
		return true, nil
	}

	// Sort scalar slices to prevent ordering issues
	// We have no way to sort non-merging lists of maps
	if elementType.Kind() != reflect.Map {
		typedLeft = uniqifyAndSortScalars(typedLeft)
		typedRight = uniqifyAndSortScalars(typedRight)
	}

	// Compare the slices element by element in order
	// This test will fail if the slices are not sorted
	for i := range typedLeft {
		if hasConflicts, err := mergingMapFieldsHaveConflicts(typedLeft[i], typedRight[i], valueType, "", ""); hasConflicts {
			return true, err
		}
	}

	return false, nil
}

func sliceOfMapsToMapOfMaps(slice []interface{}, mergeKey string) (map[string]interface{}, error) {
	result := make(map[string]interface{}, len(slice))
	for _, value := range slice {
		typedValue, ok := value.(map[string]interface{})
		if !ok {
			return nil, fmt.Errorf("invalid element type in merging list:%v", slice)
		}

		mergeValue, ok := typedValue[mergeKey]
		if !ok {
			return nil, fmt.Errorf("cannot find merge key `%s` in merging list element:%v", mergeKey, typedValue)
		}

		result[fmt.Sprintf("%s", mergeValue)] = typedValue
	}

	return result, nil
}

func mapsOfMapsHaveConflicts(typedLeft, typedRight map[string]interface{}, structType reflect.Type) (bool, error) {
	for key, leftValue := range typedLeft {
		if rightValue, ok := typedRight[key]; ok {
			if hasConflicts, err := mergingMapFieldsHaveConflicts(leftValue, rightValue, structType, "", ""); hasConflicts {
				return true, err
			}
		}
	}

	return false, nil
}

// CreateThreeWayMergePatch reconciles a modified configuration with an original configuration,
// while preserving any changes or deletions made to the original configuration in the interim,
// and not overridden by the current configuration. All three documents must be passed to the
// method as json encoded content. It will return a strategic merge patch, or an error if any
// of the documents is invalid, or if there are any preconditions that fail against the modified
// configuration, or, if overwrite is false and there are conflicts between the modified and current
// configurations. Conflicts are defined as keys changed differently from original to modified
// than from original to current. In other words, a conflict occurs if modified changes any key
// in a way that is different from how it is changed in current (e.g., deleting it, changing its
// value). We also propagate values fields that do not exist in original but are explicitly
// defined in modified.
func CreateThreeWayMergePatch(original, modified, current []byte, dataStruct interface{}, overwrite bool, fns ...mergepatch.PreconditionFunc) ([]byte, error) {
	originalMap := map[string]interface{}{}
	if len(original) > 0 {
		if err := json.Unmarshal(original, &originalMap); err != nil {
			return nil, mergepatch.ErrBadJSONDoc
		}
	}

	modifiedMap := map[string]interface{}{}
	if len(modified) > 0 {
		if err := json.Unmarshal(modified, &modifiedMap); err != nil {
			return nil, mergepatch.ErrBadJSONDoc
		}
	}

	currentMap := map[string]interface{}{}
	if len(current) > 0 {
		if err := json.Unmarshal(current, &currentMap); err != nil {
			return nil, mergepatch.ErrBadJSONDoc
		}
	}

	t, err := getTagStructType(dataStruct)
	if err != nil {
		return nil, err
	}

	// The patch is the difference from current to modified without deletions, plus deletions
	// from original to modified. To find it, we compute deletions, which are the deletions from
	// original to modified, and delta, which is the difference from current to modified without
	// deletions, and then apply delta to deletions as a patch, which should be strictly additive.
	deltaMapDiffOptions := DiffOptions{
		IgnoreChangesAndAdditions: false,
		IgnoreDeletions:           true,
	}
	deltaMap, err := diffMaps(currentMap, modifiedMap, t, deltaMapDiffOptions)
	if err != nil {
		return nil, err
	}
	deletionsMapDiffOptions := DiffOptions{
		IgnoreChangesAndAdditions: true,
		IgnoreDeletions:           false,
	}
	deletionsMap, err := diffMaps(originalMap, modifiedMap, t, deletionsMapDiffOptions)
	if err != nil {
		return nil, err
	}

	mergeOptions := MergeOptions{
		MergeDeleteList:      false,
		IgnoreUnmatchedNulls: false,
	}
	patchMap, err := mergeMap(deletionsMap, deltaMap, t, mergeOptions)
	if err != nil {
		return nil, err
	}

	// Apply the preconditions to the patch, and return an error if any of them fail.
	for _, fn := range fns {
		if !fn(patchMap) {
			return nil, mergepatch.NewErrPreconditionFailed(patchMap)
		}
	}

	// If overwrite is false, and the patch contains any keys that were changed differently,
	// then return a conflict error.
	if !overwrite {
		changeMapDiffOptions := DiffOptions{
			IgnoreChangesAndAdditions: false,
			IgnoreDeletions:           false,
		}
		changedMap, err := diffMaps(originalMap, currentMap, t, changeMapDiffOptions)
		if err != nil {
			return nil, err
		}

		hasConflicts, err := MergingMapsHaveConflicts(patchMap, changedMap, dataStruct)
		if err != nil {
			return nil, err
		}

		if hasConflicts {
			return nil, mergepatch.NewErrConflict(mergepatch.ToYAMLOrError(patchMap), mergepatch.ToYAMLOrError(changedMap))
		}
	}

	return json.Marshal(patchMap)
}

func ItemAddedToModifiedSlice(original, modified string) bool { return original > modified }

func ItemRemovedFromModifiedSlice(original, modified string) bool { return original < modified }

func ItemMatchesOriginalAndModifiedSlice(original, modified string) bool { return original == modified }

func CreateDeleteDirective(mergeKey string, mergeKeyValue interface{}) map[string]interface{} {
	return map[string]interface{}{mergeKey: mergeKeyValue, directiveMarker: deleteDirective}
}

func mapTypeAssertion(original, patch interface{}) (map[string]interface{}, map[string]interface{}, error) {
	typedOriginal, ok := original.(map[string]interface{})
	if !ok {
		return nil, nil, mergepatch.ErrBadArgType(typedOriginal, original)
	}
	typedPatch, ok := patch.(map[string]interface{})
	if !ok {
		return nil, nil, mergepatch.ErrBadArgType(typedPatch, patch)
	}
	return typedOriginal, typedPatch, nil
}

func sliceTypeAssertion(original, patch interface{}) ([]interface{}, []interface{}, error) {
	typedOriginal, ok := original.([]interface{})
	if !ok {
		return nil, nil, mergepatch.ErrBadArgType(typedOriginal, original)
	}
	typedPatch, ok := patch.([]interface{})
	if !ok {
		return nil, nil, mergepatch.ErrBadArgType(typedPatch, patch)
	}
	return typedOriginal, typedPatch, nil
}


text:
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <logger name="deng" level="DEBUG"/>

    <root level="DEBUG">
        <appender-ref ref="STDOUT" />
    </root>
</configuration>


text:
package no.deichman.services.entity.kohaadapter;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

public class MarcRecordTest {

    private MarcRecord marcRecord;

    @Before
    public void setup() {
        marcRecord = new MarcRecord();
    }

    @Test
    public void constructor_exists() {
        assertNotNull(new MarcRecord());
    }

    @Test
    public void creates_an_empty_record() {
        assertNotNull(marcRecord.getRecord());
    }

    @Test
    public void serialize_a_record_as_marcxml() {
        assertNotNull(marcRecord.getMarcXml());
    }

    @Test
    public void should_include_title() {
        MarcField marcField = MarcRecord.newDataField(MarcConstants.FIELD_245);
        marcField.addSubfield('a', "bugga");
        marcRecord.addMarcField(marcField);
        assertThat(marcRecord.getMarcXml(), containsString("<marcxml:subfield code=\"" + MarcConstants.SUBFIELD_A + "\">bugga</marcxml:subfield>"));
    }

    @Test
    public void marc_records_should_be_equal() {
        MarcRecord record1 = new MarcRecord();
        MarcField field1 = MarcRecord.newDataField("111");
        field1.addSubfield('a', "b");
        field1.addSubfield('c', "d");
        record1.addMarcField(field1);

        MarcRecord record2 = new MarcRecord();
        MarcField field2 = MarcRecord.newDataField("111");
        field2.addSubfield('c', "d");
        field2.addSubfield('a', "b");
        record2.addMarcField(field2);

        assertEquals(record1, record2);
    }

    @Test
    public void marc_records_should_not_be_equal() {
        MarcRecord record1 = new MarcRecord();
        MarcField field1 = MarcRecord.newDataField("111");
        field1.addSubfield('a', "b");
        field1.addSubfield('c', "NOT EQUAL");
        record1.addMarcField(field1);

        MarcRecord record2 = new MarcRecord();
        MarcField field2 = MarcRecord.newDataField("111");
        field2.addSubfield('c', "d");
        field2.addSubfield('a', "b");
        record2.addMarcField(field2);

        assertNotEquals(record1, record2);
    }

    @Test
    public void marc_records_should_be_equal2() {
        MarcRecord record1 = new MarcRecord();
        MarcField field1 = MarcRecord.newDataField("111");
        field1.addSubfield('a', "b");
        record1.addMarcField(field1);
        MarcField field2 = MarcRecord.newDataField("111");
        field2.addSubfield('c', "d");
        record1.addMarcField(field2);
        MarcField field3 = MarcRecord.newDataField("222");
        field3.addSubfield('e', "f");
        record1.addMarcField(field3);

        MarcRecord record2 = new MarcRecord();
        record2.addMarcField("222", 'e', "f");
        record2.addMarcField("111", 'c', "d");
        record2.addMarcField("111", 'a', "b");

        assertEquals(record1, record2);
    }

    @Test
    public void marc_records_should_not_be_equal2() {
        MarcRecord record1 = new MarcRecord();
        MarcField field1 = MarcRecord.newDataField("111");
        field1.addSubfield('a', "b");
        field1.addSubfield('x', "NOT_EQUAL");
        record1.addMarcField(field1);
        MarcField field2 = MarcRecord.newDataField("111");
        field2.addSubfield('c', "d");
        record1.addMarcField(field2);
        MarcField field3 = MarcRecord.newDataField("222");
        field3.addSubfield('e', "f");
        record1.addMarcField(field3);

        MarcRecord record2 = new MarcRecord();
        record2.addMarcField("222", 'e', "f");
        record2.addMarcField("111", 'c', "d");
        record2.addMarcField("111", 'a', "b");

        assertNotEquals(record1, record2);
    }
}


text:
GIT_DIR=/tmp/visualisation_repo
DATA_DIR=/var/www/html/ssi/drupal/sites/default/files/dashboard

#Delete the repository directory and recreate
rm -rf $GIT_DIR
mkdir -p $GIT_DIR

cd $GIT_DIR
git clone https://github.com/softwaresaved/visualisation.git
cd visualisation

#Run the shell scripts in git repository

# run consultancy shell script
source get_consultancy_data.sh 1Jmq6ongECyJih7HbroltnAGZOecWOsl1qFdemw8Hj8A $DATA_DIR

# run swc shell script
source get_swc_data.sh 1xna48IRFl-lLJrPhlI7vC-1TWnl1kICxzEfrvpIKLp8 $DATA_DIR


text:
var restify = require('restify');
var _ = require('underscore');
var EventEmitter = require('events').EventEmitter;

var localLauncher = require('../local');
var pkg = require('../../package.json');
var platforms = {
	win32 : 'win',
	darwin : 'macos',
	linux : 'unix',
	freebsd : 'unix',
	sunos : 'unix'
};

module.exports = function (config) {
	var emitter = new EventEmitter();
	var configuration = _.extend({
		port : 7998
	}, config);

	if (!configuration.username || !configuration.password) {
		throw new Error('Launchpad server configuration: username and password have to be provided and can not be empty');
	}

	var server = restify.createServer({
		name : 'launchpad-server',
		// Behold the power of a simple package.json
		version : pkg.version
	});

	var workers = {};
	var workerInfo = {};

	var api = {
		index : function (req, res) {
			// Our index is just an empty object
			res.send({});
		},
		listBrowsers : function (req, res, next) {
			// Sends the list of locally available browsers
			localLauncher(function (error, local) {
				if (error) return next(error);
				res.send(local.browsers);
			});
		},
		listWorkers : function (req, res) {
			// Sends a list with information of all workers
			res.send(_.values(workerInfo));
		},
		getWorker : function (req, res, next) {
			if (!workerInfo[req.params.id]) {
				res.status(404);
				return next(new Error('Process does not exist.'));
			}
			// Just send the worker info
			res.send(workerInfo[req.params.id]);
		},
		stopWorker : function (req, res, next) {
			var id = req.params.id;
			if (!workers[id]) {
				res.status(404);
				return next(new Error('Process does not exist or is already stopped.'));
			}

			workers[id].stop(function () {
				// The BrowserStack API returns the runtime of a stopped worker.
				// Not sure if in seconds or ms. We do it in ms
				var time = workerInfo[id].stopped - workerInfo[id].started;
				res.send({ time : time });
			});
		},
		createWorker : function (req, res, next) {
			var config = req.body;
			var getTime = function () {
				return new Date().getTime();
			};
			localLauncher(function (error, local) {
				config.url = config.url.replace(/localhost/, req.connection.remoteAddress);
				// Launch the local browser with the given URL and configuration
				local(config.url, _.omit(config, 'url'), function (error, worker, browser) {
					if (error) return next(error);

					// worker.id is the local browser PID
					var id = worker.id;
					workers[id] = worker;
					// Additionally to what the Browserstack API should provide we store `started` and `stopped` times
					workerInfo[id] = _.extend({
						id : id,
						status : 'running',
						started : getTime(),
						os : platforms[process.platform] || 'unknown'
					}, browser);

					emitter.emit('started', workerInfo[id], worker);
					// Whenever the process stops for whatever reason, update the worker information
					worker.on('stop', function () {
						workerInfo[id].status = 'stopped';
						workerInfo[id].stopped = getTime();
						emitter.emit('stopped', workerInfo[id]);
						delete workers[id];
					});

					res.send({ id : id });
				});
			});
		}
	};

	server.use(function (req, res, next) {
			// We have to drop this in here because some clients don't send their request content type for POSTS
			if (req.method === 'POST' && req.contentType === 'application/octet-stream') {
				req.contentType = 'application/x-www-form-urlencoded';
			}
			next();
		})
		// Some standard node-restify configuration
		.use(restify.acceptParser(server.acceptable))
		.use(restify.queryParser())
		.use(restify.bodyParser({ mapParams : false }))
		.use(restify.authorizationParser())
		// For our basic authorization we just compare with the configuration username and password
		.use(function (req, res, next) {
			// Simple BASIC authorization
			if (req.authorization && req.authorization.basic &&
				req.authorization.basic.username === configuration.username &&
				req.authorization.basic.password === configuration.password) {
					emitter.emit('authorized', req, res);
					return next();
			}
			res.status(401); // Not authorized
			next(new Error('You are not authorized'));
		});

	server.get('/', api.index);
	server.get('/1/browsers', api.listBrowsers);
	server.get('/1/worker', api.listWorkers);
	server.get('/1/worker/:id', api.getWorker);
	server.del('/1/worker/:id', api.stopWorker);
	server.post('/1/worker', api.createWorker);

	server.listen(configuration.port, function() {
		emitter.emit('listening', configuration, server);
	});

	server.on('uncaughtException', function (request, response, route, error) { // jshint ignore:line
		console.log(arguments);
	});

	return emitter;
};


text:
from whyattend import model
from whyattend import config

model.init_db()

from alembic.config import Config
from alembic import command
alembic_cfg = Config("alembic.ini")
alembic_cfg.set_main_option("sqlalchemy.url", config.DATABASE_URI)
command.stamp(alembic_cfg, "head")


text:
/* This file was generated by SableCC (http://www.sablecc.org/). */

package wolf.node;

import wolf.analysis.*;

@SuppressWarnings("nls")
public final class AStringArg extends PArg
{
    private PString _string_;

    public AStringArg()
    {
        // Constructor
    }

    public AStringArg(
        @SuppressWarnings("hiding") PString _string_)
    {
        // Constructor
        setString(_string_);

    }

    @Override
    public Object clone()
    {
        return new AStringArg(
            cloneNode(this._string_));
    }

    @Override
    public void apply(Switch sw)
    {
        ((Analysis) sw).caseAStringArg(this);
    }

    public PString getString()
    {
        return this._string_;
    }

    public void setString(PString node)
    {
        if(this._string_ != null)
        {
            this._string_.parent(null);
        }

        if(node != null)
        {
            if(node.parent() != null)
            {
                node.parent().removeChild(node);
            }

            node.parent(this);
        }

        this._string_ = node;
    }

    @Override
    public String toString()
    {
        return ""
            + toString(this._string_);
    }

    @Override
    void removeChild(@SuppressWarnings("unused") Node child)
    {
        // Remove child
        if(this._string_ == child)
        {
            this._string_ = null;
            return;
        }

        throw new RuntimeException("Not a child.");
    }

    @Override
    void replaceChild(@SuppressWarnings("unused") Node oldChild, @SuppressWarnings("unused") Node newChild)
    {
        // Replace child
        if(this._string_ == oldChild)
        {
            setString((PString) newChild);
            return;
        }

        throw new RuntimeException("Not a child.");
    }
}


text:
@implementation PBContentModel

@end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>ColomCode</title>

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

    <link href="css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>

    <link href="css/magnific-popup.css" rel="stylesheet">

    <link href="css/creative.min.css" rel="stylesheet">

        ColomCode
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

              Inicio

              Services

              Portfolio

              Temas

La mejor comunidad para programadores novatos

Si quieres aprender temas de programacion basicos y conocer mas sobre el mundo del software estas en la pagina indicada.

          Descubre Mas

We've got what you need!

Start Bootstrap has everything you need to get your new website up and running in no time! All of the templates and themes on Start Bootstrap are open source, free to download, and easy to use. No strings attached!

            Get Started!

Solo dale click

Herramientas

Encuentra las mejores herramientas para cualquier entorno.

Practica

practica con estos metodos no tan aburridos XD.

Noticias

Ponte al dia con las mejores noticias referente a software y mas.

Comparte

Comparte y diviertete junto a la comunidad de ColomCode.

                    Category

                    Project Name

                    Category

                    Project Name

                    Category

                    Project Name

                    Category

                    Project Name

                    Category

                    Project Name

                    Category

                    Project Name

        Mas proyectos

Creado y mantenido por Jesus Barros con la ayuda de colaboradores .
            Centrándonos en ayudar a aprender programacion.


text:
declare module '~debug~ms' {
function ms (value: string): number;
function ms (value: number, options?: ms.Options): string;

module ms {
  export interface Options {
    long: boolean;
  }
}

export = ms;
}

// Generated by typings
// Source: https://raw.githubusercontent.com/types/npm-debug/34196b8b6968197009e6725ea68b94162d5737f4/node.d.ts
declare module 'debug' {
import ms = require('~debug~ms');

function debug (namespace: string): debug.Debugger;

namespace debug {
  export interface Debugger {
    (message: any, ...args: any[]): void;
    enabled: boolean;
    namespace: string;
  }

  export function coerce (value: any): any;
  export function disable (): void;
  export function enable (namespaces: string): void;
  export function enabled (namespace: string): boolean;
  export var humanize: typeof ms;

  // Node implementation exports.
  export var log: Function;
  export function formatArgs (...args: any[]): any;
  export function save (namespaces?: string): void;
  export function load (): string | void;
  export function useColors (): boolean;
  export var colors: number[];
}

export = debug;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
    android:background="@color/main_fragment_share_bg"
    android:padding="@dimen/main_activity_bottom_margin_width">
    <TextView
        android:id="@+id/titleTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="@dimen/main_activity_top_margin_color_size"
        android:textColor="@color/name_fragment_share_txt_bg"/>

</LinearLayout>


text:
package client

type (
	ConfigMapInterface interface {
		CreateConfigMap(namespace string, item *ConfigMap) (*ConfigMap, error)
		GetConfigMap(namespace, name string) (result *ConfigMap, err error)
		ListConfigMaps(namespace string, opts *ListOptions) (*ConfigMapList, error)
		DeleteConfigMap(namespace, name string) error
		UpdateConfigMap(namespace string, item *ConfigMap) (*ConfigMap, error)
	}

	ConfigMapType string

	ConfigMap struct {
		TypeMeta   `json:",inline"`
		ObjectMeta `json:"metadata,omitempty"`
		Data       map[string][]byte `json:"data,omitempty"`
	}

	ConfigMapList struct {
		TypeMeta `json:",inline"`
		ListMeta `json:"metadata,omitempty"`

		Items []ConfigMap `json:"items"`
	}
)


text:
static GSLocalize* SingleLocalSystem = nil;

@interface GSLocalize ()
@property (nonatomic, strong) NSMutableDictionary<NSString*, NSBundle*> *bundleDictionary;
@property (nonatomic, strong) NSMutableDictionary<NSString*, NSBundle*> *languageBundleDictionary;

@property (nonatomic, strong) NSString *currentLanguage;

@end

@implementation GSLocalize

#pragma mark - Init;

+ (GSLocalize*) getInstance {
    // lazy instantiation
    if (SingleLocalSystem == nil) {
        SingleLocalSystem = [[GSLocalize alloc] init];
    }
    return SingleLocalSystem;
}

#pragma mark - Get Methods;

- (NSMutableDictionary *)bundleDictionary {
    if (!_bundleDictionary) {
        _bundleDictionary = [NSMutableDictionary dictionary];
    }
    return _bundleDictionary;
}

- (NSMutableDictionary *)languageBundleDictionary {
    if (!_languageBundleDictionary) {
        _languageBundleDictionary = [NSMutableDictionary dictionary];
    }
    return _languageBundleDictionary;
}

- (NSString *)currentLanguage {
    NSString *language = [[NSUserDefaults standardUserDefaults] objectForKey:@"lang"];
    if (!language) {
        NSDictionary *myLangDictionary = @{@"mn":@"OK",@"en":@"OK"};
        NSArray <NSString *> *languageArray = [NSLocale preferredLanguages];
        for (NSString *languageString in languageArray) {
            NSString *languageKey = languageString;
            if ([languageString length] > 2) {
                languageKey = [[languageString substringToIndex:2] lowercaseString];
            }
            NSString *value = [myLangDictionary objectForKey:languageKey];
            if (value) {
                language = languageKey;
                break;
            }
        }
        if (!language) {
            language = @"en";
        }
        [[NSUserDefaults standardUserDefaults] setObject:language forKey:@"lang"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    return language;
}

#pragma mark - Set Methods;

- (void)setCurrentLanguage:(NSString *)currentLanguage {
    [[NSUserDefaults standardUserDefaults] setObject:currentLanguage forKey:@"lang"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void) setLanguage:(NSString*) lang {
    self.currentLanguage = lang;
    NSArray <NSString *> *bundleNameArray = [self.bundleDictionary allKeys];
    [self.languageBundleDictionary removeAllObjects];
    for (NSString *bundleName in  bundleNameArray) {
        [self addBundle:self.bundleDictionary[bundleName] bundleName:bundleName];
    }
    [self setCurrentLanguage:self.currentLanguage];
}

#pragma mark - Localization;

- (NSString *)localizedStringForKey:(NSString *)key bundleName:(NSString *)bundleName {
    NSBundle *bundle = [self.languageBundleDictionary objectForKey:bundleName];
    if (bundle) {
        return [bundle localizedStringForKey:key value:@"" table:bundleName];
    }
    else {
        ATLogError(@"no language in This Bundle %@ %@",bundleName, self.currentLanguage);
        return key;
    }
}

- (void)addBundle :(NSString *)bundleName {
    [self addBundle:[NSBundle mainBundle] bundleName:bundleName];
}

- (void)addBundle:(NSBundle *)bundle bundleName:(NSString *)bundleName {
    NSBundle *oldBundle = [self.languageBundleDictionary objectForKey:bundleName];
    if (oldBundle == nil) {
        NSString *bundlePath = [bundle pathForResource:bundleName ofType:@"bundle"];

        NSBundle *mainBundle = [NSBundle bundleWithPath:bundlePath];
        NSString *languagePath = [mainBundle pathForResource:self.currentLanguage ofType:@"lproj"];
        NSBundle *languageBundle = [NSBundle bundleWithPath:languagePath];
        if (languageBundle) {
            [self.languageBundleDictionary setObject:languageBundle forKey:bundleName];
            [self.bundleDictionary setObject:bundle forKey:bundleName];
        }
        else {
            ATLogError(@"no language in This Bundle %@ %@",bundleName, self.currentLanguage);
        }
    }
}
@end


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>My Plugin</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

		<link rel="stylesheet" href="dist/css/myplugin.css" type="text/css">
		<link rel="stylesheet" href="assets/css/custom.css" type="text/css">

My Plugin

GitHub

	Navigation elements that should appear on all pages...

Content...


text:
package com.ws.ch1.javaconfig;

/**
 * Created by martin on 11/25/16.
 */
public class FunctionService {

    public String sayHello(String word){
        return "Hello " + word;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace SharpLua.AST
{
    public partial class MethodCall : Access
    {
        public string Method;

        public Args Args;

    }
}


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <winpr/crt.h>
#include <winpr/print.h>
#include <freerdp/log.h>

#include "win_rdp.h"

#include "win_wds.h"

/**
 * Windows Desktop Sharing API:
 * http://blogs.msdn.com/b/rds/archive/2007/03/08/windows-desktop-sharing-api.aspx
 *
 * Windows Desktop Sharing Interfaces:
 * http://msdn.microsoft.com/en-us/library/aa373871%28v=vs.85%29.aspx
 *
 * Offer Remote Assistance Sample C:
 * http://msdn.microsoft.com/en-us/library/ms811079.aspx#remoteassistanceapi_topic2b
 *
 * Remote Assistance in XP: Programmatically establish an RDP session:
 * http://www.codeproject.com/Articles/29939/Remote-Assistance-in-XP-Programmatically-establish
 */

#undef DEFINE_GUID
#define INITGUID

#include <initguid.h>

#define TAG SERVER_TAG("shadow.win")

DEFINE_GUID(CLSID_RDPSession,0x9B78F0E6,0x3E05,0x4A5B,0xB2,0xE8,0xE7,0x43,0xA8,0x95,0x6B,0x65);
DEFINE_GUID(DIID__IRDPSessionEvents,0x98a97042,0x6698,0x40e9,0x8e,0xfd,0xb3,0x20,0x09,0x90,0x00,0x4b);
DEFINE_GUID(IID_IRDPSRAPISharingSession,0xeeb20886,0xe470,0x4cf6,0x84,0x2b,0x27,0x39,0xc0,0xec,0x5c,0xfb);
DEFINE_GUID(IID_IRDPSRAPIAttendee,0xec0671b3,0x1b78,0x4b80,0xa4,0x64,0x91,0x32,0x24,0x75,0x43,0xe3);
DEFINE_GUID(IID_IRDPSRAPIAttendeeManager,0xba3a37e8,0x33da,0x4749,0x8d,0xa0,0x07,0xfa,0x34,0xda,0x79,0x44);
DEFINE_GUID(IID_IRDPSRAPISessionProperties,0x339b24f2,0x9bc0,0x4f16,0x9a,0xac,0xf1,0x65,0x43,0x3d,0x13,0xd4);
DEFINE_GUID(CLSID_RDPSRAPIApplicationFilter,0xe35ace89,0xc7e8,0x427e,0xa4,0xf9,0xb9,0xda,0x07,0x28,0x26,0xbd);
DEFINE_GUID(CLSID_RDPSRAPIInvitationManager,0x53d9c9db,0x75ab,0x4271,0x94,0x8a,0x4c,0x4e,0xb3,0x6a,0x8f,0x2b);

static ULONG Shadow_IRDPSessionEvents_RefCount = 0;

const char* GetRDPSessionEventString(DISPID id)
{
	switch (id)
	{
		case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_CONNECTED:
			return "OnAttendeeConnected";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_DISCONNECTED:
			return "OnAttendeeDisconnected";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_UPDATE:
			return "OnAttendeeUpdate";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_ERROR:
			return "OnError";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTED:
			return "OnConnectionEstablished";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIEWER_DISCONNECTED:
			return "OnConnectionTerminated";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIEWER_AUTHENTICATED:
			return "OnConnectionAuthenticated";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTFAILED:
			return "OnConnectionFailed";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_CTRLLEVEL_CHANGE_REQUEST:
			return "OnControlLevelChangeRequest";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_PAUSED:
			return "OnGraphicsStreamPaused";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_RESUMED:
			return "OnGraphicsStreamResumed";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_JOIN:
			return "OnChannelJoin";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_LEAVE:
			return "OnChannelLeave";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_DATARECEIVED:
			return "OnChannelDataReceived";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_SENDCOMPLETED:
			return "OnChannelDataSent";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_OPEN:
			return "OnApplicationOpen";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_CLOSE:
			return "OnApplicationClose";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_UPDATE:
			return "OnApplicationUpdate";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_WINDOW_OPEN:
			return "OnWindowOpen";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_WINDOW_CLOSE:
			return "OnWindowClose";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_WINDOW_UPDATE:
			return "OnWindowUpdate";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_APPFILTER_UPDATE:
			return "OnAppFilterUpdate";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_SHARED_RECT_CHANGED:
			return "OnSharedRectChanged";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_FOCUSRELEASED:
			return "OnFocusReleased";
			break;

		case DISPID_RDPSRAPI_EVENT_ON_SHARED_DESKTOP_SETTINGS_CHANGED:
			return "OnSharedDesktopSettingsChanged";
			break;

		case DISPID_RDPAPI_EVENT_ON_BOUNDING_RECT_CHANGED:
			return "OnViewingSizeChanged";
			break;
	}

	return "OnUnknown";
}

static HRESULT STDMETHODCALLTYPE Shadow_IRDPSessionEvents_QueryInterface(
            __RPC__in _IRDPSessionEvents * This,
            /* [in] */ __RPC__in REFIID riid,
            /* [annotation][iid_is][out] */
            _COM_Outptr_  void **ppvObject)
{
	*ppvObject = NULL;

	if (IsEqualIID(riid, &DIID__IRDPSessionEvents) ||
		IsEqualIID(riid, &IID_IDispatch) || IsEqualIID(riid, &IID_IUnknown))
	{
		*ppvObject = This;
	}

	if (!(*ppvObject))
		return E_NOINTERFACE;

	This->lpVtbl->AddRef(This);

	return S_OK;
}

static ULONG STDMETHODCALLTYPE Shadow_IRDPSessionEvents_AddRef(
            __RPC__in _IRDPSessionEvents * This)
{
	Shadow_IRDPSessionEvents_RefCount++;
	return Shadow_IRDPSessionEvents_RefCount;
}

static ULONG STDMETHODCALLTYPE Shadow_IRDPSessionEvents_Release(
            __RPC__in _IRDPSessionEvents * This)
{
	if (!Shadow_IRDPSessionEvents_RefCount)
		return 0;

	Shadow_IRDPSessionEvents_RefCount--;

	return Shadow_IRDPSessionEvents_RefCount;
}

static HRESULT STDMETHODCALLTYPE Shadow_IRDPSessionEvents_GetTypeInfoCount(
            __RPC__in _IRDPSessionEvents * This,
            /* [out] */ __RPC__out UINT *pctinfo)
{
	WLog_INFO(TAG, "Shadow_IRDPSessionEvents_GetTypeInfoCount");
	*pctinfo = 1;
	return S_OK;
}

static HRESULT STDMETHODCALLTYPE Shadow_IRDPSessionEvents_GetTypeInfo(
            __RPC__in _IRDPSessionEvents * This,
            /* [in] */ UINT iTInfo,
            /* [in] */ LCID lcid,
            /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo)
{
	WLog_INFO(TAG, "Shadow_IRDPSessionEvents_GetTypeInfo");
	return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE Shadow_IRDPSessionEvents_GetIDsOfNames(
            __RPC__in _IRDPSessionEvents * This,
            /* [in] */ __RPC__in REFIID riid,
            /* [size_is][in] */ __RPC__in_ecount_full(cNames) LPOLESTR *rgszNames,
            /* [range][in] */ __RPC__in_range(0,16384) UINT cNames,
            /* [in] */ LCID lcid,
            /* [size_is][out] */ __RPC__out_ecount_full(cNames) DISPID *rgDispId)
{
	WLog_INFO(TAG, "Shadow_IRDPSessionEvents_GetIDsOfNames");
	return E_NOTIMPL;
}

static HRESULT STDMETHODCALLTYPE Shadow_IRDPSessionEvents_Invoke(
            _IRDPSessionEvents * This,
            /* [annotation][in] */
            _In_  DISPID dispIdMember,
            /* [annotation][in] */
            _In_  REFIID riid,
            /* [annotation][in] */
            _In_  LCID lcid,
            /* [annotation][in] */
            _In_  WORD wFlags,
            /* [annotation][out][in] */
            _In_  DISPPARAMS *pDispParams,
            /* [annotation][out] */
            _Out_opt_  VARIANT *pVarResult,
            /* [annotation][out] */
            _Out_opt_  EXCEPINFO *pExcepInfo,
            /* [annotation][out] */
            _Out_opt_  UINT *puArgErr)
{
	HRESULT hr;
	VARIANT vr;
	UINT uArgErr;

	WLog_INFO(TAG, "%s (%ld)", GetRDPSessionEventString(dispIdMember), dispIdMember);

	switch (dispIdMember)
	{
		case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_CONNECTED:
			{
				int level;
				IDispatch* pDispatch;
				IRDPSRAPIAttendee* pAttendee;

				vr.vt = VT_DISPATCH;
				vr.pdispVal = NULL;

				hr = DispGetParam(pDispParams, 0, VT_DISPATCH, &vr, &uArgErr);

				if (FAILED(hr))
				{
					WLog_ERR(TAG, "%s DispGetParam(0, VT_DISPATCH) failure: 0x%08lX",
						GetRDPSessionEventString(dispIdMember), hr);
					return hr;
				}

				pDispatch = vr.pdispVal;

				hr = pDispatch->lpVtbl->QueryInterface(pDispatch, &IID_IRDPSRAPIAttendee, (void**) &pAttendee);

				if (FAILED(hr))
				{
					WLog_INFO(TAG, "%s IDispatch::QueryInterface(IRDPSRAPIAttendee) failure: 0x%08lX",
						GetRDPSessionEventString(dispIdMember), hr);
					return hr;
				}

				level = CTRL_LEVEL_VIEW;
				//level = CTRL_LEVEL_INTERACTIVE;

				hr = pAttendee->lpVtbl->put_ControlLevel(pAttendee, level);

				if (FAILED(hr))
				{
					WLog_INFO(TAG, "%s IRDPSRAPIAttendee::put_ControlLevel() failure: 0x%08lX",
						GetRDPSessionEventString(dispIdMember), hr);
					return hr;
				}

				pAttendee->lpVtbl->Release(pAttendee);
			}
			break;

		case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_DISCONNECTED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_ATTENDEE_UPDATE:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_ERROR:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIEWER_DISCONNECTED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIEWER_AUTHENTICATED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIEWER_CONNECTFAILED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_CTRLLEVEL_CHANGE_REQUEST:
			{
				int level;
				IDispatch* pDispatch;
				IRDPSRAPIAttendee* pAttendee;

				vr.vt = VT_INT;
				vr.pdispVal = NULL;

				hr = DispGetParam(pDispParams, 1, VT_INT, &vr, &uArgErr);

				if (FAILED(hr))
				{
					WLog_INFO(TAG, "%s DispGetParam(1, VT_INT) failure: 0x%08lX",
						GetRDPSessionEventString(dispIdMember), hr);
					return hr;
				}

				level = vr.intVal;

				vr.vt = VT_DISPATCH;
				vr.pdispVal = NULL;

				hr = DispGetParam(pDispParams, 0, VT_DISPATCH, &vr, &uArgErr);

				if (FAILED(hr))
				{
					WLog_ERR(TAG, "%s DispGetParam(0, VT_DISPATCH) failure: 0x%08lX",
						GetRDPSessionEventString(dispIdMember), hr);
					return hr;
				}

				pDispatch = vr.pdispVal;

				hr = pDispatch->lpVtbl->QueryInterface(pDispatch, &IID_IRDPSRAPIAttendee, (void**) &pAttendee);

				if (FAILED(hr))
				{
					WLog_INFO(TAG, "%s IDispatch::QueryInterface(IRDPSRAPIAttendee) failure: 0x%08lX",
						GetRDPSessionEventString(dispIdMember), hr);
					return hr;
				}

				hr = pAttendee->lpVtbl->put_ControlLevel(pAttendee, level);

				if (FAILED(hr))
				{
					WLog_INFO(TAG, "%s IRDPSRAPIAttendee::put_ControlLevel() failure: 0x%08lX",
						GetRDPSessionEventString(dispIdMember), hr);
					return hr;
				}

				pAttendee->lpVtbl->Release(pAttendee);
			}
			break;

		case DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_PAUSED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_GRAPHICS_STREAM_RESUMED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_JOIN:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_LEAVE:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_DATARECEIVED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_VIRTUAL_CHANNEL_SENDCOMPLETED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_OPEN:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_CLOSE:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_APPLICATION_UPDATE:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_WINDOW_OPEN:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_WINDOW_CLOSE:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_WINDOW_UPDATE:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_APPFILTER_UPDATE:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_SHARED_RECT_CHANGED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_FOCUSRELEASED:
			break;

		case DISPID_RDPSRAPI_EVENT_ON_SHARED_DESKTOP_SETTINGS_CHANGED:
			break;

		case DISPID_RDPAPI_EVENT_ON_BOUNDING_RECT_CHANGED:
			break;
	}

	return S_OK;
}

static _IRDPSessionEventsVtbl Shadow_IRDPSessionEventsVtbl =
{
	/* IUnknown */
	Shadow_IRDPSessionEvents_QueryInterface,
	Shadow_IRDPSessionEvents_AddRef,
	Shadow_IRDPSessionEvents_Release,

	/* IDispatch */
	Shadow_IRDPSessionEvents_GetTypeInfoCount,
	Shadow_IRDPSessionEvents_GetTypeInfo,
	Shadow_IRDPSessionEvents_GetIDsOfNames,
	Shadow_IRDPSessionEvents_Invoke
};

static _IRDPSessionEvents Shadow_IRDPSessionEvents =
{
	&Shadow_IRDPSessionEventsVtbl
};

static LRESULT CALLBACK ShadowWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg)
	{
		case WM_CLOSE:
			DestroyWindow(hwnd);
			break;

		case WM_DESTROY:
			PostQuitMessage(0);
			break;

		default:
			return DefWindowProc(hwnd, uMsg, wParam, lParam);
			break;
	}

	return 0;
}

int win_shadow_wds_wnd_init(winShadowSubsystem* subsystem)
{
	HMODULE hModule;
	HINSTANCE hInstance;
	WNDCLASSEX wndClassEx;

	hModule = GetModuleHandle(NULL);

	ZeroMemory(&wndClassEx, sizeof(WNDCLASSEX));
	wndClassEx.cbSize = sizeof(WNDCLASSEX);
	wndClassEx.style = 0;
	wndClassEx.lpfnWndProc = ShadowWndProc;
	wndClassEx.cbClsExtra = 0;
	wndClassEx.cbWndExtra = 0;
	wndClassEx.hInstance = hModule;
	wndClassEx.hIcon = NULL;
	wndClassEx.hCursor = NULL;
	wndClassEx.hbrBackground = NULL;
	wndClassEx.lpszMenuName = _T("ShadowWndMenu");
	wndClassEx.lpszClassName = _T("ShadowWndClass");
	wndClassEx.hIconSm = NULL;

	if (!RegisterClassEx(&wndClassEx))
	{
		WLog_ERR(TAG, "RegisterClassEx failure");
		return -1;
	}

	hInstance = wndClassEx.hInstance;

	subsystem->hWnd = CreateWindowEx(0, wndClassEx.lpszClassName,
		0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hInstance, NULL);

	if (!subsystem->hWnd)
	{
		WLog_INFO(TAG, "CreateWindowEx failure");
		return -1;
	}

	return 1;
}

int win_shadow_wds_init(winShadowSubsystem* subsystem)
{
	int status;
	HRESULT hr;
	DWORD dwCookie;
	long left, top;
	long right, bottom;
	long width, height;
	IUnknown* pUnknown;
	rdpSettings* settings;
	BSTR bstrAuthString;
	BSTR bstrGroupName;
	BSTR bstrPassword;
	BSTR bstrConnectionString;
	BSTR bstrPropertyName;
	VARIANT varPropertyValue;
	rdpAssistanceFile* file;
	IConnectionPoint* pCP;
	IConnectionPointContainer* pCPC;

	win_shadow_wds_wnd_init(subsystem);

	hr = OleInitialize(NULL);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "OleInitialize() failure");
		return -1;
	}

	hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "CoInitialize() failure");
		return -1;
	}

	hr = CoCreateInstance(&CLSID_RDPSession, NULL, CLSCTX_ALL,
		&IID_IRDPSRAPISharingSession, (void**) &(subsystem->pSharingSession));

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "CoCreateInstance(IRDPSRAPISharingSession) failure: 0x%08lX", hr);
		return -1;
	}

	pUnknown = (IUnknown*) subsystem->pSharingSession;
	hr = pUnknown->lpVtbl->QueryInterface(pUnknown, &IID_IConnectionPointContainer, (void**) &pCPC);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "QueryInterface(IID_IConnectionPointContainer) failure: 0x%08lX", hr);
		return -1;
	}

	pCPC->lpVtbl->FindConnectionPoint(pCPC, &DIID__IRDPSessionEvents, &pCP);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IConnectionPointContainer::FindConnectionPoint(_IRDPSessionEvents) failure: 0x%08lX", hr);
		return -1;
	}

	dwCookie = 0;
	subsystem->pSessionEvents = &Shadow_IRDPSessionEvents;
	subsystem->pSessionEvents->lpVtbl->AddRef(subsystem->pSessionEvents);

	hr = pCP->lpVtbl->Advise(pCP, (IUnknown*) subsystem->pSessionEvents, &dwCookie);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IConnectionPoint::Advise(Shadow_IRDPSessionEvents) failure: 0x%08lX", hr);
		return -1;
	}

	hr = subsystem->pSharingSession->lpVtbl->put_ColorDepth(subsystem->pSharingSession, 32);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISharingSession::put_ColorDepth() failure: 0x%08lX", hr);
		return -1;
	}

	hr = subsystem->pSharingSession->lpVtbl->GetDesktopSharedRect(subsystem->pSharingSession,
		&left, &top, &right, &bottom);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISharingSession::GetDesktopSharedRect() failure: 0x%08lX", hr);
		return -1;
	}

	width = right - left;
	height = bottom - top;

	WLog_INFO(TAG, "GetDesktopSharedRect(): left: %ld top: %ld right: %ld bottom: %ld width: %ld height: %ld",
		left, top, right, bottom, width, height);

	hr = subsystem->pSharingSession->lpVtbl->get_VirtualChannelManager(subsystem->pSharingSession,
		&(subsystem->pVirtualChannelMgr));

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISharingSession::get_VirtualChannelManager() failure: 0x%08lX", hr);
		return -1;
	}

	hr = subsystem->pSharingSession->lpVtbl->get_ApplicationFilter(subsystem->pSharingSession,
		&(subsystem->pApplicationFilter));

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISharingSession::get_ApplicationFilter() failure: 0x%08lX", hr);
		return -1;
	}

	hr = subsystem->pSharingSession->lpVtbl->get_Attendees(subsystem->pSharingSession,
		&(subsystem->pAttendeeMgr));

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISharingSession::get_Attendees() failure: 0x%08lX", hr);
		return -1;
	}

	hr = subsystem->pSharingSession->lpVtbl->get_Properties(subsystem->pSharingSession, &(subsystem->pSessionProperties));

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISharingSession::get_Properties() failure: 0x%08lX", hr);
		return -1;
	}

	bstrPropertyName = SysAllocString(L"PortId");
	varPropertyValue.vt = VT_I4;
	varPropertyValue.intVal = 40000;

	hr = subsystem->pSessionProperties->lpVtbl->put_Property(subsystem->pSessionProperties,
		bstrPropertyName, varPropertyValue);

	SysFreeString(bstrPropertyName);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISessionProperties::put_Property(PortId) failure: 0x%08lX", hr);
		return -1;
	}

	bstrPropertyName = SysAllocString(L"DrvConAttach");
	varPropertyValue.vt = VT_BOOL;
	varPropertyValue.boolVal = VARIANT_TRUE;

	hr = subsystem->pSessionProperties->lpVtbl->put_Property(subsystem->pSessionProperties,
		bstrPropertyName, varPropertyValue);

	SysFreeString(bstrPropertyName);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISessionProperties::put_Property(DrvConAttach) failure: 0x%08lX", hr);
		return -1;
	}

	bstrPropertyName = SysAllocString(L"PortProtocol");
	varPropertyValue.vt = VT_I4;

	//varPropertyValue.intVal = 0; // AF_UNSPEC
	varPropertyValue.intVal = 2; // AF_INET
	//varPropertyValue.intVal = 23; // AF_INET6

	hr = subsystem->pSessionProperties->lpVtbl->put_Property(subsystem->pSessionProperties,
		bstrPropertyName, varPropertyValue);

	SysFreeString(bstrPropertyName);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISessionProperties::put_Property(PortProtocol) failure: 0x%08lX", hr);
		return -1;
	}

	hr = subsystem->pSharingSession->lpVtbl->Open(subsystem->pSharingSession);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISharingSession::Open() failure: 0x%08lX", hr);
		return -1;
	}

	hr = subsystem->pSharingSession->lpVtbl->get_Invitations(subsystem->pSharingSession,
		&(subsystem->pInvitationMgr));

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPISharingSession::get_Invitations() failure");
		return -1;
	}

	bstrAuthString = SysAllocString(L"Shadow");
	bstrGroupName = SysAllocString(L"ShadowGroup");
	bstrPassword = SysAllocString(L"Shadow123!");

	hr = subsystem->pInvitationMgr->lpVtbl->CreateInvitation(subsystem->pInvitationMgr, bstrAuthString,
		bstrGroupName, bstrPassword, 5, &(subsystem->pInvitation));

	SysFreeString(bstrAuthString);
	SysFreeString(bstrGroupName);
	SysFreeString(bstrPassword);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPIInvitationManager::CreateInvitation() failure: 0x%08lX", hr);
		return -1;
	}

	hr = subsystem->pInvitation->lpVtbl->get_ConnectionString(subsystem->pInvitation, &bstrConnectionString);

	if (FAILED(hr))
	{
		WLog_ERR(TAG, "IRDPSRAPIInvitation::get_ConnectionString() failure: 0x%08lX", hr);
		return -1;
	}

	file = subsystem->pAssistanceFile = freerdp_assistance_file_new();

	if (!file)
	{
		WLog_ERR(TAG, "freerdp_assistance_file_new() failed");
		return -1;
	}

	status = ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) bstrConnectionString,
		((UINT32*) bstrConnectionString)[-1], &(file->ConnectionString2), 0, NULL, NULL);

	SysFreeString(bstrConnectionString);

	if (status < 1)
	{
		WLog_ERR(TAG, "failed to convert connection string");
		return -1;
	}

	status = freerdp_assistance_parse_connection_string2(file);

	if (status < 0)
		return -1;

	WLog_INFO(TAG, "ConnectionString: %s", file->ConnectionString2);

#if 0
	FILE* fp;
	size_t size;

	fp = fopen("inv.xml", "w+b");

	if (fp)
	{
		size = strlen(file->ConnectionString2);
		if (fwrite(file->ConnectionString2, size, 1, fp) != 1 || fwrite("\r\n", 2, 1, fp) != 1)
		{
			fclose(fp);
			WLog_ERR(TAG, "Problem writing to inv.xml");
			return -1;
		}
		fclose(fp);
	}
#endif

	status = win_shadow_rdp_init(subsystem);

	if (status < 0)
	{
		WLog_ERR(TAG, "win_shadow_rdp_init() failure: %d", status);
		return status;
	}

	settings = subsystem->shw->settings;

	freerdp_set_param_bool(settings, FreeRDP_RemoteAssistanceMode, TRUE);

	freerdp_set_param_string(settings, FreeRDP_RemoteAssistanceSessionId, file->RASessionId);

	freerdp_set_param_string(settings, FreeRDP_RemoteAssistanceRCTicket, file->ConnectionString2);

	freerdp_set_param_string(settings, FreeRDP_Domain, "RDP");
	freerdp_set_param_string(settings, FreeRDP_Username, "Shadow");
	freerdp_set_param_string(settings, FreeRDP_RemoteAssistancePassword, "Shadow123!");
	freerdp_set_param_bool(settings, FreeRDP_AutoLogonEnabled, TRUE);

	freerdp_set_param_string(settings, FreeRDP_ServerHostname, file->MachineAddress);
	freerdp_set_param_uint32(settings, FreeRDP_ServerPort, file->MachinePort);

	freerdp_set_param_uint32(settings, FreeRDP_DesktopWidth, width);
	freerdp_set_param_uint32(settings, FreeRDP_DesktopHeight, height);

	status = win_shadow_rdp_start(subsystem);

	if (status < 0)
	{
		WLog_ERR(TAG, "win_shadow_rdp_start() failure: %d", status);
		return status;
	}

	return 1;
}

int win_shadow_wds_uninit(winShadowSubsystem* subsystem)
{
	if (subsystem->pSharingSession)
	{
		subsystem->pSharingSession->lpVtbl->Close(subsystem->pSharingSession);
		subsystem->pSharingSession->lpVtbl->Release(subsystem->pSharingSession);
		subsystem->pSharingSession = NULL;
	}

	if (subsystem->pVirtualChannelMgr)
	{
		subsystem->pVirtualChannelMgr->lpVtbl->Release(subsystem->pVirtualChannelMgr);
		subsystem->pVirtualChannelMgr = NULL;
	}

	if (subsystem->pApplicationFilter)
	{
		subsystem->pApplicationFilter->lpVtbl->Release(subsystem->pApplicationFilter);
		subsystem->pApplicationFilter = NULL;
	}

	if (subsystem->pAttendeeMgr)
	{
		subsystem->pAttendeeMgr->lpVtbl->Release(subsystem->pAttendeeMgr);
		subsystem->pAttendeeMgr = NULL;
	}

	if (subsystem->pSessionProperties)
	{
		subsystem->pSessionProperties->lpVtbl->Release(subsystem->pSessionProperties);
		subsystem->pSessionProperties = NULL;
	}

	if (subsystem->pInvitationMgr)
	{
		subsystem->pInvitationMgr->lpVtbl->Release(subsystem->pInvitationMgr);
		subsystem->pInvitationMgr = NULL;
	}

	if (subsystem->pInvitation)
	{
		subsystem->pInvitation->lpVtbl->Release(subsystem->pInvitation);
		subsystem->pInvitation = NULL;
	}

	if (subsystem->pAssistanceFile)
	{
		freerdp_assistance_file_free(subsystem->pAssistanceFile);
		subsystem->pAssistanceFile = NULL;
	}

	if (subsystem->hWnd)
	{
		DestroyWindow(subsystem->hWnd);
		subsystem->hWnd = NULL;
	}

	if (subsystem->shw)
	{
		win_shadow_rdp_uninit(subsystem);
		subsystem->shw = NULL;
	}

	return 1;
}