text:
package daemon

import (
	"testing"

	apps "k8s.io/api/apps/v1"
	"k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/util/intstr"
)

func TestDaemonSetUpdatesPods(t *testing.T) {
	ds := newDaemonSet("foo")
	manager, podControl, _, err := newTestController(ds)
	if err != nil {
		t.Fatalf("error creating DaemonSets controller: %v", err)
	}
	maxUnavailable := 2
	addNodes(manager.nodeStore, 0, 5, nil)
	err = manager.dsStore.Add(ds)
	if err != nil {
		t.Fatal(err)
	}
	err = syncAndValidateDaemonSets(manager, ds, podControl, 5, 0, 0)
	if err != nil {
		t.Error(err)
	}
	markPodsReady(podControl.podStore)

	ds.Spec.Template.Spec.Containers[0].Image = "foo2/bar2"
	ds.Spec.UpdateStrategy.Type = apps.RollingUpdateDaemonSetStrategyType
	intStr := intstr.FromInt(maxUnavailable)
	ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
	err = manager.dsStore.Update(ds)
	if err != nil {
		t.Fatal(err)
	}

	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, maxUnavailable, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, maxUnavailable, 0, 0)
	if err != nil {
		t.Error(err)
	}
	markPodsReady(podControl.podStore)

	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, maxUnavailable, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, maxUnavailable, 0, 0)
	if err != nil {
		t.Error(err)
	}
	markPodsReady(podControl.podStore)

	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, 1, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 1, 0, 0)
	if err != nil {
		t.Error(err)
	}
	markPodsReady(podControl.podStore)

	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, 0, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
}

func TestDaemonSetUpdatesWhenNewPosIsNotReady(t *testing.T) {
	ds := newDaemonSet("foo")
	manager, podControl, _, err := newTestController(ds)
	if err != nil {
		t.Fatalf("error creating DaemonSets controller: %v", err)
	}
	maxUnavailable := 3
	addNodes(manager.nodeStore, 0, 5, nil)
	err = manager.dsStore.Add(ds)
	if err != nil {
		t.Fatal(err)
	}
	err = syncAndValidateDaemonSets(manager, ds, podControl, 5, 0, 0)
	if err != nil {
		t.Error(err)
	}
	markPodsReady(podControl.podStore)

	ds.Spec.Template.Spec.Containers[0].Image = "foo2/bar2"
	ds.Spec.UpdateStrategy.Type = apps.RollingUpdateDaemonSetStrategyType
	intStr := intstr.FromInt(maxUnavailable)
	ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
	err = manager.dsStore.Update(ds)
	if err != nil {
		t.Fatal(err)
	}

	// new pods are not ready numUnavailable == maxUnavailable
	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, maxUnavailable, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, maxUnavailable, 0, 0)
	if err != nil {
		t.Error(err)
	}

	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, 0, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
}

func TestDaemonSetUpdatesAllOldPodsNotReady(t *testing.T) {
	ds := newDaemonSet("foo")
	manager, podControl, _, err := newTestController(ds)
	if err != nil {
		t.Fatalf("error creating DaemonSets controller: %v", err)
	}
	maxUnavailable := 3
	addNodes(manager.nodeStore, 0, 5, nil)
	err = manager.dsStore.Add(ds)
	if err != nil {
		t.Fatal(err)
	}
	err = syncAndValidateDaemonSets(manager, ds, podControl, 5, 0, 0)
	if err != nil {
		t.Error(err)
	}

	ds.Spec.Template.Spec.Containers[0].Image = "foo2/bar2"
	ds.Spec.UpdateStrategy.Type = apps.RollingUpdateDaemonSetStrategyType
	intStr := intstr.FromInt(maxUnavailable)
	ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
	err = manager.dsStore.Update(ds)
	if err != nil {
		t.Fatal(err)
	}

	// all old pods are unavailable so should be removed
	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, 5, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 5, 0, 0)
	if err != nil {
		t.Error(err)
	}

	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, 0, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
}

func TestDaemonSetUpdatesNoTemplateChanged(t *testing.T) {
	ds := newDaemonSet("foo")
	manager, podControl, _, err := newTestController(ds)
	if err != nil {
		t.Fatalf("error creating DaemonSets controller: %v", err)
	}
	maxUnavailable := 3
	addNodes(manager.nodeStore, 0, 5, nil)
	err = manager.dsStore.Add(ds)
	if err != nil {
		t.Fatal(err)
	}
	err = syncAndValidateDaemonSets(manager, ds, podControl, 5, 0, 0)
	if err != nil {
		t.Error(err)
	}

	ds.Spec.UpdateStrategy.Type = apps.RollingUpdateDaemonSetStrategyType
	intStr := intstr.FromInt(maxUnavailable)
	ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
	err = manager.dsStore.Update(ds)
	if err != nil {
		t.Fatal(err)
	}

	// template is not changed no pod should be removed
	clearExpectations(t, manager, ds, podControl)
	err = syncAndValidateDaemonSets(manager, ds, podControl, 0, 0, 0)
	if err != nil {
		t.Error(err)
	}
	clearExpectations(t, manager, ds, podControl)
}

func TestGetUnavailableNumbers(t *testing.T) {
	cases := []struct {
		name           string
		Manager        *daemonSetsController
		ds             *apps.DaemonSet
		nodeToPods     map[string][]*v1.Pod
		maxUnavailable int
		numUnavailable int
		Err            error
	}{
		{
			name: "No nodes",
			Manager: func() *daemonSetsController {
				manager, _, _, err := newTestController()
				if err != nil {
					t.Fatalf("error creating DaemonSets controller: %v", err)
				}
				return manager
			}(),
			ds: func() *apps.DaemonSet {
				ds := newDaemonSet("x")
				intStr := intstr.FromInt(0)
				ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
				return ds
			}(),
			nodeToPods:     make(map[string][]*v1.Pod),
			maxUnavailable: 0,
			numUnavailable: 0,
		},
		{
			name: "Two nodes with ready pods",
			Manager: func() *daemonSetsController {
				manager, _, _, err := newTestController()
				if err != nil {
					t.Fatalf("error creating DaemonSets controller: %v", err)
				}
				addNodes(manager.nodeStore, 0, 2, nil)
				return manager
			}(),
			ds: func() *apps.DaemonSet {
				ds := newDaemonSet("x")
				intStr := intstr.FromInt(1)
				ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
				return ds
			}(),
			nodeToPods: func() map[string][]*v1.Pod {
				mapping := make(map[string][]*v1.Pod)
				pod0 := newPod("pod-0", "node-0", simpleDaemonSetLabel, nil)
				pod1 := newPod("pod-1", "node-1", simpleDaemonSetLabel, nil)
				markPodReady(pod0)
				markPodReady(pod1)
				mapping["node-0"] = []*v1.Pod{pod0}
				mapping["node-1"] = []*v1.Pod{pod1}
				return mapping
			}(),
			maxUnavailable: 1,
			numUnavailable: 0,
		},
		{
			name: "Two nodes, one node without pods",
			Manager: func() *daemonSetsController {
				manager, _, _, err := newTestController()
				if err != nil {
					t.Fatalf("error creating DaemonSets controller: %v", err)
				}
				addNodes(manager.nodeStore, 0, 2, nil)
				return manager
			}(),
			ds: func() *apps.DaemonSet {
				ds := newDaemonSet("x")
				intStr := intstr.FromInt(0)
				ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
				return ds
			}(),
			nodeToPods: func() map[string][]*v1.Pod {
				mapping := make(map[string][]*v1.Pod)
				pod0 := newPod("pod-0", "node-0", simpleDaemonSetLabel, nil)
				markPodReady(pod0)
				mapping["node-0"] = []*v1.Pod{pod0}
				return mapping
			}(),
			maxUnavailable: 0,
			numUnavailable: 1,
		},
		{
			name: "Two nodes with pods, MaxUnavailable in percents",
			Manager: func() *daemonSetsController {
				manager, _, _, err := newTestController()
				if err != nil {
					t.Fatalf("error creating DaemonSets controller: %v", err)
				}
				addNodes(manager.nodeStore, 0, 2, nil)
				return manager
			}(),
			ds: func() *apps.DaemonSet {
				ds := newDaemonSet("x")
				intStr := intstr.FromString("50%")
				ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
				return ds
			}(),
			nodeToPods: func() map[string][]*v1.Pod {
				mapping := make(map[string][]*v1.Pod)
				pod0 := newPod("pod-0", "node-0", simpleDaemonSetLabel, nil)
				pod1 := newPod("pod-1", "node-1", simpleDaemonSetLabel, nil)
				markPodReady(pod0)
				markPodReady(pod1)
				mapping["node-0"] = []*v1.Pod{pod0}
				mapping["node-1"] = []*v1.Pod{pod1}
				return mapping
			}(),
			maxUnavailable: 1,
			numUnavailable: 0,
		},
		{
			name: "Two nodes with pods, MaxUnavailable in percents, pod terminating",
			Manager: func() *daemonSetsController {
				manager, _, _, err := newTestController()
				if err != nil {
					t.Fatalf("error creating DaemonSets controller: %v", err)
				}
				addNodes(manager.nodeStore, 0, 2, nil)
				return manager
			}(),
			ds: func() *apps.DaemonSet {
				ds := newDaemonSet("x")
				intStr := intstr.FromString("50%")
				ds.Spec.UpdateStrategy.RollingUpdate = &apps.RollingUpdateDaemonSet{MaxUnavailable: &intStr}
				return ds
			}(),
			nodeToPods: func() map[string][]*v1.Pod {
				mapping := make(map[string][]*v1.Pod)
				pod0 := newPod("pod-0", "node-0", simpleDaemonSetLabel, nil)
				pod1 := newPod("pod-1", "node-1", simpleDaemonSetLabel, nil)
				now := metav1.Now()
				markPodReady(pod0)
				markPodReady(pod1)
				pod1.DeletionTimestamp = &now
				mapping["node-0"] = []*v1.Pod{pod0}
				mapping["node-1"] = []*v1.Pod{pod1}
				return mapping
			}(),
			maxUnavailable: 1,
			numUnavailable: 1,
		},
	}

	for _, c := range cases {
		c.Manager.dsStore.Add(c.ds)
		nodeList, err := c.Manager.nodeLister.List(labels.Everything())
		if err != nil {
			t.Fatalf("error listing nodes: %v", err)
		}
		maxUnavailable, numUnavailable, err := c.Manager.getUnavailableNumbers(c.ds, nodeList, c.nodeToPods)
		if err != nil && c.Err != nil {
			if c.Err != err {
				t.Errorf("Test case: %s. Expected error: %v but got: %v", c.name, c.Err, err)
			}
		} else if err != nil {
			t.Errorf("Test case: %s. Unexpected error: %v", c.name, err)
		} else if maxUnavailable != c.maxUnavailable || numUnavailable != c.numUnavailable {
			t.Errorf("Test case: %s. Wrong values. maxUnavailable: %d, expected: %d, numUnavailable: %d. expected: %d", c.name, maxUnavailable, c.maxUnavailable, numUnavailable, c.numUnavailable)
		}
	}
}


text:
from sklearn import svm
import ast

# Description: This is the wrapper class around the svm model from sklearn.
# This class feeds training data into the SVM machine learning model, and
# provides an API to decide if a grammar is interesting or not based on its content
# and its first and follow set.

# grammar = {'S': ['F', '(S + F)'],
#          'F': ['a']}

# Production scoring:
# all terminals: 1, ε: 2,  only nonterminal is itself: 3, include other nonterminals: 4

epsilon = 'ε'
maxProduction = 3

class SvmLearn:
    def __init__(self, nVariable, filenameI, filenameN):
        # Input: nVariable: Number of variables this learning
        #   model is build for
        # nameI: file name of the training data categorized as
        #   intereing grammars
        # nameN: file name of the training data categorized as
        #   not intereing grammars

        self.nVariable = nVariable
        # tData: an array X of size [n_samples, n_features] holding
        # the training samples
        self.tData = []
        # labels: an array y of class labels, size [n_samples]
        # in our case 0 can be interesting, 1 be not interesting
        self.labels = []

        #Extract the features from training data
        fI = open(filenameI, 'r')
        fILines = fI.readlines()
        i = 0
        #this part is based on the knowledge of the format of our training data
        while i < len(fILines):
            #extract each line as a dictionary
            grammar = ast.literal_eval(fILines[i])
            first = ast.literal_eval(fILines[i+1].split("First Set: ")[1])
            follow = ast.literal_eval(fILines[i+2].split("Follow Set: ")[1])
            i+=5
            #building a feature list with the information given
            feature = self.buildFeature(grammar, first, follow)
            self.tData.append(feature)
            #1 representing interesting
            self.labels.append(1)
        if not (i == len(fILines)+1):
            raise Exception('Julien messed up the training data format')
        fI.close()

        fN = open(filenameN, 'r')
        fNLines = fN.readlines()
        n = 0
        while n < len(fNLines):
            #this part is based on the knowledge of the format of our training data
            grammar = ast.literal_eval(fNLines[n])
            first = ast.literal_eval(fNLines[n+1].split("First Set: ")[1])
            follow = ast.literal_eval(fNLines[n+2].split("Follow Set: ")[1])
            n+=5
            #building a feature list with the information given
            feature = self.buildFeature(grammar, first, follow)
            self.tData.append(feature)
            #0 representing not interesting
            self.labels.append(0)
            # print("grammar: "+str(grammar)
            #         +"\n\tfirst: "+str(first)
            #         +"\n\tfollow: "+str(follow)
            #         +"\n\tfeature: "+str(feature)
            #         +"\n")
        if not (n == len(fNLines)+1):
            raise Exception('Julien messed up the training data format')
        fN.close()

        #use the training data to build the model
        self.clf = svm.SVC()
        self.clf.fit(self.tData, self.labels)

    def predictGrammar(self, grammar, first, follow):
        # A helper function that predict whether a single grammar is interesting
        # Input: the feature array of a single grammar
        # Return: [0] indicating not interesting or [1] indicating interesting
        if not (isinstance(grammar,dict) and isinstance(first,dict) and isinstance(follow,dict)):
            raise Exception('Wrong format of grammar input')
        if not (len(grammar)==self.nVariable and len(first)==self.nVariable and len(follow)==self.nVariable):
            raise Exception('Wrong format of grammar input')

        feature=self.buildFeature(grammar,first,follow)
        return self.clf.predict([feature])

    def buildFeature(self, grammar, first, follow):
        # This helper function builds a feature array of a grammar
        # Input: grammar, first and follow as the grammar checker returns (refer to that for format)
        # Output: an array of integers representing the features
        if not (isinstance(grammar,dict) and isinstance(first,dict) and isinstance(follow,dict)):
            raise Exception('Wrong format of grammar input')
        if not (len(grammar)==self.nVariable and len(first)==self.nVariable and len(follow)==self.nVariable):
            raise Exception('Wrong format of grammar input')

        result = []

        #features of the grammar
        for key in grammar:
            l=[]
            for production in grammar[key]:
                pClass = self.pDescribe(production, key)
                l.append(pClass)
            #pad each row with 0 if there are less than 3 productions
            while len(l) < maxProduction:
                l.append(0)
            l.sort()
            l.reverse()
            result = result+l

        #feature of the first and follow set
        fi=[]
        fo=[]
        for key in grammar:
            fi.append(len(first[key]))
            fo.append(len(follow[key]))
        fi.sort()
        fi.reverse()
        fo.sort()
        fo.reverse()
        result = result+fi+fo

        if not (len(result) == self.nVariable*(maxProduction+2)):
            raise Exception('Error occured while building the features')

        return result

    def pDescribe(self, production, nonTerminal):
        #This helper function describes a production using an integer
        #   from [1-4]
        # Input: a production <String> and its associated nonTerminal <Char>
        # Output: 1: Only consisted of terminals
        #        2: Epislon
        #        3: The only non-terminal included is itself
        #        4: Includes other non-terminals
        if production == epsilon:
            return 2

        result = 1
        for c in production:
            if c.isupper():
                result = 3
                if not c == nonTerminal:
                    result = 4
                    return result
        return result

redpajama_set_name: RedPajamaGithub


text:
#ifndef TC_KEY_REQ_H
#define TC_KEY_REQ_H

#include "SignalData.hpp"

/**
 * @class TcKeyReq
 * @brief Contains KeyInfo and AttrInfo and is commonly followed by more signals
 *
 * - SENDER:    API, NDBCNTR
 * - RECEIVER:  TC
 */
class TcKeyReq {
  /**
   * Receiver(s)
   */
  friend class Dbtc;         // Receiver

  /**
   * Sender(s)
   */
  friend class Ndbcntr;
  friend class NdbOperation;
  friend class NdbIndexOperation;
  friend class NdbScanOperation;
  friend class NdbBlob;
  friend class DbUtil;

  /**
   * For printing
   */
  friend bool printTCKEYREQ(FILE *, const Uint32 *, Uint32, Uint16);
  friend bool printTCINDXREQ(FILE *, const Uint32 *, Uint32, Uint16);

public:
  /**
   * Length of signal
   */
  STATIC_CONST( StaticLength = 8 );
  STATIC_CONST( SignalLength = 25 );
  STATIC_CONST( MaxKeyInfo = 8 );
  STATIC_CONST( MaxAttrInfo = 5 );
  STATIC_CONST( MaxTotalAttrInfo = 0xFFFF );

private:

  enum AbortOption {
    CommitIfFailFree = 0, AbortOnError = 0,
    CommitAsMuchAsPossible = 2, IgnoreError = 2
  };

  typedef AbortOption CommitType;

  /**
   * DATA VARIABLES
   */

  // ----------------------------------------------------------------------
  //  Unconditional part = must be present in signal.  First 8 words
  // ----------------------------------------------------------------------
  Uint32 apiConnectPtr;        // DATA 0
  union {
    Uint32 senderData;
    UintR apiOperationPtr;      // DATA 1
  };
  /**
   * ATTRIBUTE INFO (attrinfo) LENGTH
   * This is the total length of all attribute info that is sent from
   * the application as part of this operation.
   * It includes all attribute info sent in possible attrinfo
   * signals as well as the attribute info sent in TCKEYREQ.
   */
  UintR attrLen;              // DATA 2   (also stores API Version)
  UintR tableId;              // DATA 3
  UintR requestInfo;          // DATA 4   Various transaction flags
  UintR tableSchemaVersion;   // DATA 5
  UintR transId1;             // DATA 6
  UintR transId2;             // DATA 7

  // ----------------------------------------------------------------------
  //  Conditional part = can be present in signal.
  //  These four words will be sent only if their indicator is set.
  // ----------------------------------------------------------------------
  UintR scanInfo;             // DATA 8   Various flags for scans
  UintR distrGroupHashValue;  // DATA 9
  UintR distributionKeySize;  // DATA 10
  UintR storedProcId;         // DATA 11

  // ----------------------------------------------------------------------
  //  Variable sized KEY and ATTRINFO part.
  //  These will be placed to pack the signal in an appropriate manner.
  // ----------------------------------------------------------------------
  UintR keyInfo[MaxKeyInfo];           // DATA 12 - 19
  UintR attrInfo[MaxAttrInfo];          // DATA 20 - 24

  /**
   * Get:ers for attrLen
   */

  static Uint16  getAPIVersion(const UintR & attrLen);
  static Uint16  getAttrinfoLen(const UintR & attrLen);
  static void setAPIVersion(UintR & attrLen, Uint16 apiVersion);
  static void setAttrinfoLen(UintR & attrLen, Uint16 aiLen);

  /**
   * Get:ers for requestInfo
   */
  static Uint8 getCommitFlag(const UintR & requestInfo);
  static Uint8 getAbortOption(const UintR & requestInfo);
  static Uint8 getStartFlag(const UintR & requestInfo);
  static Uint8 getSimpleFlag(const UintR & requestInfo);
  static Uint8 getDirtyFlag(const UintR & requestInfo);
  static Uint8 getInterpretedFlag(const UintR & requestInfo);
  static Uint8 getDistributionKeyFlag(const UintR & requestInfo);
  static Uint8 getScanIndFlag(const UintR & requestInfo);
  static Uint8 getOperationType(const UintR & requestInfo);
  static Uint8 getExecuteFlag(const UintR & requestInfo);

  static Uint16 getKeyLength(const UintR & requestInfo);
  static Uint8  getAIInTcKeyReq(const UintR & requestInfo);
  static Uint8  getExecutingTrigger(const UintR & requestInfo);
  static UintR  getNoDiskFlag(const UintR & requestInfo);

  /**
   * Get:ers for scanInfo
   */
  static Uint8  getTakeOverScanFlag(const UintR & scanInfo);
  static Uint16 getTakeOverScanFragment(const UintR & scanInfo);
  static Uint32 getTakeOverScanInfo(const UintR & scanInfo);

  /**
   * Set:ers for requestInfo
   */
  static void clearRequestInfo(UintR & requestInfo);
  static void setAbortOption(UintR & requestInfo, Uint32 type);
  static void setCommitFlag(UintR & requestInfo, Uint32 flag);
  static void setStartFlag(UintR & requestInfo, Uint32 flag);
  static void setSimpleFlag(UintR & requestInfo, Uint32 flag);
  static void setDirtyFlag(UintR & requestInfo, Uint32 flag);
  static void setInterpretedFlag(UintR & requestInfo, Uint32 flag);
  static void setDistributionKeyFlag(UintR & requestInfo, Uint32 flag);
  static void setScanIndFlag(UintR & requestInfo, Uint32 flag);
  static void setExecuteFlag(UintR & requestInfo, Uint32 flag);
  static void setOperationType(UintR & requestInfo, Uint32 type);

  static void setKeyLength(UintR & requestInfo, Uint32 len);
  static void setAIInTcKeyReq(UintR & requestInfo, Uint32 len);
  static void setExecutingTrigger(UintR & requestInfo, Uint32 flag);
  static void setNoDiskFlag(UintR & requestInfo, UintR val);

  /**
   * Set:ers for scanInfo
   */
  static void setTakeOverScanFlag(UintR & scanInfo, Uint8 flag);
  static void setTakeOverScanFragment(UintR & scanInfo, Uint16 fragment);
  static void setTakeOverScanInfo(UintR & scanInfo, Uint32 aScanInfo);
};

/**
 * Request Info
 *
 a = Attr Info in TCKEYREQ - 3  Bits -> Max 7 (Bit 16-18)
 b = Distribution Key Ind  - 1  Bit 2
 c = Commit Indicator      - 1  Bit 4
 d = Dirty Indicator       - 1  Bit 0
 e = Scan Indicator        - 1  Bit 14
 f = Execute fired trigger - 1  Bit 19
 i = Interpreted Indicator - 1  Bit 15
 k = Key length            - 12 Bits -> Max 4095 (Bit 20 - 31)
 o = Operation Type        - 3  Bits -> Max 7 (Bit 5-7)
 l = Execute               - 1  Bit 10
 p = Simple Indicator      - 1  Bit 8
 s = Start Indicator       - 1  Bit 11
 y = Commit Type           - 2  Bit 12-13
 n = No disk flag          - 1  Bit 1

           1111111111222222222233
 01234567890123456789012345678901
 dnb cooop lsyyeiaaafkkkkkkkkkkkk
*/

#define TCKEY_NODISK_SHIFT (1)
#define COMMIT_SHIFT       (4)
#define START_SHIFT        (11)
#define SIMPLE_SHIFT       (8)
#define DIRTY_SHIFT        (0)
#define EXECUTE_SHIFT      (10)
#define INTERPRETED_SHIFT  (15)
#define DISTR_KEY_SHIFT    (2)
#define SCAN_SHIFT         (14)

#define OPERATION_SHIFT   (5)
#define OPERATION_MASK    (7)

#define AINFO_SHIFT       (16)
#define AINFO_MASK        (7)

#define KEY_LEN_SHIFT     (20)
#define KEY_LEN_MASK      (4095)

#define COMMIT_TYPE_SHIFT  (12)
#define COMMIT_TYPE_MASK   (3)

#define EXECUTING_TRIGGER_SHIFT (19)

/**
 * Scan Info
 *
 t = Scan take over indicator -  1 Bit
 n = Take over node           - 12 Bits -> max 65535
 p = Scan Info                - 18 Bits -> max 4095

           1111111111222222222233
 01234567890123456789012345678901
 tpppppppppppppppppp nnnnnnnnnnnn
*/

#define TAKE_OVER_SHIFT      (0)

#define TAKE_OVER_FRAG_SHIFT (20)
#define TAKE_OVER_FRAG_MASK  (4095)

#define SCAN_INFO_SHIFT      (1)
#define SCAN_INFO_MASK       (262143)

/**
 * Attr Len
 *
 n = Attrinfo length(words)   - 16 Bits -> max 65535
 a = API version no           - 16 Bits -> max 65535

           1111111111222222222233
 01234567890123456789012345678901
 aaaaaaaaaaaaaaaannnnnnnnnnnnnnnn
*/

#define API_VER_NO_SHIFT     (16)
#define API_VER_NO_MASK      (65535)

#define ATTRLEN_SHIFT        (0)
#define ATTRLEN_MASK         (65535)

inline
Uint8
TcKeyReq::getCommitFlag(const UintR & requestInfo){
  return (Uint8)((requestInfo >> COMMIT_SHIFT) & 1);
}

inline
Uint8
TcKeyReq::getAbortOption(const UintR & requestInfo){
  return (Uint8)((requestInfo >> COMMIT_TYPE_SHIFT) & COMMIT_TYPE_MASK);
}

inline
Uint8
TcKeyReq::getStartFlag(const UintR & requestInfo){
  return (Uint8)((requestInfo >> START_SHIFT) & 1);
}

inline
Uint8
TcKeyReq::getSimpleFlag(const UintR & requestInfo){
  return (Uint8)((requestInfo >> SIMPLE_SHIFT) & 1);
}

inline
Uint8
TcKeyReq::getExecuteFlag(const UintR & requestInfo){
  return (Uint8)((requestInfo >> EXECUTE_SHIFT) & 1);
}

inline
Uint8
TcKeyReq::getDirtyFlag(const UintR & requestInfo){
  return (Uint8)((requestInfo >> DIRTY_SHIFT) & 1);
}

inline
Uint8
TcKeyReq::getInterpretedFlag(const UintR & requestInfo){
  return (Uint8)((requestInfo >> INTERPRETED_SHIFT) & 1);
}

inline
Uint8
TcKeyReq::getDistributionKeyFlag(const UintR & requestInfo){
  return (Uint8)((requestInfo >> DISTR_KEY_SHIFT) & 1);
}

inline
Uint8
TcKeyReq::getScanIndFlag(const UintR & requestInfo){
  return (Uint8)((requestInfo >> SCAN_SHIFT) & 1);
}

inline
Uint8
TcKeyReq::getOperationType(const UintR & requestInfo){
  return (Uint8)((requestInfo >> OPERATION_SHIFT) & OPERATION_MASK);
}

inline
Uint16
TcKeyReq::getKeyLength(const UintR & requestInfo){
  return (Uint16)((requestInfo >> KEY_LEN_SHIFT) & KEY_LEN_MASK);
}

inline
Uint8
TcKeyReq::getAIInTcKeyReq(const UintR & requestInfo){
  return (Uint8)((requestInfo >> AINFO_SHIFT) & AINFO_MASK);
}

inline
Uint8
TcKeyReq::getExecutingTrigger(const UintR & requestInfo){
  return (Uint8)((requestInfo >> EXECUTING_TRIGGER_SHIFT) & 1);
}

inline
void
TcKeyReq::clearRequestInfo(UintR & requestInfo){
  requestInfo = 0;
}

inline
void
TcKeyReq::setAbortOption(UintR & requestInfo, Uint32 type){
  ASSERT_MAX(type, COMMIT_TYPE_MASK, "TcKeyReq::setAbortOption");
  requestInfo &= ~(COMMIT_TYPE_MASK << COMMIT_TYPE_SHIFT);
  requestInfo |= (type << COMMIT_TYPE_SHIFT);
}

inline
void
TcKeyReq::setCommitFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setCommitFlag");
  requestInfo &= ~(1 << COMMIT_SHIFT);
  requestInfo |= (flag << COMMIT_SHIFT);
}

inline
void
TcKeyReq::setStartFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setStartFlag");
  requestInfo &= ~(1 << START_SHIFT);
  requestInfo |= (flag << START_SHIFT);
}

inline
void
TcKeyReq::setSimpleFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setSimpleFlag");
  requestInfo &= ~(1 << SIMPLE_SHIFT);
  requestInfo |= (flag << SIMPLE_SHIFT);
}

inline
void
TcKeyReq::setDirtyFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setDirstFlag");
  requestInfo &= ~(1 << DIRTY_SHIFT);
  requestInfo |= (flag << DIRTY_SHIFT);
}

inline
void
TcKeyReq::setExecuteFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setExecuteFlag");
  requestInfo &= ~(1 << EXECUTE_SHIFT);
  requestInfo |= (flag << EXECUTE_SHIFT);
}

inline
void
TcKeyReq::setInterpretedFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setInterpretedFlag");
  requestInfo &= ~(1 << INTERPRETED_SHIFT);
  requestInfo |= (flag << INTERPRETED_SHIFT);
}

inline
void
TcKeyReq::setDistributionKeyFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setDistributionKeyFlag");
  requestInfo &= ~(1 << DISTR_KEY_SHIFT);
  requestInfo |= (flag << DISTR_KEY_SHIFT);
}

inline
void
TcKeyReq::setScanIndFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setScanIndFlag");
  requestInfo &= ~(1 << SCAN_SHIFT);
  requestInfo |= (flag << SCAN_SHIFT);
}

inline
void
TcKeyReq::setOperationType(UintR & requestInfo, Uint32 type){
  ASSERT_MAX(type, OPERATION_MASK, "TcKeyReq::setOperationType");
  requestInfo &= ~(OPERATION_MASK << OPERATION_SHIFT);
  requestInfo |= (type << OPERATION_SHIFT);
}

inline
void
TcKeyReq::setKeyLength(UintR & requestInfo, Uint32 len){
  ASSERT_MAX(len, KEY_LEN_MASK, "TcKeyReq::setKeyLength");
  requestInfo &= ~(KEY_LEN_MASK << KEY_LEN_SHIFT);
  requestInfo |= (len << KEY_LEN_SHIFT);
}

inline
void
TcKeyReq::setAIInTcKeyReq(UintR & requestInfo, Uint32 len){
  ASSERT_MAX(len, AINFO_MASK, "TcKeyReq::setAIInTcKeyReq");
  requestInfo &= ~(AINFO_MASK << AINFO_SHIFT);
  requestInfo |= (len << AINFO_SHIFT);
}

inline
void
TcKeyReq::setExecutingTrigger(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setExecutingTrigger");
  requestInfo &= ~(1 << EXECUTING_TRIGGER_SHIFT);
  requestInfo |= (flag << EXECUTING_TRIGGER_SHIFT);
}

inline
Uint8
TcKeyReq::getTakeOverScanFlag(const UintR & scanInfo){
  return (Uint8)((scanInfo >> TAKE_OVER_SHIFT) & 1);
}

inline
Uint16
TcKeyReq::getTakeOverScanFragment(const UintR & scanInfo){
  return (Uint16)((scanInfo >> TAKE_OVER_FRAG_SHIFT) & TAKE_OVER_FRAG_MASK);
}

inline
Uint32
TcKeyReq::getTakeOverScanInfo(const UintR & scanInfo){
  return (Uint32)((scanInfo >> SCAN_INFO_SHIFT) & SCAN_INFO_MASK);
}

inline
void
TcKeyReq::setTakeOverScanFlag(UintR & scanInfo, Uint8 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setTakeOverScanFlag");
  scanInfo |= (flag << TAKE_OVER_SHIFT);
}

inline
void
TcKeyReq::setTakeOverScanFragment(UintR & scanInfo, Uint16 node){
//  ASSERT_MAX(node, TAKE_OVER_NODE_MASK, "TcKeyReq::setTakeOverScanNode");
  scanInfo |= (node << TAKE_OVER_FRAG_SHIFT);
}

inline
void
TcKeyReq::setTakeOverScanInfo(UintR & scanInfo, Uint32 aScanInfo){
//  ASSERT_MAX(aScanInfo, SCAN_INFO_MASK, "TcKeyReq::setTakeOverScanInfo");
  scanInfo |= (aScanInfo << SCAN_INFO_SHIFT);
}

inline
Uint16
TcKeyReq::getAPIVersion(const UintR & anAttrLen){
  return (Uint16)((anAttrLen >> API_VER_NO_SHIFT) & API_VER_NO_MASK);
}

inline
void
TcKeyReq::setAPIVersion(UintR & anAttrLen, Uint16 apiVersion){
// ASSERT_MAX(apiVersion, API_VER_NO_MASK, "TcKeyReq::setAPIVersion");
  anAttrLen |= (apiVersion << API_VER_NO_SHIFT);
}

inline
Uint16
TcKeyReq::getAttrinfoLen(const UintR & anAttrLen){
  return (Uint16)((anAttrLen) & ATTRLEN_MASK);
}

inline
void
TcKeyReq::setAttrinfoLen(UintR & anAttrLen, Uint16 aiLen){
//  ASSERT_MAX(aiLen, ATTRLEN_MASK, "TcKeyReq::setAttrinfoLen");
  anAttrLen |= aiLen;
}

inline
UintR
TcKeyReq::getNoDiskFlag(const UintR & requestInfo){
  return (requestInfo >> TCKEY_NODISK_SHIFT) & 1;
}

inline
void
TcKeyReq::setNoDiskFlag(UintR & requestInfo, Uint32 flag){
  ASSERT_BOOL(flag, "TcKeyReq::setNoDiskFlag");
  requestInfo &= ~(1 << TCKEY_NODISK_SHIFT);
  requestInfo |= (flag << TCKEY_NODISK_SHIFT);
}

#endif


text:
const {app, dialog, Menu} = require('electron');

// Utilities
const {getConfig} = require('../config');
const {icon} = require('../config/paths');
const viewMenu = require('./menus/view');
const shellMenu = require('./menus/shell');
const editMenu = require('./menus/edit');
const pluginsMenu = require('./menus/plugins');
const windowMenu = require('./menus/window');
const helpMenu = require('./menus/help');
const darwinMenu = require('./menus/darwin');
const {getDecoratedKeymaps} = require('../plugins');
const {execCommand} = require('../commands');

const appName = app.getName();
const appVersion = app.getVersion();

let menu_ = [];

exports.createMenu = (createWindow, getLoadedPluginVersions) => {
  const config = getConfig();
  // We take only first shortcut in array for each command
  const allCommandKeys = getDecoratedKeymaps();
  const commandKeys = Object.keys(allCommandKeys).reduce((result, command) => {
    result[command] = allCommandKeys[command][0];
    return result;
  }, {});

  let updateChannel = 'stable';

  if (config && config.updateChannel && config.updateChannel === 'canary') {
    updateChannel = 'canary';
  }

  const showAbout = () => {
    const loadedPlugins = getLoadedPluginVersions();
    const pluginList =
      loadedPlugins.length === 0 ? 'none' : loadedPlugins.map(plugin => `\n  ${plugin.name} (${plugin.version})`);

    dialog.showMessageBox({
      title: `About ${appName}`,
      message: `${appName} ${appVersion} (${updateChannel})`,
      detail: `Plugins: ${pluginList}\n\nCreated by Guillermo Rauch\nCopyright © 2017 Zeit, Inc.`,
      buttons: [],
      icon
    });
  };
  const menu = [
    ...(process.platform === 'darwin' ? [darwinMenu(commandKeys, showAbout)] : []),
    shellMenu(commandKeys, execCommand),
    editMenu(commandKeys, execCommand),
    viewMenu(commandKeys, execCommand),
    pluginsMenu(commandKeys, execCommand),
    windowMenu(commandKeys, execCommand),
    helpMenu(commandKeys, showAbout)
  ];

  return menu;
};

exports.buildMenu = template => {
  menu_ = Menu.buildFromTemplate(template);
  return menu_;
};


text:
import ShaderSource from "../Renderer/ShaderSource.js";

/**
 * Support for rendering things on only one side of the screen.
 *
 * @private
 */
const Splitter = {
  /**
   * Given a fragment shader string, returns a modified version of it that
   * only renders on one side of the screen or the other. Fragments on the
   * other side are discarded. The screen side is given by a uniform called
   * `czm_splitDirection`, which can be added by calling
   * {@link Splitter#addUniforms}, and the split position is given by an
   * automatic uniform called `czm_splitPosition`.
   */
  modifyFragmentShader: function modifyFragmentShader(shader) {
    shader = ShaderSource.replaceMain(shader, "czm_splitter_main");
    shader +=
      // czm_splitPosition is not declared because it is an automatic uniform.
      "uniform float czm_splitDirection; \n" +
      "void main() \n" +
      "{ \n" +
      // Don't split when rendering the shadow map, because it is rendered from
      // the perspective of a totally different camera.
      "#ifndef SHADOW_MAP\n" +
      "    if (czm_splitDirection < 0.0 && gl_FragCoord.x > czm_splitPosition) discard; \n" +
      "    if (czm_splitDirection > 0.0 && gl_FragCoord.x < czm_splitPosition) discard; \n" +
      "#endif\n" +
      "    czm_splitter_main(); \n" +
      "} \n";

    return shader;
  },

  /**
   * Add `czm_splitDirection` to the given uniform map.
   *
   * @param {Object} object The object on which the `splitDirection` property may be found.
   * @param {Object} uniformMap The uniform map.
   */
  addUniforms: function addUniforms(object, uniformMap) {
    uniformMap.czm_splitDirection = function () {
      return object.splitDirection;
    };
  },
};

export default Splitter;


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('news', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Comment',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('content', models.TextField(default='')),
                ('date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date commented')),
                ('author', models.ForeignKey(default='', null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
                ('related_news', models.ForeignKey(default='', null=True, on_delete=django.db.models.deletion.CASCADE, to='news.News')),
            ],
        ),
    ]


text:
At its most fundamental level, this module translates lists of data and
constraints into name-value pairs of data and contstraints as expected by the
validation functions from [validate.js](https://validatejs.org/).

Consider the following call to this module's
[vaidateParams()]{module:validateParams~validateParams} function:

```
var errs = validateParams(
  ['stuff', 42], // parameter list
  [ // constraints list
    { presence: true }, // constraints for 1st param
    { // constraints for 2nd param
      numericality: {
        onlyInteger: true,
        greaterThanOrEqualTo: 1
      }
    }
  ]
);
```

This gets translated to the following call to  the
[validate()]{@link external:validate} function from `validate.js`:

```
var errs = validate(
  { // attributes object - from parameter list
    param1: 'stuff',
    param2: 42
  },
  { // constrants object - from constraints list
    param1: { presence: true },
    param2: {
      numericality: {
        onlyInteger: true,
        greaterThanOrEqualTo: 1
      }
    }
  }
);
```

You can access the generated attributes and constraints objects if you run the
validation via the
[validateParams.validate()]{@link module:validateParams.validate} function
which returns a [validateParams.Result]{@link module:validateParams.Result}
object:

```
var res = validateParams.validate(
  ['stuff', 42],
  [
    { presence: true },
    {
      numericality: {
        onlyInteger: true,
        greaterThanOrEqualTo: 1
      }
    }
  ]
);
console.log('the generated attributes object', res.validateAttributes());
console.log('the generated constraints object', res.validateConstraints());
```

The per-parameter option `name` can be used to customise the names.

Consider the following call to `validateParams.validate()`:

```
var res = validateParams.validate(
  ['stuff', 42],
  [
    {
      presence: true,
      vpopt_name: 'str'
    },
    {
      numericality: {
        onlyInteger: true,
        greaterThanOrEqualTo: 1
      },
      vpopt_name: 'repeatBy'
    }
  ]
);
```

This will result in the following attributes object being generated:

```
{
  str: 'stuff',
  repeatBy: 42
}
```

And the following constraints object:

```
{
  str: { presence: true },
  repeatBy: {
    numericality: {
      onlyInteger: true,
      greaterThanOrEqualTo: 1
    }
  }
}
```

This per-paramter option is particuarlly useful when combined with one of the
data defaulting per-parameter options, or with coercion:

```
function stringRepeater(){
  var args = validateParams.assert(
    arguments,
    [
      {
        presence: true,
        paramOptions: {
          name: 'str',
          coerce: function(v){
            if(validateParams.validateJS().isEmpty(v)){
              return undefined;
            }
            return String(v); }
        }
      },
      {
        numericality: {
          onlyInteger: true,
          greaterThanOrEqualTo: 1
        },
        paramOptions: {
          name: 'n',
          defaultWhenEmpty: 1
        }
      }
    ]
  );

  var ans = args.str;
  while(args.n > 1){
    ans += args.str;
    args.n--;
  }
  return ans;
}
console.log(stringRepeater()); // throws validation error
console.log(stringRepeater('stuff')); // logs 'stuff'
console.log(stringRepeater('stuff', 3)); // logs 'stuffstuffstuff'
```


text:
package io.realm.realmloginkit.util;

public class UriHelper {
    public static String getValidAuthUri(String uri) {
        String scheme = "http";
        String host = uri;
        String path = "/auth";
        int port = 9080;

        final String delimiter = "://";
        final int schemeEnd = uri.indexOf("://");
        if (schemeEnd != -1) {
            final String lowerCase = uri.toLowerCase();
            if (lowerCase.startsWith("https") || lowerCase.startsWith("realms")) {
                port = 9443;
                scheme = "https";
            }
            host = host.substring(schemeEnd + delimiter.length());
        }

        final int pathStart = host.indexOf('/');
        if (pathStart != -1) {
            path = host.substring(pathStart);
            host = host.substring(0, pathStart);
        }

        final int portStart = host.indexOf(":");
        if (portStart != -1) {
            port = Integer.parseInt(host.substring(portStart + 1));
            host = host.substring(0, portStart);
        }

        final String authUri = String.format("%1$s://%2$s:%3$d%4$s", scheme, host, port, path);
        return authUri;
    }
}


text:
namespace System.Windows.Forms
{
    using System.Drawing;

    public class DrawTreeNodeEventArgs : EventArgs
    {
        public DrawTreeNodeEventArgs(Graphics graphics, TreeNode node, Rectangle bounds, TreeNodeStates state)
        {
            Graphics = graphics;
            Node = node;
            Bounds = bounds;
            State = state;
        }

        public Rectangle Bounds { get; internal set; }
        public bool DrawDefault { get; internal set; }
        public Graphics Graphics { get; internal set; }
        public TreeNode Node { get; internal set; }
        public TreeNodeStates State { get; internal set; }
    }
}


text:
//----------------------------------------------------------------
// <copyright company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//----------------------------------------------------------------

namespace System.Activities.Presentation.FreeFormEditing
{
    /// <summary>
    /// Defines alignment for auto-split
    /// </summary>
    internal enum AutoSplitAlignment
    {
        /// <summary>
        /// No alignment
        /// </summary>
        None,

        /// <summary>
        /// Vertical alignment
        /// </summary>
        Vertical,

        /// <summary>
        /// Horizontal alignment
        /// </summary>
        Horizontal
    }
}


text:
type: reference
stage: Manage
group: Access
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#designated-technical-writers
---

# Authentiq OmniAuth Provider

To enable the Authentiq OmniAuth provider for passwordless authentication you must register an application with Authentiq.

Authentiq will generate a Client ID and the accompanying Client Secret for you to use.

1. Get your Client credentials (Client ID and Client Secret) at [Authentiq](https://www.authentiq.com/developers).

1. On your GitLab server, open the configuration file:

   For omnibus installation

   ```shell
   sudo editor /etc/gitlab/gitlab.rb
   ```

   For installations from source:

   ```shell
   sudo -u git -H editor /home/git/gitlab/config/gitlab.yml
   ```

1. See [Initial OmniAuth Configuration](../../integration/omniauth.md#initial-omniauth-configuration) for initial settings to enable single sign-on and add Authentiq as an OAuth provider.

1. Add the provider configuration for Authentiq:

   For Omnibus packages:

   ```ruby
   gitlab_rails['omniauth_providers'] = [
     {
       "name" => "authentiq",
       "app_id" => "YOUR_CLIENT_ID",
       "app_secret" => "YOUR_CLIENT_SECRET",
       "args" => {
              "scope": 'aq:name email~rs address aq:push'
        }
     }
   ]
   ```

   For installations from source:

   ```yaml
   - { name: 'authentiq',
       app_id: 'YOUR_CLIENT_ID',
       app_secret: 'YOUR_CLIENT_SECRET',
       args: {
              scope: 'aq:name email~rs address aq:push'
             }
     }
   ```

1. The `scope` is set to request the user's name, email (required and signed), and permission to send push notifications to sign in on subsequent visits.
   See [OmniAuth Authentiq strategy](https://github.com/AuthentiqID/omniauth-authentiq/wiki/Scopes,-callback-url-configuration-and-responses) for more information on scopes and modifiers.

1. Change `YOUR_CLIENT_ID` and `YOUR_CLIENT_SECRET` to the Client credentials you received in step 1.

1. Save the configuration file.

1. [Reconfigure](../restart_gitlab.md#omnibus-gitlab-reconfigure) or [restart GitLab](../restart_gitlab.md#installations-from-source) for the changes to take effect if you installed GitLab via Omnibus or from source respectively.

On the sign in page there should now be an Authentiq icon below the regular sign in form. Click the icon to begin the authentication process.

- If the user has the Authentiq ID app installed in their iOS or Android device, they can:
  1. Scan the QR code.
  1. Decide what personal details to share.
  1. Sign in to your GitLab installation.
- If not they will be prompted to download the app and then follow the procedure above.

If everything goes right, the user will be returned to GitLab and will be signed in.

<!-- ## Troubleshooting

Include any troubleshooting steps that you can foresee. If you know beforehand what issues
one might have when setting this up, or when something is changed, or on upgrading, it's
important to describe those, too. Think of things that may go wrong and include them here.
This is important to minimize requests for support, and to avoid doc comments with
questions that you know someone might ask.

Each scenario can be a third-level heading, e.g. `### Getting error message X`.
If you have none to add when creating a doc, leave this section in place
but commented out to help encourage others to add to it in the future. -->


text:
<navbar></navbar>

About

Famous Places is a web game where you can test your geography knowledge about famous places around the world. You can also compete against your friends! To play, you need to have a smartphone device, as it will be used as your controller.

Credits

Images

Old Earth Map - Artistic Wallpapers from
            wallpapercave.com

          All photos of places used in the game are hosted by Flickr and are allowed by Flickr to be shared through the Flickr API.

Music

"Fingerpoppin'" by
              Purple Planet

"Arum Bandung" by unknown, from
              asianclassicalmp3.org

"Albinoni - Concerto for 2 Oboes in F Major Op9 no3, 1 Allegro" by Advent Chamber Orchestra from
              Free Music Archive

"Airport Lounge" by Kevin MacLeod from incompetech.com

              Licensed under Creative Commons: By Attribution 3.0

              The Elevator Bossa Nova from www.bensound.com

Sounds Effects

Ta Da by Mike Koenig from soundbible.com

Mario Jumping by Mike Koenig from soundbible.com

Tick by DeepFrozenApps from soundbible.com

Tiny Button Push by Mike Koenig from soundbible.com

Glass Ping by Go445 from soundbible.com

Reverse by Mike Koenig from soundbible.com

Technologies

This web app uses the following technologies prominently:

                    {{item.title}}

Author

My name is Hendry. I'm a student in computer science major in Binus University.

This web application is made by me for my graduation thesis project. The source code are open, and can be accessed at https://github.com/hendryl.


text:
Static-Website-Boilerplate
=======================

Boilerplate for static websites SASS, CoffeeScript (with sourcemaps support), compiled with Gulp

## Dependencies
- npm
- bower => `npm install -g bower`

## Using the Boilerplate
- Clone this repo `git clone https://github.com/hc2p/website-boilerplate.git`
- `npm install`
- `bower install`
- `gulp`
- Go make stuff.


text:
<?php
/**
 * YanPHP
 * User: weilongjiang(江炜隆)<willliam@jwlchina.cn>
 * Date: 2017/8/31
 * Time: 21:43
 */

namespace Yan\Core;

use Assert\Assertion as BaseAssertion;

class YAssert extends BaseAssertion
{
    protected static $exceptionClass = 'Yan\Core\Exception\YAssertionFailedException';

    /**
     * Helper method that handles building the assertion failure exceptions.
     * They are returned from this method so that the stack trace still shows
     * the assertions method.
     *
     * @param mixed           $value
     * @param string|callable $message
     * @param int             $code
     * @param string|null     $propertyPath
     * @param array           $constraints
     *
     * @return mixed
     */
    protected static function createException($value, $message, $code, $propertyPath = null, array $constraints = array())
    {
        $exceptionClass = static::$exceptionClass;

        return new $exceptionClass($message, ReturnCode::INVALID_ARGUMENT, $propertyPath, $value, $constraints);
    }
}


text:
<?php

namespace Kenjis\MonkeyPatch\Patcher;

require __DIR__ . '/ConstantPatcher/NodeVisitor.php';
require __DIR__ . '/ConstantPatcher/Proxy.php';

use LogicException;

use Kenjis\MonkeyPatch\Patcher\ConstantPatcher\NodeVisitor;

class ConstantPatcher extends AbstractPatcher
{
	/**
	 * @var special constant names which we don't patch
	 */
	private static $blacklist = [
		'true',
		'false',
		'null',
	];

	public static $replacement;

	public function __construct()
	{
		$this->node_visitor = new NodeVisitor();
	}

	/**
	 * @param string $name constant name
	 * @return boolean
	 */
	public static function isBlacklisted($name)
	{
		if (in_array(strtolower($name), self::$blacklist))
		{
			return true;
		}

		return false;
	}

	protected static function generateNewSource($source)
	{
		$tokens = token_get_all($source);
		$new_source = '';
		$i = -1;

		ksort(self::$replacement);
		reset(self::$replacement);
		$replacement['key'] = key(self::$replacement);
		$replacement['value'] = current(self::$replacement);
		next(self::$replacement);
		if ($replacement['key'] === null)
		{
			$replacement = false;
		}

		foreach ($tokens as $token)
		{
			$i++;

			if (is_string($token))
			{
				$new_source .= $token;
			}
			elseif ($i == $replacement['key'])
			{
				$new_source .= $replacement['value'];
				$replacement['key'] = key(self::$replacement);
				$replacement['value'] = current(self::$replacement);
				next(self::$replacement);
				if ($replacement['key'] === null)
				{
					$replacement = false;
				}
			}
			else
			{
				$new_source .= $token[1];
			}
		}

		if ($replacement !== false)
		{
			throw new LogicException('Replacement data still remain');
		}

		return $new_source;
	}
}


text:
package fullcodes.session.accessModifiers;

/**
 * Created by dotcom on 6/30/17.
 */
public class CurrentAccount extends Account{

    protected void payIn(){
        System.out.println(amountInTheWill);
        System.out.println("Paying some cash in to the account");
    }
}


text:
package rx.internal.schedulers;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import java.lang.reflect.Method;
import java.util.concurrent.*;

import org.junit.Test;

public class NewThreadWorkerTest {

    @Test
    public void findSetRemoveOnCancelPolicyMethodShouldFindMethod() {
        ScheduledExecutorService executor = spy(new ScheduledThreadPoolExecutor(1));
        Method setRemoveOnCancelPolicyMethod = NewThreadWorker.findSetRemoveOnCancelPolicyMethod(executor);

        assertNotNull(setRemoveOnCancelPolicyMethod);
        assertEquals("setRemoveOnCancelPolicy", setRemoveOnCancelPolicyMethod.getName());
        assertEquals(1, setRemoveOnCancelPolicyMethod.getParameterTypes().length);
        assertEquals(Boolean.TYPE, setRemoveOnCancelPolicyMethod.getParameterTypes()[0]);
        verifyZeroInteractions(executor);
    }

    @Test
    public void findSetRemoveOnCancelPolicyMethodShouldNotFindMethod() {
        ScheduledExecutorService executor = mock(ScheduledExecutorService.class);

        Method setRemoveOnCancelPolicyMethod = NewThreadWorker.findSetRemoveOnCancelPolicyMethod(executor);
        assertNull(setRemoveOnCancelPolicyMethod);
        verifyZeroInteractions(executor);
    }

    private static abstract class ScheduledExecutorServiceWithSetRemoveOnCancelPolicy implements ScheduledExecutorService {
        // Just declaration of required method to allow run tests on JDK 6
        public void setRemoveOnCancelPolicy(boolean value) { }
    }

    @Test
    public void tryEnableCancelPolicyShouldInvokeMethodOnExecutor() {
        ScheduledExecutorServiceWithSetRemoveOnCancelPolicy executor
                = mock(ScheduledExecutorServiceWithSetRemoveOnCancelPolicy.class);

        boolean result = NewThreadWorker.tryEnableCancelPolicy(executor);

        assertTrue(result);
        verify(executor).setRemoveOnCancelPolicy(true);
        verifyNoMoreInteractions(executor);
    }

    @Test
    public void tryEnableCancelPolicyShouldNotInvokeMethodOnExecutor() {
        // This executor does not have setRemoveOnCancelPolicy method
        ScheduledExecutorService executor = mock(ScheduledExecutorService.class);

        boolean result = NewThreadWorker.tryEnableCancelPolicy(executor);

        assertFalse(result);
        verifyZeroInteractions(executor);
    }
}


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

	<groupId>groupId</groupId>
	<artifactId>Game21</artifactId>
	<version>1.0</version>

	<properties>
		<java.version>1.8</java.version>
		<packaging.type>jar</packaging.type>
	</properties>
	<profiles>
		<profile>
			<id>war</id>
			<properties>
				<packaging.type>war</packaging.type>
			</properties>
			<dependencies>
				<dependency>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-tomcat</artifactId>
					<scope>provided</scope>
				</dependency>
			</dependencies>
			<build>
				<finalName>${project.artifactId}</finalName>
				<plugins>
					<plugin>
						<groupId>org.springframework.boot</groupId>
						<artifactId>spring-boot-maven-plugin</artifactId>
					</plugin>
					<plugin>
						<artifactId>maven-clean-plugin</artifactId>
						<version>2.5</version>
						<executions>
							<execution>
								<id>auto-clean</id>
								<phase>initialize</phase>
								<goals>
									<goal>clean</goal>
								</goals>
							</execution>
						</executions>
					</plugin>
				</plugins>
			</build>
		</profile>
	</profiles>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.4.2.RELEASE</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-autoconfigure</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-spring-service-connector</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-localconfig-connector</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-cloudfoundry-connector</artifactId>
		</dependency>

	</dependencies>

	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>


text:
<?php

namespace Fannan\MembersModule\Test\Unit\Gold;

class GoldRepositoryTest extends \TestCase
{

}


text:
using InterflowFramework.Core.Message;
using InterflowFramework.Core.Message.Interface;
using InterflowFramework.Core.Message.Model.Html;
using InterflowFramework.Core.Message.Model.Json;
using InterflowFrameworkRunner.TestProvider;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterflowFrameworkRunner.TestCase.ByMessageType.JsonTextImport
{
	class JsonTextImport : ITest
	{
		IMessageRequestProvider requestProvider = new JsonMessageRequestProvider();
		public void Execute()
		{
			var text = GetInputText();
			var message = GetMessage(text);
			var request1 = GetTestMessageRequest();
			var response = message.ExecuteRequest(request1);
			var textResponse = response as JsonMessageRequestResponse;
			if (textResponse != null)
			{
				textResponse
					.GetResponse()
					.Where(x => x != null)
					.All(x =>
					{
						Console.WriteLine(x);
						return true;
					});
			}
		}
		protected string GetInputText()
		{
			using (var reader = new StreamReader(new FileStream(@"C:\Dev\All Stuff\InterflowFramework\InterflowFramework\InterflowFrameworkRunner\TestCase\ByMessageType\Json\inputText.txt", FileMode.Open)))
			{
				return reader.ReadToEnd();
			}
		}
		protected IMessage GetMessage(string text)
		{
			var provider = new JsonMessageProvider();
			return provider.Create(text);
		}
		protected IMessageRequest GetTestMessageRequest()
		{
			return requestProvider.CreateRequest(@"jpaths:test.a1");
		}
	}
}


text:
<?php

namespace Flipbox\Craft3\Spark\Controllers\Traits;

use Craft;
use craft\app\errors\HttpException;
use Flipbox\Craft3\Spark\Exceptions\InvalidControllerServiceException;
use Flipbox\Craft3\Spark\Exceptions\InvalidModelException;
use Flipbox\Craft3\Spark\Models\Interfaces\ModelInterface;
use Flipbox\Craft3\Spark\Services\Interfaces\SavableModelAccessorInterface;
use Flipbox\Craft3\Spark\Services\ModelAccessorByIdOrHandle;

trait SaveActionTrait
{

    /*******************************************
     * ABSTRACTS
     *******************************************/

    /**
     * @return SavableModelAccessorInterface|ModelAccessorByIdOrHandle
     */
    abstract protected function getService();

    /**
     * @param $error
     * @return mixed
     */
    abstract public function returnErrorJson($error);

    /**
     * @param array $var
     * @return mixed
     */
    abstract public function returnJson($var = array());

    /**
     * @param null $object
     * @param null $default
     * @return mixed
     */
    abstract public function redirectToPostedUrl($object = null, $default = null);

    /**
     * @return mixed
     */
    abstract public function requirePostRequest();

    /**
     * @return mixed
     */
    abstract public function requireAdmin();

    /*******************************************
     * PERMISSIONS
     *******************************************/

    /**
     * @throws InvalidControllerServiceException
     */
    protected function canSave()
    {

        if (!$this->getService() instanceof SavableModelAccessorInterface) {

            throw new InvalidControllerServiceException(sprintf(
                "Controller service must implement '%s'.",
                'Flipbox\Craft3\Spark\Services\Interfaces\SavableModelAccessorInterface'
            ));

        }

        // Require admin role
        $this->requireAdmin();

        // we require post data
        $this->requirePostRequest();

        return true;

    }

    /**
     * @param ModelInterface $model
     * @return mixed
     */
    protected function saveSuccessMessage(ModelInterface $model)
    {
        return sprintf(
            "'%s' was saved successfully",
            (string)$model
        );
    }

    /**
     * @param ModelInterface $model
     * @return mixed
     */
    protected function saveSuccessJsonResponse(ModelInterface $model)
    {
        return $this->returnJson(array(
                'success' => true,
                'message' => $this->saveSuccessMessage($model),
                'data' => $model
            )
        );
    }

    /**
     * @param ModelInterface $model
     * @return mixed
     */
    protected function saveFailMessage(ModelInterface $model)
    {
        return sprintf(
            "'%s' was NOT saved successfully",
            (string)$model
        );
    }

    /**
     * @param ModelInterface $model
     * @return mixed
     */
    protected function saveFailJsonResponse(ModelInterface $model)
    {
        return $this->returnErrorJson(array(
                'success' => false,
                'errors' => $model->getErrors()
            )
        );
    }

    /**
     * @param ModelInterface $model
     * @return mixed
     */
    protected function saveRouteVariables(ModelInterface $model)
    {
        return array(
            'model' => $model
        );
    }

    /**
     * @return array
     */
    public function getSaveData()
    {
        return Craft::$app->getRequest()->getBodyParams();
    }

    /**
     * Standard save action.  Attempt to get posted 'id' and an array of 'fields'.
     *
     * @throws HttpException
     */
    public function actionSave()
    {

        // Check if we can save
        $this->canSave();

        // hidden field
        $id = Craft::$app->getRequest()->getBodyParam('identifier');

        if (!empty($id)) {

            try {

                $model = $this->getService()->getById($id);

            } catch (InvalidModelException $e) {

                throw new HttpException(500, $e->getMessage());

            }

        } else {

            $model = $this->getService()->create();

        }

        // set post data as attributes
        $model->setAttributes(
            $this->getSaveData()
        );

        // Allow controllers to perform additional actions
        $this->onBeforeSave($model);

        // perform save action against service
        if ($this->getService()->save($model)) {

            // Allow controllers to perform additional actions
            $this->onAfterSave($model);

            // Handle AJAX calls
            if (Craft::$app->getRequest()->getIsAjax()) {

                return $this->saveSuccessJsonResponse($model);

            }

            // Set flash success notice
            Craft::$app->getSession()->setNotice(
                $this->saveSuccessMessage($model)
            );

            return $this->redirectToPostedUrl($model);

        }

        // Handle AJAX calls
        if (Craft::$app->getRequest()->getIsAjax()) {

            return $this->saveFailJsonResponse($model);

        }

        // set flash success notice
        Craft::$app->getSession()->setError(
            $this->saveFailMessage($model)
        );

        // set model
        Craft::$app->getUrlManager()->setRouteParams(
            $this->saveRouteVariables($model)
        );

    }

    /**
     * Allow manipulations to model prior to saving.
     *
     * @param ModelInterface $model
     * @return ModelInterface
     */
    protected function onBeforeSave(ModelInterface $model)
    {
        return $model;
    }

    /**
     * Allow manipulations to model after to saving.
     *
     * @param ModelInterface $model
     * @return ModelInterface
     */
    protected function onAfterSave(ModelInterface $model)
    {
        return $model;
    }

}


text:
import sys

from reclass_tools import helpers
from reclass_tools import reclass_models

def create_inventory_context(domain=None, keys=None):
    """Dumps the current inventory per domain

    Example of context:

    <global_settings>: # only if required
      ...
    current_clusters:
      <cluster_names>:
        # here are cluster settings if required
        nodes:
          <node_names>:
            name: ctl01
            reclass_storage_name: openstack_control_node01
            roles:
            - vcp        # 'vcp' or None
            parameters:  # specified keys to dump, for example
                         # parameters.linux.network.interface below:
              linux:
                network:
                  interfaces:
                    ..
    """
    inventory = reclass_models.inventory_list(domain=domain)
    vcp_list = reclass_models.vcp_list(domain=domain, inventory=inventory)
    reclass_storage = reclass_models.reclass_storage(domain=domain,
                                                     inventory=inventory)

    if domain is None:
        sys.exit("Error: please specify a domain name from: \n{}"
                 .format('\n'.join(reclass_storage.keys())))

    for storage_domain, storage_nodes in reclass_storage.items():
        if storage_domain != domain:
            continue

        current_cluster_nodes = {}
        for storage_node_name, storage_node in storage_nodes.items():
            inventory_node_name = "{0}.{1}".format(storage_node['name'],
                                                   storage_node['domain'])
            current_cluster_nodes[inventory_node_name] = {
                'name': storage_node['name'],
                'reclass_storage_name': storage_node_name,
                'roles': list(),
                'parameters': dict(),
            }

            if (storage_node['name'], storage_node['domain']) in vcp_list:
                # Add role 'vcp' to mark the VM nodes.
                current_cluster_nodes[
                    inventory_node_name]['roles'].append('vcp')

            if keys:
                # Dump specified parameters for the node
                # Will fail with KeyError if 'inventory_node_name' doesn't
                # exists in reclass inventory
                # (wasn't generated with reclass.storage yet, for example)
                node = inventory[inventory_node_name]
                for key in keys:
                    key_path = key.split('.')
                    reclass_key = helpers.get_nested_key(node, path=key_path)
                    if reclass_key:
                        helpers.create_nested_key(
                            current_cluster_nodes[inventory_node_name],
                            path=key_path,
                            value=reclass_key)

        current_underlay_context = {
            'cookiecutter': {
                'cluster_name': storage_domain,
                'nodes': current_cluster_nodes,
            }
        }

    return current_underlay_context


text:
import { generator } from './http-common';

export default generator({
  getFractions: {
    url: 'laboratory/fractions',
    onReject: { fractions: [], title: 'error' },
  },
  getFraction: {
    url: 'laboratory/fraction',
    onReject: { fractions: [], title: 'error' },
  },
  saveFsli: {
    url: 'laboratory/save-fsli',
  },
});


text:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>value_stack::push_double</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.JSON">
<link rel="up" href="../boost__json__value_stack.html" title="value_stack">
<link rel="prev" href="push_uint64.html" title="value_stack::push_uint64">
<link rel="next" href="push_bool.html" title="value_stack::push_bool">

Home
Libraries
People
FAQ
More

value_stack::push_double

          Push a number onto the stack.

          Synopsis

void
push_double(
    double d);

          Description

          This function pushes a number value onto the stack.

          Exception
          Safety

          Basic guarantee. Calls to memory_resource::allocate
          may throw.

          Parameters

<colgroup>
<col>
<col>
</colgroup>

                    Name

                    Description

                    d

                    The number to insert.

Copyright © 2019, 2020 Vinnie Falco
Copyright © 2020 Krystian Stasiowski

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


text:
import sys
import os

sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import json
import random
from bson import json_util
from pymongo import MongoClient
from service.TenantService import TenantService
from service.UserService import UserService
from service.ProductService import ProductService
from service.StoreService import StoreService
from service.PincodeService import PincodeService
import logging

logger = logging.getLogger(__name__)

cuisines = ['north indian', 'south indian',
            'chineese', 'italian', 'english', 'american']
category = ['starter', 'maincourse', 'desserts', 'specials']
food_types = ['veg', 'non-veg']
weekdays = ['Monday', 'Tuesday', 'Wednesday',
            'Thursday', 'Friday', 'Saturday', 'Sunday']
log_enabled = True

def log(msg):
    global log_enabled
    if not log_enabled:
        return
    logger.info(msg)

def create_sample_data(db, tenant_id):
    store_service = StoreService(db)
    store = store_service.get_by_name('Test Store')

    if store is not None:
        log("Sample seed data already created!!")
        return

    for i in range(1, 50):
        store_name = "My Store %d" % (i)
        store = {'tenant_id': tenant_id,
                 'name': store_name,
                 'contact_name': 'test contact',
                 'contact_email': 'test@test.com',
                 'address': 'sample address',
                 'phone': random.randint(600000, 6999999),
                 'food_type': food_types,
                 'holidays': [weekdays[i % len(weekdays)]],
                 'is_closed': False,
                 'rating': 0,
                 'cuisines': [cuisines[i % len(cuisines)], cuisines[i % (len(cuisines) - 1)]],
                 'open_time': random.randint(7, 11),
                 'close_time': random.randint(8, 12),
                 'deliver_time': random.randint(20, 60)}
        store_service.save(store)
        item_count = create_items(db, tenant_id, store['_id'])
        log("Created %s with %d items" % (store_name, item_count))

def create_items(db, tenant_id, store_id):
    product_service = ProductService(db)
    items = product_service.search(tenant_id, store_id)
    if len(items) > 20:
        log('Products already added!')
        return

    item_count = random.randint(20, 50)
    for i in range(0, item_count):
        no = str(random.randint(100, 12563))
        price = random.randint(10, 500)
        item = {'tenant_id': tenant_id,
                'store_id': store_id,
                'name': 'Item ' + no,
                'barcode': '1256' + no,
                'food_type': [food_types[i % len(food_types)]],
                'cuisines': [cuisines[i % len(cuisines)]],
                'category': category[i % len(category)],
                'open_time': 8,
                'close_time': 11,
                'status': False,
                'deliver_time': 45,
                'buy_price': price - 10.0,
                'sell_price': price,
                'discount': 0.0}
        product_service.create(item)
    # log("Created %d products" % (item_count))
    return item_count

def setup_test_product(client, dbname='foodbeaztDb'):
    db = client[dbname]
    store_service = StoreService(db)
    product_service = ProductService(db)
    tenant_service = TenantService(db)
    tenant = tenant_service.get_by_name("FoodBeazt")
    tenant_id = tenant['_id']
    store = store_service.get_by_name('My Store 1')
    store_id = store['_id']
    pd = [{'no': 1, 'name': 'low', 'description': 'some desc',
           'price': 100.0, 'discount': 10.0}]
    p1 = product_service.create(
        test_item(tenant_id, store_id, 'test product1', 100.0, 10.0, pd))
    p2 = product_service.create(
        test_item(tenant_id, store_id, 'test product2', 333.0, 0.0))
    p3 = product_service.create(
        test_item(tenant_id, store_id, 'test product3', 100.0, 3.3))
    return p1, p2, p3

def test_item(tenant_id, store_id, name, price, discount, pd=None):
    return {
        'tenant_id': tenant_id,
        'store_id': store_id,
        'name': name,
        'barcode': '1256',
        'food_type': ['veg'],
        'cuisines': ['testcusine'],
        'category': 'starter',
        'open_time': 8,
        'close_time': 11,
        'status': True,
        'deliver_time': 45,
        'buy_price': price-10,
        'sell_price': price,
        'discount': discount,
        'price_table': pd
    }

def setup(client, dbname='foodbeaztDb', sample_data=False, debug=True):
    global log_enabled
    log_enabled = debug
    db = client[dbname]
    log("Checking admin tenant")
    tenant_service = TenantService(db)
    user_service = UserService(db)
    pincode_service = PincodeService(db)

    if not tenant_service.check_name_exists(None, "FoodBeazt"):
        log("Creating admin tenant")
        item = {"name": "FoodBeazt", "description": "super admin tenant", "website": "http://www.foodbeazt.in",
                "url": "http://www.foodbeazt.in", "type": "super_admin", "logo": "foodbeazt_logo.png",
                "contact": {"name": "admin", "email": "foodbeazt@gmail.com", "phone": "+91 7373730484"},
                "registered_ip": "10.0.0.1",
                "address": {"address": "Puducherry", "zipcode": "605001", "country": "INDIA", "state": "Puducherry"}}
        tenant_id = tenant_service.create(item)

        item['tenant_id'] = tenant_id
        tenant_service.update(item)

    log('\nTenant:')
    tenant = tenant_service.get_by_name("FoodBeazt")
    log(json.dumps(tenant, default=json_util.default))
    tenant_id = tenant['_id']

    log('\nUser:')
    user = user_service.get_by_email("foodbeazt@gmail.com")
    log(json.dumps(user, default=json_util.default))

    log("Setup pincode")
    pincode = {'pincode': '605001'}
    pincode_service.save(pincode)

    if sample_data:
        log('\nCreating sample product data:')
        create_sample_data(db, tenant_id)

def drop_db(client, dbname):
    log('Dropping database...')
    client.drop_database(dbname)
    log('Dropped successfully!!')

if __name__ == "__main__":
    sample_data = False
    host = os.environ.get('MONGO_HOST', 'localhost')
    port = int(os.environ.get('MONGO_PORT', 27017))
    dbname = os.environ.get('MONGO_DBNAME', 'foodbeaztDb')
    username = os.environ.get('MONGO_USERNAME', None)
    password = os.environ.get('MONGO_PASSWORD', None)
    log("Connecting to '%s':%d" % (host, port))
    uri = "mongodb://%s:%d" % (host,port)
    if not username is None and not password is None:
        uri = "mongodb://%s:%s@%s:%d" % (username,password,host,port)
    mclient = MongoClient(uri)
    if len(sys.argv) > 1:
        if sys.argv[1] == "drop":
            drop_db(mclient, dbname)
        if len(sys.argv) > 2 and sys.argv[2] == "test-data":
            sample_data = True

    log("Initializing database...")
    setup(mclient, dbname, sample_data, False)


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Email_service extends MY_Controller {
    function __construct()
    {
        parent::__construct();
         if (!$this->user) {
            $this->set_last_url();
            redirect('login');
        } else {
            if ( !in_array("3", explode(",", $this->user->access_child)) ) {
                  show_404();
            }
        }
    }

	public function index()
	{
		$this->view_data['settings'] = Setting::first();
        $this->view_data['form_action'] = "email_service/update_settings";
        $this->content_view = 'settings/email_settings';
	}

    function testpostmaster($mode = NULL){

            switch ($mode) {
                case 'email':
                        $this->load->library('email');
                        $emailconfig = Setting::first();

                        $subject = 'This is a test';
                        $message = '
This message has been sent for testing purposes.
';

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

                            <meta http-equiv="Content-Type" content="text/html; charset='.strtolower(config_item('charset')).'" />
                            <title>'.html_escape($subject).'</title>

                        '.$message.'

                        ';
                        // Also, for getting full html you may use the following internal method:
                        //$body = $this->email->full_html($subject, $message);

                        $result = $this->email
                            ->from($this->user->email)
                            ->to($emailconfig->email_username)
                            ->subject($subject)
                            ->message($body);

                        //echo $this->email->print_debugger();

                        if($result->send()){
                            $this->view_data['msgresult'] = "success";
                            $this->view_data['result'] = "Sending test email success.";
                            $this->view_data['trace'] = "Message send please check your smtp email address.";
                        }else{
                            $this->view_data['msgresult'] = "danger";
                            $this->view_data['result'] = "Sending test email failed!";
                            $this->view_data['trace'] = "Something went wrong please check your settings.
".strip_tags($this->email->print_debugger());
                        }

                        $this->content_view = 'settings/_testpostmaster';
                        $this->theme_view = 'modal_nojs';
                        $this->view_data['title'] = '
                                             Email sending test.';

                    break;

                case 'mailbox':
                        $emailconfig = Setting::first();
                        $config['login'] = $emailconfig->mailbox_username;
                        $config['pass'] = $emailconfig->mailbox_password;
                        $config['host'] = $emailconfig->mailbox_host;
                        $config['port'] = $emailconfig->mailbox_port;
                        $config['mailbox'] = $emailconfig->mailbox_box;

                        if($emailconfig->mailbox_imap == "1"){$flags = "/imap";}else{$flags = "/pop3";}
                        if($emailconfig->mailbox_ssl == "1"){$flags .= "/ssl";}

                        $config['service_flags'] = $flags.$emailconfig->mailbox_flags;

                        $this->load->library('peeker_connect');
                        $this->peeker_connect->initialize($config);

                        if($this->peeker_connect->is_connected()){
                            $this->view_data['msgresult'] = "success";
                            $this->view_data['result'] = "Connection to email mailbox successful!";
                        }else{
                            $this->view_data['msgresult'] = "danger";
                            $this->view_data['result'] = "Connection to email mailbox not successful!";
                        }
                        $this->peeker_connect->message_waiting();

                        $this->peeker_connect->close();
                        $this->view_data['trace'] = $this->peeker_connect->trace();
                        $this->content_view = 'settings/_testpostmaster';
                        $this->theme_view = 'modal_nojs';
                        $this->view_data['title'] = '
                                             POP / IMAP testing.';
                    break;

                default:
                    show_404();
                    break;
            }

    }

    function update_settings(){
        $this->theme_view ="";

        if ($this->user && $this->user->admin) {
                            $info = Setting::first();
                            $error_message = array();
                            $final = array();

                            $data = array(
                                "email_protocol"=> $info->email_protocol,
                                "email_host"=> $info->email_host,
                                "email_username"=> $info->email_username,
                                "email_password"=> $info->email_password,
                                "email_port"=> $info->email_port,
                                "email_crypto"=> $info->email_crypto,

                                "mailbox_address"=> $info->mailbox_address,
                                "mailbox_host"=> $info->mailbox_host,
                                "mailbox_username"=> $info->mailbox_username,
                                "mailbox_password"=> $info->mailbox_password,
                                "mailbox_port"=> $info->mailbox_port,
                                "mailbox_box"=> $info->mailbox_box,
                                "mailbox_flags"=> $info->mailbox_flags,
                                "mailbox_search"=> $info->mailbox_search,
                                "mailbox_imap"=> $info->mailbox_imap,
                                "mailbox_ssl"=> $info->mailbox_ssl,

                            );

                            $changes = array(
                                'email_protocol' => htmlspecialchars($this->input->post('email_protocol')),
                                'email_host' => htmlspecialchars($this->input->post('email_host')),
                                'email_username' => htmlspecialchars($this->input->post('email_username')),
                                'email_password' => htmlspecialchars($this->input->post('email_password')),
                                'email_port' => htmlspecialchars($this->input->post('email_port')),
                                'email_crypto' => htmlspecialchars($this->input->post('email_crypto')),

                                "mailbox_address"=>  htmlspecialchars($this->input->post('mailbox_address')),
                                "mailbox_host"=>  htmlspecialchars($this->input->post('mailbox_host')),
                                "mailbox_username"=>  htmlspecialchars($this->input->post('mailbox_username')),
                                "mailbox_password"=>  htmlspecialchars($this->input->post('mailbox_password')),
                                "mailbox_port"=>  htmlspecialchars($this->input->post('mailbox_port')),
                                "mailbox_box"=>  htmlspecialchars($this->input->post('mailbox_box')),
                                "mailbox_flags"=>  htmlspecialchars($this->input->post('mailbox_flags')),
                                "mailbox_search"=>  htmlspecialchars($this->input->post('mailbox_search')),
                            );

                            if ( $this->input->post('mailbox_imap', TRUE) === "on") {
                                $changes["mailbox_imap"] = 1;
                            } else {
                                $changes["mailbox_imap"] = 0;
                            }

                            if ( $this->input->post('mailbox_ssl', TRUE) === "on") {
                                $changes["mailbox_ssl"] = 1;
                            } else {
                                $changes["mailbox_ssl"] = 0;
                            }

                            if ( array_diff_assoc($changes, $data) ) {
                                    $this->load->library('form_validation');

                                    $config = array(
                                        array(
                                                'field' => 'email_protocol',
                                                'label' => 'email protocol',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                        array(
                                                'field' => 'email_host',
                                                'label' => 'host',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                        array(
                                                'field' => 'email_username',
                                                'label' => 'username',
                                                'rules' => "trim|required|max_length[30]|valid_email"
                                        ),

                                        array(
                                                'field' => 'email_password',
                                                'label' => 'password',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                        array(
                                                'field' => 'email_port',
                                                'label' => 'port',
                                                'rules' => "trim|required|max_length[30]|numeric|is_natural_no_zero"
                                        ),

                                        array(
                                                'field' => 'email_crypto',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                        array(
                                                'field' => 'mailbox_address',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]|valid_email"
                                        ),

                                        array(
                                                'field' => 'mailbox_host',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                        array(
                                                'field' => 'mailbox_username',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]|valid_email"
                                        ),

                                        array(
                                                'field' => 'mailbox_password',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                        array(
                                                'field' => 'mailbox_port',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]|numeric|is_natural_no_zero"
                                        ),

                                        array(
                                                'field' => 'mailbox_box',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                        array(
                                                'field' => 'mailbox_flags',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                        array(
                                                'field' => 'mailbox_search',
                                                'label' => 'encryption mode',
                                                'rules' => "trim|required|max_length[30]"
                                        ),

                                    );

                                    $this->form_validation->set_error_delimiters('', '');
                                    $this->form_validation->set_rules($config);

                                    if ($this->form_validation->run() == FALSE){
                                        foreach ($this->form_validation->error_array() as $key => $value) {
                                            $error_message[] = "error:" .$value;
                                            unset($changes[$key]);
                                        }

                                    }
                            }

            $final = array_diff_assoc($changes, $data);

            if ($data['mailbox_imap'] != $changes['mailbox_imap']) {
                $final['mailbox_imap'] = $changes['mailbox_imap'];
            }

            if ($data['mailbox_ssl'] != $changes['mailbox_ssl']) {
                $final['mailbox_ssl'] = $changes['mailbox_ssl'];
            }
            /*var_dump(array_filter(array_diff_assoc($changes, $data)));
            var_dump($data);
            var_dump($changes);*/

            if ( count($error_message) == 0 && !count($final) ) {
                 $error = array('info: Nothing changed.');
                 $this->session->set_flashdata('message', $error);

            } elseif ( count($error_message) == 0 && count($final) ) {
                 $info->update_attributes($final);
                 $info->save();

                 $error = array('success: Settings updated.');
                 $this->session->set_flashdata('message', $error);

            } elseif ( count($error_message) >= 0 && count($final) ) {
                 $info->update_attributes($final);
                 $info->save();

                 array_push($error_message, 'info: Settings updated, but with some errors.');
                 $this->session->set_flashdata('message', $error_message);

            } elseif ( count($error_message) >= 0 && count($final) ) {
                 $this->session->set_flashdata('message', $error_message);

            }

            redirect('email_service');

        }
    }

}