text:
layout: post
title:  "ITA Baranov's Walkthrough. Chapter 8"
date:   2017-01-05
excerpt: "Linear Sorting"
tag:
- Sorting
- Algorithms
---

**Linear Sorting**
{: style="text-align: center;"}

The book has now introduced several algorithms that can sort n numbers in **O(nlgn)** time. Merge sort and heapsort achieve this upper bound in the worst case; quicksort achieves it on average. These algorithms share an interesting property: __the sorted order they determine is based only on comparisons between the input elements__. Thus, such sorting algorithms are called comparison sorts. By doing some math, you can prove that any comparison sort must make **Ω(nlgn)** comparisons in the worst case to sort n elements. Thus, merge sort and heapsort are asymptotically optimal, and no comparison sort exists that is faster by more than a constant factor.

**Counting sort**
{: style="text-align: center;"}
Counting sort assumes that each of the n input elements is an integer in the range 0 to k, for some integer k. When k = O(n), the sort runs in Θ(n) time.

COUNTING-SORT(A,B,k)
let C[0..k] be a new array
for i = 0 to k
	C[i] = 0
for j = 1 to A.length
	C[A[j]] = C[A[j]] + 1
// C[i] now contains the number of elements equal to i
for i = 1 to k
	C[i] = C[i] + C[i - 1]
// C[i] now has the number of elements less than or equal to i
for j = A.length downto 1
	B[C[A[j]]] = A[j]
	C[A[j]] = C[A[j]] - 1

Counting sort determines, for each input element x, the number of elements less than x. It uses this information to place element x directly into its position in the output array. In the code below we assume that the input is an array **A[1..n]**, and thus A.length = n. We need two other arrays: the array **B[1..n]** holds the sorted output, and the array **C[0..k]** provides temporary working storage.

![image-center](/images/countsort.png){: .align-center}

How much time does counting sort require? The first for loop takes time Θ(k), second one takes time Θ(n), third - Θ(k), fourth - Θ(n). Thus, the overall time is Θ(k+n). In practice, the algorithm is used when we have k = O(n), in which case the running time is **Θ(n)**.

Counting sort beats the comparison sorts' lower bound of Ω(nlgn). In fact, no comparisons between input elements occur anywhere in the code. Instead, counting sort uses the actual values of the elements to index into an array. An important property of counting sort is that it is **stable**: numbers with the same value appear in the output array in the same order as they do in the input array. This is important for our next algorithm.

**Radix sort**
{: style="text-align: center;"}

Radix sort solves the sorting problem counterintuitively - by sorting on the **least significant digit** first. In order for it to work, the digit sorts must be stable. The code for radix sort is straightforward. The following procedure assumes that each element in the n-element array A has d digits, where digit 1 is the lowest-order digit and digit d is the highest-order digit.

RADIX-SORT(A,d)
for i = 1 to d
	use a stable sort to sort array A on digit i

 ![image-center](/images/radixsort.png){: .align-center}

Is radix sort preferable to a comparison-based sorting algorithm, such as quicksort? Which sorting algorithm we prefer depends on the characteristics of the implementations, of the underlying machine (e.g., quicksort often uses hardware caches more effectively than radix sort), and of the input data. Moreover, the version of radix sort that uses counting sort as the intermediate stable sort does not sort in place, which many of the Θ(nlgn)-time comparison sorts do. Thus, when primary memory storage is at a premium, we might prefer an in-place algorithm such as quicksort.

**Bucket sort**
{: style="text-align: center;"}

Bucket sort assumes that the input is drawn from a uniform distribution and has an average-case running time of **O(n)**. Like counting sort, bucket sort is fast because it assumes something about the input. Whereas counting sort assumes that the input consists of integers in a small range, bucket sort assumes that the input is **generated by a random process** that distributes elements **uniformly** and independently over the interval **[0,1)**.

Bucket sort divides this interval into n equal-size subintervals, or **buckets**, and then distributes the n input numbers into the buckets. Since the inputs are uniformly and independently distributed, we don't expect many numbers to fall into each bucket. To produce the output, we simply sort the numbers in each bucket and then go through the buckets in order, listing the elements in each.

BUCKET-SORT(A)
n = A.length
let B[0..n - 1] be a new array
for i = 0 to n - 1
	make B[i] an empty list
for i = 1 to n
	insert A[i] into list B[floor(n*A[i])]
for i = 0 to n - 1
	sort list B[i] with insertion sort
concat the lists B[0], B[1], ..., B[n - 1] together in order

Even if the input is not drawn from a uniform distribution, bucket sort may still run in linear time. As long as the input has the property that the sum of the squares of the bucket sizes is linear in the total number of elements, the bucket sort will run in linear time.


text:
<?php

/**
 * @file
 * Contains \Drupal\system\Tests\Common\MergeAttachmentsTest.
 */

namespace Drupal\system\Tests\Common;

use Drupal\simpletest\KernelTestBase;

/**
 * Tests the merging of attachments.
 *
 * @see \Drupal::service('renderer')->mergeAttachments()
 *
 * @group Common
 */
class MergeAttachmentsTest extends KernelTestBase {

  /**
   * Tests library asset merging.
   */
  function testLibraryMerging() {
    $renderer = \Drupal::service('renderer');

    $a['#attached'] = array(
      'library' => array(
        'core/drupal',
        'core/drupalSettings',
      ),
      'drupalSettings' => [
        'foo' => ['d'],
      ],
    );
    $b['#attached'] = array(
      'library' => array(
        'core/jquery',
      ),
      'drupalSettings' => [
        'bar' => ['a', 'b', 'c'],
      ],
    );
    $expected['#attached'] = array(
      'library' => array(
        'core/drupal',
        'core/drupalSettings',
        'core/jquery',
      ),
      'drupalSettings' => [
        'foo' => ['d'],
        'bar' => ['a', 'b', 'c'],
      ],
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($a['#attached'], $b['#attached']), 'Attachments merged correctly.');

    // Merging in the opposite direction yields the opposite library order.
    $expected['#attached'] = array(
      'library' => array(
        'core/jquery',
        'core/drupal',
        'core/drupalSettings',
      ),
      'drupalSettings' => [
        'bar' => ['a', 'b', 'c'],
        'foo' => ['d'],
      ],
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($b['#attached'], $a['#attached']), 'Attachments merged correctly; opposite merging yields opposite order.');

    // Merging with duplicates: duplicates are simply retained, it's up to the
    // rest of the system to handle duplicates.
    $b['#attached']['library'][] = 'core/drupalSettings';
    $expected['#attached'] = array(
      'library' => array(
        'core/drupal',
        'core/drupalSettings',
        'core/jquery',
        'core/drupalSettings',
      ),
      'drupalSettings' => [
        'foo' => ['d'],
        'bar' => ['a', 'b', 'c'],
      ],
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($a['#attached'], $b['#attached']), 'Attachments merged correctly; duplicates are retained.');

    // Merging with duplicates (simple case).
    $b['#attached']['drupalSettings']['foo'] = ['a', 'b', 'c'];
    $expected['#attached'] = array(
      'library' => array(
        'core/drupal',
        'core/drupalSettings',
        'core/jquery',
        'core/drupalSettings',
      ),
      'drupalSettings' => [
        'foo' => ['a', 'b', 'c'],
        'bar' => ['a', 'b', 'c'],
      ],
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($a['#attached'], $b['#attached']));

    // Merging with duplicates (simple case) in the opposite direction yields
    // the opposite JS setting asset order, but also opposite overriding order.
    $expected['#attached'] = array(
      'library' => array(
        'core/jquery',
        'core/drupalSettings',
        'core/drupal',
        'core/drupalSettings',
      ),
      'drupalSettings' => [
        'bar' => ['a', 'b', 'c'],
        'foo' => ['d', 'b', 'c'],
      ],
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($b['#attached'], $a['#attached']));

    // Merging with duplicates: complex case.
    // Only the second of these two entries should appear in drupalSettings.
    $build = array();
    $build['a']['#attached']['drupalSettings']['commonTest'] = 'firstValue';
    $build['b']['#attached']['drupalSettings']['commonTest'] = 'secondValue';
    // Only the second of these entries should appear in drupalSettings.
    $build['a']['#attached']['drupalSettings']['commonTestJsArrayLiteral'] = ['firstValue'];
    $build['b']['#attached']['drupalSettings']['commonTestJsArrayLiteral'] = ['secondValue'];
    // Only the second of these two entries should appear in drupalSettings.
    $build['a']['#attached']['drupalSettings']['commonTestJsObjectLiteral'] = ['key' => 'firstValue'];
    $build['b']['#attached']['drupalSettings']['commonTestJsObjectLiteral'] = ['key' => 'secondValue'];
    // Real world test case: multiple elements in a render array are adding the
    // same (or nearly the same) JavaScript settings. When merged, they should
    // contain all settings and not duplicate some settings.
    $settings_one = array('moduleName' => array('ui' => array('button A', 'button B'), 'magical flag' => 3.14159265359));
    $build['a']['#attached']['drupalSettings']['commonTestRealWorldIdentical'] = $settings_one;
    $build['b']['#attached']['drupalSettings']['commonTestRealWorldIdentical'] = $settings_one;
    $settings_two_a = array('moduleName' => array('ui' => array('button A', 'button B', 'button C'), 'magical flag' => 3.14159265359, 'thingiesOnPage' => array('id1' => array())));
    $build['a']['#attached']['drupalSettings']['commonTestRealWorldAlmostIdentical'] = $settings_two_a;
    $settings_two_b = array('moduleName' => array('ui' => array('button D', 'button E'), 'magical flag' => 3.14, 'thingiesOnPage' => array('id2' => array())));
    $build['b']['#attached']['drupalSettings']['commonTestRealWorldAlmostIdentical'] = $settings_two_b;

    $merged = $renderer->mergeAttachments($build['a']['#attached'], $build['b']['#attached']);

    // Test whether #attached can be used to override a previous setting.
    $this->assertIdentical('secondValue', $merged['drupalSettings']['commonTest']);

    // Test whether #attached can be used to add and override a JavaScript
    // array literal (an indexed PHP array) values.
    $this->assertIdentical('secondValue', $merged['drupalSettings']['commonTestJsArrayLiteral'][0]);

    // Test whether #attached can be used to add and override a JavaScript
    // object literal (an associate PHP array) values.
    $this->assertIdentical('secondValue', $merged['drupalSettings']['commonTestJsObjectLiteral']['key']);

    // Test whether the two real world cases are handled correctly: the first
    // adds the exact same settings twice and hence tests idempotency, the
    // second adds *almost* the same settings twice: the second time, some
    // values are altered, and some key-value pairs are added.
    $settings_two['moduleName']['thingiesOnPage']['id1'] = array();
    $this->assertIdentical($settings_one, $merged['drupalSettings']['commonTestRealWorldIdentical']);
    $expected_settings_two = $settings_two_a;
    $expected_settings_two['moduleName']['ui'][0] = 'button D';
    $expected_settings_two['moduleName']['ui'][1] = 'button E';
    $expected_settings_two['moduleName']['ui'][2] = 'button C';
    $expected_settings_two['moduleName']['magical flag'] = 3.14;
    $expected_settings_two['moduleName']['thingiesOnPage']['id2'] = [];
    $this->assertIdentical($expected_settings_two, $merged['drupalSettings']['commonTestRealWorldAlmostIdentical']);
  }

  /**
   * Tests feed asset merging.
   */
  function testFeedMerging() {
    $renderer = \Drupal::service('renderer');

    $a['#attached'] = array(
      'feed' => array(
        array(
          'aggregator/rss',
          t('Feed title'),
        ),
      ),
    );
    $b['#attached'] = array(
      'feed' => array(
        array(
          'taxonomy/term/1/feed',
          'RSS - foo',
        ),
      ),
    );
    $expected['#attached'] = array(
      'feed' => array(
        array(
          'aggregator/rss',
          t('Feed title'),
        ),
        array(
          'taxonomy/term/1/feed',
          'RSS - foo',
        ),
      ),
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($a['#attached'], $b['#attached']), 'Attachments merged correctly.');

    // Merging in the opposite direction yields the opposite library order.
    $expected['#attached'] = array(
      'feed' => array(
        array(
          'taxonomy/term/1/feed',
          'RSS - foo',
        ),
        array(
          'aggregator/rss',
          t('Feed title'),
        ),
      ),
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($b['#attached'], $a['#attached']), 'Attachments merged correctly; opposite merging yields opposite order.');
  }

  /**
   * Tests html_head asset merging.
   */
  function testHtmlHeadMerging() {
    $renderer = \Drupal::service('renderer');

    $a['#attached'] = array(
      'html_head' => array(
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'charset' => 'utf-8',
          ),
          '#weight' => -1000,
        ),
        'system_meta_content_type',
      ),
    );
    $b['#attached'] = array(
      'html_head' => array(
        array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'Generator',
            'content' => 'Kitten 1.0 (https://www.drupal.org/project/kitten)',
          ),
        ),
        'system_meta_generator',
      ),
    );
    $expected['#attached'] = array(
      'html_head' => array(
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'charset' => 'utf-8',
          ),
          '#weight' => -1000,
        ),
        'system_meta_content_type',
        array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'Generator',
            'content' => 'Kitten 1.0 (https://www.drupal.org/project/kitten)',
          ),
        ),
        'system_meta_generator',
      ),
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($a['#attached'], $b['#attached']), 'Attachments merged correctly.');

    // Merging in the opposite direction yields the opposite library order.
    $expected['#attached'] = array(
      'html_head' => array(
        array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'Generator',
            'content' => 'Kitten 1.0 (https://www.drupal.org/project/kitten)',
          ),
        ),
        'system_meta_generator',
        array(
          '#tag' => 'meta',
          '#attributes' => array(
            'charset' => 'utf-8',
          ),
          '#weight' => -1000,
        ),
        'system_meta_content_type',
      ),
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($b['#attached'], $a['#attached']), 'Attachments merged correctly; opposite merging yields opposite order.');
  }

  /**
   * Tests html_head_link asset merging.
   */
  function testHtmlHeadLinkMerging() {
    $renderer = \Drupal::service('renderer');

    $a['#attached'] = array(
      'html_head_link' => array(
        array(
          'rel' => 'rel',
          'href' => 'http://rel.example.com',
        ),
        TRUE,
      ),
    );
    $b['#attached'] = array(
      'html_head_link' => array(
        array(
          'rel' => 'shortlink',
          'href' => 'http://shortlink.example.com',
        ),
        FALSE,
      ),
    );
    $expected['#attached'] = array(
      'html_head_link' => array(
        array(
          'rel' => 'rel',
          'href' => 'http://rel.example.com',
        ),
        TRUE,
        array(
          'rel' => 'shortlink',
          'href' => 'http://shortlink.example.com',
        ),
        FALSE,
      ),
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($a['#attached'], $b['#attached']), 'Attachments merged correctly.');

    // Merging in the opposite direction yields the opposite library order.
    $expected['#attached'] = array(
      'html_head_link' => array(
        array(
          'rel' => 'shortlink',
          'href' => 'http://shortlink.example.com',
        ),
        FALSE,
        array(
          'rel' => 'rel',
          'href' => 'http://rel.example.com',
        ),
        TRUE,
      ),
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($b['#attached'], $a['#attached']), 'Attachments merged correctly; opposite merging yields opposite order.');
  }

  /**
   * Tests http_header asset merging.
   */
  function testHttpHeaderMerging() {
    $renderer = \Drupal::service('renderer');

    $a['#attached'] = array(
      'http_header' => array(
        array(
          'Content-Type',
          'application/rss+xml; charset=utf-8',
        ),
      ),
    );
    $b['#attached'] = array(
      'http_header' => array(
        array(
          'Expires',
          'Sun, 19 Nov 1978 05:00:00 GMT',
        ),
      ),
    );
    $expected['#attached'] = array(
      'http_header' => array(
        array(
          'Content-Type',
          'application/rss+xml; charset=utf-8',
        ),
        array(
          'Expires',
          'Sun, 19 Nov 1978 05:00:00 GMT',
        ),
      ),
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($a['#attached'], $b['#attached']), 'Attachments merged correctly.');

    // Merging in the opposite direction yields the opposite library order.
    $expected['#attached'] = array(
      'http_header' => array(
        array(
          'Expires',
          'Sun, 19 Nov 1978 05:00:00 GMT',
        ),
        array(
          'Content-Type',
          'application/rss+xml; charset=utf-8',
        ),
      ),
    );
    $this->assertIdentical($expected['#attached'], $renderer->mergeAttachments($b['#attached'], $a['#attached']), 'Attachments merged correctly; opposite merging yields opposite order.');
  }

}

redpajama_set_name: RedPajamaGithub


text:
//
//  PKEmpty.h
//  ParseKit
//
//  Created by Todd Ditchendorf on 7/13/08.
//  Copyright 2009 Todd Ditchendorf. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <ParseKit/PKParser.h>

/*!
    @class      PKEmpty
    @brief      A <tt>PKEmpty</tt> parser matches any assembly once, and applies its assembler that one time.
    @details
Language elements often contain empty parts. For example, a language may at some point allow a list of parameters in parentheses, and may allow an empty list. An empty parser makes it easy to match, within the parenthesis, either a list of parameters or "empty".

*/
@interface PKEmpty : PKParser {

}

/*!
    @brief      Convenience factory method for initializing an autoreleased <tt>PKEmpty</tt> parser.
    @result     an initialized autoreleased <tt>PKEmpty</tt> parser.
*/
+ (id)empty;
@end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_84_bad.cpp
Label Definition File: CWE78_OS_Command_Injection.strings.label.xml
Template File: sources-sink-84_bad.tmpl.cpp
*/
/*
 * @description
 * CWE: 78 OS Command Injection
 * BadSource: console Read input from the console
 * GoodSource: Fixed string
 * Sinks: w32_execvp
 *    BadSink : execute command with wexecvp
 * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use
 *
 * */
#ifndef OMITBAD

#include "std_testcase.h"
#include "CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_84.h"

#include <process.h>
#define EXECVP _wexecvp

namespace CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_84
{
CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_84_bad::CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_84_bad(wchar_t * dataCopy)
{
    data = dataCopy;
    {
        /* Read input from the console */
        size_t dataLen = wcslen(data);
        /* if there is room in data, read into it from the console */
        if (100-dataLen > 1)
        {
            /* POTENTIAL FLAW: Read data from the console */
            if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL)
            {
                /* The next few lines remove the carriage return from the string that is
                 * inserted by fgetws() */
                dataLen = wcslen(data);
                if (dataLen > 0 && data[dataLen-1] == L'\n')
                {
                    data[dataLen-1] = L'\0';
                }
            }
            else
            {
                printLine("fgetws() failed");
                /* Restore NUL terminator if fgetws fails */
                data[dataLen] = L'\0';
            }
        }
    }
}

CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_84_bad::~CWE78_OS_Command_Injection__wchar_t_console_w32_execvp_84_bad()
{
    {
        wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL};
        /* wexecvp - searches for the location of the command among
         * the directories specified by the PATH environment variable */
        /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
        EXECVP(COMMAND_INT, args);
    }
}
}
#endif /* OMITBAD */


text:
using System;

class RemoveElementsFromArray
{
    static int[] output;
    static int maxLength;
    static void GenerateSubset(int[] arr, int[] subset, int index, int current, int elementsInSubset)
    {
        if (index == elementsInSubset)
        {
            CheckSubsets(subset, elementsInSubset);
            return;
        }

        for (int i = current; i < arr.Length; i++)
        {
            subset[index] = arr[i];
            GenerateSubset(arr, subset, index + 1, i + 1, elementsInSubset);
        }
    }

    static void CheckSubsets(int[] subset, int elementsInSubset)
    {
        for (int i = 1; i < elementsInSubset; i++)
        {
            if (subset[i] < subset[i - 1])
            {
                return;
            }
            if (i > maxLength)
            {
                maxLength = i;
                for (int j = 0; j <= maxLength; j++)
                {
                    output[j] = subset[j];
                }
            }
        }
    }

    static void Main()
    {
        Console.Write("Enter number of elements: ");
        int n = int.Parse(Console.ReadLine());
        int[] arr = new int[n];
        for (int index = 0; index < n; index++)
        {
            Console.Write("Enter element {0}: ", index);
            arr[index] = int.Parse(Console.ReadLine());
        }
        output = new int[n];
        int[] subset = new int[n];
        for (int elementsInSubset = 1; elementsInSubset <= n; elementsInSubset++)
        {
            GenerateSubset(arr, subset, 0, 0, elementsInSubset);
        }

        for (int i = 0; i <= maxLength; i++)
        {
            Console.WriteLine("{0} ", output[i]);
        }
    }
}


text:
<?php
//This Model Class was generated with Disco on: Sat, 25 Oct 14 12:52:13 -0400
Class user extends Disco\classes\Model {

    public $table = 'user';
    public $ids = 'id';

    public function createTable(){
        return DB::query('
            CREATE TABLE `user` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `email` varchar(120) NOT NULL,
              `password` varchar(180) NOT NULL,
              `created` datetime NOT NULL,
              `last_access` datetime DEFAULT NULL,
              `verified` tinyint(1) DEFAULT 0,
              `admin` tinyint(1) DEFAULT 0,
              PRIMARY KEY (`id`)
          )'
        );

    }//createTable

    public function signup($data){
        $data['password'] = Crypt::hash($data['password']);

        if($this->emailInUse($data['email'])){
            return -1;
        }//if

        $id = $this->insert($data);

        if($id)
            return $id;

        return 0;

    }//signup

    public function signin($email,$password){
        $row = $this->select('id')
            ->where(Array('email'=>$email,'password'=>Crypt::hash($password)))
            ->data()->fetch_assoc();

        if($row['id']){
            Session::set('user',$row['id']);
            Session::regen();
            return true;
        }//if

        return false;
    }//signin

    public function emailInUse($email){
        $result = $this->select('email')->where(Array('email'=>$email))->data();
        if($result->num_rows != 0){
            return true;
        }//if
        return false;
    }//emailInUse

}//user
?>


text:
<?xml version='1.0' encoding='UTF-8' ?>
<!--

    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<beanio xmlns="http://www.beanio.org/2012/03"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.beanio.org/2011/01 http://www.beanio.org/2011/01/mapping.xsd">

  <stream name="stream1" format="csv">
    <!-- TODO warning - if class is ommitted then this test case just does nothing; no messages consumed and no warnings! :) -->
    <record name="record1" class="map">
       <field name="${field1}" />
       <field name="${field2}" />
       <field name="age" type="int"/>
     </record>
  </stream>
</beanio>


text:
package com.cortez.samples.javaee7angular.rest;

import com.cortez.samples.javaee7angular.data.Person;
import com.cortez.samples.javaee7angular.pagination.PaginatedListWrapper;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.ws.rs.*;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import java.util.List;

/**
 * REST Service to expose the data to display in the UI grid.
 *
 * @author Roberto Cortez
 */
@Stateless
@ApplicationPath("/resources")
@Path("persons")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PersonResource extends Application {
    @PersistenceContext
    private EntityManager entityManager;

    private Integer countPersons() {
        Query query = entityManager.createQuery("SELECT COUNT(p.id) FROM Person p");
        return ((Long) query.getSingleResult()).intValue();
    }

    @SuppressWarnings("unchecked")
    private List<Person> findPersons(int startPosition, int maxResults, String sortFields, String sortDirections) {
        Query query =
                entityManager.createQuery("SELECT p FROM Person p ORDER BY p." + sortFields + " " + sortDirections);
        query.setFirstResult(startPosition);
        query.setMaxResults(maxResults);
        return query.getResultList();
    }

    private PaginatedListWrapper findPersons(PaginatedListWrapper wrapper) {
        wrapper.setTotalResults(countPersons());
        int start = (wrapper.getCurrentPage() - 1) * wrapper.getPageSize();
        wrapper.setList(findPersons(start,
                                    wrapper.getPageSize(),
                                    wrapper.getSortFields(),
                                    wrapper.getSortDirections()));
        return wrapper;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public PaginatedListWrapper listPersons(@DefaultValue("1")
                                            @QueryParam("page")
                                            Integer page,
                                            @DefaultValue("id")
                                            @QueryParam("sortFields")
                                            String sortFields,
                                            @DefaultValue("asc")
                                            @QueryParam("sortDirections")
                                            String sortDirections) {
        PaginatedListWrapper paginatedListWrapper = new PaginatedListWrapper();
        paginatedListWrapper.setCurrentPage(page);
        paginatedListWrapper.setSortFields(sortFields);
        paginatedListWrapper.setSortDirections(sortDirections);
        paginatedListWrapper.setPageSize(10);
        return findPersons(paginatedListWrapper);
    }

    @GET
    @Path("{id}")
    public Person getPerson(@PathParam("id") Long id) {
        return entityManager.find(Person.class, id);
    }

    @POST
    public Person savePerson(Person person) {
        if (person.getId() == null) {
            Person personToSave = new Person();
            personToSave.setName(person.getName());
            personToSave.setDescription(person.getDescription());
            personToSave.setImageUrl(person.getImageUrl());
            entityManager.persist(person);
        } else {
            Person personToUpdate = getPerson(person.getId());
            personToUpdate.setName(person.getName());
            personToUpdate.setDescription(person.getDescription());
            personToUpdate.setImageUrl(person.getImageUrl());
            person = entityManager.merge(personToUpdate);
        }

        return person;
    }

    @DELETE
    @Path("{id}")
    public void deletePerson(@PathParam("id") Long id) {
        entityManager.remove(getPerson(id));
    }
}


text:
interface ITest {
  void act<caret>ion(Object o);
}

class Test implements ITest{

  public void action(Object o) {
  }

  private class ActionHandler {
    public void handleAction(Object o, Object o1) {
      action(o);
    }
  }
}


text:
package engine

// Table is defined by a name and attributes
// A table with data is called a Relation
type Table struct {
	name       string
	attributes []Attribute
}

// NewTable initializes a new Table
func NewTable(name string) *Table {
	t := &Table{
		name: name,
	}

	return t
}

// AddAttribute is used by CREATE TABLE and ALTER TABLE
// Want to check that name isn't already taken
func (t *Table) AddAttribute(attr Attribute) error {
	t.attributes = append(t.attributes, attr)
	return nil
}

// String returns a printable string with table name and attributes
func (t Table) String() string {
	stringy := t.name + " ("
	for i, a := range t.attributes {
		if i != 0 {
			stringy += " | "
		}
		stringy += a.name + " " + a.typeName
	}
	stringy += ")"
	return stringy
}


text:
package io.springside.springtime.examples.helloservice;

import static org.assertj.core.api.Assertions.*;

import java.io.IOException;

import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * via HTTP 1.1
 */
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
public class GreetingServerWithApacheTest {

	@Test
	public void helloService() throws ClientProtocolException, IOException {
		String requestJson = "{\"name\":\"david\"}";
		String expectdResponse = "{\"message\":\"Hello david\"}";
		String response = Request.Post("http://localhost:8080/rpc/greeting/hello").version(HttpVersion.HTTP_1_1)
				.bodyString(requestJson, ContentType.APPLICATION_JSON).execute().returnContent().asString();
		assertThat(response).isEqualTo(expectdResponse);
	}

	@Test
	public void weatherService() throws ClientProtocolException, IOException {
		String requestJson = "{\"city\":{\"name\":\"guangzhou\"}}";
		String expectdResponse = "{\"weather\":\"Sunny at guangzhou\"}";

		String response = Request.Post("http://localhost:8080/rpc/greeting/weather").version(HttpVersion.HTTP_1_1)
				.bodyString(requestJson, ContentType.APPLICATION_JSON).execute().returnContent().asString();
		assertThat(response).isEqualTo(expectdResponse);
	}

	@Test
	public void helloRest() throws ClientProtocolException, IOException {
		String expectdResponse = "Hello World!";
		String response = Request.Get("http://localhost:8080/web/hello").version(HttpVersion.HTTP_1_1).execute()
				.returnContent().asString();
		assertThat(response).isEqualTo(expectdResponse);
	}
}


text:
'Gomoku players'

from __future__ import print_function
from ..board import InvalidMoveError
from .lib import Playerlibrary

# base class
class Player(Playerlibrary):
    """
    Describtion of a player to be used in the Game.
    To implement your own AI, override the function
    ``_make_move``.
    .. important::
        Note the leading underscore. Do *NOT* override ``make_move``.
    The member string ``name`` appears in the options dialog.

    :param color:

        The color that the player plays as described in "board.py".

    """
    def __init__(self, color):
        self.color = color

    def make_move(self, gui):
        """
        Place a stone onto the `board`.
        This is a common function that *should not be overridden*.
        Override ``_make_move`` instead.

        :param gui:

            The game ``BoardGui`` as described in "gui.py"

        """
        gui.renew_board()
        if hasattr(gui.board, 'lastmove'):
            gui.highlight_lastmove()
        gui.color_in_turn = self.color
        moves_left = gui.board.moves_left

        self._make_move(gui)

        if not gui.in_game:
            return

        if not moves_left - 1 == gui.board.moves_left:
            raise InvalidMoveError('Player "%s" did not place a stone.' % self.name)

    def _make_move(self, gui):
        "Override this function for specific players"
        raise NotImplementedError

# Human player
class Human(Player):
    """
    A human player using a gui for input.

    :param color:

        The color that the player plays as described in "board.py".

    """
    name = 'Human'
    def _make_move(self, gui):
        # wait for user input
        gui.need_user_input = True
        moves_left = gui.board.moves_left
        while gui.board.moves_left == moves_left and gui.in_game:
            gui.update()
        gui.need_user_input = False

# search for player types in all files of this folder
available_player_types = [Human]
from os import listdir, path
player_directory = path.split(__file__)[0]
print('Searching for players in', player_directory)
filenames = listdir(player_directory)
filenames.sort() # search in alphabetical order
for filename in filenames:
    if filename[-3:] != '.py' or 'test' in filename or \
       filename == '__init__.py' or filename == 'lib.py':
           continue
    print('Processing', filename)
    exec('from . import ' + filename[:-3] + ' as playerlib')
    # search for classes derived from the base class ``Player``
    for objname in dir(playerlib):
        obj = playerlib.__dict__[objname]
        if type(obj) is not type or obj in available_player_types:
            continue
        if issubclass(obj, Player) and obj is not Player:
            print('    found', obj.name)
            available_player_types.append(obj)

# player management
available_player_names = [player.name for player in available_player_types]
def get_player_index(name, hint=None):
    """
    Convert the player name into an integer valued index.

    :param name:
        string; the name if the player that is listed in ``available_player_names``

    :param hint:
        integer, optional; the first index do be checked.

    """
    for i,n in enumerate(available_player_names):
        if n == name:
            return i
    # the following is executed if the name is not found
    raise ValueError('"%s" is not a registered player type' % name)


text:
// book.h

#ifndef BOOK_H
#define BOOK_H

// includes

#include "board.h"
#include "util.h"

// functions

extern void book_clear      ();

extern void book_open       (const char file_name[]);
extern void book_close      ();

extern bool is_in_book      (const board_t * board);
extern int  book_move       (const board_t * board, bool random);
extern void book_disp       (const board_t * board);

extern void book_learn_move (const board_t * board, int move, int result);
extern void book_flush      ();

#endif // !defined BOOK_H

// end of book.h


text:
#ifndef CXXLAPACK_INTERFACE_LARRC_H
#define CXXLAPACK_INTERFACE_LARRC_H 1

#include <cxxstd/complex.h>

namespace cxxlapack {

template <typename IndexType>
    IndexType
    larrc(char                  jobt,
          IndexType             n,
          float                 vl,
          float                 vu,
          const float           *d,
          const float           *e,
          float                 pivmin,
          IndexType             &eigcnt,
          IndexType             &lcnt,
          IndexType             &rcnt);

template <typename IndexType>
    IndexType
    larrc(char                  jobt,
          IndexType             n,
          double                vl,
          double                vu,
          const double          *d,
          const double          *e,
          double                pivmin,
          IndexType             &eigcnt,
          IndexType             &lcnt,
          IndexType             &rcnt);

} // namespace cxxlapack

#endif // CXXLAPACK_INTERFACE_LARRC_H


text:
/**
 * Wraps a <li class="tag"> representing a tag in the tag widget. Instances
 * are managed by a {TagList} to which they delegate both selection and DOM
 * event handling.
 */
wesabe.$class('wesabe.views.widgets.tags.TagListItem', wesabe.views.widgets.BaseWidget, function($class, $super, $package) {
  $.extend($class.prototype, {
    /**
     * Name of the tag (e.g. "food").
     */
    name: null,

    /**
     * URI for the tag (e.g. "/tags/food").
     *
     * See {wesabe.views.pages.accounts#storeState}.
     */
    uri: null,

    _tagList: null,
    _summary: null,
    _percent: null,
    _count: null,
    _nameElement: null,
    _countElement: null,

    init: function(element, tagList) {
      $super.init.call(this, element);
      this._tagList = tagList;
      this._nameElement = element.children('a.text-content');
      this._countElement = element.children('.count');
      // NOTE: Looking for a click handler binding?
      // See #onClick and TagList#onClick for an explanation of why it's not here.
    },

    /**
     * Handles changes to the current style of this {TagListItem}.
     */
    onStyleChanged: function(newStyle, oldStyle) {
      var size, display;

      if (newStyle == 'cloud') {
        size = ((95 + 120 * this._percent) + '%');
        display = 'inline';
      } else {
        size = '';
        display = 'block';
      }

      this.get('element').css('display', display);
      this._nameElement.css('font-size', size);
    },

    /**
     * Handles clicks for this {TagListItem}'s element, but is called
     * by the parent {TagList} since using event delegation means it
     * has the DOM event handler instead.
     *
     * See {TagList#onClick}.
     */
    onClick: function(event) {
      event.preventDefault();

      if ($(event.target).is('.edit-button')) {
        // clicked an edit pencil, start editing the tag
        this._tagList.onBeginEdit(this);
      } else if (event.metaKey || event.ctrlKey) {
        // cmd/ctrl+click to toggle the selection of the tag
        this._tagList.toggleListItemSelection(this);
      } else {
        // just clicked on the tag, so select it
        this.select();
      }
    },

    /**
     * Called by {wesabe.util.Selection} instances when this object
     * becomes part of the current selection.
     */
    onSelect: function() {
      if (this.get('element'))
        this.get('element').addClass('on');
    },

    /**
     * Called by {wesabe.util.Selection} instances when this object
     * ceases to be part of the current selection.
     */
    onDeselect: function() {
      if (this.get('element'))
        this.get('element').removeClass('on');
    },

    /**
     * Update the display for this {TagListItem} based on new data.
     */
    update: function(summary) {
      this.set('name', summary.tag.name);
      this.set('percent', summary.percent);
      this.set('count', summary.net.count);
    },

    /**
     * Sets the name of the tag and updates the label.
     */
    setName: function(name) {
      if (this.name === name)
        return;

      this.name = name;
      this.set('uri', '/tags/'+name);
      this._nameElement.text(name)
        .attr('href', '#'+this.uri);
    },

    /**
     * Sets the percent (size) of this tag list item.
     *
     * @private
     */
    _setPercent: function(percent) {
      if (this._percent === percent)
        return;

      this._percent = percent;
      this.onStyleChanged(this._tagList.get('style'));
    },

    /**
     * Sets the transaction count for this tag list item.
     *
     * @private
     */
    _setCount: function(count) {
      if (this._count === count)
        return;

      this._count = count;
      this._countElement.text(count);
    },

    /**
     * Gets the URL parameters for this {TagListItem}.
     *
     * See {wesabe.views.pages.accounts#paramsForCurrentSelection}.
     */
    toParams: function() {
      return [{name: 'tag', value: this.get('uri')}];
    },

    /**
     * Selects this {TagListItem}.
     */
    select: function() {
      this._tagList.selectListItem(this);
    }
  });
});


text:
CD Store - HBase solutions
==========================

* [What is HBase?](#what-is-hbase)
* [Missing native tools on Windows](#missing-native-tools-on-windows)
* [Docker setup update for Integration Testing](#docker-setup-update-for-integration-testing)
* [More setup details - Linux](#more-setup-details---linux)
* [More setup details - Windows](#more-setup-details---windows)

What is HBase?
--------------

Apache HBase (TM) is distributed NoSQL BigData database.

More info [here](https://hbase.apache.org/).

This project uses basic features of HBase:
- Single column family
- Writing single item
- Reading single item
- Scanning items with simple criteria (SingleColumnValueFilter for substring)
- Update cells of single item

Also shows possible configuration of development environment, solving a couple
of issues and making project portable.

Missing native tools on Windows
-------------------------------

HBase client uses native utils that are available on Linux, but not on Windows.
If we want to make it working on Windows, we need to explicitly load dll files
to compensate this shortage if Windows is detected.

Solution comes with two steps:

1. Maven

   Make sure Windows libraries are available in fat jar, so can be extracted if
   Windows is detected. To do this we should:

   1. Add maven repository so that libraries can be downloaded:

      ```xml
      <repository>
          <id>mapr</id>
          <name>Mapr releases repository</name>
          <url>http://repository.mapr.com/nexus/content/groups/mapr-public/releases</url>
      </repository>
      ```

    2. Add following dependency to `pom.xml`:

       ```xml
       <dependency>
           <groupId>org.apache.hadoop</groupId>
           <artifactId>hadoop-winutils</artifactId>
           <version>2.7.1</version>
           <type>zip</type>
           <scope>runtime</scope>
       </dependency>
        ```

        This brings files to root folder of fat jar.

2. Java

   Once dependency is there, unpack to temporary directory and load libraries
   if running on Windows:

    ```java
        if (SystemUtils.IS_OS_WINDOWS) {  // commons-lang3
            configureWindowsNatives();
        }
    ```

    ```java
    private void configureWindowsNatives() throws IOException {
        Path tempDirectory = Files.createTempDirectory("cdstore-");
        Path winUtils = tempDirectory.resolve("winutils");
        Path winUtilsBin = winUtils.resolve("bin");
        Files.createDirectories(winUtilsBin);
        System.setProperty("hadoop.home.dir", winUtils.toAbsolutePath().toString());

        for (String fileName: asList(
                "hadoop.dll", "hadoop.exp", "hadoop.lib", "hadoop.pdb",
                "libwinutils.lib", "winutils.exe", "winutils.pdb"))
            FileUtils.copyURLToFile(
                getClass().getResource("/" + fileName),
                winUtilsBin.resolve(fileName).toFile());
    }
    ```

    Now build/application should run on both: Linux and Windows.

Docker setup update for Integration Testing
-------------------------------------------

Even more interesting is Integration Testing, especially it's setup with
docker.

Many components that our applications connect to, exposes just a single port
which application can use. If that components run in docker container,
we can simply map that ports to ephemeral ports of docker host and configure
our tested application to connect to that mapped ones.

This approach does not work with HBase however. HBase client inside of
application running in host learns about region connection details from
Zookeeper, where region was registered before during HBase process startup.
Unfortunately HBase registers itself in Zookeeper with local (relative
to docker virtual network) host name and port that may not be available
from host (i.e. if we use docker machine).

To overcome this, we need to make sure that hostname that HBase registers
in Zookeeper (by default random docker container name) is resolvable by
host running client application. Moreover, we need to make sure that HBase is
available at that IP on exactly the same port that it was registered in
Zookeeper with. Of course, Zookeeper itself must be reachable as well, but this
is relatively _easy_ ;-)

Example:
- Docker machine interface: 192.168.99.100
- Docker bridge network (initially unreachable from host): 172.17.0.0/16
- HBase and Zookeeper running at 172.17.0.1
  - HBase Hostname: 15efb1840ce0
  - Zookeeper port: 2181/tcp
  - HBase Master port: 60000/tcp
  - HBase Region port: 60020/tcp

To examine what are IPs of docker bridge network and containers, we can use
following commands:
  ```
  $ docker network list
  $ docker network inspect bridge
  ```

With this configuration, HBase registers its region as 15efb1840ce0/60020.
One way to make it reachable from application running in host OS is:

1. Make sure that 172.17.0.1 is reachable from host.

   - If your docker does not use docker machine (default installation on Linux
     and Windows 10 Pro with Hyper-V), this should work out of the box.

   - If it does use docker machine, we need to add entry to routing table,
     so that traffic dedicated to 172.17.0.0/16 network is routed to
     192.168.99.100 gateway.

2. Make sure that 15efb1840ce0 is resolvable to 172.17.0.1 in host OS. This is
   a little bit challenging, since host names are chosen randomly and differ
   between runs.

   One possible option is to:

   - Run extra docker container hosting DNS server being able to resolve docker
     host names.

   - Expose it to host (map it's 53/udp port to docker host port).

   - Add docker host exposing DNS server as another DNS server to host OS, so
     that all applications running on host can use 15efb1840ce0 as synonym of
     172.17.0.1.

   I used one of publicly available docker images hosted DNS, basing on
   [dnsmasq](http://www.thekelleys.org.uk/dnsmasq/doc.html).

   Adding `<link/>` elements in DNS container configuration makes linked
   containers resolvable.

More setup details - Linux
--------------------------

We are starting with default Linux docker installation (no docker machine used).

0. Start containers: ```$ mvn docker:start```

1. Routing - No changes needed. To verify: ```$ ping 172.17.0.1```

2. DNS: ```# echo "nameserver 127.0.0.1" >> /etc/resolv.conf ```

3. Verify DNS:

   ```$ nslookup 15efb1840ce0```

   ```$ ping 15efb1840ce0```

4. Verify region availability: ```$ telnet 15efb1840ce0 60020```

More setup details - Windows
----------------------------

We are starting with default Windows docker installation, no Hyper-V (docker
machine used).

0. Start containers: ```C:\> mvn docker:start```

1. Routing -  As Administrator: ```C:\> route ADD 172.17.0.0 MASK 255.255.0.0 192.168.99.100```

   To verify: ```C:\>  ping 172.17.0.1 ```

2. DNS
   1. Go to details of network connection that is used to connect to your
      docker machine
   2. On _Networking_ tab select _Internet Protocol Version 4 (TCP/IPv4)_
   3. Click _Properties_
   4. On _General_ tab, section _Use the following DNS server addresses:_
      add IP of your docker machine (127.0.0.1 if you use docker on Windows with
      Hyper-V and no docker machine is needed/used)
   5. Click _Advanced_
   6. On _DNS_ tab add suffix "." (single dot). This prevents Windows from
      skipping using DNS while resolving names with empty domain (being just
      a single word representing hostname, as ones used by docker).
   7. Confirm by clicking _OK_ everywhere.
      See more info about _adding 'dot'_ e.g.
      [here](http://stackoverflow.com/questions/330395/dns-problem-nslookup-works-ping-doesnt#23377946)
   8. You may also need to refresh your DNS client:

    ```
    C:\> ipconfig /registerdns
    C:\> ipconfig /flushdns
    ```

3. Verify DNS:

   ```C:\> nslookup 15efb1840ce0```

   ```C:\> ping 15efb1840ce0```

3. Verify region availability: ```C:\> telnet 15efb1840ce0 60020```

Now you can start application or run all tests:

```mvn clean verify```

Enjoy :)


text:
function table_pagination(table_node){
  /*
  Simple table pagination with filtering support.

  To filter/skip a row from the table pagination, just include a 'filtered' class
  to the row (tr).
  */

  $(table_node).each(function() {
    var currentPage = 0;
    var numPerPage = 20;

    var $table = $(this);

    $table.bind('repaginate', function() {
      var first = currentPage * numPerPage;
      var last = first + numPerPage -1;
      var count = 0;

      $table.find('tbody tr').each(function() {
        if(!$(this).is('.filtered')) {
          if(first <= count && count <= last) {
            $(this).show();
          } else {
            $(this).hide();
        }
        count++;
      }
    });
  });

  $table.bind('setupPagination', function() {
    $table.siblings('.pager').remove();
    var numRows = $table.find('tbody tr:not(.filtered)').length;
    var numPages = Math.ceil(numRows / numPerPage);

    var $pager = $('

');
      for (var page = 0; page < numPages; page++) {
        $('' + (page + 1) + '')
          .bind('click', {'newPage': page}, function(event) {
            currentPage = event.data['newPage'];
            $table.trigger('repaginate');
            $(this).addClass('active').siblings().removeClass('active');
          })
          .appendTo($pager).addClass('clickable');
        }
        $pager.find('span.page-number:first').addClass('active');
        $pager.insertAfter($table);

        currentPage = 0;
        $table.trigger('repaginate');
    });

    $table.trigger('setupPagination');
  });

}


text:
set -e

url=http://ec2-52-28-130-84.eu-central-1.compute.amazonaws.com/config/scoring.project

curl -H "Content-Type: application/json; charset=ISO-8859-1" -X POST -d @scoring.project.js --header "X-Organizations: galanto" $url


text:
package com.aboutcoder.packease.utils.xml;

public class PEJsonXmlConfigFactory {
    /**
     * Place a singleton instance of PEJsonXMLConfig.
     */
    protected final PEJsonXMLConfig config;

    /**
     * Create a new factory.
     */
    public PEJsonXmlConfigFactory() {
        this(new PEJsonXMLConfig());
    }

    /**
     * Initial PEJsonXmlConfigFactory properties.
     *
     * @param config
     */
    protected PEJsonXmlConfigFactory(PEJsonXMLConfig config) {
        this.config = config;
    }

    /**
     * Build a new configuration.
     *
     * @return configuration instance
     */
    public PEJsonXMLConfig newPEJsonXmlConfigInstance() {
        return config.clone();
    }
}


text:
#pragma once

#include "../oovisualization_api.h"
#include "VKeywordMethodCallStyle.h"
#include "../expressions/VExpression.h"

#include "OOModel/src/expressions/MethodCallExpression.h"

#include "VisualizationBase/src/items/LayoutProvider.h"

namespace Visualization {
	class Static;
	class VList;
}

namespace OOVisualization {

class OOVISUALIZATION_API VKeywordMethodCall
	: public Super<VExpression<VKeywordMethodCall,
	  Visualization::LayoutProvider<>, OOModel::MethodCallExpression, false>>
{
		ITEM_COMMON(VKeywordMethodCall)

	public:
		VKeywordMethodCall(Item* parent, NodeType* node, const StyleType* style = itemStyles().get());
		virtual ~VKeywordMethodCall();

		Visualization::Static* keyword() const;
		Visualization::VList* arguments() const;

	protected:
		void determineChildren() override;

	private:
		Visualization::Static* keyword_;
		Visualization::VList* arguments_;
};

inline Visualization::Static* VKeywordMethodCall::keyword() const { return keyword_; }
inline Visualization::VList* VKeywordMethodCall::arguments() const { return arguments_; }

} /* namespace OOVisualization */


text:
require 'spec_helper'

describe InventoriesController do
  let(:user) { FactoryGirl.create(:user) }

  before :each do
    sign_in user
  end

  describe "POST create" do

    shared_examples "a valid inventory file" do
      it "creates a new inventory" do
        post :create, inventory: { csv_file: inventory_file }, :locale => "es"
        assigns(:inventory).should be_kind_of(Inventory)
        assigns(:inventory).should be_persisted
      end

      it "assigns the inventory to the current organization" do
        post :create, inventory: { csv_file: inventory_file }, :locale => "es"
        assigns(:inventory).organization.should == user.organization
      end

      it "redirects to new inventory page" do
        post :create, inventory: { csv_file: inventory_file }, :locale => "es"
        response.should render_template("new")
      end
    end

    context "UTF-8 file" do
      it_behaves_like "a valid inventory file" do
        let(:inventory_file) { fixture_file_upload("files/inventory.csv") }
      end
    end

    context "ISO 8859-1 file" do
      it_behaves_like "a valid inventory file" do
        let(:inventory_file) { fixture_file_upload("files/inventory-latin-1.csv") }
      end
    end

    shared_examples "an invalid inventory file" do
      it "redirects to inventories_path" do
        post :create, inventory: { csv_file: "" }, :locale => "es"
        expect(response).to redirect_to(inventories_path)
      end

      it "has 302 status" do
        post :create, inventory: { csv_file: "" }, :locale => "es"
        expect(response.status).to eq(302)
      end

      it "shows invalid encoding message" do
        post :create, inventory: { csv_file: "" }, :locale => "es"
        expect(flash[:alert]).to eq(error_message)
      end

      it "raises Exceptions::UnknownEncodingError" do
        bypass_rescue
        expect { post :create, inventory: { csv_file: "" }, :locale => "es" }.to raise_error
      end
    end

    context "file with invalid encoding" do
      before do
        def controller.create
          raise Exceptions::UnknownEncodingError
        end
      end
      it_behaves_like "an invalid inventory file" do
        let(:error_message) { I18n.t("activerecord.errors.models.inventory.attributes.csv_file.encoding") }
      end
    end

    context "malformed csv file" do
      before do
        def controller.create
          raise CSV::MalformedCSVError
        end
      end
      it_behaves_like "an invalid inventory file" do
        let(:error_message) { I18n.t("activerecord.errors.models.inventory.attributes.csv_file.malformed") }
      end
    end

    context "empty inventory file" do
      it "renders the template again on error" do
        post :create, inventory: { csv_file: "" }, :locale => "es"
        response.should render_template("new")
      end
    end
  end
end


text:
using namespace alpr;

namespace openalprnet
{
	namespace types
	{
		public enum class AlprDetectorTypeNet : int {
			DetectorLbpCpu = alpr::DETECTOR_LBP_CPU,
			DetectorLbpGpu = alpr::DETECTOR_LBP_GPU,
			DetectorLbpMorphCpu = alpr::DETECTOR_MORPH_CPU,
			DetectorLbpOpencl = alpr::DETECTOR_LBP_OPENCL
		};
	}
}


text:
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
This document is the API specification for the Reactor Addons libraries, a set of
artifacts that complement the Reactor-Core library.
</body>
</html>


text:
module SendGrid4r::REST
  #
  # SendGrid Web API v3 Users
  #
  module Users
    include Request

    Profile = Struct.new(
      :address, :city, :company, :country, :first_name, :last_name,
      :phone, :state, :website, :zip
    )

    Account = Struct.new(:type, :reputation)

    Email = Struct.new(:email)

    Username = Struct.new(:username, :user_id)

    Credits = Struct.new(
      :remain, :total, :overage, :used, :last_reset, :next_reset,
      :reset_frequency
    )

    Password = Struct.new(:new_password, :old_password)

    def self.url(path)
      "#{BASE_URL}/user/#{path}"
    end

    def self.create_profile(resp)
      return resp if resp.nil?
      Profile.new(
        resp['address'],
        resp['city'],
        resp['company'],
        resp['country'],
        resp['first_name'],
        resp['last_name'],
        resp['phone'],
        resp['state'],
        resp['website'],
        resp['zip']
      )
    end

    def self.create_account(resp)
      return resp if resp.nil?
      Account.new(resp['type'], resp['reputation'])
    end

    def self.create_email(resp)
      return resp if resp.nil?
      Email.new(resp['email'])
    end

    def self.create_username(resp)
      return resp if resp.nil?
      Username.new(resp['username'], resp['user_id'])
    end

    def self.create_credits(resp)
      return resp if resp.nil?
      Credits.new(
        resp['remain'],
        resp['total'],
        resp['overage'],
        resp['used'],
        resp['last_reset'],
        resp['next_reset'],
        resp['reset_frequency']
      )
    end

    def self.create_password(resp)
      return resp if resp.nil?
      Password.new(resp['new_password'], resp['old_password'])
    end

    def get_user_profile(&block)
      resp = get(@auth, Users.url(:profile), nil, &block)
      finish(resp, @raw_resp) { |r| Users.create_profile(r) }
    end

    def patch_user_profile(params:, &block)
      resp = patch(@auth, Users.url(:profile), params, &block)
      finish(resp, @raw_resp) { |r| Users.create_profile(r) }
    end

    def get_user_account(&block)
      resp = get(@auth, Users.url(:account), nil, &block)
      finish(resp, @raw_resp) { |r| Users.create_account(r) }
    end

    def get_user_email(&block)
      resp = get(@auth, Users.url(:email), nil, &block)
      finish(resp, @raw_resp) { |r| Users.create_email(r) }
    end

    def put_user_email(email:, &block)
      params = { email: email }
      resp = put(@auth, Users.url(:email), params, &block)
      finish(resp, @raw_resp) { |r| Users.create_email(r) }
    end

    def get_user_username(&block)
      resp = get(@auth, Users.url(:username), nil, &block)
      finish(resp, @raw_resp) { |r| Users.create_username(r) }
    end

    def put_user_username(username:, &block)
      params = { username: username }
      resp = put(@auth, Users.url(:username), params, &block)
      finish(resp, @raw_resp) { |r| Users.create_username(r) }
    end

    def get_user_credits(&block)
      resp = get(@auth, Users.url(:credits), &block)
      finish(resp, @raw_resp) { |r| Users.create_credits(r) }
    end

    def put_user_password(new_password:, old_password:, &block)
      params = {
        new_password: new_password,
        old_password: old_password
      }
      resp = put(@auth, Users.url(:password), params, &block)
      finish(resp, @raw_resp) { |r| Users.create_password(r) }
    end
  end
end


text:
Waste Example
===========

An example showing waste flows

####Process flow diagram
![Process Flow Output](./process-top-flow.png)

![Process Flow Output](./process-left-flow.png)

Xml: [Source](./ProcessFlow.xml)