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

namespace Playground.DataStructure
{
    public class Tree<T> where T : IComparable
    {
        public class Node
        {
            public Node (T value)
            {
                Value = value;
            }

            public Node Left;
            public Node Right;
            public T Value;
        }

        private Node _root;
        public Node Root
        {
            get
            {
                return _root;
            }

            set
            {
                _root = value;
            }
        }

        public string InOrder ()
        {
            StringBuilder sb = new StringBuilder();
            InOrder(_root, sb);
            return sb.ToString();
        }

        public string InOrderWithoutRecursive()
        {
            if (Root == null)
            {
                return string.Empty;
            }

            StringBuilder sb = new StringBuilder();
            System.Collections.Generic.Stack<Node> stack = new System.Collections.Generic.Stack<Node>();
            var node = Root;
            while (node != null)
            {
                stack.Push(node);
                node = node.Left;
            }

            while (stack.Count > 0)
            {
                node = stack.Pop();
                sb.Append(node.Value + ",");

                if (node.Right != null)
                {
                    var nodeToVisit = node.Right;
                    while (nodeToVisit != null)
                    {
                        stack.Push(nodeToVisit);
                        nodeToVisit = nodeToVisit.Left;
                    }
                }
            }

            return sb.ToString();
        }

        private void InOrder(Node node, StringBuilder sb)
        {
            if(node == null)
            {
                return;
            }

            InOrder(node.Left, sb);
            sb.Append(node.Value.ToString() + ",");
            InOrder(node.Right, sb);
        }

        public string PreOrder()
        {
            StringBuilder sb = new StringBuilder();
            PreOrder(_root, sb);
            return sb.ToString();
        }

        private void PreOrder(Node node, StringBuilder sb)
        {
            if (node == null)
            {
                return;
            }

            sb.Append(node.Value.ToString() + ",");
            PreOrder(node.Left, sb);
            PreOrder(node.Right, sb);
        }

        public List<T> PreOrderIterative(Node root)
        {
            if (root == null)
            {
                return null;
            }

            // Root Left Right
            System.Collections.Generic.Stack<Node> stack = new System.Collections.Generic.Stack<Node>();
            stack.Push(root);

            List<T> res = new List<T>();

            while (stack.Count > 0)
            {
                Node node = stack.Pop();
                res.Add(node.Value);

                if (node.Right != null)
                {
                    stack.Push(node.Right);
                }

                if (node.Left != null)
                {
                    stack.Push(node.Left);
                }
            }

            return res;
        }

        public string PostOrder()
        {
            StringBuilder sb = new StringBuilder();
            PostOrder(_root, sb);
            return sb.ToString();
        }

        // Breath First Search
        public string LevelOrder()
        {
            StringBuilder sb = new StringBuilder();
            Queue<Node> queue = new Queue<Node>();
            queue.Enqueue(_root);

            while (!queue.IsEmpty())
            {
                var node = queue.Dequeue();
                sb.Append(node.Value.ToString() + ",");

                if(node.Left != null)
                {
                    queue.Enqueue(node.Left);
                }

                if (node.Right != null)
                {
                    queue.Enqueue(node.Right);
                }
            }

            return sb.ToString();
        }

        private void PostOrder(Node node, StringBuilder sb)
        {
            if (node == null)
            {
                return;
            }

            PostOrder(node.Left, sb);
            PostOrder(node.Right, sb);
            sb.Append(node.Value.ToString() + ",");
        }

        public int MaxHeight()
        {
            return MaxHeight(Root);
        }

        private int MaxHeight(Node node)
        {
            if(node == null)
            {
                return 0;
            }

            int lDepth = 1 + MaxHeight(node.Left);
            int rDepth = 1 + MaxHeight(node.Right);

            return lDepth > rDepth ? lDepth : rDepth;
        }

        public int isBalanced(Node node)
        {
            if (node == null)
            {
                return 0;
            }

            bool result = true;
            GetHeight(node, ref result);
            return result ? 1 : 0;
        }

        private int GetHeight(Node node, ref bool result)
        {
            if (node == null)
            {
                return 0;
            }

            int lHeight = 1 + GetHeight(node.Left, ref result);
            int rHeight = 1 + GetHeight(node.Right, ref result);

            if (Math.Abs(lHeight - rHeight) > 1)
            {
                result = false;
            }

            return lHeight > rHeight ? lHeight : rHeight;
        }

        public bool isBalancedRecurcive(Node node)
        {
            if(node == null)
            {
                return true;
            }

            int lH = MaxHeight(node.Left);
            int rH = MaxHeight(node.Right);

            if(Math.Abs(lH - rH) < 2 && isBalancedRecurcive(node.Left) && isBalancedRecurcive(node.Right))
            {
                return true;
            }

            return false;
        }

        public bool HasPathSum(T sum)
        {
            return HasPathSum(Root, Convert.ToInt32(sum));
        }

        public bool HasPathSum(Node node, int sum)
        {
            if (node == null)
            {
                return false;
            }

            if (node.Left == null && node.Right == null && node.Value.Equals(sum))
            {
                return true;
            }

            int value = Convert.ToInt32(node.Value);
            if (HasPathSum(node.Left, sum - value))
            {
                return true;
            }

            return HasPathSum(node.Right, sum - value);
        }

        public static Node BuildTreeFromInAndPostOrder(List<T> inOrder, List<T> postOrder)
        {
            int postOrderIndex = postOrder.Count - 1;
            Node root = BuildTreeFromInAndPostOrder(inOrder, 0, inOrder.Count - 1, postOrder, ref postOrderIndex);
            return root;
        }

        private static Node BuildTreeFromInAndPostOrder(List<T> inOrder, int start, int end,
            List<T> postOrder, ref int postOrderIndex)
        {

            if (start > end || postOrderIndex < 0)
            {
                return null;
            }

            Node node = new Node(postOrder[postOrderIndex]);
            postOrderIndex--;

            int rootIndex = InOrderIndex(inOrder, start, end, node.Value);
            node.Right = BuildTreeFromInAndPostOrder(inOrder, rootIndex + 1, end, postOrder, ref postOrderIndex);
            node.Left = BuildTreeFromInAndPostOrder(inOrder, start, rootIndex - 1, postOrder, ref postOrderIndex);
            return node;
        }

        private static int InOrderIndex(List<T> inorder, int start, int end, T value)
        {
            for (int i = start; i <= end; i++)
            {
                if (inorder[i].Equals(value))
                {
                    return i;
                }
            }

            return -1;
        }

        public List<List<T>> LevelOrderArrayByLevels()
        {

            System.Collections.Generic.Queue<Node> queue = new System.Collections.Generic.Queue<Node>();
            List<List<T>> res = new List<List<T>>();

            queue.Enqueue(Root);

            while (true)
            {
                if (queue.Count == 0)
                {
                    break;
                }

                int nodeCount = queue.Count;

                List<T> level = new List<T>();
                while (nodeCount > 0)
                {
                    Node node = queue.Dequeue();
                    level.Add(node.Value);
                    if (node.Left != null)
                    {
                        queue.Enqueue(node.Left);
                    }
                    if (node.Right != null)
                    {
                        queue.Enqueue(node.Right);
                    }

                    nodeCount--;
                }

                res.Add(level);
            }

            return res;
        }

        public int MinDepth(Node Root)
        {
            /*
            Level Order traversal
            Maintain level.
            When find first leaf return
            */

            System.Collections.Generic.Queue<Node> queue = new System.Collections.Generic.Queue<Node>();
            System.Collections.Generic.Queue<int> levels = new System.Collections.Generic.Queue<int>();

            queue.Enqueue(Root);
            levels.Enqueue(1);

            int min = int.MaxValue;
            while (queue.Count > 0)
            {
                Node node = queue.Dequeue();
                int level = levels.Dequeue();

                if (node.Left == null && node.Right == null)
                {
                    return level;
                }

                if (node.Left != null)
                {
                    queue.Enqueue(node.Left);
                    levels.Enqueue(level + 1);
                }

                if (node.Right != null)
                {
                    queue.Enqueue(node.Right);
                    levels.Enqueue(level + 1);
                }
            }

            return min;
        }

        public int MinDepth2(Node node)
        {
            /*
            Level Order traversal
            Maintain level.
            When find first leaf return
            */

            if (node == null) return 0;
            if (node.Left == null && node.Right == null) return 1;

            if (node.Left == null)
            {
                return 1 + MinDepth2(node.Right);
            }

            if (node.Right == null)
            {
                return 1 + MinDepth2(node.Left);
            }

            return 1 + Math.Min(MinDepth2(node.Left), MinDepth2(node.Right));
        }

        public Node Flatten()
        {
            /*
             1
            / \
           2   5
          / \   \
         3   4   6

         1
          \
           2
            \
             3
              \
               4
                \
                 5
                  \
                   6
           */
            var node = Root;
            while (node != null)
            {
                if (node.Left != null)
                {
                    var rightMost = node.Left;
                    while (rightMost.Right != null)
                    {
                        rightMost = rightMost.Right;
                    }

                    rightMost.Right = node.Right;
                    node.Right = node.Left;
                    node.Left = null;
                }

                node = node.Right;
            }

            return Root;
        }

        public Node ToDoubleLinedList()
        {
            ConvertToDll(Root);

            Node head = Root;
            while(head.Left != null)
            {
                head = head.Left;
            }

            return head;
        }

        private Node ConvertToDll(Node node)
        {
            if (node == null)
            {
                return node;
            }

            if (node.Left != null)
            {
                // Convert the left subtree
                Node left = ConvertToDll(node.Left);

                // take the rightmost elem
                while (left.Right != null)
                {
                    left = left.Right;
                }

                left.Right = node;
                node.Left = left;
            }

            if (node.Right != null)
            {
                // Convert the right subtree
                Node right = ConvertToDll(node.Right);

                // take the left most elem
                while (right.Left != null)
                {
                    right = right.Left;
                }

                right.Left = node;
                node.Right = right;
            }

            return node;
        }

        List<List<T>> treeTraversal = new List<List<T>>();
        Dictionary<int, List<T>> dict = new Dictionary<int, List<T>>();

        public List<List<T>> VerticalOrderTraversal()
        {
            BuildVertOrderTraversal(Root, 0);

            var list = dict.Keys.ToList();
            list.Sort();

            // Loop through keys.
            foreach (var key in list)
            {
                var vertList = dict[key];
                treeTraversal.Add(vertList);
            }

            return treeTraversal;
        }

        public void BuildVertOrderTraversal(Node node, int level)
        {
            if (node == null)
            {
                return;
            }

            // PreOrder traversal
            // do stuff here
            if (!dict.ContainsKey(level))
            {
                var newList = new List<T>();
                newList.Add(node.Value);
                dict.Add(level, newList);
            }
            else
            {
                var list = dict[level];
                list.Add(node.Value);
            }

            BuildVertOrderTraversal(node.Left, level - 1);
            BuildVertOrderTraversal(node.Right, level + 1);
        }

        public List<List<T>> VerticalOrderTraversal_Level()
        {
            /*
            Level Order traversal
            Have a queue
            Have a queue of levels and put them into hash
            Maintain the max and min value to iterate throuh resulted keys to
            generate array

            */

            treeTraversal.Clear();
            dict.Clear();

            System.Collections.Generic.Queue<Node> qNodes = new System.Collections.Generic.Queue<Node>();
            Queue<int> qLevels = new Queue<int>();

            qNodes.Enqueue(Root);
            qLevels.Enqueue(0);

            int min = int.MaxValue;
            int max = int.MinValue;

            while (qNodes.Count > 0)
            {
                int level = qLevels.Dequeue();
                var node = qNodes.Dequeue();

                min = Math.Min(level, min);
                max = Math.Max(level, max);

                if (dict.ContainsKey(level))
                {
                    dict[level].Add(node.Value);
                }
                else
                {
                    List<T> newList = new List<T>() { node.Value };
                    dict.Add(level, newList);
                }

                if (node.Left != null)
                {
                    qNodes.Enqueue(node.Left);
                    qLevels.Enqueue(level - 1);
                }

                if (node.Right != null)
                {
                    qNodes.Enqueue(node.Right);
                    qLevels.Enqueue(level + 1);
                }
            }

            for (int i = min; i <= max; i++)
            {
                if (dict.ContainsKey(i))
                {
                    treeTraversal.Add(dict[i]);
                }
            }

            return treeTraversal;
        }
    }

    public class BST<T> : Tree<T> where T:IComparable
    {
        private T _min;
        private T _max;
        public BST(T min, T max)
        {
            _min = min;
            _max = max;
        }

        public Node Search (T value)
        {
            var node = Root;
            while (node != null)
            {
                if (node.Value.Equals(value))
                {
                    return node;
                }
                else if (value.CompareTo(node.Value) < 0)
                {
                    node = node.Left;
                }
                else
                {
                    node = node.Right;
                }
            }

            return null;
        }

        public Node SearchRecurcive(T value)
        {
            return Search(value, Root);
        }
        private Node Search(T value, Node node)
        {
            if (node == null)
            {
                return null;
            }
            else if(node.Value.Equals(value))
            {
                return node;
            }

            return Search(value, value.CompareTo(node.Value) < 0 ? node.Left : node.Right);
        }

        public Node Insert(T value)
        {
            if (Root == null)
            {
                Root = new Node(value);
                return Root;
            }

            var node = Root;
            while (node != null)
            {
                if (node.Value.Equals(value))
                {
                    return node;
                }
                else if (value.CompareTo(node.Value) < 0)
                {
                    if (node.Left == null)
                    {
                        node.Left = new Node(value);
                    }
                    node = node.Left;
                }
                else
                {
                    if (node.Right == null)
                    {
                        node.Right = new Node(value);
                    }
                    node = node.Right;
                }
            }

            return null;
        }

        public Node InsertRecurcive(T value)
        {
            return Insert(value, Root);
        }
        private Node Insert(T value, Node node)
        {
            if (node == null)
            {
                return new Node(value);
            }

            if (node.Value.Equals(value))
            {
                return node;
            }
            else if (value.CompareTo(node.Value) < 0)
            {
                node.Left = Insert(value, node.Left);
            }
            else
            {
                node.Right = Insert(value, node.Right);
            }

            return node;
        }

        public Node NextGreaterSuccessor(T value)
        {

            // find node
            // 1 case: has right node -> traverse until find the left most node
            // 2 case: no right node -> start from head go down until find the same node with maintainf parent

            var node = Search(value);
            if(node.Right != null)
            {
                var nodeL = node.Right;
                while (nodeL.Left != null)
                {
                    nodeL = node.Left;
                }
                return nodeL;
            }

            var nodeParent = Root;
            Node nodeSeek = null;
            while (nodeSeek != node)
            {
                if(nodeParent.Value.CompareTo(value) > 0)
                {
                    nodeSeek = nodeParent;
                    nodeParent = nodeParent.Left;
                }
                else
                {
                    nodeParent = nodeParent.Right;
                }
            }

            return nodeSeek;

        }

        public T LeastCommonAncestor (T value1, T value2)
        {

            /*
            Build path from node to the root
            Until find node
            Make paths equals
            Start from paths to find common point
            */

            List<T> empty = new List<T>();
            List<T> path1 = FindAndBuildPath(Root, value1, empty);
            List<T> path2 = FindAndBuildPath(Root, value2, empty);

            if (path1 == null || path2 == null)
            {
                return default(T);
            }

            if (value1.CompareTo(value2) == 0)
            {
                return value1;
            }

            int index1 = path1.Count - 1;
            int index2 = path2.Count - 1;

            while (index1 != index2)
            {
                if (index1 > index2)
                {
                    if (path1[index1].CompareTo(value2) != 0)
                    {
                        index1--;
                    }
                    else
                    {
                        return value2;
                    }
                }
                else
                {
                    if (path2[index2].CompareTo(value1) != 0)
                    {
                        index2--;
                    }
                    else
                    {
                        return value1;
                    }
                }
            }

            while (index1 >= 0 && path1[index1].CompareTo(path2[index2]) != 0)
            {
                index1--;
                index2--;
            }

            return index1 >= 0 ? path1[index1] : default(T);
        }

        public List<T> FindAndBuildPath(Node node, T value, List<T> pathSoFar)
        {
            if (node == null)
            {
                return null;
            }

            if (node.Value.CompareTo(value) == 0)
            {
                return pathSoFar;
            }

            List<T> newPath = new List<T>(pathSoFar);
            newPath.Add(node.Value);

            List<T> found = FindAndBuildPath(node.Left, value, newPath);
            if (found == null)
            {
                found = FindAndBuildPath(node.Right, value, newPath);
            }

            return found;
        }

        /// <summary>
        /// Given a binary search tree T, where each node contains a positive integer, and an integer K,
        /// you have to find whether or not there exist two different nodes A and B such that A.value + B.value = K.
        /// Return 1 to denote that two such nodes exist.Return 0, otherwise.
        /// </summary>
        public bool IsSumExist(T sum)
        {
            if (sum.CompareTo(Root.Value) == 0)
            {
                return false;
            }

            System.Collections.Generic.Stack<Node> normal = new System.Collections.Generic.Stack<Node>();
            System.Collections.Generic.Stack<Node> reverse = new System.Collections.Generic.Stack<Node>();

            // done1, val1 and curr1 are used for normal inorder traversal using s1
            // done2, val2 and curr2 are used for reverse inorder traversal using s2
            bool done1 = false, done2 = false;
            int val1 = 0, val2 = 0;
            Node curr1 = Root;
            Node curr2 = Root;

            // The loop will break when we either find a pair or one of the two
            // traversals is complete
            while (true)
            {
                // Find next node in normal Inorder traversal. See following post
                while (!done1)
                {
                    if (curr1 != null)
                    {
                        normal.Push(curr1);
                        curr1 = curr1.Left;
                    }
                    else
                    {
                        if (normal.Count == 0)
                            done1 = true;
                        else
                        {
                            curr1 = normal.Pop();
                            val1 = Convert.ToInt32(curr1.Value);
                            curr1 = curr1.Right;
                            done1 = true;
                        }
                    }
                }

                // Find next node in REVERSE Inorder traversal.
                // The only difference between above and below loop is, in below loop
                // right subtree is traversed before left subtree
                while (!done2)
                {
                    if (curr2 != null)
                    {
                        reverse.Push(curr2);
                        curr2 = curr2.Right;
                    }
                    else
                    {
                        if (reverse.Count == 0)
                            done2 = true;
                        else
                        {
                            curr2 = reverse.Pop();
                            val2 = Convert.ToInt32(curr2.Value);
                            curr2 = curr2.Left;
                            done2 = true;
                        }
                    }
                }

                // If we find a pair, then print the pair and return. The first
                // condition makes sure that two same values are not added
                if ((val1 != val2) && (val1 + val2).CompareTo(sum) == 0)
                {
                    return true;
                }

                // If sum of current values is smaller, then move to next node in
                // normal inorder traversal
                else if ((val1 + val2).CompareTo(sum) < 0)
                    done1 = false;

                // If sum of current values is greater, then move to next node in
                // reverse inorder traversal
                else if ((val1 + val2).CompareTo(sum) > 0)
                    done2 = false;

                // If any of the inorder traversals is over, then there is no pair
                // so return false
                if (val1 >= val2)
                    return false;
            }
        }

        /// <summary>
        /// O(n2) - solution
        /// Given a binary search tree T, where each node contains a positive integer, and an integer K,
        /// you have to find whether or not there exist two different nodes A and B such that A.value + B.value = K.
        /// Return 1 to denote that two such nodes exist.Return 0, otherwise.
        /// </summary>
        public int IsSumExistOption2(int sum)
        {

            if (sum.CompareTo(Root.Value) == 0)
            {
                return 0;
            }

            int rootValue = Convert.ToInt32(Root.Value);
            if (sum - rootValue < rootValue)
            {
                return IsSumExist(Root.Left, Root, sum) ? 1 : 0;
            }

            return IsSumExist(Root, Root.Right, sum) ? 1 : 0;
        }

        private bool IsSumExist(Node left, Node rigth, int sum)
        {
            if (left == null || rigth == null)
            {
                return false;
            }

            int curSum = Convert.ToInt32(left.Value) + Convert.ToInt32(rigth.Value);
            if (curSum == sum && left != rigth)
            {
                return true;
            }

            if (curSum < sum)
            {
                return IsSumExist(left.Right, rigth, sum) || IsSumExist(left, rigth.Right, sum);
            }

            // more than sum
            return IsSumExist(left.Left, rigth, sum) || IsSumExist(left, rigth.Left, sum);
        }
    }
}


text:
<component name="ArtifactManager">
  <artifact type="jar" name="JProfilePicImagifier:jar">
    <output-path>$PROJECT_DIR$/out/artifacts/JProfilePicImagifier_jar</output-path>
    <root id="archive" name="JProfilePicImagifier.jar">
      <element id="module-output" name="JProfilePicImagifier" />
    </root>
  </artifact>
</component>

redpajama_set_name: RedPajamaGithub


text:
package org.elasticsearch.common.geo;

import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.text.ParseException;

/**
 * Geometry serializer/deserializer
 */
public interface GeometryFormat<ParsedFormat> {

    /**
     * The name of the format, for example 'wkt'.
     */
    String name();

    /**
     * Parser JSON representation of a geometry
     */
    ParsedFormat fromXContent(XContentParser parser) throws IOException, ParseException;

    /**
     * Serializes the geometry into its JSON representation
     */
    XContentBuilder toXContent(ParsedFormat geometry, XContentBuilder builder, ToXContent.Params params) throws IOException;

    /**
     * Serializes the geometry into a standard Java object.
     *
     * For example, the GeoJson format returns the geometry as a map, while WKT returns a string.
     */
    Object toXContentAsObject(ParsedFormat geometry);
}


text:
package org.helm.notation2.exception;

/**
 * AnalogSequenceException
 *
 * @author hecht
 */
public class AnalogSequenceException extends Exception {

  /**
   *
   */
  private static final long serialVersionUID = 1L;

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

}


text:
package jahmm.io;

import jahmm.observables.ObservationReal;
import java.io.IOException;
import java.io.Writer;

/**
 * Writes an {@link ObservationReal ObservationReal} up to (and including) the
 * semi-colon.
 */
public class ObservationRealWriter
        extends ObservationWriter<ObservationReal> {

    @Override
    public void write(ObservationReal observation, Writer writer)
            throws IOException {
        writer.write(observation.value + "; ");
    }
}


text:
global_var = 0

def outter():
    def inner():
        global global_var
        global_var = 10
    inner()

outter()
print(global_var)


text:
package org.commacq.client.spring;

import org.springframework.beans.factory.xml.NamespaceHandlerSupport;

public class NamespaceHandler extends NamespaceHandlerSupport {

	@Override
	public void init() {
		registerBeanDefinitionParser("manager", new ManagerBeanDefinitionParser());
	}

}


text:
from __future__ import print_function
import os
import capnp

import addressbook_capnp

def writeAddressBook(file):
    addresses = addressbook_capnp.AddressBook.new_message()
    people = addresses.init('people', 2)

    alice = people[0]
    alice.id = 123
    alice.name = 'Alice'
    alice.email = 'alice@example.com'
    alicePhones = alice.init('phones', 1)
    alicePhones[0].number = "555-1212"
    alicePhones[0].type = 'mobile'
    alice.employment.school = "MIT"

    bob = people[1]
    bob.id = 456
    bob.name = 'Bob'
    bob.email = 'bob@example.com'
    bobPhones = bob.init('phones', 2)
    bobPhones[0].number = "555-4567"
    bobPhones[0].type = 'home'
    bobPhones[1].number = "555-7654"
    bobPhones[1].type = 'work'
    bob.employment.unemployed = None

    addresses.write(file)

def printAddressBook(file):
    addresses = addressbook_capnp.AddressBook.read(file)

    for person in addresses.people:
        print(person.name, ':', person.email)
        for phone in person.phones:
            print(phone.type, ':', phone.number)

        which = person.employment.which()
        print(which)

        if which == 'unemployed':
            print('unemployed')
        elif which == 'employer':
            print('employer:', person.employment.employer)
        elif which == 'school':
            print('student at:', person.employment.school)
        elif which == 'selfEmployed':
            print('self employed')
        print()

if __name__ == '__main__':
    f = open('example', 'w')
    writeAddressBook(f)

    f = open('example', 'r')
    printAddressBook(f)


text:
<?xml version="1.0" encoding="UTF-8"?>
<openerp>
    <data noupdate="1">
        <record id="base.group_cinda_cmdb_admin" model="res.groups">
            <field name="name">admin</field>
            <field name="category_id" ref="base.module_category_cinda_cmdb"/>
            <field name="implied_ids" eval="[(4,ref('base.group_user'))]"/>
        </record>
    </data>
</openerp>


text:
from __future__ import absolute_import, unicode_literals

import logging

from django.utils.functional import cached_property

logger = logging.getLogger(__name__)

ERROR_TYPE_STOP = "stop"
ERROR_TYPE_WARNING = "warning"
ERROR_TYPE_INFO = "information"
error_types = [ERROR_TYPE_STOP, ERROR_TYPE_WARNING, ERROR_TYPE_INFO]

# validate = ["integer", "decimal", "list", "date", "time", "length", "custom", "any"]
# criteria = {"between": "between",
#             "not between": "not between",
#             "equal to": "==",
#             "not equal to": "!=",
#             "greater than": ">",
#             "less than": "<",
#             "greater than or equal to": ">=",
#             "less than or equal to": "<="
#             }

THIS_COL = 'INDIRECT(ADDRESS(1,COLUMN()) & ":" & ADDRESS(65536, COLUMN()))'
CELL1 = 'INDIRECT(ADDRESS(ROW(),1) & ":" & ADDRESS(ROW(), 1))'
BASE = {"validate": "any",
        "criteria": "",
        "value": 0,
        "maximum": None,
        "ignore_blank": True,
        "dropdown": False,
        "input_title": "",
        "input_message": "",
        "show_input": False,
        "error_title": "Error",
        "error_message": "Invalid input",
        "error_type": ERROR_TYPE_STOP,
        "show_error": True}

class Rule(object):
    def __init__(self, parts=None, error="", message="", is_vba=False):
        self.name = None
        self.formulas = parts or []
        self.error = error
        self.message = message
        self.is_vba = is_vba
        super(Rule, self).__init__()

    def __eq__(self, other):
        return other.name == self.name

class Registry(object):
    __FORMULAS = {
        "any": [],
        "unique": Rule(['COUNTIF({current_column},THIS)=1'],
                       "No duplicates allowed in this column"),
        "number": Rule(['ISNUMBER(VALUE(THIS))'],
                       "Enter a value between {min_value} and {max_value}"),
        "date": Rule(['ISDATE(VALUE(THIS))']),
        "email": Rule(['SEARCH(".",THIS,(SEARCH("@",THIS,1))+2)'],
                      "Not valid email address"),
        "ip": Rule(['(LEN(THIS)-LEN(SUBSTITUTE(THIS,".","")))=3',
                    'ISNUMBER(SUBSTITUTE(THIS,".","")+0)'],
                   "Not a valid IP address"),
        "range": Rule(["VALUE(THIS)>={min_value}", "VALUE(THIS)<={max_value}"],
                      "Enter a value between {min_value} and {max_value}"),
        "max": Rule(["VALUE(THIS)<={max_value}"],
                    "Enter a value between {min_value} and {max_value}"),
        "min": Rule(["VALUE(THIS)>={min_value}"],
                    "Enter a value between {min_value} and {max_value}"),
        "max_length": Rule(["LEN(THIS)<={max_length}"],
                           "String length must be lower than {max_length} chars"),
        "min_length": Rule(["LEN(THIS)>={min_length}"],
                           "String length must be higher than {max_length} chars"),
        "length": Rule(["LEN(THIS)={length}"],
                       "String length must be exactly {length} chars"),
        "uuid": Rule(["HEX2DEC(THIS)"],
                     "It is not a valid UUID"),
        "required": Rule(["LEN(THIS)>0"],
                         "This cell cannot be blank"),
    }

    def __getitem__(self, item):
        return self.__FORMULAS[item]

    def register(self, name, rule, overwrite=False):
        if not isinstance(rule, Rule):
            raise ValueError("not a Rule instance")

        if name in self.__FORMULAS and not overwrite:
            raise ValueError("{} ".format(name))
        rule.name = name
        self.__FORMULAS[name] = rule

        return rule

class RuleEngine(list):
    def __init__(self, iterable=None):
        iterable = iterable or []
        super(RuleEngine, self).__init__(iterable)

    # def append(self, p_object):
    #     if p_object not in self:
    #         super(RuleEngine, self).append(p_object)

    @cached_property
    def rules(self):
        return [registry[y] for y in self]

    def get_rule(self, context):
        ret = []
        for x in self.rules:
            for r in x.formulas:
                f = r.format(**context)
                if f not in ret:
                    ret.append(f)
        return ret

    def get_messages(self, context):
        ret = []
        for x in self.rules:
            msg = x.error.format(**context)
            if msg not in ret:
                ret.append(msg)
        return ret

registry = Registry()


text:
/*******************************************************************************
 * \file state_telemetry.hpp
 *
 * \author MAV'RIC Team
 * \author Nicolas Dousse
 *
 * \brief This module takes care of sending periodic telemetric messages for
 * the state
 *
 ******************************************************************************/

#ifndef STATE_TELEMETRY_HPP_
#define STATE_TELEMETRY_HPP_

#include "communication/mavlink_stream.hpp"
#include "communication/mavlink_message_handler.hpp"
#include "status/state_machine.hpp"

/**
 * \brief   Initialise the state telemetry module
 *
 * \param   state       The pointer to the state structure
 * \param   mavlink_stream      The pointer to the MAVLink stream structure
 * \param   message_handler     The pointer to the message handler
 *
 * \return  True if the init succeed, false otherwise
 */
bool state_telemetry_init(State_machine* state_machine, Mavlink_message_handler* message_handler);

/**
 * \brief   Function to send the MAVLink heartbeat message
 *
 * \param   state       The pointer to the state structure
 * \param   mavlink_stream          The pointer to the MAVLink stream structure
 * \param   msg                     The pointer to the MAVLink message
 */
void state_telemetry_send_heartbeat(const State* state, const Mavlink_stream* mavlink_stream, mavlink_message_t* msg);

/**
 * \brief   Function to send the MAVLink system status message, project specific message!
 *
 * \param   state       The pointer to the state structure
 * \param   mavlink_stream          The pointer to the MAVLink stream structure
 * \param   msg                     The pointer to the MAVLink message
 */
void state_telemetry_send_status(const State* state, const Mavlink_stream* mavlink_stream, mavlink_message_t* msg);

#endif /* STATE_TELEMETRY_HPP_ */


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Deprecated List (twitter4j-core 3.0.3 API)</title>
<meta name="date" content="2012-12-23">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Deprecated API

Contents

Deprecated Methods

Deprecated Methods

Method and Description

twitter4j.api.ListsResources.addUserListMember(int, long)

use ListsResources.createUserListMember(int, long)} instead

twitter4j.api.ListsResources.addUserListMember(long, String, long)

use ListsResources.createUserListMember(long, String, long) instead

twitter4j.api.ListsResources.addUserListMembers(int, long[])

use ListsResources.createUserListMembers(int, long[]) instead

twitter4j.api.ListsResources.addUserListMembers(int, String[])

use ListsResources.createUserListMembers(int, String[]) instead

twitter4j.api.ListsResources.addUserListMembers(long, String, long[])

use ListsResources.createUserListMembers(int, long[]) instead

twitter4j.api.ListsResources.addUserListMembers(long, String, String[])

use ListsResources.createUserListMembers(int, String[]) instead

twitter4j.api.ListsResources.deleteUserListMember(int, long)

use ListsResources.destroyUserList(int) instead

twitter4j.api.ListsResources.deleteUserListMember(long, String, long)

use ListsResources.destroyUserListMember(long, String, long) List(int)} instead

twitter4j.api.TrendsResources.getAvailableTrends(GeoLocation)

use TrendsResources.getClosestTrends(twitter4j.GeoLocation) instead

twitter4j.api.TrendsResources.getLocationTrends(int)

use TrendsResources.getPlaceTrends(int) instead

twitter4j.api.TimelinesResources.getMentions()

use TimelinesResources.getMentionsTimeline() instead

twitter4j.api.TimelinesResources.getMentions(Paging)

use TimelinesResources.getMentionsTimeline(twitter4j.Paging) instead

twitter4j.User.getProfileBackgroundImageUrl()

use User.getProfileImageURL() instead

twitter4j.User.getProfileImageUrlHttps()

use User.getProfileImageURL() instead

twitter4j.QueryResult.getRefreshUrl()

use QueryResult.getRefreshURL() instead

twitter4j.RateLimitStatus.getRemainingHits()

use RateLimitStatus.getRemaining() instead

twitter4j.Trend.getUrl()

use Trend.getURL() instead

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2012. All Rights Reserved.


text:
#nullable disable warnings
using WizBot.Db.Models;
using WizBot.Modules.Gambling.Common;
using WizBot.Modules.Gambling.Services;
using SixLabors.Fonts;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Drawing.Processing;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
using System.Text;
using Wiz.Econ.Gambling;
using Color = SixLabors.ImageSharp.Color;
using Image = SixLabors.ImageSharp.Image;

namespace WizBot.Modules.Gambling;

public enum GamblingError
{
    InsufficientFunds,
}

public partial class Gambling
{
    [Group]
    public partial class SlotCommands : GamblingSubmodule<IGamblingService>
    {
        private static decimal totalBet;
        private static decimal totalPaidOut;

        private readonly IImageCache _images;
        private readonly FontProvider _fonts;
        private readonly DbService _db;
        private object _slotStatsLock = new();

        public SlotCommands(
            ImageCache images,
            FontProvider fonts,
            DbService db,
            GamblingConfigService gamb)
            : base(gamb)
        {
            _images = images;
            _fonts = fonts;
            _db = db;
        }

        public Task Test()
            => Task.CompletedTask;

        [Cmd]
        public async Task Slot(ShmartNumber amount)
        {
            if (!await CheckBetMandatory(amount))
                return;

            // var slotInteraction = CreateSlotInteractionIntenal(amount);

            await ctx.Channel.TriggerTypingAsync();

            if (await InternalSlotAsync(amount) is not SlotResult result)
            {
                await ReplyErrorLocalizedAsync(strs.not_enough(CurrencySign));
                return;
            }

            var text = GetSlotMessageTextInternal(result);

            using var image = await GenerateSlotImageAsync(amount, result);
            await using var imgStream = await image.ToStreamAsync();

            var eb = _eb.Create(ctx)
                .WithAuthor(ctx.User)
                .WithDescription(Format.Bold(text))
                .WithImageUrl($"attachment://result.png")
                .WithOkColor();

            var bb = new ButtonBuilder(emote: Emoji.Parse("🔁"), customId: "slot:again", label: "Pull Again");
            var si = new SimpleInteraction<ShmartNumber>(bb, (_, amount) => Slot(amount), amount);

            var inter = _inter.Create(ctx.User.Id, si);
            var msg = await ctx.Channel.SendFileAsync(imgStream,
                "result.png",
                embed: eb.Build(),
                components: inter.CreateComponent()
            );
            await inter.RunAsync(msg);
        }

        // private SlotInteraction CreateSlotInteractionIntenal(long amount)
        // {
        //     return new SlotInteraction((DiscordSocketClient)ctx.Client,
        //         ctx.User.Id,
        //         async (smc) =>
        //         {
        //             try
        //             {
        //                 if (await InternalSlotAsync(amount) is not SlotResult result)
        //                 {
        //                     await smc.RespondErrorAsync(_eb, GetText(strs.not_enough(CurrencySign)), true);
        //                     return;
        //                 }
        //
        //                 var msg = GetSlotMessageInternal(result);
        //
        //                 using var image = await GenerateSlotImageAsync(amount, result);
        //                 await using var imgStream = await image.ToStreamAsync();
        //
        //                 var guid = Guid.NewGuid();
        //                 var imgName = $"result_{guid}.png";
        //
        //                 var slotInteraction = CreateSlotInteractionIntenal(amount).GetInteraction();
        //
        //                 await smc.Message.ModifyAsync(m =>
        //                 {
        //                     m.Content = msg;
        //                     m.Attachments = new[]
        //                     {
        //                         new FileAttachment(imgStream, imgName)
        //                     };
        //                     m.Components = slotInteraction.CreateComponent();
        //                 });
        //
        //                 _ = slotInteraction.RunAsync(smc.Message);
        //             }
        //             catch (Exception ex)
        //             {
        //                 Log.Error(ex, "Error pulling slot again");
        //             }
        //             // finally
        //             // {
        //             //     await Task.Delay(1000);
        //             //     _runningUsers.TryRemove(ctx.User.Id);
        //             // }
        //         });
        // }

        private string GetSlotMessageTextInternal(SlotResult result)
        {
            var multi = result.Multiplier.ToString("0.##");
            var msg = result.WinType switch
            {
                SlotWinType.SingleJoker => GetText(strs.slot_single(CurrencySign, multi)),
                SlotWinType.DoubleJoker => GetText(strs.slot_two(CurrencySign, multi)),
                SlotWinType.TrippleNormal => GetText(strs.slot_three(multi)),
                SlotWinType.TrippleJoker => GetText(strs.slot_jackpot(multi)),
                _ => GetText(strs.better_luck),
            };
            return msg;
        }

        private async Task<SlotResult?> InternalSlotAsync(long amount)
        {
            var maybeResult = await _service.SlotAsync(ctx.User.Id, amount);

            if (!maybeResult.TryPickT0(out var result, out var error))
            {
                return null;
            }

            lock (_slotStatsLock)
            {
                totalBet += amount;
                totalPaidOut += result.Won;
            }

            return result;
        }

        private async Task<Image<Rgba32>> GenerateSlotImageAsync(long amount, SlotResult result)
        {
            long ownedAmount;
            await using (var uow = _db.GetDbContext())
            {
                ownedAmount = uow.Set<DiscordUser>().FirstOrDefault(x => x.UserId == ctx.User.Id)?.CurrencyAmount
                              ?? 0;
            }

            var slotBg = await _images.GetSlotBgAsync();
            var bgImage = Image.Load<Rgba32>(slotBg, out _);
            var numbers = new int[3];
            result.Rolls.CopyTo(numbers, 0);

            Color fontColor = Config.Slots.CurrencyFontColor;

            bgImage.Mutate(x => x.DrawText(new TextOptions(_fonts.DottyFont.CreateFont(65))
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    WrappingLength = 140,
                    Origin = new(298, 100)
                },
                ((long)result.Won).ToString(),
                fontColor));

            var bottomFont = _fonts.DottyFont.CreateFont(50);

            bgImage.Mutate(x => x.DrawText(new TextOptions(bottomFont)
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    WrappingLength = 135,
                    Origin = new(196, 480)
                },
                amount.ToString(),
                fontColor));

            bgImage.Mutate(x => x.DrawText(new(bottomFont)
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center,
                    Origin = new(393, 480)
                },
                ownedAmount.ToString(),
                fontColor));
            //sw.PrintLap("drew red text");

            for (var i = 0; i < 3; i++)
            {
                using var img = Image.Load(await _images.GetSlotEmojiAsync(numbers[i]));
                bgImage.Mutate(x => x.DrawImage(img, new Point(148 + (105 * i), 217), 1f));
            }

            return bgImage;
        }
    }
}


text:
/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var home = require('./routes/home');
var login = require('./routes/login');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nemLogin');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

app.get('/home', function(req,res){res.render('home', {title: 'home'});});
app.post('/home', routes.home)

app.get('/login', function(req,res){res.render('login', {title: 'login'});});
app.post('/login', routes.login(db));

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试"
        android:ems="10" />
</LinearLayout>


text:
package com.google.cloud.compute;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import com.google.common.collect.ImmutableList;

import org.junit.Test;

import java.util.List;

public class SubnetNetworkConfigurationTest {

  private static final Boolean AUTO_CREATE_SUBNETWORKS = true;
  private static final List<SubnetworkId> SUBNETWORKS = ImmutableList.of(
      SubnetworkId.of("project", "region", "subnetwork1"),
      SubnetworkId.of("project", "region", "subnetwork2"));
  private static final SubnetNetworkConfiguration NETWORK_CONFIGURATION =
      new SubnetNetworkConfiguration(AUTO_CREATE_SUBNETWORKS, SUBNETWORKS);

  @Test
  public void testConstructor() {
    assertEquals(AUTO_CREATE_SUBNETWORKS, NETWORK_CONFIGURATION.autoCreateSubnetworks());
    assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.getType());
    assertEquals(SUBNETWORKS, NETWORK_CONFIGURATION.getSubnetworks());
    assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.getType());
    SubnetNetworkConfiguration networkConfiguration =
        new SubnetNetworkConfiguration(AUTO_CREATE_SUBNETWORKS, null);
    assertEquals(NetworkConfiguration.Type.SUBNET, networkConfiguration.getType());
    assertEquals(AUTO_CREATE_SUBNETWORKS, networkConfiguration.autoCreateSubnetworks());
    assertNull(networkConfiguration.getSubnetworks());
  }

  @Test
  public void testConstructorDeprecated() {
    assertEquals(AUTO_CREATE_SUBNETWORKS, NETWORK_CONFIGURATION.autoCreateSubnetworks());
    assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.type());
    assertEquals(SUBNETWORKS, NETWORK_CONFIGURATION.subnetworks());
    assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.type());
    SubnetNetworkConfiguration networkConfiguration =
        new SubnetNetworkConfiguration(AUTO_CREATE_SUBNETWORKS, null);
    assertEquals(NetworkConfiguration.Type.SUBNET, networkConfiguration.type());
    assertEquals(AUTO_CREATE_SUBNETWORKS, networkConfiguration.autoCreateSubnetworks());
    assertNull(networkConfiguration.subnetworks());
  }

  @Test
  public void testToAndFromPb() {
    assertTrue(NetworkConfiguration.fromPb(NETWORK_CONFIGURATION.toPb())
        instanceof SubnetNetworkConfiguration);
    compareNetworkConfiguration(NETWORK_CONFIGURATION,
        NetworkConfiguration.<SubnetNetworkConfiguration>fromPb(NETWORK_CONFIGURATION.toPb()));
    SubnetNetworkConfiguration networkConfiguration =
        new SubnetNetworkConfiguration(AUTO_CREATE_SUBNETWORKS, null);
    assertTrue(NetworkConfiguration.fromPb(networkConfiguration.toPb())
        instanceof SubnetNetworkConfiguration);
    compareNetworkConfiguration(networkConfiguration,
        NetworkConfiguration.<SubnetNetworkConfiguration>fromPb(networkConfiguration.toPb()));
  }

  @Test
  public void testOf() {
    SubnetNetworkConfiguration configuration =
        SubnetNetworkConfiguration.of(AUTO_CREATE_SUBNETWORKS);
    assertEquals(AUTO_CREATE_SUBNETWORKS, configuration.autoCreateSubnetworks());
    assertNull(configuration.getSubnetworks());
    assertEquals(NetworkConfiguration.Type.SUBNET, configuration.getType());
  }

  private void compareNetworkConfiguration(SubnetNetworkConfiguration expected,
      SubnetNetworkConfiguration value) {
    assertEquals(expected, value);
    assertEquals(expected.autoCreateSubnetworks(), value.autoCreateSubnetworks());
    assertEquals(expected.getSubnetworks(), value.getSubnetworks());
    assertEquals(expected.getType(), value.getType());
    assertEquals(expected.hashCode(), value.hashCode());
  }
}


text:
Kopia zapasowa do

<<<<<<< HEAD
Mo¿e byæ to ¶cie¿ka do pliku, w którym ma zostaæ zapisana kopia,
¶cie¿ka do urz±dzenia ta¶mowego (jak np. <tt>/dev/st0</tt>) lub
plik lub urz±dzenie na ho¶cie zdalnym. Kopie zapasowe do hosta
zdalnego bêd± wykonane przez protokó³ SSH lub opcjonalnie przez
starszy i mniej bezpieczny protokó³ RSH.

=======
Może być to ścieżka do pliku, w którym ma zostać zapisana kopia,
ścieżka do urządzenia taśmowego (jak np. <tt>/dev/st0</tt>) lub
plik lub urządzenie na hoście zdalnym. Kopie zapasowe do hosta
zdalnego będą wykonane przez protokół SSH lub opcjonalnie przez
starszy i mniej bezpieczny protokół RSH.

>>>>>>> upstream/master


text:
package com.alibaba.nacos.core.distributed.raft.exception;

/**
 * Abnormal JRaft.
 *
 * @author liaochuntao
 */
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
public class JRaftException extends RuntimeException {

    private static final long serialVersionUID = 8802314713344513544L;

    public JRaftException() {
    }

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

    public JRaftException(String message, Throwable cause) {
        super(message, cause);
    }

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

    public JRaftException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}


text:
describe('angularjs create users', function() {

	var newUserButton = element(by.id('new-user-button'));

    var firstName = element(by.model('credentials.firstName'));
    var lastName = element(by.model('credentials.lastName'));
    var email = element(by.model('credentials.username'));
    var password = element(by.model('credentials.password'));
    var createButton = element(by.id('create-user-button'));

    beforeEach(function() {
        browser.get('http://localhost:3333/#!/users');
        browser.waitForAngular();
        newUserButton.click();
        browser.waitForAngular();
    });

    it('should allow creation (Skyler)', function() {
        firstName.sendKeys('Skyler');
        lastName.sendKeys('White');
        email.sendKeys('swhite@beneke.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(2);
    });

    it('should allow sign-up (Jesse)', function() {
        firstName.sendKeys('Jesse');
        lastName.sendKeys('Pinkman');
        email.sendKeys('capncook@heisenberg.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(3);
    });

    it('should allow sign-up (Hank)', function() {
        firstName.sendKeys('Hank');
        lastName.sendKeys('Schrader');
        email.sendKeys('asacschrader@abqdea.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(4);
    });

    it('should allow sign-up (Marie)', function() {
        firstName.sendKeys('Marie');
        lastName.sendKeys('Schrader');
        email.sendKeys('purple@ilovepurple.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(5);
    });

    it('should allow sign-up (Walter White Jr.)', function() {
        firstName.sendKeys('Walter');
        lastName.sendKeys('White');
        email.sendKeys('flynn@savewalterwhite.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(6);
    });

    it('should allow sign-up (Saul)', function() {
        firstName.sendKeys('Saul');
        lastName.sendKeys('Goodman');
        email.sendKeys('jmcgill@hhm.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(7);
    });

    it('should allow sign-up (Mike)', function() {
        firstName.sendKeys('Mike');
        lastName.sendKeys('Ehrmantraut');
        email.sendKeys('ilovekaylee@imaboss.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(8);
    });

    it('should allow sign-up (Lydia)', function() {
        firstName.sendKeys('Lydia');
        lastName.sendKeys('Rodarte-Quayle');
        email.sendKeys('lrodar@madrigal.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(9);
    });

    it('should allow sign-up (Todd)', function() {
        firstName.sendKeys('Todd');
        lastName.sendKeys('Alquist');
        email.sendKeys('todd@vamonospest.com');
        password.sendKeys('password');

        createButton.click();
        browser.waitForAngular();
        expect(element.all(by.repeater('user in users')).count()).toEqual(10);
    });
});


text:
from django.shortcuts import render
from fossevents.events import services as event_services

def homepage(request):
    ctx = {
        'events': event_services.get_public_event_listings()
    }
    return render(request, 'pages/home.html', ctx)


text:
<!DOCTYPE html>
<title>CSS aspect-ratio: auto size img with aspect-ratio inside column flexbox</title>
<link rel="help" href="https://www.w3.org/TR/css-sizing-4/#propdef-aspect-ratio">
<link rel="help" href="https://www.w3.org/TR/css-flexbox-1/#layout-algorithm">
<link rel="match" href="../../reference/ref-filled-green-100px-square.xht" />

Test passes if there is a filled green square and no red.


text:
function [data] = om_load_full(filename,format)

% LOAD_BIN   Load full Matrix
%
%   Load full Matrix
%
%   SYNTAX
%       [DATA] = OM_LOAD_FULL(FILENAME,FORMAT)
%
%       FORMAT : can be 'ascii' or 'binary' (default)
%
%   Created by Alexandre Gramfort on 2007-11-27.
%   Copyright (c) 2007 Alexandre Gramfort. All rights reserved.

if nargin == 1
    format = 'binary';
end

switch format
case 'binary'
    file = fopen(filename,'r');
    dims = fread(file,2,'uint32','ieee-le');
    data = fread(file,prod(dims),'double','ieee-le');
    data = reshape(data,dims');
    fclose(file);
case 'ascii'
    data = load(filename);
otherwise
    error([me,' : Unknown file format'])
end


text:
//
//  ABFRealmMapView.h
//
//  Created by Adam Fish on 6/3/15.
//  Copyright (c) 2015 Adam Fish. All rights reserved.
//

#import "ABFLocationFetchedResultsController.h"

@import MapKit;

#if __has_include(<RealmMapView/RealmMapView.h>)
@import Realm;
#else
#import <Realm/Realm.h>
#endif

/**
 *  The class creates a map interface to display annotations representing Realm object locations.
 *
 *  ABFRealmMapView inherits MKMapView and is editable from Interface Builder. Simply drag a MKMapView onto your Xib or Storyboard and replace the class with ABFRealmMapView.
 *
 *  The class will create a ABFLocationFetchedResultsController internally to manage retrieving Realm objects based on the current visible map rectangle. The Realm objects must contain a key path to latitude and longitude values.
 *
 *  The class will display annotations and uses the supplied title and subtitle key paths to create the annotation values. By default the class will cluster the annotations based on the zoom level.
 */
@interface ABFRealmMapView : MKMapView

/**
 *  The Realm in which the specified entity exists
 *
 *  Default returns Realm at default path.
 *
 *  @see realmPath
 *  @see initWithEntityName:inRealm:latitudeKeyPath:longitudeKeyPath:titleKeypath:subtitleKeyPath:
 */
@property (nonatomic, readonly, nonnull) RLMRealm *realm;

/**
 *  The configuration for the Realm in which the entity resides
 */
@property (nonatomic, strong, nullable) RLMRealmConfiguration *realmConfiguration;

/**
 *  The internal controller that fetches the Realm objects
 *
 *  @see ABFLocationFetchedResultsController clusterTitleFormatString to localize the subtitle string
 */
@property (nonatomic, readonly, nonnull) ABFLocationFetchedResultsController *fetchResultsController;

/**
 *  The Realm object's name being fetched for the map view
 */
@property (nonatomic, strong, nullable) IBInspectable NSString *entityName;

/**
 *  The key path on fetched Realm objects for the latitude value
 */
@property (nonatomic, strong, nullable) IBInspectable NSString *latitudeKeyPath;

/**
 *  The key path on fetched Realm objects for the longitude value
 */
@property (nonatomic, strong, nullable) IBInspectable NSString *longitudeKeyPath;

/**
 *  The key path on fetched Realm objects for the title of the annotation view
 */
@property (nonatomic, strong, nullable) IBInspectable NSString *titleKeyPath;

/**
 *  The key path on fetched Realm objects for the subtitle of the annotation view
 */
@property (nonatomic, strong, nullable) IBInspectable NSString *subtitleKeyPath;

/**
 *  Designates if the map view will cluster the annotations
 *
 *  Default is YES
 */
@property (nonatomic, assign) IBInspectable BOOL clusterAnnotations;

/**
 *  Designates if the map view automatically refreshes when the map moves
 *
 *  Also will respond to change notifications in Realm to autorefresh
 *
 *  Default is YES
 */
@property (nonatomic, assign) IBInspectable BOOL autoRefresh;

/**
 *  Designates if the map view will zoom to a region that contains all points
 *  on the first refresh of the map annotations (presumably on viewWillAppear)
 *
 *  Default is YES
 */
@property (nonatomic, assign) IBInspectable BOOL zoomOnFirstRefresh;

/**
 *  If enabled, annotation views will be animated when added to the map.
 *
 *  Default is YES
 */
@property (nonatomic, assign) IBInspectable BOOL animateAnnotations;

/**
 *  If YES, a standard callout bubble will be shown when the annotation is selected.
 *  The annotation must have a title for the callout to be shown.
 *
 *  Default is YES
 */
@property (nonatomic, assign) IBInspectable BOOL canShowCallout;

/**
 *  Max zoom level of the map view to perform clustering on.
 *
 *  ABFZoomLevel is inherited from MapKit's Google days:
 *  0 is the entire 2D Earth
 *  20 is max zoom
 *
 *  Default is 20, which means clustering will occur at every zoom level if clusterAnnotations is YES
 */
@property (nonatomic, assign) ABFZoomLevel maxZoomLevelForClustering;

/**
 *  The limit on how many results from Realm will be added to the map.
 *
 *  This applies whether or not clustering is enabled.
 *
 *  Default is -1, or unlimited results.
 */
@property (nonatomic, assign) ABFResultsLimit resultsLimit;

/**
 *  Use this property to filter items found by the map. This predicate will be included, via AND,
 *  along with the generated predicate for the location bounding box.
 */
@property (nonatomic, strong, nullable) NSPredicate *basePredicate;

/**
 *  Creates a map view that automatically handles fetching Realm objects and displaying annotations
 *
 *  @param entityName       the class name for the Realm objects to fetch
 *  @param realm            the Realm in which the fetched Realm objects exists
 *  @param latitudeKeyPath  the key path on fetched Realm objects for the latitude value
 *  @param longitudeKeyPath the key path on fetched Realm objects for the longitude value
 *  @param titleKeyPath     the key path on fetched Realm objects for the title of the annotation view
 *  @param subtitleKeyPath  the key path on fetched Realm objects for the subtitle of the annotation view
 *
 *  @return instance of ABFRealmMapView
 */
- (nonnull instancetype)initWithEntityName:(nonnull NSString *)entityName
                                   inRealm:(nonnull RLMRealm *)realm
                           latitudeKeyPath:(nonnull NSString *)latitudeKeyPath
                          longitudeKeyPath:(nonnull NSString *)longitudeKeyPath
                              titleKeypath:(nonnull NSString *)titleKeyPath
                           subtitleKeyPath:(nonnull NSString *)subtitleKeyPath;

/**
 *  Performs a fresh fetch for Realm objects based on the current visible map rect
 *
 *  @see autoRefresh
 */
- (void)refreshMapView;

@end


text:
                <button type="button" class="close" data-dismiss="modal">×</button>

Import Links

                <?= Form::open(['url' => action('LinkController@import'), 'method' => 'POST', 'files' => true]) ?>

                File to import
                <?= Form::file('resource', ['id' => 'inputFile', 'required'=>'true']) ?>

Select a local File to import

                    <?= Form::label('project_id', 'Select Project to Import Links') ?>
                    <?= Form::select('project_id', $projects->pluck('name', 'id')->all(), null, ['class' => 'form-control']) ?>

                      <input type="radio" name="filetype" id="optionsRDFXML" value="rdfxml" checked="">
                      RDF/XML

                      <input type="radio" name="filetype" id="optionsTurtle" value="turtle">
                      Turtle

                      <input type="radio" name="filetype" id="optionsNtriples" value="ntriples">
                      N-Triples

                      <input type="radio" name="filetype" id="optionsTriG" value="trig">
                      TriG

                      <input type="radio" name="filetype" id="optionsNQuads" value="nquads">
                      N-Quads

                <?= Form::submit('Import') ?>
                <?= Form::close() ?>


text:
#ifndef FACE_ALIGNMENT_H
#define FACE_ALIGNMENT_H

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include "cv.h"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <ctime>
#include <string>
#include <limits>
#include <algorithm>
#include <cmath>
#include <vector>
#include <fstream>
#include <numeric>
#include <utility>

#define BINARY_IO

struct BoundingBox{
        double start_x;
        double start_y;
        double width;
        double height;
        double centroid_x;
        double centroid_y;
};

struct FeatureExtractor
{
	template <class T> inline T clamp(const T& v, const T& v_min, const T& v_max) { return std::max(v_min, std::min(v, v_max)); }
	cv::Mat1i selected_nearest_landmark_index_;
	cv::Mat1d threshold_;

	// the index of selected pixels pairs in fern
	std::vector<cv::Point2d> selected_pixel_index_;

	// the locations of selected pixel pairs stored in the format (x_1,y_1)(x_2,y_2) for each row
	std::pair<cv::Mat1d, cv::Mat1d> selected_pixel_locations_;

	std::vector<bool> feature_vector(const cv::Mat_<uchar>& image, const cv::Mat1d& shape, const cv::Mat1d& rotation, const BoundingBox& bounding_box, const double scale)
	{
		const auto get_intensity = [&](const cv::Mat1d& pixel_locations, const int i, const bool is_y_coord) {
			const int& nearest_landmark_index = selected_nearest_landmark_index_(i, is_y_coord ? 1 : 0);
			const double& x = pixel_locations(i, 0);
			const double& y = pixel_locations(i, 1);
			const double project_x = scale * (rotation(0, 0) * x + rotation(0, 1) * y) * bounding_box.width / 2.0 + shape(nearest_landmark_index, 0);
			const double project_y = scale * (rotation(1, 0) * x + rotation(1, 1) * y) * bounding_box.height / 2.0 + shape(nearest_landmark_index, 1);
			const double bounded_project_x = clamp(project_x, 0.0, image.cols - 1.0);
			const double bounded_project_y = clamp(project_y, 0.0, image.rows - 1.0);
			const double intensity = double(image(bounded_project_y, bounded_project_x));
			return intensity;
		};
	}
};

class Fern
{
	int fern_pixel_num_;
	int landmark_num_;

	cv::Mat1i selected_nearest_landmark_index_;
	cv::Mat1d threshold_;

	// fern_pixel_num*2 matrix, the index of selected pixels pairs in fern
	//cv::Mat1i selected_pixel_index_;
	std::vector<cv::Point2d> selected_pixel_index_;

	// fern_pixel_num*4 matrix, the locations of selected pixel pairs stored in the format (x_1,y_1,x_2,y_2) for each row
	//cv::Mat1d selected_pixel_locations_;
	std::pair<cv::Mat1d, cv::Mat1d> selected_pixel_locations_;

	std::vector<cv::Mat1d> bin_output_;
public:
	std::vector<cv::Mat1d> Train(const std::vector<std::vector<double> >& candidate_pixel_intensity,
		const cv::Mat1d& covariance,
		const cv::Mat1d& candidate_pixel_locations,
		const cv::Mat1i& nearest_landmark_index,
		const std::vector<cv::Mat1d >& regression_targets,
		int fern_pixel_num);

	void FeatureSelection(int fern_pixel_num,
		const std::vector<cv::Mat1d> &regression_targets,
		int candidate_pixel_num,
		const std::vector<std::vector<double>> &candidate_pixel_intensity,
		const cv::Mat1d& covariance,
		const cv::Mat1d& candidate_pixel_locations,
		const cv::Mat1i& nearest_landmark_index);

	const cv::Mat1d& Predict(const cv::Mat_<uchar>& image,
		const cv::Mat1d& shape,
		const cv::Mat1d& rotation,
		const BoundingBox& bounding_box,
		const double scale) const;
	void Read(std::istream& fin);
	void Write(std::ostream& fout);
};

class FernCascade{
    public:
        std::vector<cv::Mat_<double> > Train(const std::vector<cv::Mat_<uchar> >& images,
                                             const std::vector<cv::Mat_<double> >& current_shapes,
                                             const std::vector<cv::Mat_<double> >& ground_truth_shapes,
                                             const std::vector<BoundingBox> & bounding_box,
                                             const cv::Mat_<double>& mean_shape,
                                             int second_level_num,
                                             int candidate_pixel_num,
                                             int fern_pixel_num,
                                             int curr_level_num,
                                             int first_level_num);
        cv::Mat_<double> Predict(const cv::Mat_<uchar>& image,
                                 const BoundingBox& bounding_box,
                                 const cv::Mat_<double>& mean_shape,
                                 const cv::Mat_<double>& shape);
        void Read(std::istream& fin);
        void Write(std::ostream& fout);
    private:
        std::vector<Fern> ferns_;
        int second_level_num_;
};

class ShapeRegressor{
    public:
        ShapeRegressor();
        void Train(const std::vector<cv::Mat_<uchar> >& images,
                   const std::vector<cv::Mat_<double> >& ground_truth_shapes,
                   const std::vector<BoundingBox>& bounding_box,
                   int first_level_num, int second_level_num,
                   int candidate_pixel_num, int fern_pixel_num,
                   int initial_num);
        cv::Mat_<double> Predict(const cv::Mat_<uchar>& image, const BoundingBox& bounding_box, int initial_num, const cv::Mat1d& initial_contour = cv::Mat1d());
        void Read(std::istream& fin);
        void Write(std::ostream& fout);
        void Load(std::string path);
        void Save(std::string path);
    private:
        int first_level_num_;
        int landmark_num_;
        std::vector<FernCascade> fern_cascades_;
        cv::Mat_<double> mean_shape_;
        std::vector<cv::Mat_<double> > training_shapes_;
        std::vector<BoundingBox> bounding_box_;
};

cv::Mat_<double> GetMeanShape(const std::vector<cv::Mat_<double> >& shapes,
                              const std::vector<BoundingBox>& bounding_box);
cv::Mat_<double> ProjectShape(const cv::Mat_<double>& shape, const BoundingBox& bounding_box);
cv::Mat_<double> ReProjectShape(const cv::Mat_<double>& shape, const BoundingBox& bounding_box);
void SimilarityTransform(const cv::Mat_<double>& shape1, const cv::Mat_<double>& shape2,
                         cv::Mat_<double>& rotation,double& scale);
double calculate_covariance(const std::vector<double>& v_1,
                            const std::vector<double>& v_2);

namespace io {

	//void draw_landmarks(cv::Mat3b& image, const cv::Mat1d& landmarks, const double thickness, const cv::Scalar& color);

	// TODO: Code is not portable, just fast error-prone solution
	template<class T>
	void write_scalar(std::ostream& o, const T& s)
	{
		o.write((char*)&s, sizeof(T));
	}
	template<class T>
	void read_scalar(std::istream& i, T& s)
	{
		i.read((char*)&s, sizeof(T));
	}

	template<class T>
	void write_mat(std::ostream& o, cv::Mat_<T>& m)
	{
		static_assert(std::is_same<T, double>::value || std::is_same<T, float>::value || std::is_same<T, int>::value || std::is_same<T, char>::value, "");

		io::write_scalar(o, m.cols);
		io::write_scalar(o, m.rows);
		const int m_bytesize = m.total() * m.elemSize();
		o.write(reinterpret_cast<char*>(m.data), m_bytesize);
	}

	template<class T>
	void read_mat(std::istream& i, cv::Mat_<T>& m)
	{
		static_assert(std::is_same<T, double>::value || std::is_same<T, float>::value || std::is_same<T, int>::value || std::is_same<T, char>::value, "");

		io::read_scalar(i, m.cols);
		io::read_scalar(i, m.rows);
		m.create(m.rows, m.cols);

		const int m_bytesize = m.cols * m.rows * m.elemSize();
		i.read(reinterpret_cast<char*>(m.data), m_bytesize);
	}

	template<class T>
	void write_vector(std::ostream& o, const std::vector<T>& v)
	{
		static_assert(!std::is_pointer<T>::value, "");
		io::write_scalar(o, v.size());
		o.write((char*)&v[0], v.size() * sizeof(T));
	}

	template<class T>
	void read_vector(std::istream& i, std::vector<T>& v)
	{
		static_assert(!std::is_pointer<T>::value, "");
		size_t size;
		io::read_scalar(i, size);
		v.resize(size);
		i.read((char*)&v[0], v.size() * sizeof(T));
	}

}

#endif


text:
package com.myconnector.webservice;

import java.util.List;

import com.myconnector.dto.TodoListDTO;
import com.myconnector.dto.TodoListSimpleDTO;

public interface TodoWebService extends BaseWS {

    public List<TodoListSimpleDTO> getTodoLists();

    public TodoListDTO getCompleteListById(Long id);

    /***
     *
     * @param title
     * @return id of newly created todo list
     */
    public Long addTodoList(String title);

    /**
     *
     * @param todoListId
     * @param title
     * @return id of newly created todo item
     */
    public Long addTodoItem(Long todoListId, String title);

    public void updateTodoList(Long id, String title);

    public void updateTodoItem(Long id, String title);

    public void moveTodoItem(Long todoItemId, Long destinationTodoListId);

//    public TodoDTO getTodo(String id);
//    public void saveTodo(TodoDTO todo);
//    public void updateTodo(TodoDTO todo);
//    public void deleteTodoById(String id);
//    public TodoDTO[] getTodoList();
//    public TodoDTO[] getTodoListSortedBy(String orderBy, boolean descending);

}


text:
{base},
Standard as (
SELECT distinct SOURCE_CODE, TARGET_CONCEPT_ID, TARGET_DOMAIN_ID, SOURCE_VALID_START_DATE as VALID_START_DATE, SOURCE_VALID_END_DATE as VALID_END_DATE, SOURCE_VOCABULARY_ID
FROM Source_to_Standard
WHERE lower(SOURCE_VOCABULARY_ID) IN ('cvx')
AND (TARGET_STANDARD_CONCEPT IS NOT NULL or TARGET_STANDARD_CONCEPT != '')
AND (TARGET_INVALID_REASON IS NULL or TARGET_INVALID_REASON = '')
), Source as (
SELECT distinct SOURCE_CODE, TARGET_CONCEPT_ID, SOURCE_VALID_START_DATE, SOURCE_VALID_END_DATE
FROM Source_to_Source
WHERE lower(SOURCE_VOCABULARY_ID) IN ('cvx')
AND lower(TARGET_VOCABULARY_ID) IN ('cvx')
), S_S as
(
select SOURCE_CODE from Standard
union
select SOURCE_CODE from Source
)

select distinct S_S.SOURCE_CODE, Standard.TARGET_CONCEPT_ID, Standard.TARGET_DOMAIN_ID, Standard.VALID_START_DATE, Standard.VALID_END_DATE, Standard.SOURCE_VOCABULARY_ID, Source.TARGET_CONCEPT_ID as SOURCE_TARGET_CONCEPT_ID, Source.SOURCE_VALID_START_DATE as SOURCE_VALID_START_DATE, Source.SOURCE_VALID_END_DATE, ingredient_level.ingredient_concept_id
from S_S
left join Standard on Standard.SOURCE_CODE = S_S.SOURCE_CODE
left join Source on Source.SOURCE_CODE = S_S.SOURCE_CODE
left join ingredient_level on ingredient_level.concept_id = Standard.TARGET_CONCEPT_ID


text:
layout: doc
title: "RouterService"
position: 1011
---

RouterService позволяет настроить маршрутизацию для Single Page Application.

Объект RouterService доступен через `InfinniUI.RouterService`.

# Description

RouterService предоставляет возможность настройки маршрутизации на стороне клиента, а также связывания этих действий с событиями. Для браузеров, которые не поддерживают History API, RouterService проделает то же самое, используя фрагментарную структуру URL.

Во время загрузки страницы, после того, как ваше приложение откроет HomePage view и будут созданы все роуты описанные в [InfinniUI.config.Routes](../../Config), автоматически будет запущен роутер используя настройки History API из [InfinniUI.config.HistoryAPI](../../Config). RouterService представляет собой обертку над [Backbone.Router](http://backbonejs.org/#Router).

## Parameters

Нет.

# Methods

|Name|Description|
|----|---------|
|[`getLinkByName()`](RouterService.getLinkByName/)|Возвращает путь соответсвующий переданому имени.|
|[`startRouter()`](RouterService.startRouter/)|Запускает роутинг.|
|[`setContext()`](RouterService.setContext/)|Устанавливает контекст, который будет передаваться в скрипты, вызываемые RouterService.|
|[`setParams()`](RouterService.setParams/)|Устанавливает параметры, который будут передаваться в скрипты, вызываемые RouterService.|
|[`addParams()`](RouterService.addParams/)|Добавляет параметры, которые нужно передавать в скрипты, вызываемые RouterService.|


text:
export type TraverseObjectCallBack = (
  keyPath: string[],
  value: any,
  key: string,
  obj: any
) => void;

export function traverseObject(
  traversedObject,
  fn: TraverseObjectCallBack,
  keyPath: any[] = []
) {
  if (traversedObject === null) {
    return;
  }
  Object.entries(traversedObject).forEach(([key, value]) => {
    fn([...keyPath, key], value, key, traversedObject);
    if (typeof value === "object") {
      traverseObject(value, fn, [...keyPath, key]);
    }
  });
}


text:
/** Automatically generated file. DO NOT MODIFY */
package ryebread761.darktube;

public final class BuildConfig {
    public final static boolean DEBUG = true;
}


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="match_parent"
    android:gravity="center">
    <ImageView
        android:id="@+id/imv_empty"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/empty"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:text="获取不到相关数据"
        android:textColor="#0277bd"
        android:textSize="18sp"/>

</LinearLayout>


text:
package twg2.text.test;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

import org.junit.Assert;
import org.junit.Test;

import twg2.junitassist.checks.CheckTask;
import twg2.text.stringUtils.StringJoin;

/**
 * @author TeamworkGuy2
 * @since 2015-5-26
 */
public class StringJoinTest {

	private static class ToString {
		private int idx;

		public ToString(int idx) {
			this.idx = idx;
		}

		@Override
		public String toString() {
			return "arg" + idx;
		}

	}

	final String delimiter = ", ";
	final String[] strAry = new String[] { "glarg", "narg", "warg", "varg", "yarg" };
	final List<String> strList = Arrays.asList(strAry);
	final Set<String> strSet = new LinkedHashSet<>(strList);

	final Object[] objAry = new Object[] { new ToString(0), "subset", new ToString(4), null, new File("a\\b\\c.d") };
	final List<Object> objList = Arrays.asList(objAry);
	final Set<Object> objSet = new LinkedHashSet<>(objList);
	final String[] objAryStrs = new String[] { "arg0", "subset", "arg4", "null", "a\\b\\c.d" };

	@Test
	public void joinStringList() {
		List<String> strList = Arrays.asList("A", "B", "C");
		Set<String> strSet = new HashSet<>();
		strSet.add("A");
		strSet.add("B");
		strSet.add("C");
		strSet.add("D");
		Collection<Collection<String>> strColls = Arrays.asList(strList, strSet);

		StringBuilder sb = new StringBuilder();

		for(Collection<String> strColl : strColls) {
			// baseline using java.util.StringJoiner
			Object[] ary = strColl.toArray();
			String expectedStr = stringJoiner(delimiter, ary, 0, ary.length);

			// test Iterable<String> -> String
			Assert.assertEquals(expectedStr, StringJoin.join(strColl, delimiter));

			// test Iterable<String> -> StringBuilder
			StringJoin.join(strColl, delimiter, sb);
			Assert.assertEquals(expectedStr, sb.toString());
			sb.setLength(0);

			expectedStr = stringJoiner(delimiter, ary, 1, 2);

			// test Iterable<String> -> String
			Assert.assertEquals(expectedStr, StringJoin.join(strColl, 1 ,2, delimiter));

			// test Iterable<String> -> StringBuilder
			StringJoin.join(strColl, 1, 2, delimiter, sb);
			Assert.assertEquals(expectedStr, sb.toString());
			sb.setLength(0);
		}

		// test List<String> -> String
		Assert.assertEquals("A, B, C", StringJoin.join(Arrays.asList("A", "B", "C"), ", "));
		Assert.assertEquals("", StringJoin.join(Arrays.asList(), ", "));

		// test (List<String>, dst) -> String
		StringJoin.join(strList, ", ", sb);
		Assert.assertEquals("A, B, C", sb.toString());
	}

	@Test
	public void joinStringListOffLen() {
		List<String> strColl = Arrays.asList("0", "A", "B", "C", "D", "E");

		// baseline using java.util.StringJoiner
		Object[] ary = strColl.toArray();
		String expectedStr = stringJoiner(delimiter, ary, 1, 3);

		// test Iterable<String> -> String
		Assert.assertEquals(expectedStr, StringJoin.join(strColl, 1, 3, delimiter));

		// test Iterable<String> -> StringBuilder
		StringBuilder sb = new StringBuilder();

		StringJoin.join(strColl, 1, 3, delimiter, sb);
		Assert.assertEquals(expectedStr, sb.toString());
	}

	@Test
	public void joinStringsIterable() {
		// test Iterable<String> -> String
		Assert.assertEquals(stringJoiner(delimiter, strAry, 0, strAry.length), StringJoin.join(strSet, delimiter));
		Assert.assertEquals(stringJoiner(delimiter, strAry, 1, 2), StringJoin.join(strSet, 1, 2, delimiter));

		// test (Iterable<String>, dst) -> String
		StringBuilder sb = new StringBuilder();

		StringJoin.join(strSet, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, strAry, 0, strAry.length), sb.toString());
		sb.setLength(0);

		StringJoin.join(strSet, 2, 3, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, strAry, 2, 3), sb.toString());
	}

	@Test
	public void joinStringsIterator() {
		// test Iterator<String> -> String
		Assert.assertEquals(stringJoiner(delimiter, strAry, 0, strAry.length), StringJoin.join(strList.iterator(), delimiter));
		Assert.assertEquals(stringJoiner(delimiter, strAry, 1, 2), StringJoin.join(strList.iterator(), 1, 2, delimiter));

		// test (Iterator<String>, dst) -> String
		StringBuilder sb = new StringBuilder();

		StringJoin.join(strList.iterator(), delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, strAry, 0, strAry.length), sb.toString());
		sb.setLength(0);

		StringJoin.join(strList.iterator(), 2, 3, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, strAry, 2, 3), sb.toString());
	}

	@Test
	public void joinStringArray() {
		// test String[] -> String
		Assert.assertEquals(stringJoiner(delimiter, strAry, 0, strAry.length), StringJoin.join(strAry, delimiter));
	}

	@Test
	public void joinStringArrayOffLen() {
		// test (String[], off, len) -> String
		Assert.assertEquals("null, Cc", StringJoin.join(new String[] { "A", null, "Cc", "Dd" }, 1, 2, ", "));

		// test (String[], off, len, dst) -> String
		StringBuilder sb  = new StringBuilder();

		StringJoin.join(strAry, 2, 2, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, strAry, 2, 2), sb.toString());
	}

	@Test
	public void joinObjectsArray() {
		// test Object[] -> String
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 0, objAryStrs.length), StringJoin.join(objAry, delimiter));
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 2, 3), StringJoin.join(objAry, 2, 3, delimiter));
		Assert.assertEquals("", StringJoin.join(new Object[0], ", "));

		// test (Object[], off, len, dst) -> String
		StringBuilder sb = new StringBuilder();

		StringJoin.join(objAry, 2, 2, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 2, 2), sb.toString());
	}

	@Test
	public void joinObjectsList() {
		// test List<Object> -> String
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 0, objAryStrs.length), StringJoin.join(objList, delimiter));
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 2, 2), StringJoin.join(objList, 2, 2, delimiter));

		// test (List<Object>, dst) -> String
		StringBuilder sb = new StringBuilder();

		StringJoin.join(objList, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 0, objAryStrs.length), sb.toString());
	}

	@Test
	public void joinObjectsIterable() {
		// test Iterable<Object> -> String
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 0, objAryStrs.length), StringJoin.join(objSet, delimiter));
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 1, 2), StringJoin.join(objSet, 1, 2, delimiter));

		// test (Iterable<Object>, dst) -> String
		StringBuilder sb = new StringBuilder();

		StringJoin.join(objSet, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 0, objAryStrs.length), sb.toString());
		sb.setLength(0);

		StringJoin.join(objSet, 2, 3, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 2, 3), sb.toString());
	}

	@Test
	public void joinObjectsIterator() {
		// test Iterator<Object> -> String
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 0, objAryStrs.length), StringJoin.join(objList.iterator(), delimiter));
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 1, 2), StringJoin.join(objList.iterator(), 1, 2, delimiter));

		// test (Iterator<Object>, dst) -> String
		StringBuilder sb = new StringBuilder();

		StringJoin.join(objList.iterator(), delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 0, objAryStrs.length), sb.toString());
		sb.setLength(0);

		StringJoin.join(objList.iterator(), 2, 3, delimiter, sb);
		Assert.assertEquals(stringJoiner(delimiter, objAryStrs, 2, 3), sb.toString());
	}

	@Test
	public void stringJoinFunc() {
		Assert.assertEquals("", StringJoin.join(Arrays.asList(), delimiter, (a) -> "t:" + a));
		Assert.assertEquals("t:a", StringJoin.join(Arrays.asList("a"), delimiter, (a) -> "t:" + a));
		Assert.assertEquals("t:arg2, t:arg12", StringJoin.join(Arrays.asList(new ToString(2), new ToString(12)), delimiter, (a) -> "t:" + a));
		Assert.assertEquals("t:arg2, null", StringJoin.join(Arrays.asList(new ToString(2), null), delimiter, (a) -> "t:" + a));
		Assert.assertEquals("t:arg2, t:NIL", StringJoin.joinManualNulls(Arrays.asList(new ToString(2), null), delimiter, (a) -> "t:" + (a != null ? a : "NIL")));
	}

	@Test
	public void repeatTest() throws IOException {
		Assert.assertEquals("---", StringJoin.repeat('-', 3));
		Assert.assertEquals("t+t+", StringJoin.repeat("t+", 2));
		Assert.assertEquals("str", StringJoin.repeat("str", 1));
		Assert.assertEquals("", StringJoin.repeat("str", 0));

		StringBuilder sb = new StringBuilder();
		StringJoin.repeat('5', 2, sb);
		Assert.assertEquals("55", sb.toString());
		sb.setLength(0);
		StringJoin.repeat("5*", 0, sb);
		Assert.assertEquals("", sb.toString());
		sb.setLength(0);
		StringJoin.repeat("5*", 3, sb);
		Assert.assertEquals("5*5*5*", sb.toString());
		sb.setLength(0);
	}

	@Test
	public void repeatJoinTest() throws IOException {
		Assert.assertEquals("A-A-A", StringJoin.repeatJoin("A", '-', 3));
		Assert.assertEquals("A", StringJoin.repeatJoin("A", '-', 1));
		Assert.assertEquals("str-str-str", StringJoin.repeatJoin("str", '-', 3));
		Assert.assertEquals("str", StringJoin.repeatJoin("str", '-', 1));
		Assert.assertEquals("", StringJoin.repeatJoin("str", '-', 0));

		Assert.assertEquals("A||A||A", StringJoin.repeatJoin("A", "||", 3));
		Assert.assertEquals("A", StringJoin.repeatJoin("A", "||", 1));
		Assert.assertEquals("str||str||str", StringJoin.repeatJoin("str", "||", 3));
		Assert.assertEquals("str", StringJoin.repeatJoin("str", "||", 1));
		Assert.assertEquals("", StringJoin.repeatJoin("str", "||", 0));
		Assert.assertEquals("A|A", StringJoin.repeatJoin("A", "|", 2));

		StringBuilder sb = new StringBuilder();
		StringJoin.repeatJoin("5", '-', 2, sb);
		Assert.assertEquals("5-5", sb.toString());
		sb.setLength(0);
		StringJoin.repeatJoin("5*", '-', 0, sb);
		Assert.assertEquals("", sb.toString());
		sb.setLength(0);
		StringJoin.repeatJoin("5*", '-', 3, sb);
		Assert.assertEquals("5*-5*-5*", sb.toString());
		sb.setLength(0);

		StringJoin.repeatJoin("5", "|", 2, sb);
		Assert.assertEquals("5|5", sb.toString());
		sb.setLength(0);
		StringJoin.repeatJoin("5*", "||", 0, sb);
		Assert.assertEquals("", sb.toString());
		sb.setLength(0);
		StringJoin.repeatJoin("5*", "||", 3, sb);
		Assert.assertEquals("5*||5*||5*", sb.toString());
		sb.setLength(0);
	}

	@Test
	public void stringJoinMiscellaneous() {
		String[][] strs = new String[][] { { "Aa", "Bb" }, { "123", "_", ".." }, { "", "" }, { "" } };
		String[] delimiters = new String[] { "-", "||", "=", "=" };
		String[] expect = new String[] { "Aa-Bb", "123||_||..", "=", "" };

		CheckTask.assertTests(strs, expect, (s, i) -> StringJoin.join(s, delimiters[i]));
	}

	private static String stringJoiner(String delimiter, Object[] strs, int off, int len) {
		StringJoiner strJoiner = new StringJoiner(delimiter);
		for(int i = off, size = off + len; i < size; i++) {
			strJoiner.add(strs[i].toString());
		}
		return strJoiner.toString();
	}

}


text:
package com.prime.dao;

import com.prime.api.PitchStats;

import java.util.List;

public interface PitchDao {

  public List<PitchStats> getMonthlyPitchStatsByPitcher(int pitcherId);

  public List<PitchStats> getYearlyPitchStatsByPitcher(int pitcherId);

}


text:
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace HealthMonitoring.Monitors.Http
{
    public class HttpMonitor : IHealthMonitor
    {
        static HttpMonitor()
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
        }

        public HttpMonitor() : this("http") { }

        protected HttpMonitor(string name)
        {
            Name = name;
        }

        public string Name { get; }

        public async Task<HealthInfo> CheckHealthAsync(string address, CancellationToken cancellationToken)
        {
            using (var client = new HttpClient())
            using (var response = await client.GetAsync(address, cancellationToken))
            {
                switch (response.StatusCode)
                {
                    case HttpStatusCode.NotFound:
                        return new HealthInfo(HealthStatus.NotExists);
                    case HttpStatusCode.ServiceUnavailable:
                        return new HealthInfo(HealthStatus.Offline);
                    case HttpStatusCode.OK:
                        return new HealthInfo(HealthStatus.Healthy, await ReadSuccessfulContent(response.Content));
                    default:
                        return new HealthInfo(HealthStatus.Faulty, await GetFaultyResponseDetails(response));
                }
            }
        }

        protected virtual Task<IReadOnlyDictionary<string, string>> ReadSuccessfulContent(HttpContent content)
        {
            IReadOnlyDictionary<string, string> result = new Dictionary<string, string>();
            return Task.FromResult(result);
        }

        private async Task<IReadOnlyDictionary<string, string>> GetFaultyResponseDetails(HttpResponseMessage response)
        {
            return new Dictionary<string, string>
            {
                {"code",response.StatusCode.ToString()},
                {"content",await response.Content.ReadAsStringAsync()}
            };
        }
    }
}


text:
namespace _3.Sum__Min__Max__Average
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class SumMinMaxAv
    {
        public static void Main()
        {
            int number = int.Parse(Console.ReadLine());

            PrintResults(number);
        }

        public static void PrintResults(int n)
        {
            var inputNums = new List<int>();

            for (int i = 0; i < n; i++)
            {
                var currNum = int.Parse(Console.ReadLine());
                inputNums.Add(currNum);
            }

            Console.WriteLine("Sum = {0}", inputNums.Sum());
            Console.WriteLine("Min = {0}", inputNums.Min());
            Console.WriteLine("Max = {0}", inputNums.Max());
            Console.WriteLine("Average = {0}", inputNums.Average());
        }
    }
}


text:
using System;
using Newtonsoft.Json;
using SFA.DAS.CosmosDb;

namespace SFA.DAS.EmployerAccounts.ReadStore.Models
{
    public abstract class Document : IDocument
    {
        [JsonProperty("id")]
        public Guid Id { get; protected set; }

        [JsonIgnore]
        public string ETag { get; private set; }

        [JsonProperty("_etag")]
        private string ReadOnlyETag { set => ETag = value; }

        [JsonProperty("metadata")]
        public DocumentMetadata Metadata { get; protected set;}

        protected Document(short schemaVersion, string schemaType)
        {
            Metadata = new DocumentMetadata(schemaVersion, schemaType);
        }

        protected Document()
        {
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>AssignmentGrade</title>
<meta name="date" content="2015-03-18">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

assignment

Class AssignmentGrade

java.lang.Object

assignment.AssignmentGrade

All Implemented Interfaces:

GraderObject

public abstract class AssignmentGrade
extends java.lang.Object
implements GraderObject

An AssignmentGrade contains an Assignment for which the grade is associated
  with, an integer, rawScore, which is the points assignment has earned, and
  a LetterGrade which represents the letter grade the assignment has earned.

Field Summary

Fields

Modifier and Type
Field and Description

(package private) Assignment
assignment

(package private) LetterGrade
letter

(package private) int
rawScore

(package private) User
user

Constructor Summary

Constructors

Constructor and Description

AssignmentGrade()

Method Summary

Methods

Modifier and Type
Method and Description

abstract Assignment
getAssignment()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

user

User user

assignment

Assignment assignment

rawScore

int rawScore

letter

LetterGrade letter

Constructor Detail

AssignmentGrade

public AssignmentGrade()

Method Detail

getAssignment

public abstract Assignment getAssignment()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method