text:
from __future__ import absolute_import

import threading
import uuid

import google.api_core.future
from google.cloud.pubsub_v1.publisher import exceptions

class Future(google.api_core.future.Future):
    """Encapsulation of the asynchronous execution of an action.

    This object is returned from asychronous Pub/Sub calls, and is the
    interface to determine the status of those calls.

    This object should not be created directly, but is returned by other
    methods in this library.

    Args:
        completed (Optional[Any]): An event, with the same interface as
            :class:`threading.Event`. This is provided so that callers
            with different concurrency models (e.g. ``threading`` or
            ``multiprocessing``) can supply an event that is compatible
            with that model. The ``wait()`` and ``set()`` methods will be
            used. If this argument is not provided, then a new
            :class:`threading.Event` will be created and used.
    """

    # This could be a sentinel object or None, but the sentinel object's ID
    # can change if the process is forked, and None has the possibility of
    # actually being a result.
    _SENTINEL = uuid.uuid4()

    def __init__(self, completed=None):
        self._result = self._SENTINEL
        self._exception = self._SENTINEL
        self._callbacks = []
        if completed is None:
            completed = threading.Event()
        self._completed = completed

    def cancel(self):
        """Actions in Pub/Sub generally may not be canceled.

        This method always returns False.
        """
        return False

    def cancelled(self):
        """Actions in Pub/Sub generally may not be canceled.

        This method always returns False.
        """
        return False

    def running(self):
        """Actions in Pub/Sub generally may not be canceled.

        Returns:
            bool: ``True`` if this method has not yet completed, or
                ``False`` if it has completed.
        """
        return not self.done()

    def done(self):
        """Return True the future is done, False otherwise.

        This still returns True in failure cases; checking :meth:`result` or
        :meth:`exception` is the canonical way to assess success or failure.
        """
        return self._exception != self._SENTINEL or self._result != self._SENTINEL

    def result(self, timeout=None):
        """Resolve the future and return a value where appropriate.

        Args:
            timeout (Union[int, float]): The number of seconds before this call
                times out and raises TimeoutError.

        Raises:
            concurrent.futures.TimeoutError: If the request times out.
            Exception: For undefined exceptions in the underlying
                call execution.
        """
        # Attempt to get the exception if there is one.
        # If there is not one, then we know everything worked, and we can
        # return an appropriate value.
        err = self.exception(timeout=timeout)
        if err is None:
            return self._result
        raise err

    def exception(self, timeout=None):
        """Return the exception raised by the call, if any.

        Args:
            timeout (Union[int, float]): The number of seconds before this call
                times out and raises TimeoutError.

        Raises:
            concurrent.futures.TimeoutError: If the request times out.

        Returns:
            Exception: The exception raised by the call, if any.
        """
        # Wait until the future is done.
        if not self._completed.wait(timeout=timeout):
            raise exceptions.TimeoutError("Timed out waiting for result.")

        # If the batch completed successfully, this should return None.
        if self._result != self._SENTINEL:
            return None

        # Okay, this batch had an error; this should return it.
        return self._exception

    def add_done_callback(self, callback):
        """Attach the provided callable to the future.

        The provided function is called, with this future as its only argument,
        when the future finishes running.

        Args:
            callback (Callable): The function to call.

        Returns:
            None
        """
        if self.done():
            return callback(self)
        self._callbacks.append(callback)

    def set_result(self, result):
        """Set the result of the future to the provided result.

        Args:
            result (Any): The result
        """
        # Sanity check: A future can only complete once.
        if self.done():
            raise RuntimeError("set_result can only be called once.")

        # Set the result and trigger the future.
        self._result = result
        self._trigger()

    def set_exception(self, exception):
        """Set the result of the future to the given exception.

        Args:
            exception (:exc:`Exception`): The exception raised.
        """
        # Sanity check: A future can only complete once.
        if self.done():
            raise RuntimeError("set_exception can only be called once.")

        # Set the exception and trigger the future.
        self._exception = exception
        self._trigger()

    def _trigger(self):
        """Trigger all callbacks registered to this Future.

        This method is called internally by the batch once the batch
        completes.

        Args:
            message_id (str): The message ID, as a string.
        """
        self._completed.set()
        for callback in self._callbacks:
            callback(self)


text:
@import QuartzCore;

@interface CALayer (TWAnimations)

- (void)tw_animateToPosition:(CGPoint)newPosition withDuration:(NSTimeInterval)duration;
- (void)tw_animateOpacityToValue:(CGFloat)toValue withDuration:(NSTimeInterval)duration;

@end

redpajama_set_name: RedPajamaGithub


text:
using System;
using Grasshopper.Graphics.Rendering.Blending;
using SharpDX.Direct3D11;

namespace Grasshopper.SharpDX.Graphics.Rendering
{
    class BlendState : ActivatableD3DResource, IBlendState
    {
        public BlendState(DeviceManager deviceManager, string id, IBlendSettings settings) : base(deviceManager, id)
        {
            if(settings == null) throw new ArgumentNullException("settings");
            Settings = settings;
        }

        public IBlendSettings Settings { get; private set; }
        public global::SharpDX.Direct3D11.BlendState State { get; private set; }

        protected override void InitializeInternal()
        {
            var descr = new BlendStateDescription
            {
                AlphaToCoverageEnable = Settings.EnableAlphaToCoverage,
                IndependentBlendEnable = false,
            };

            descr.RenderTarget[0] = new RenderTargetBlendDescription
            {
                IsBlendEnabled = true,
                SourceBlend = GetBlendOption(Settings.FirstRGB),
                DestinationBlend = GetBlendOption(Settings.SecondRGB),
                BlendOperation = GetBlendOperation(Settings.OutputRGB),
                SourceAlphaBlend = GetBlendOption(Settings.FirstAlpha),
                DestinationAlphaBlend = GetBlendOption(Settings.SecondAlpha),
                AlphaBlendOperation = GetBlendOperation(Settings.OutputAlpha),
                RenderTargetWriteMask = (ColorWriteMaskFlags)Settings.OutputColorComponents
            };

            State = new global::SharpDX.Direct3D11.BlendState(DeviceManager.Device, descr);
        }

        private BlendOption GetBlendOption(PreBlend value)
        {
            switch(value)
            {
                case PreBlend.Zero: return BlendOption.Zero;
                case PreBlend.One: return BlendOption.One;
                case PreBlend.SourceColor: return BlendOption.SourceColor;
                case PreBlend.InverseSourceColor: return BlendOption.InverseSourceColor;
                case PreBlend.SourceAlpha: return BlendOption.SourceAlpha;
                case PreBlend.InverseSourceAlpha: return BlendOption.InverseSourceAlpha;
                case PreBlend.DestinationAlpha: return BlendOption.DestinationAlpha;
                case PreBlend.InverseDestinationAlpha: return BlendOption.InverseDestinationAlpha;
                case PreBlend.DestinationColor: return BlendOption.DestinationColor;
                case PreBlend.InverseDestinationColor: return BlendOption.InverseDestinationColor;
                case PreBlend.SourceAlphaSaturate: return BlendOption.SourceAlphaSaturate;
                case PreBlend.BlendFactor: return BlendOption.BlendFactor;
                case PreBlend.InverseBlendFactor: return BlendOption.InverseBlendFactor;
                case PreBlend.SecondarySourceColor: return BlendOption.SecondarySourceColor;
                case PreBlend.InverseSecondarySourceColor: return BlendOption.InverseSecondarySourceColor;
                case PreBlend.SecondarySourceAlpha: return BlendOption.SecondarySourceAlpha;
                case PreBlend.InverseSecondarySourceAlpha: return BlendOption.InverseSecondarySourceAlpha;
            }

            throw new NotSupportedException("The specified blend value is not supported");
        }

        private BlendOperation GetBlendOperation(BlendEquation value)
        {
            switch(value)
            {
                case BlendEquation.AddBothValues: return BlendOperation.Add;
                case BlendEquation.SubtractFirstFromSecond: return BlendOperation.Subtract;
                case BlendEquation.SubtractSecondFromFirst: return BlendOperation.ReverseSubtract;
                case BlendEquation.Minimum: return BlendOperation.Minimum;
                case BlendEquation.Maximum: return BlendOperation.Maximum;
            }

            throw new NotSupportedException("The specified blend operation is not supported");
        }

        protected override void UninitializeInternal()
        {
            if(State != null)
            {
                State.Dispose();
                State = null;
            }
        }

        protected override void SetActive()
        {
            DeviceManager.Context.OutputMerger.SetBlendState(State);
        }
    }
}


text:
/*
** Copy standard input to standard output, one line
** at a time.  Lines must be 80 data bytes or shorter.
*/

#include <stdio.h>

#define	BUFSIZE	81	/* 80 data bytes + the null byte */

main()
{
	char	buf[BUFSIZE];

	while( gets( buf ) != NULL )
		puts( buf );

	return EXIT_SUCCESS;
}


text: console.log('Por favor, revisa el README.md');


text:
/*!
 * Angular Material Design
 * https://github.com/angular/material
 * @license MIT
 * v0.8.3
 */
goog.provide('ng.material.components.autocomplete');
goog.require('ng.material.components.icon');
goog.require('ng.material.core');
(function () {
  'use strict';
  /**
   * @ngdoc module
   * @name material.components.autocomplete
   */
  /*
   * @see js folder for autocomplete implementation
   */
  angular.module('material.components.autocomplete', [
    'material.core',
    'material.components.icon'
  ]);
})();

(function () {
  'use strict';
  angular
      .module('material.components.autocomplete')
      .controller('MdAutocompleteCtrl', MdAutocompleteCtrl);

  function MdAutocompleteCtrl ($scope, $element, $q, $mdUtil, $mdConstant) {

    //-- private variables
    var self = this,
        itemParts = $scope.itemsExpr.split(/ in /i),
        itemExpr = itemParts[1],
        elements = {
          main:  $element[0],
          ul:    $element[0].getElementsByTagName('ul')[0],
          input: $element[0].getElementsByTagName('input')[0]
        },
        promise = null,
        cache = {},
        noBlur = false;

    //-- public variables
    self.scope = $scope;
    self.parent = $scope.$parent;
    self.itemName = itemParts[0];
    self.matches = [];
    self.loading = false;
    self.hidden = true;
    self.index = 0;
    self.keydown = keydown;
    self.blur = blur;
    self.clear = clearValue;
    self.select = select;
    self.getCurrentDisplayValue = getCurrentDisplayValue;
    self.fetch = $mdUtil.debounce(fetchResults);
    self.messages = [];

    //-- While the mouse is inside of the dropdown, we don't want to handle input blur
    //-- This is to allow the user to scroll the list without causing it to hide
    self.listEnter = function () { noBlur = true; };
    self.listLeave = function () { noBlur = false; };
    self.mouseUp   = function () { elements.input.focus(); };

    return init();

    //-- start method definitions
    function init () {
      configureWatchers();
      configureAria();
    }

    function configureAria () {
      var ul = angular.element(elements.ul),
          input = angular.element(elements.input),
          id = ul.attr('id') || 'ul_' + $mdUtil.nextUid();
      ul.attr('id', id);
      input.attr('aria-owns', id);
    }

    function getItemScope (item) {
      if (!item) return;
      var locals = {};
      if (self.itemName) locals[self.itemName] = item;
      return locals;
    }

    function configureWatchers () {
      var wait = parseInt($scope.delay, 10) || 0;
      $scope.$watch('searchText', wait
          ? $mdUtil.debounce(handleSearchText, wait)
          : handleSearchText);
      $scope.$watch('selectedItem', function (selectedItem, previousSelectedItem) {
        if ($scope.itemChange && selectedItem !== previousSelectedItem)
          $scope.itemChange(getItemScope(selectedItem));
      });
    }

    function handleSearchText (searchText, previousSearchText) {
      self.index = -1;
      if (!searchText || searchText.length < Math.max(parseInt($scope.minLength, 10), 1)) {
        self.loading = false;
        self.matches = [];
        self.hidden = shouldHide();
        updateMessages();
        return;
      }
      var term = searchText.toLowerCase();
      if (promise && promise.cancel) {
        promise.cancel();
        promise = null;
      }
      if (!$scope.noCache && cache[term]) {
        self.matches = cache[term];
        updateMessages();
      } else {
        self.fetch(searchText);
      }
      self.hidden = shouldHide();
      if ($scope.textChange && searchText !== previousSearchText)
        $scope.textChange(getItemScope($scope.selectedItem));
    }

    function fetchResults (searchText) {
      var items = $scope.$parent.$eval(itemExpr),
          term = searchText.toLowerCase();
      if (angular.isArray(items)) {
        handleResults(items);
      } else {
        self.loading = true;
        promise = $q.when(items).then(handleResults);
      }
      function handleResults (matches) {
        cache[term] = matches;
        if (searchText !== $scope.searchText) return; //-- just cache the results if old request
        promise = null;
        self.loading = false;
        self.matches = matches;
        self.hidden = shouldHide();
        updateMessages();
      }
    }

    function updateMessages () {
      if (self.hidden) return;
      switch (self.matches.length) {
        case 0:  return self.messages.splice(0);
        case 1:  return self.messages.push({ display: 'There is 1 match available.' });
        default: return self.messages.push({ display: 'There are '
            + self.matches.length
            + ' matches available.' });
      }
    }

    function updateSelectionMessage () {
      self.messages.push({ display: getCurrentDisplayValue() });
    }

    function blur () {
      if (!noBlur) self.hidden = true;
    }

    function keydown (event) {
      switch (event.keyCode) {
        case $mdConstant.KEY_CODE.DOWN_ARROW:
            if (self.loading) return;
            event.preventDefault();
            self.index = Math.min(self.index + 1, self.matches.length - 1);
            updateScroll();
            updateSelectionMessage();
            break;
        case $mdConstant.KEY_CODE.UP_ARROW:
            if (self.loading) return;
            event.preventDefault();
            self.index = Math.max(0, self.index - 1);
            updateScroll();
            updateSelectionMessage();
            break;
        case $mdConstant.KEY_CODE.ENTER:
            if (self.loading || self.index < 0) return;
            event.preventDefault();
            select(self.index);
            break;
        case $mdConstant.KEY_CODE.ESCAPE:
            self.matches = [];
            self.hidden = true;
            self.index = -1;
            break;
        case $mdConstant.KEY_CODE.TAB:
            break;
        default:
      }
    }

    function clearValue () {
      $scope.searchText = '';
      select(-1);
      elements.input.focus();
    }

    function shouldHide () {
      return self.matches.length === 1 && $scope.searchText === getDisplayValue(self.matches[0]);
    }

    function getCurrentDisplayValue () {
      return getDisplayValue(self.matches[self.index]);
    }

    function getDisplayValue (item) {
      return (item && $scope.itemText) ? $scope.itemText(getItemScope(item)) : item;
    }

    function select (index) {
      $scope.selectedItem = self.matches[index];
      $scope.searchText = getDisplayValue($scope.selectedItem) || $scope.searchText;
      self.hidden = true;
      self.index = -1;
      self.matches = [];
    }

    function updateScroll () {
      var top = 41 * self.index,
          bot = top + 41,
          hgt = 41 * 5.5;
      if (top < elements.ul.scrollTop) {
        elements.ul.scrollTop = top;
      } else if (bot > elements.ul.scrollTop + hgt) {
        elements.ul.scrollTop = bot - hgt;
      }
    }

  }
  MdAutocompleteCtrl.$inject = ["$scope", "$element", "$q", "$mdUtil", "$mdConstant"];
})();

(function () {
  'use strict';
  angular
      .module('material.components.autocomplete')
      .directive('mdAutocomplete', MdAutocomplete);

  /**
   * @ngdoc directive
   * @name mdAutocomplete
   * @module material.components.autocomplete
   *
   * @description
   * `<md-autocomplete>` is a special input component with a drop-down of all possible matches to a custom query.
   * This component allows you to provide real-time suggestions as the user types in the input area.
   *
   * @param {string=} md-search-text A model to bind the search query text to
   * @param {object=} md-selected-item A model to bind the selected item to
   * @param {expression} md-items An expression in the format of `item in items` to iterate over matches for your search.
   * @param {string=} md-item-text An expression that will convert your object to a single string.
   * @param {string=} placeholder Placeholder text that will be forwarded to the input.
   * @param {boolean=} md-no-cache Disables the internal caching that happens in autocomplete
   * @param {expression} md-selected-item-change An expression to be run each time a new item is selected
   * @param {expression} md-search-text-change An expression to be run each time the search text updates
   * @param {boolean=} ng-disabled Determines whether or not to disable the input field
   * @param {number=} md-min-length Specifies the minimum length of text before autocomplete will make suggestions
   * @param {number=} md-delay Specifies the amount of time (in milliseconds) to wait before looking for results
   *
   * @usage
   * <hljs lang="html">
   *   <md-autocomplete
   *       md-selected-item="selectedItem"
   *       md-search-text="searchText"
   *       md-items="item in getMatches(searchText)"
   *       md-item-text="item.display">
   *     {{item.display}}
   *   </md-autocomplete>
   * </hljs>
   */

  function MdAutocomplete () {
    return {
      template:     '\
        <md-autocomplete-wrap role="listbox">\
          <input type="text"\
              ng-disabled="isDisabled"\
              ng-model="searchText"\
              ng-keydown="$mdAutocompleteCtrl.keydown($event)"\
              ng-blur="$mdAutocompleteCtrl.blur()"\
              placeholder="{{placeholder}}"\
              aria-label="{{placeholder}}"\
              aria-autocomplete="list"\
              aria-haspopup="true"\
              aria-activedescendant=""\
              aria-expanded="{{!$mdAutocompleteCtrl.hidden}}"/>\
          <button\
              type="button"\
              ng-if="searchText"\
              ng-click="$mdAutocompleteCtrl.clear()">\
            <md-icon md-svg-icon="cancel"></md-icon>\
            Clear\
          </button>\
          <md-progress-linear\
              ng-if="$mdAutocompleteCtrl.loading"\
              md-mode="indeterminate"></md-progress-linear>\
        </md-autocomplete-wrap>\

\

\

\

\
        <aria-status\
            class="visually-hidden"\
            role="status"\
            aria-live="assertive">\

{{message.display}}
\
        </aria-status>',
      transclude:   true,
      controller:   'MdAutocompleteCtrl',
      controllerAs: '$mdAutocompleteCtrl',
      scope:        {
        searchText:   '=mdSearchText',
        selectedItem: '=mdSelectedItem',
        itemsExpr:    '@mdItems',
        itemText:     '&mdItemText',
        placeholder:  '@placeholder',
        noCache:      '=mdNoCache',
        itemChange:   '&mdSelectedItemChange',
        textChange:   '&mdSearchTextChange',
        isDisabled:   '=ngDisabled',
        minLength:    '=mdMinLength',
        delay:        '=mdDelay'
      }
    };
  }
})();

(function () {
  'use strict';
  angular
      .module('material.components.autocomplete')
      .controller('MdHighlightCtrl', MdHighlightCtrl);

  function MdHighlightCtrl ($scope, $element, $interpolate) {
    var term = $element.attr('md-highlight-text'),
        text = $interpolate($element.text())($scope),
        watcher = $scope.$watch(term, function (term) {
          var regex = new RegExp('^' + sanitize(term), 'i'),
              html = text.replace(regex, '$&');
          $element.html(html);
        });
    $element.on('$destroy', function () { watcher(); });

    function sanitize (term) {
      if (!term) return term;
      return term.replace(/[\*\[\]\(\)\{\}\\\^\$]/g, '\\$&');
    }
  }
  MdHighlightCtrl.$inject = ["$scope", "$element", "$interpolate"];

})();

(function () {
  'use strict';
  angular
      .module('material.components.autocomplete')
      .directive('mdHighlightText', MdHighlight);

  /**
   * @ngdoc directive
   * @name mdHighlightText
   * @module material.components.autocomplete
   *
   * @description
   * The `md-highlight-text` directive allows you to specify text that should be highlighted within
   * an element.  Highlighted text will be wrapped in `<span class="highlight"></span>` which can
   * be styled through CSS.  Please note that child elements may not be used with this directive.
   *
   * @param {string=} md-highlight-text A model to be searched for
   *
   * @usage
   * <hljs lang="html">
   * <input placeholder="Enter a search term..." ng-model="searchTerm" type="text" />
   *

   *

   *     {{result.text}}
   *

   *

   * </hljs>
   */

  function MdHighlight () {
    return {
      terminal: true,
      scope: false,
      controller: 'MdHighlightCtrl'
    };
  }
})();

(function () {
  'use strict';
  angular
      .module('material.components.autocomplete')
      .directive('mdAutocompleteListItem', MdAutocompleteListItem);

  function MdAutocompleteListItem ($compile, $mdUtil) {
    return {
      require: '^?mdAutocomplete',
      terminal: true,
      link: link,
      scope: false
    };
    function link (scope, element, attr, ctrl) {
      var newScope = ctrl.parent.$new(false, ctrl.parent),
          itemName = ctrl.scope.$eval(attr.mdAutocompleteListItem);
      newScope[itemName] = scope.item;
      $compile(element.contents())(newScope);
      element.attr({ 'role': 'option', 'id': 'item_' + $mdUtil.nextUid() });
    }
  }
  MdAutocompleteListItem.$inject = ["$compile", "$mdUtil"];
})();


text:
Sevak is a concept prototype developed as an entry for the Civic Data App Challenge in 2013.
It is a finalist in the challenge, and seeks to address a perceived gap in connecting a new
generation of volunteers to the causes they believe in, and to the organizations that most
urgently need their help and expertise.

We believe that 'service' has many layers of meaning and value, and that everyone - regardless of
their backgrounds, skills, schedules and interests - can contribute and make a difference. With Sevak,
we wish to create awareness, and recognize contributions, of all these levels - from direct service, to
indirect advocacy, recruitment, mentoring and review.

#Acknowlegments

We wish to acknowledge the many organizations and people who have given us feedback on the directions
and value of this project.

#Attributions

Some of the images used by this application were obtained from 3rd party sources. Where applicable, we
are providing explicit links to licensing terms and attribution. The images include:
    1. [Advocate](http://www.flickr.com/photos/eucyclistsfed/7896627110/in/photolist-d2Nh8h-aCwGf9-c1JicG-e9QEgZ-bmQat8-bmQake-bmQfck-d2NdX1-d2NfAf-d2NmMu-d2NghS-a9L6Vt-d2Nknd-d2Neey-8612a4-8hFxgx-9JGtHR-864d9N-85ZJSp-85ZLSg-864j1A-8644s7-864ioU-8642Z7-85ZX9z-8648Co-86458G-863Zb1-85ZHnF-85ZSSr-8642ed-85ZNMR-863TNU-85ZFb4-8611uZ-85ZGGM-85ZV3n-8614rr-863W1q-85ZYst-8613TZ-8641qY-863Vjq-85ZVFP-864eU9-8617Ui-85ZFYT-85ZQ2T-8617ik-85ZZ9k-864gzm/)
       with Some Rights Reserved [Creative Commons License](http://creativecommons.org/licenses/by/2.0/deed.en) by the European Cyclists' Federation
    2. [Connector](http://commons.wikimedia.org/wiki/File:Hands_Across_America_Philadelphia.jpg)
    3. [Volunteer](http://commons.wikimedia.org/wiki/File:M_tic.jpg) with attribution to author "Fir0002/Flagstaffotos".

#Licensing

The project makes extensive use of themes and templates from the excellent
[Bootstraptor](http://www.bootstraptor.com) service. Please do not extract,
extend or redistribute these files from this project. Instead, refer to the
Bootstraptor site for the most recent licensing terms.

We also wish to acknowledge the generosity of the Bootstraptor folks for making
an exception and allowing us to include the theme and template files in our
GitHub repository. This was expressly done for this specific project, given its
status as an Open Source project and participant in the Civic Data Challenge,
and is not meant to be extended to other projects outside this context.


text:
package org.apache.myfaces.trinidadinternal.skin.parse;

/**
 * Constants used by look and feel parsing.
 *
 * @version $Name:  $ ($Revision: adfrt/faces/adf-faces-impl/src/main/java/oracle/adfinternal/view/faces/ui/laf/xml/XMLConstants.java#0 $) $Date: 10-nov-2005.18:50:35 $
 */
public interface XMLConstants
{
  public static final String SKIN_NAMESPACE =
      "http://myfaces.apache.org/trinidad/skin";

  public static final String NULL_NAME             = "null";
}


text:
package com.simplechat.shared.commands.user;

import com.simplechat.shared.commands.AbstractCommand;
import com.simplechat.shared.commands.AbstractCommandBuilder;
import com.simplechat.shared.commands.Command;

/**
 * Created by lampt on 6/24/2017.
 */
public class UserCommand implements AbstractCommand {

    @Override
    public Command getCommandName() {
        return Command.USER;
    }

    @Override
    public AbstractCommandBuilder buildCommand(String... commandArgs) {
        return new UserCommandBuilder(commandArgs);
    }
}


text:
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using iRuler.Utility;

namespace iRuler.Dialogs
{
	/// <summary>
	/// Summary description for TestForm.
	/// </summary>
	public partial class PromptDialog : System.Windows.Forms.Form
	{
        public int m_mode = 0;
        public String m_ruleName = "";
        public String m_ruleDefault = "";
        public String[] m_LTMEvents = null;
        public String[] m_GTMEvents = null;
		public String[] m_existingiRules = null;
        public iRuleInfo.RuleType m_ruleType = iRuleInfo.RuleType.LOCALLB;

		public PromptDialog()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		private void loadTemplates()
		{
            String sConfigPath = Configuration.getConfigSubDir("Templates");

			string [] templates = Directory.GetFiles(sConfigPath, "*.txt");
			for(int i=0; i<templates.Length; i++)
			{
				String sTemplateName = Path.GetFileNameWithoutExtension(templates[i]);

				if ( ! sTemplateName.StartsWith("_") )
				{
					StreamReader sr = File.OpenText(templates[i]);
					String sContents = sr.ReadToEnd();
                    TreeNode tn = new TreeNode();
                    tn.Text = sTemplateName;
                    tn.Tag = sContents;
                    treeView_Templates.Nodes.Add(tn);
                    sr.Close();
                }
			}
		}

		private void loadEvents()
		{
            String sConfigPath = Configuration.getConfigSubDir("Templates");
            String sEventsFile = sConfigPath + "_Events.txt";

			if ( File.Exists(sEventsFile) )
			{
				StreamReader sr = File.OpenText(sEventsFile);
				String input;
				while ((input=sr.ReadLine())!=null)
				{
					listBox_Events.Items.Add(input);
				}
				sr.Close();

                if (listBox_Events.Items.Count > 0)
                {
                    m_LTMEvents = new String[listBox_Events.Items.Count];
                    for (int i = 0; i < listBox_Events.Items.Count; i++)
                    {
                        m_LTMEvents[i] = listBox_Events.Items[i].ToString();
                    }
                    listBox_Events.Items.Clear();
                }
			}

            sEventsFile = sConfigPath + "_GTMEvents.txt";

            if (File.Exists(sEventsFile))
            {
                StreamReader sr = File.OpenText(sEventsFile);
                String input;
                while ((input = sr.ReadLine()) != null)
                {
                    listBox_Events.Items.Add(input);
                }
                sr.Close();

                if (listBox_Events.Items.Count > 0)
                {
                    m_GTMEvents = new String[listBox_Events.Items.Count];
                    for (int i = 0; i < listBox_Events.Items.Count; i++)
                    {
                        m_GTMEvents[i] = listBox_Events.Items[i].ToString();
                    }
                    listBox_Events.Items.Clear();
                }
            }

		}

        private void fillEventsListBox(String[] list)
        {
            if (null != list)
            {
                listBox_Events.Items.Clear();
                for (int i = 0; i < list.Length; i++)
                {
                    listBox_Events.Items.Add(list[i]);
                }
            }
        }

        private void button_OK_Click(object sender, System.EventArgs e)
		{
			if ( textBox_Name.Text.Trim().Length > 0 )
			{
				bool bRuleExists = false;
				m_ruleName = textBox_Name.Text.Trim();

				// Check to make sure that this name wasn't already used...
				for (int i = 0; i < m_existingiRules.Length; i++)
				{
					if (m_ruleName.ToLower().Equals(m_existingiRules[i].ToLower()))
					{
						bRuleExists = true;
						break;
					}
				}

				if (bRuleExists)
				{
					MessageBox.Show("You must enter a unique name for your iRule", "Error");
				}
				else
				{
					// Check for invalid characters
					//System.Text.RegularExpressions.Regex validNamePattern = new System.Text.RegularExpressions.Regex("[^a-zA-Z.*/\\-:_?=@,]");
					System.Text.RegularExpressions.Regex validNamePattern = new System.Text.RegularExpressions.Regex("[^a-zA-Z0-9._\\-]");
					bool bMatch = validNamePattern.IsMatch(m_ruleName);
					if ( bMatch )
					{
						MessageBox.Show("Invalid characters in the iRule name.  Only alpha characters, numbers, and the following special characters are allowed (._-)", "Error");
					}
					else
					{
						if (0 == tabControl_Options.SelectedIndex)
						{
							// already handled by the SelectedIndexChanged event.
						}
						else if (1 == tabControl_Options.SelectedIndex)
						{
							m_ruleDefault = "";
							if (listBox_Events.SelectedItems.Count > 0)
							{
								for (int i = 0; i < listBox_Events.SelectedItems.Count; i++)
								{
									m_ruleDefault = m_ruleDefault +
										"when " + listBox_Events.SelectedItems[i].ToString() + " {\n" +
										"  log local0. \"in " + listBox_Events.SelectedItems[i].ToString() + "\"\n" +
										"}\n\n";
								}
							}
						}
						this.DialogResult = DialogResult.OK;
						this.Close();
					}
				}
			}
			else
			{
				MessageBox.Show("An iRule with this name already exists.  Please select a unique name.", "Error");
			}

		}

		private void button_Cancel_Click(object sender, System.EventArgs e)
		{
			this.DialogResult = DialogResult.Cancel;
			this.Close();
		}

		private void textBox_Name_TextChanged(object sender, System.EventArgs e)
		{

		}

		private void label2_Click(object sender, System.EventArgs e)
		{

		}

		private void PromptDialog_Load(object sender, System.EventArgs e)
		{
            RuleTypeComboBox.Items.Add("Local Traffic Management");
            if (Clients.ConnectionInfo.getGTMLicensed())
            {
                RuleTypeComboBox.Items.Add("Global Traffic Management");
            }
            RuleTypeComboBox.SelectedIndex = 0;
			loadTemplates();
			loadEvents();
            fillEventsListBox(m_LTMEvents);
		}

		private void tabControl_Options_TabIndexChanged(object sender, System.EventArgs e)
		{
			m_mode = tabControl_Options.SelectedIndex;
		}

        private void treeView_Templates_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (null != treeView_Templates.SelectedNode)
            {
                m_ruleDefault = treeView_Templates.SelectedNode.Tag.ToString();
            }
        }

        private void PromptDialog_HelpButtonClicked(object sender, CancelEventArgs e)
        {
            Configuration.LaunchProcess(Configuration.getWebHelpURL() + "#NewiRuleDialog");
        }

        private void RuleTypeComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (RuleTypeComboBox.SelectedIndex == 0)
            {
                m_ruleType = iRuleInfo.RuleType.LOCALLB;
                fillEventsListBox(m_LTMEvents);
            }
            else
            {
                m_ruleType = iRuleInfo.RuleType.GLOBALLB;
                fillEventsListBox(m_GTMEvents);
            }
        }

	}
}


text:
<?php

declare(strict_types=1);

namespace Nelmio\Alice\FixtureBuilder\Denormalizer\FlagParser;

use Nelmio\Alice\Definition\FlagBag;
use Nelmio\Alice\Throwable\Exception\FixtureBuilder\Denormalizer\FlagParser\FlagParserExceptionFactory;
use Nelmio\Alice\FixtureBuilder\Denormalizer\FlagParserInterface;
use Nelmio\Alice\IsAServiceTrait;

/**
 * Delegates the responsibility to the first suitable parser found.
 */
final class FlagParserRegistry implements FlagParserInterface
{
    use IsAServiceTrait;

    /**
     * @var ChainableFlagParserInterface[]
     */
    private $parsers;

    /**
     * @param ChainableFlagParserInterface[] $parsers
     */
    public function __construct(array $parsers)
    {
        $this->parsers = (
            function (ChainableFlagParserInterface ...$parsers) {
                return $parsers;
            }
        )(...$parsers);
    }

    /**
     * @inheritdoc
     */
    public function parse(string $element): FlagBag
    {
        foreach ($this->parsers as $parser) {
            if ($parser->canParse($element)) {
                return $parser->parse($element);
            }
        }

        throw FlagParserExceptionFactory::createForNoParserFoundForElement($element);
    }
}


text:
title: "Startup Trivia"
date: 2011-10-30 00:00
---

<import>
I wish someone had taken me aside sometime between my second and third years at the University of New Brunswick (when I started to write worthwhile software) and explained to me how startups worked. Startup culture. Venture Capitalists. Angel investors. Vesting schedules. Bootstrapping. Founders. All of it.
</import>


text:
import { Binder } from './binder';
import { Dialog } from './dialog';
import { Channel } from './channel';

export class Bot {

  constructor() {
    /** @internal */
    this._dialogHandlers = [];
    /** @internal */
    this._performerHandlers = [];
    this.when = Binder.for(this);
    this._channels = new Map();
  }

  /** @internal */
  _channelFor(channelId) {
    const channel = this._channels.get(channelId) || new Channel();
    this._channels.set(channelId, channel);
    return channel;
  }

  dialog(channel, users) {
    return new Dialog(this, channel, users);
  }

  @deprecated
  abortDialog(channel, user) {
    this._channelFor(channel).abort(user);
  }

  onMessage(message) {
    const performer = this._performerHandlers.find(c => c.match(message));
    if (performer) return performer.handler(message, this);
    const channel = this._channelFor(message.channel);
    const hasActions = channel.hasFor(message.user);
    if (hasActions) return channel.processMessage(message);
    const dialog = this._dialogHandlers.find(c => c.match(message));

    if (dialog) {
      const obj = this.dialog(message.channel, [message.user]);
      obj._manager.perform(message);
      dialog.handler(obj, this);
    }
  }
}


text:
(function(angular, $) {
    'use strict';
    angular.module('FileManagerApp').service('apiHandler', ['$http', '$q', '$window', '$translate', 'Upload',
        function ($http, $q, $window, $translate, Upload) {

        $http.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

        var ApiHandler = function() {
            this.inprocess = false;
            this.asyncSuccess = false;
            this.error = '';
        };

        ApiHandler.prototype.deferredHandler = function(data, deferred, code, defaultMsg) {
            if (!data || typeof data !== 'object') {
                this.error = 'Error %s - Bridge response error, please check the API docs or this ajax response.'.replace('%s', code);
            }
            if (code == 404) {
                this.error = 'Error 404 - Backend bridge is not working, please check the ajax response.';
            }
            if (data.result && data.result.error) {
                this.error = data.result.error;
            }
            if (!this.error && data.error) {
                this.error = data.error.message;
            }
            if (!this.error && defaultMsg) {
                this.error = defaultMsg;
            }
            if (this.error) {
                return deferred.reject(data);
            }
            return deferred.resolve(data);
        };

        ApiHandler.prototype.list = function(apiUrl, path, customDeferredHandler, exts) {
            var self = this;
            var dfHandler = customDeferredHandler || self.deferredHandler;
            var deferred = $q.defer();
            var data = {
                action: 'list',
                path: path,
                fileExtensions: exts && exts.length ? exts : undefined
            };

            self.inprocess = true;
            self.error = '';

            $http.post(apiUrl, data).success(function(data, code) {
                dfHandler(data, deferred, code);
            }).error(function(data, code) {
                dfHandler(data, deferred, code, 'Unknown error listing, check the response');
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.copy = function(apiUrl, items, path, singleFilename) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'copy',
                items: items,
                newPath: path
            };

            if (singleFilename && items.length === 1) {
                data.singleFilename = singleFilename;
            }

            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_copying'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.move = function(apiUrl, items, path) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'move',
                items: items,
                newPath: path
            };
            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_moving'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.remove = function(apiUrl, items) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'remove',
                items: items
            };

            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_deleting'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.upload = function(apiUrl, destination, files) {
            var self = this;
            var deferred = $q.defer();
            self.inprocess = true;
            self.progress = 0;
            self.error = '';

            var data = {
                destination: destination
            };

            for (var i = 0; i < files.length; i++) {
                data['file-' + i] = files[i];
            }

            if (files && files.length) {
                Upload.upload({
                    url: apiUrl,
                    data: data
                }).then(function (data) {
                    self.deferredHandler(data.data, deferred, data.status);
                }, function (data) {
                    self.deferredHandler(data.data, deferred, data.status, 'Unknown error uploading files');
                }, function (evt) {
                    self.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total)) - 1;
                })['finally'](function() {
                    self.inprocess = false;
                    self.progress = 0;
                });
            }

            return deferred.promise;
        };

        ApiHandler.prototype.getContent = function(apiUrl, itemPath) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'getContent',
                item: itemPath
            };

            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_getting_content'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.edit = function(apiUrl, itemPath, content) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'edit',
                item: itemPath,
                content: content
            };

            self.inprocess = true;
            self.error = '';

            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_modifying'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.rename = function(apiUrl, itemPath, newPath) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'rename',
                item: itemPath,
                newItemPath: newPath
            };
            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_renaming'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.getUrl = function(apiUrl, path) {
            var data = {
                action: 'download',
                path: path
            };
            return path && [apiUrl, $.param(data)].join('?');
        };

        ApiHandler.prototype.download = function(apiUrl, itemPath, toFilename, downloadByAjax, forceNewWindow) {
            var self = this;
            var url = this.getUrl(apiUrl, itemPath);

            if (!downloadByAjax || forceNewWindow || !$window.saveAs) {
                !$window.saveAs && $window.console.log('Your browser dont support ajax download, downloading by default');
                return !!$window.open(url, '_blank', '');
            }

            var deferred = $q.defer();
            self.inprocess = true;
            $http.get(url).success(function(data) {
                var bin = new $window.Blob([data]);
                deferred.resolve(data);
                $window.saveAs(bin, toFilename);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_downloading'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.downloadMultiple = function(apiUrl, items, toFilename, downloadByAjax, forceNewWindow) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'downloadMultiple',
                items: items,
                toFilename: toFilename
            };
            var url = [apiUrl, $.param(data)].join('?');

            if (!downloadByAjax || forceNewWindow || !$window.saveAs) {
                !$window.saveAs && $window.console.log('Your browser dont support ajax download, downloading by default');
                return !!$window.open(url, '_blank', '');
            }

            self.inprocess = true;
            $http.get(apiUrl).success(function(data) {
                var bin = new $window.Blob([data]);
                deferred.resolve(data);
                $window.saveAs(bin, toFilename);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_downloading'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.compress = function(apiUrl, items, compressedFilename, path) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'compress',
                items: items,
                destination: path,
                compressedFilename: compressedFilename
            };

            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_compressing'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.extract = function(apiUrl, item, folderName, path) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'extract',
                item: item,
                destination: path,
                folderName: folderName
            };

            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_extracting'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.changePermissions = function(apiUrl, items, permsOctal, permsCode, recursive) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'changePermissions',
                items: items,
                perms: permsOctal,
                permsCode: permsCode,
                recursive: !!recursive
            };

            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_changing_perms'));
            })['finally'](function() {
                self.inprocess = false;
            });
            return deferred.promise;
        };

        ApiHandler.prototype.createFolder = function(apiUrl, path) {
            var self = this;
            var deferred = $q.defer();
            var data = {
                action: 'createFolder',
                newPath: path
            };

            self.inprocess = true;
            self.error = '';
            $http.post(apiUrl, data).success(function(data, code) {
                self.deferredHandler(data, deferred, code);
            }).error(function(data, code) {
                self.deferredHandler(data, deferred, code, $translate.instant('error_creating_folder'));
            })['finally'](function() {
                self.inprocess = false;
            });

            return deferred.promise;
        };

        return ApiHandler;

    }]);
})(angular, jQuery);


text:
"""API context definition. Context defines request/response behavior."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import itertools

from future.builtins import map

from grr_api_client import utils

class GrrApiContext(object):
  """API context object. Used to make every API request."""

  def __init__(self, connector=None):
    super(GrrApiContext, self).__init__()

    if not connector:
      raise ValueError("connector can't be None")

    self.connector = connector
    self.user = None

  def SendRequest(self, handler_name, args):
    return self.connector.SendRequest(handler_name, args)

  def _GeneratePages(self, handler_name, args):
    offset = args.offset

    while True:
      args_copy = utils.CopyProto(args)
      args_copy.offset = offset
      args_copy.count = self.connector.page_size
      result = self.connector.SendRequest(handler_name, args_copy)

      yield result

      if not result.items:
        break

      offset += self.connector.page_size

  def SendIteratorRequest(self, handler_name, args):
    if not args or not hasattr(args, "count"):
      result = self.connector.SendRequest(handler_name, args)
      total_count = getattr(result, "total_count", None)
      return utils.ItemsIterator(items=result.items, total_count=total_count)
    else:
      pages = self._GeneratePages(handler_name, args)

      first_page = next(pages)
      total_count = getattr(first_page, "total_count", None)

      page_items = lambda page: page.items
      next_pages_items = itertools.chain.from_iterable(map(page_items, pages))
      all_items = itertools.chain(first_page.items, next_pages_items)

      if args.count:
        all_items = itertools.islice(all_items, args.count)

      return utils.ItemsIterator(items=all_items, total_count=total_count)

  def SendStreamingRequest(self, handler_name, args):
    return self.connector.SendStreamingRequest(handler_name, args)

  @property
  def username(self):
    if not self.user:
      self.user = self.SendRequest("GetGrrUser", None)

    return self.user.username


text:
from .core import Item, Field, MapField, prepare  # noqa
from .magic import MagicField

MAGIC = MagicField()


text:
#import "TSKSPKIHashCache.h"
#import "../TSKLog.h"
#import <CommonCrypto/CommonDigest.h>

#pragma mark Missing ASN1 SPKI Headers

// These are the ASN1 headers for the Subject Public Key Info section of a certificate
// TODO(AD): Are they returned by the new iOS API https://developer.apple.com/documentation/security/2963103-seccertificatecopykey ?
static const unsigned char rsa2048Asn1Header[] =
{
    0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
    0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00
};

static const unsigned char rsa4096Asn1Header[] =
{
    0x30, 0x82, 0x02, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
    0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00
};

static const unsigned char ecDsaSecp256r1Asn1Header[] =
{
    0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
    0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
    0x42, 0x00
};

static const unsigned char ecDsaSecp384r1Asn1Header[] =
{
    0x30, 0x76, 0x30, 0x10, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
    0x01, 0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22, 0x03, 0x62, 0x00
};

static BOOL isKeySupported(NSString *publicKeyType, NSNumber *publicKeySize)
{
    if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeRSA]) && ([publicKeySize integerValue] == 2048))
    {
        return YES;
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeRSA]) && ([publicKeySize integerValue] == 4096))
    {
        return YES;
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeECSECPrimeRandom]) && ([publicKeySize integerValue] == 256))
    {
        return YES;
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeECSECPrimeRandom]) && ([publicKeySize integerValue] == 384))
    {
        return YES;
    }
    return NO;
}

static char *getAsn1HeaderBytes(NSString *publicKeyType, NSNumber *publicKeySize)
{
    if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeRSA]) && ([publicKeySize integerValue] == 2048))
    {
        return (char *)rsa2048Asn1Header;
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeRSA]) && ([publicKeySize integerValue] == 4096))
    {
        return (char *)rsa4096Asn1Header;
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeECSECPrimeRandom]) && ([publicKeySize integerValue] == 256))
    {
        return (char *)ecDsaSecp256r1Asn1Header;
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeECSECPrimeRandom]) && ([publicKeySize integerValue] == 384))
    {
        return (char *)ecDsaSecp384r1Asn1Header;
    }

    @throw([NSException exceptionWithName:@"Unsupported public key algorithm" reason:@"Tried to generate the SPKI hash for an unsupported key algorithm" userInfo:nil]);
}

static unsigned int getAsn1HeaderSize(NSString *publicKeyType, NSNumber *publicKeySize)
{
    if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeRSA]) && ([publicKeySize integerValue] == 2048))
    {
        return sizeof(rsa2048Asn1Header);
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeRSA]) && ([publicKeySize integerValue] == 4096))
    {
        return sizeof(rsa4096Asn1Header);
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeECSECPrimeRandom]) && ([publicKeySize integerValue] == 256))
    {
        return sizeof(ecDsaSecp256r1Asn1Header);
    }
    else if (([publicKeyType isEqualToString:(NSString *)kSecAttrKeyTypeECSECPrimeRandom]) && ([publicKeySize integerValue] == 384))
    {
        return sizeof(ecDsaSecp384r1Asn1Header);
    }

    @throw([NSException exceptionWithName:@"Unsupported public key algorithm" reason:@"Tried to generate the SPKI hash for an unsupported key algorithm" userInfo:nil]);
}

@interface TSKSPKIHashCache ()

// Dictionnary to cache SPKI hashes instead of having to compute them on every connection
@property (nonatomic) SPKICacheDictionnary *spkiCache;
@property (nonatomic) dispatch_queue_t lockQueue;
@property (nonatomic) NSString *spkiCacheFilename;

/**
 Load the SPKI cache from the filesystem. This triggers blocking file I/O.
 */
- (SPKICacheDictionnary *)loadSPKICacheFromFileSystem;

@end

@implementation TSKSPKIHashCache

- (instancetype)initWithIdentifier:(NSString *)uniqueIdentifier
{
    self = [super init];
    if (self) {
        // Initialize our locks
        _lockQueue = dispatch_queue_create("TSKSPKIHashLock", DISPATCH_QUEUE_CONCURRENT);

        // Ensure a non-nil identifier was provided
        NSAssert(uniqueIdentifier, @"TSKSPKIHashCache initializer must be passed a unique identifier");
        _spkiCacheFilename = uniqueIdentifier;

        // First try to load a cached version from the filesystem
        _spkiCache = [self loadSPKICacheFromFileSystem];
        TSKLog(@"Loaded %lu SPKI cache entries from the filesystem", (unsigned long)_spkiCache.count);
        if (_spkiCache == nil)
        {
            _spkiCache = [NSMutableDictionary new];
        }
    }
    return self;
}

- (NSData *)hashSubjectPublicKeyInfoFromCertificate:(SecCertificateRef)certificate
{
    __block NSData *cachedSubjectPublicKeyInfo;

    // Have we seen this certificate before? Look for the SPKI in the cache
    NSData *certificateData = (__bridge_transfer NSData *)(SecCertificateCopyData(certificate));

    dispatch_sync(_lockQueue, ^{
        cachedSubjectPublicKeyInfo = self->_spkiCache[certificateData];
    });

    if (cachedSubjectPublicKeyInfo)
    {
        TSKLog(@"Subject Public Key Info hash was found in the cache");
        return cachedSubjectPublicKeyInfo;
    }

    // We didn't this certificate in the cache so we need to generate its SPKI hash
    TSKLog(@"Generating Subject Public Key Info hash...");

    // First extract the public key
    SecKeyRef publicKey = [self copyPublicKeyFromCertificate:certificate];
    if (publicKey == nil)
    {
        TSKLog(@"Error - could not copy the public key from the certificate");
        return nil;
    }

    // Obtain the public key bytes from the key reference
    NSData *publicKeyData = (__bridge_transfer NSData *)SecKeyCopyExternalRepresentation(publicKey, NULL);
    if (publicKeyData == nil)
    {
        TSKLog(@"Error - could not extract the public key bytes");
        CFRelease(publicKey);
        return nil;
    }

    // Obtain the SPKI header based on the key's algorithm
    CFDictionaryRef publicKeyAttributes = SecKeyCopyAttributes(publicKey);
    NSString *publicKeyType = CFDictionaryGetValue(publicKeyAttributes, kSecAttrKeyType);
    NSNumber *publicKeysize = CFDictionaryGetValue(publicKeyAttributes, kSecAttrKeySizeInBits);
    CFRelease(publicKeyAttributes);

    if (!isKeySupported(publicKeyType, publicKeysize))
    {
        TSKLog(@"Error - public key algorithm or length is not supported");
        CFRelease(publicKey);
        return nil;
    }

    char *asn1HeaderBytes = getAsn1HeaderBytes(publicKeyType, publicKeysize);
    unsigned int asn1HeaderSize = getAsn1HeaderSize(publicKeyType, publicKeysize);

    CFRelease(publicKey);

    // Generate a hash of the subject public key info
    NSMutableData *subjectPublicKeyInfoHash = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
    CC_SHA256_CTX shaCtx;
    CC_SHA256_Init(&shaCtx);

    // Add the missing ASN1 header for public keys to re-create the subject public key info
    CC_SHA256_Update(&shaCtx, asn1HeaderBytes, asn1HeaderSize);

    // Add the public key
    CC_SHA256_Update(&shaCtx, [publicKeyData bytes], (unsigned int)[publicKeyData length]);
    CC_SHA256_Final((unsigned char *)[subjectPublicKeyInfoHash bytes], &shaCtx);

    // Store the hash in our memory cache
    dispatch_barrier_sync(_lockQueue, ^{
        self->_spkiCache[certificateData] = subjectPublicKeyInfoHash;
    });

    // Update the cache on the filesystem
    if (self.spkiCacheFilename.length > 0)
    {
        NSData *serializedSpkiCache = [NSKeyedArchiver archivedDataWithRootObject:_spkiCache requiringSecureCoding:YES error:nil];
        if ([serializedSpkiCache writeToURL:[self SPKICachePath] atomically:YES] == NO)
        {
            NSAssert(false, @"Failed to write cache");
            TSKLog(@"Could not persist SPKI cache to the filesystem");
        }
    }

    return subjectPublicKeyInfoHash;
}

- (SPKICacheDictionnary *)loadSPKICacheFromFileSystem
{
    NSMutableDictionary *spkiCache = nil;
    NSData *serializedSpkiCache = [NSData dataWithContentsOfURL:[self SPKICachePath]];
    if (serializedSpkiCache) {
        NSError *decodingError = nil;
        spkiCache = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithArray:@[[SPKICacheDictionnary class], [NSData class]]] fromData:serializedSpkiCache error:&decodingError];
        if (decodingError)
        {
            TSKLog(@"Could not retrieve SPKI cache from the filesystem: %@", decodingError);
        }
    }
    return spkiCache;
}

#pragma mark Public Key Converter - iOS 10.0+, macOS 10.12+, watchOS 3.0, tvOS 10.0

- (SecKeyRef)copyPublicKeyFromCertificate:(SecCertificateRef)certificate
{
    OSStatus status;

    // Create an X509 trust using the using the certificate
    SecTrustRef trust;
    SecPolicyRef policy = SecPolicyCreateBasicX509();
    status = SecTrustCreateWithCertificates(certificate, policy, &trust);
    CFRelease(policy);

    if (status != errSecSuccess)
    {
        TSKLog(@"Could not create trust from certificate, got status %d", status);
        return nil;
    }

    // Get a public key reference for the certificate from the trust
    SecTrustResultType result;
    status = SecTrustEvaluate(trust, &result);
    if (status != errSecSuccess)
    {
        TSKLog(@"Could not evaluate trust for the certificate, got status %d", status);
        CFRelease(trust);
        return nil;
    }

    SecKeyRef publicKey = SecTrustCopyPublicKey(trust);
    CFRelease(trust);
    return publicKey;
}

- (NSURL *)SPKICachePath
{
    NSURL *cachesDirUrl = [NSFileManager.defaultManager URLsForDirectory:NSCachesDirectory
                                                               inDomains:NSUserDomainMask].firstObject;
    return [cachesDirUrl URLByAppendingPathComponent:self.spkiCacheFilename];
}

@end

@implementation TSKSPKIHashCache (TestSupport)

- (void)resetSubjectPublicKeyInfoDiskCache
{
    // Discard SPKI cache
    [NSFileManager.defaultManager removeItemAtURL:[self SPKICachePath] error:nil];
}

- (SPKICacheDictionnary *)getSubjectPublicKeyInfoHashesCache
{
    return _spkiCache;
}

@end


text:
layout: tutorial
title: "Encoding entire collections"
section: tutorial
sort_order: 15
---
While kantan.csv was written with large amount of data in mind - or at least, more data than a standard laptop can
comfortably fit in memory - it's still fairly common to have a collection that needs to be written down as CSV.

This is something that kantan.csv attempts to make as straightforward as possible. First, let's define some CSV data
that needs to be serialized (see [this](case_classes_as_rows) if you're not clear what the following code is for):

```scala mdoc:silent
import kantan.csv._
import kantan.csv.ops._
import kantan.csv.generic._

case class Person(id: Int, name: String, age: Int)

val ps = List(Person(0, "Nicolas", 38), Person(1, "Kazuma", 1), Person(2, "John", 18))
```

All types that support the [`asCsvWriter`] method also support [`writeCsv`], which takes a collection of values and
writes them directly as CSV:

```scala mdoc:silent
// File in which we'll be writing the CSV data.
val out = java.io.File.createTempFile("kantan.csv", "csv")

// Writes ps using , as a column separator and with a header row.
out.writeCsv(ps, rfc.withHeader("Id", "Name", "Age"))
```

[`writeCsv`] takes three value arguments:

* a collection (an instance of [`TraversableOnce`], really) to encode.
* a character to use as column separator
* an optional header row

Now that we have serialized our data, let's make sure it comes out the way we expected:

```scala mdoc
scala.io.Source.fromFile(out).mkString
```

Note that the need for turning a collection into a CSV string is so common that kantan.csv has a special helper for
that: [`asCsv`]. For example:

```scala mdoc
ps.asCsv(rfc.withHeader("Id", "Name", "Age"))
```

## What to read next

If you want to learn more about:

* [how we were able to turn a `File` into a `CsvWriter`](csv_sinks.html)
* [how to write CSV row by row](step_by_step_serialization.html)

[`asCsvWriter`]:{{ site.baseurl }}/api/kantan/csv/ops/CsvSinkOps.html#asCsvWriter[B](sep:Char,header:Seq[String])(implicitevidence$1:kantan.csv.RowEncoder[B],implicitoa:kantan.csv.CsvSink[A],implicite:kantan.csv.engine.WriterEngine):kantan.csv.CsvWriter[B]
[`writeCsv`]:{{ site.baseurl }}/api/kantan/csv/ops/CsvSinkOps.html#writeCsv[B](rows:TraversableOnce[B],sep:Char,header:Seq[String])(implicitevidence$2:kantan.csv.RowEncoder[B],implicitoa:kantan.csv.CsvSink[A],implicite:kantan.csv.engine.WriterEngine):Unit
[`TraversableOnce`]:http://www.scala-lang.org/api/current/scala/collection/TraversableOnce.html
[`asCsv`]:{{ site.baseurl }}/api/kantan/csv/ops/CsvRowsOps.html#asCsv(sep:Char,header:Seq[String])(implicitea:kantan.csv.RowEncoder[A],implicite:kantan.csv.engine.WriterEngine):String


text:
package com.ircclouds.irc.api;

import java.io.*;

import javax.net.ssl.*;

import com.ircclouds.irc.api.commands.*;
import com.ircclouds.irc.api.comms.*;
import com.ircclouds.irc.api.domain.*;
import com.ircclouds.irc.api.domain.messages.*;
import com.ircclouds.irc.api.filters.*;
import com.ircclouds.irc.api.listeners.*;
import com.ircclouds.irc.api.state.*;

public abstract class AbstractIRCSession implements IIRCSession
{
	private final IMessageDispatcher dispatcher = new MessageDispatcherImpl();
	private final ICommandServer cmdServ;
	private final IMessageReader reader;
	private final AbstractApiDaemon daemon;
	private IConnection conn;
	private Callback<IIRCState> callback;

	public AbstractIRCSession()
	{
		cmdServ = new AbstractCommandServerImpl()
		{
			@Override
			public IConnection getConnection()
			{
				return conn;
			}
		};

		reader = new AbstractMessageReader()
		{
			@Override
			protected IRCServerOptions getIRCServerOptions()
			{
				return AbstractIRCSession.this.getIRCServerOptions();
			}

			@Override
			public IConnection getConnection()
			{
				return conn;
			}
		};

		daemon = new AbstractApiDaemon(reader, dispatcher)
		{
			@Override
			protected void onExit()
			{
				try
				{
					close();
				}
				catch (IOException aExc)
				{
					throw new RuntimeException(aExc);
				}
			}

			@Override
			protected IMessageFilter getMessageFilter()
			{
				return AbstractIRCSession.this.getMessageFilter();
			}

			@Override
			protected void signalExceptionToApi(Exception aExc)
			{
				callback.onFailure(aExc);
			}
		};
	}

	public void execute(ICommand aCommand) throws IOException
	{
		cmdServ.execute(aCommand);
	}

	@Override
	public void addListeners(MESSAGE_VISIBILITY aListenerLevel, IMessageListener... aListeners)
	{
		for (IMessageListener _listener : aListeners)
		{
			dispatcher.register(_listener, aListenerLevel);
		}
	}

	@Override
	public ICommandServer getCommandServer()
	{
		return cmdServ;
	}

	@Override
	public void removeListener(IMessageListener aListener)
	{
		dispatcher.unregister(aListener);
	}

	@Override
	public boolean open(IRCServer aServer, Callback<IIRCState> aCallback) throws IOException
	{
		callback = aCallback;

		if (!aServer.isSSL())
		{
			conn = new SocketChannelConnection();
		}
		else
		{
			conn = new SSLSocketChannelConnection();
		}

		SSLContext _ctx = null;
		if (aServer instanceof SecureIRCServer)
		{
			_ctx = ((SecureIRCServer) aServer).getSSLContext();
		}

		if (conn.open(aServer.getHostname(), aServer.getPort(), _ctx, aServer.getProxy(), aServer.isResolveByProxy()))
		{
			if (!daemon.isAlive())
			{
				daemon.start();
			}

			return true;
		}

		return false;
	}

	@Override
	public void close() throws IOException
	{
		conn.close();

		reader.reset();
	}

	protected abstract IRCServerOptions getIRCServerOptions();

	@Override
	public void dispatchClientError(final Exception e)
	{
		final IMessageDispatcher currentDispatcher = this.dispatcher;
		new Thread()
		{

			@Override
			public void run()
			{
				final ClientErrorMessage errorMsg = new ClientErrorMessage(e);
				currentDispatcher.dispatch(errorMsg, TargetListeners.ALL);
			}
		}.start();
	}
}


text:
package net.starschema.clouddb.jdbc;

import com.google.api.services.bigquery.model.BiEngineReason;
import com.google.api.services.bigquery.model.BiEngineStatistics;
import com.google.api.services.bigquery.model.Job;
import com.google.api.services.bigquery.model.JobReference;
import com.google.api.services.bigquery.model.QueryResponse;
import com.google.api.services.bigquery.model.TableRow;
import com.google.api.services.bigquery.model.TableSchema;
import java.io.IOException;
import java.math.BigInteger;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class partially implements java.sql.Statement, and java.sql.PreparedStatement
 *
 * @author Horváth Attila
 * @author Balazs Gunics
 */
public abstract class BQStatementRoot {

  /** Reference to store the ran Query run by Executequery or Execute */
  ResultSet resset = null;

  /** String containing the context of the Project */
  String projectId = null;

  Logger logger = LoggerFactory.getLogger(BQStatementRoot.class);

  /** Variable that stores the closed state of the statement */
  boolean closed = false;

  /** Reference for the Connection that created this Statement object */
  BQConnection connection;

  /** Variable that stores the set query timeout */
  int querytimeout = Integer.MAX_VALUE / 1000 - 1;
  /** Instance of log4j.Logger */
  /** Variable stores the time an execute is made */
  long starttime = 0;
  /** Variable that stores the max row number which can be stored in the resultset */
  int resultMaxRowCount = Integer.MAX_VALUE - 1;

  /** Variable to Store EscapeProc state */
  boolean EscapeProc = false;

  /** These Variables contain information about the type of resultset this statement creates */
  int resultSetType;

  int resultSetConcurrency;

  /** to be used with setMaxFieldSize */
  private int maxFieldSize = 0;

  protected AtomicReference<JobReference> mostRecentJobReference = new AtomicReference<>();

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public void addBatch(String arg0) throws SQLException {
    throw new BQSQLException("Not implemented." + "addBatch(string)");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLFeatureNotSupportedException
   */
  public void cancel() throws SQLException {
    throw new BQSQLFeatureNotSupportedException("cancel()");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public void clearBatch() throws SQLException {
    throw new BQSQLException("Not implemented." + "clearBatch()");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public void clearWarnings() throws SQLException {
    throw new BQSQLException("Not implemented." + "clearWarnings()");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Only sets closed boolean to true
   */
  public void close() throws SQLException {
    this.closed = true;
    if (this.resset != null) {
      this.resset.close();
    }
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Wrapper for execute; calls execute(arg0, false). Does NOT bypass maxBillingBytes.
   */
  public boolean execute(String sql) throws SQLException {
    return this.execute(sql, false);
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Executes the given SQL statement on BigQuery (note: it returns only 1 resultset). This function
   * directly uses executeQuery function. It also allows bypassing maxBillingBytes for PDTs.
   */
  public boolean execute(String sql, boolean unlimitedBillingBytes) throws SQLException {
    if (this.isClosed()) {
      throw new BQSQLException("This Statement is Closed");
    }
    this.resset = this.executeQuery(sql, unlimitedBillingBytes);
    this.logger.info("Executing Query: " + sql);
    if (this.resset != null) {
      return true;
    } else {
      return false;
    }
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLFeatureNotSupportedException
   */
  public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
    throw new BQSQLFeatureNotSupportedException("execute(String, int)");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLFeatureNotSupportedException
   */
  public boolean execute(String sql, int[] columnIndexes) throws SQLException {
    throw new BQSQLFeatureNotSupportedException("execute(string,int[])");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLFeatureNotSupportedException
   */
  public boolean execute(String sql, String[] columnNames) throws SQLException {
    throw new BQSQLFeatureNotSupportedException("execute(string,string[])");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public int[] executeBatch() throws SQLException {
    throw new BQSQLException("Not implemented." + "executeBatch()");
  }

  /**
   * Execute DML (DELETE, INSERT, UPDATE). If you want to perform a SELECT or other DDL look at
   * {@link #execute(String)}
   */
  private int executeDML(String sql) throws SQLException {
    if (this.isClosed()) {
      throw new BQSQLException("This Statement is Closed");
    }
    if (connection.getUseLegacySql()) {
      throw new BQSQLFeatureNotSupportedException("Legacy SQL does not support DML");
    }
    this.starttime = System.currentTimeMillis();

    final Job referencedJob;

    try {
      QueryResponse qr =
          BQSupportFuncts.runSyncQuery(
              this.connection.getBigquery(),
              projectId,
              sql,
              connection.getDataSet(),
              this.connection.getUseLegacySql(),
              this.connection.getMaxBillingBytes(),
              (long) querytimeout * 1000,
              (long) getMaxRows(),
              this.getAllLabels(),
              this.connection.getUseQueryCache());
      this.mostRecentJobReference.set(qr.getJobReference());

      if (defaultValueIfNull(qr.getJobComplete(), false)) {
        // I hope they don't insert more than 2^32-1 :)
        return Math.toIntExact(defaultValueIfNull(qr.getNumDmlAffectedRows(), 0L));
      }

      referencedJob =
          this.connection
              .getBigquery()
              .jobs()
              .get(projectId, qr.getJobReference().getJobId())
              .execute();
    } catch (IOException e) {
      throw new BQSQLException("Something went wrong with the query: " + sql, e);
    }

    try {
      do {
        if (BQSupportFuncts.getQueryState(referencedJob, this.connection.getBigquery(), projectId)
            .equals("DONE")) {
          return Math.toIntExact(
              BQSupportFuncts.getQueryResults(
                      this.connection.getBigquery(), projectId, referencedJob)
                  .getNumDmlAffectedRows());
        }
        Thread.sleep(500);
        this.logger.debug("slept for 500" + "ms, querytimeout is: " + this.querytimeout + "s");
      } while (System.currentTimeMillis() - this.starttime <= (long) this.querytimeout * 1000);
    } catch (IOException | InterruptedException e) {
      throw new BQSQLException("Something went wrong with the query: " + sql, e);
    }
    // here we should kill/stop the running job, but bigquery doesn't
    // support that :(
    throw new BQSQLException("Query run took more than the specified timeout");
  }

  public ResultSet executeQuery(String querySql, boolean unlimitedBillingBytes)
      throws SQLException {
    if (this.isClosed()) {
      throw new BQSQLException("This Statement is Closed");
    }
    this.starttime = System.currentTimeMillis();
    Job referencedJob;

    Long billingBytes = !unlimitedBillingBytes ? this.connection.getMaxBillingBytes() : null;

    boolean jobAlreadyCompleted = false;

    try {
      QueryResponse qr =
          BQSupportFuncts.runSyncQuery(
              this.connection.getBigquery(),
              projectId,
              querySql,
              connection.getDataSet(),
              this.connection.getUseLegacySql(),
              billingBytes,
              (long) querytimeout * 1000,
              (long) getMaxRows(),
              this.getAllLabels(),
              this.connection.getUseQueryCache());
      this.mostRecentJobReference.set(qr.getJobReference());

      referencedJob =
          this.connection
              .getBigquery()
              .jobs()
              .get(projectId, qr.getJobReference().getJobId())
              .execute();

      if (defaultValueIfNull(qr.getJobComplete(), false)) {
        List<TableRow> rows = defaultValueIfNull(qr.getRows(), new ArrayList<TableRow>());
        if (BigInteger.valueOf(rows.size()).equals(qr.getTotalRows())) {
          TableSchema schema = defaultValueIfNull(qr.getSchema(), new TableSchema());
          String biEngineMode = null;
          List<BiEngineReason> biEngineReasons = null;

          if (referencedJob != null) {
            BiEngineStatistics biEngineStatistics =
                referencedJob.getStatistics().getQuery().getBiEngineStatistics();
            if (biEngineStatistics != null) {
              biEngineMode = biEngineStatistics.getBiEngineMode();
              biEngineReasons = biEngineStatistics.getBiEngineReasons();
            }
          }
          return new BQScrollableResultSet(
              rows,
              this,
              schema,
              qr.getTotalBytesProcessed(),
              qr.getCacheHit(),
              biEngineMode,
              biEngineReasons,
              referencedJob.getJobReference());
        }
        jobAlreadyCompleted = true;
      }

      this.logger.info("Executing Query: " + querySql);
    } catch (IOException e) {
      throw new BQSQLException("Something went wrong with the query: " + querySql, e);
    }
    try {
      do {
        if (jobAlreadyCompleted
            || BQSupportFuncts.getQueryState(
                    referencedJob, this.connection.getBigquery(), projectId)
                .equals("DONE")) {
          if (resultSetType == ResultSet.TYPE_SCROLL_INSENSITIVE) {
            return new BQScrollableResultSet(
                BQSupportFuncts.getQueryResults(
                    this.connection.getBigquery(), projectId, referencedJob),
                this);
          } else {
            return new BQForwardOnlyResultSet(
                this.connection.getBigquery(), projectId, referencedJob, this);
          }
        }
        // Pause execution for half second before polling job status
        // again, to
        // reduce unnecessary calls to the BigQUery API and lower
        // overall
        // application bandwidth.
        Thread.sleep(500);
        this.logger.debug("slept for 500" + "ms, querytimeout is: " + this.querytimeout + "s");
      } while (System.currentTimeMillis() - this.starttime <= (long) this.querytimeout * 1000);
      // it runs for a minimum of 1 time
    } catch (IOException e) {
      throw new BQSQLException("Something went wrong with the query: " + querySql, e);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    // here we should kill/stop the running job, but bigquery doesn't
    // support that :(
    throw new BQSQLException("Query run took more than the specified timeout");
  }

  protected Map<String, String> getAllLabels() {
    return this.connection.getLabels();
  }

  private static <T> T defaultValueIfNull(T value, T defaultValue) {
    return value == null ? defaultValue : value;
  }

  /**
   * Only supported for standard SQL (non-legacy)
   *
   * @throws BQSQLException
   */
  public int executeUpdate(String sql) throws SQLException {
    return executeDML(sql);
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLFeatureNotSupportedException
   */
  public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
    throw new BQSQLFeatureNotSupportedException("executeUpdate(String,int)");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLFeatureNotSupportedException
   */
  public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
    throw new BQSQLFeatureNotSupportedException("executeUpdate(string,int[])");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLFeatureNotSupportedException
   */
  public int executeUpdate(String sql, String[] columnNames) throws SQLException {
    throw new BQSQLFeatureNotSupportedException("execute(update(string,string[])");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Returns the connection that made the object.
   *
   * @returns connection
   */
  public Connection getConnection() throws SQLException {
    return this.connection;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Fetch direction is unknown.
   *
   * @return FETCH_UNKNOWN
   */
  public int getFetchDirection() throws SQLException {
    return ResultSet.FETCH_UNKNOWN;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public int getFetchSize() throws SQLException {
    throw new BQSQLException("Not implemented." + "getFetchSize()");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public ResultSet getGeneratedKeys() throws SQLException {
    throw new BQSQLFeatureNotSupportedException("getGeneratedKeys()");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public int getMaxFieldSize() throws SQLException {
    return maxFieldSize;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * We store it in an array which indexed through, int We could return Integer.MAX_VALUE too, but i
   * don't think we could get that much row.
   *
   * @return 0 -
   */
  public int getMaxRows() throws SQLException {
    return this.resultMaxRowCount;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet, since Bigquery Does not support precompiled sql
   *
   * @throws BQSQLException
   */
  public ResultSetMetaData getMetaData() throws SQLException {
    throw new BQSQLException(new SQLFeatureNotSupportedException("getMetaData()"));
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Multiple result sets are not supported currently.
   *
   * @return false;
   */
  public boolean getMoreResults() throws SQLException {
    return false;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Multiple result sets are not supported currently. we check that the result set is open, the
   * parameter is acceptable, and close our current resultset or throw a
   * FeatureNotSupportedException
   *
   * @param current - one of the following Statement constants indicating what should happen to
   *     current ResultSet objects obtained using the method getResultSet:
   *     Statement.CLOSE_CURRENT_RESULT, Statement.KEEP_CURRENT_RESULT, or
   *     Statement.CLOSE_ALL_RESULTS
   * @throws BQSQLException
   */
  public boolean getMoreResults(int current) throws SQLException {
    if (this.closed) {
      throw new BQSQLException("Statement is closed.");
    }
    if (current == Statement.CLOSE_CURRENT_RESULT
        || current == Statement.KEEP_CURRENT_RESULT
        || current == Statement.CLOSE_ALL_RESULTS) {

      if (BQDatabaseMetadata.multipleOpenResultsSupported
          && (current == Statement.KEEP_CURRENT_RESULT || current == Statement.CLOSE_ALL_RESULTS)) {
        throw new BQSQLFeatureNotSupportedException();
      }
      // Statement.CLOSE_CURRENT_RESULT
      this.close();
      return false;
    } else {
      throw new BQSQLException("Wrong parameter.");
    }
  }

  public int getQueryTimeout() throws SQLException {
    if (this.isClosed()) {
      throw new BQSQLException("This Statement is Closed");
    }
    if (this.starttime == 0) {
      return 0;
    }
    if (this.querytimeout == Integer.MAX_VALUE) {
      return 0;
    } else {
      if (System.currentTimeMillis() - this.starttime > this.querytimeout) {
        throw new BQSQLException("Time is over");
      }
      return this.querytimeout;
    }
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Gives back reultset stored in resset
   */
  public ResultSet getResultSet() throws SQLException {
    if (this.isClosed()) {
      throw new BQSQLException("This Statement is Closed");
    }
    if (this.resset != null) {
      return this.resset;
    } else {
      return null;
    }
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * The driver is read only currently.
   *
   * @return CONCUR_READ_ONLY
   */
  public int getResultSetConcurrency() throws SQLException {
    return ResultSet.CONCUR_READ_ONLY;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Read only mode, no commit.
   *
   * @return CLOSE_CURSORS_AT_COMMIT
   */
  public int getResultSetHoldability() throws SQLException {
    return ResultSet.CLOSE_CURSORS_AT_COMMIT;
    // TODO
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Updates and deletes not supported.
   *
   * @return TYPE_SCROLL_INSENSITIVE
   */
  public int getResultSetType() throws SQLException {
    return ResultSet.TYPE_SCROLL_INSENSITIVE;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Result will be a ResultSet object.
   *
   * @return -1
   */
  public int getUpdateCount() throws SQLException {
    return -1;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * returns null
   *
   * @return null
   */
  public SQLWarning getWarnings() throws SQLException {
    return null;
    // TODO Implement Warning Handling
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Returns the value of boolean closed
   */
  public boolean isClosed() throws SQLException {
    return this.closed;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public boolean isPoolable() throws SQLException {
    throw new BQSQLException("Not implemented." + "isPoolable()");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @return false
   */
  public boolean isWrapperFor(Class<?> iface) throws SQLException {
    return false;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * FeatureNotSupportedExceptionjpg
   *
   * @throws BQSQLFeatureNotSupportedException
   */
  public void setCursorName(String arg0) throws SQLException {
    throw new BQSQLFeatureNotSupportedException("setCursorName(string)");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Now Only setf this.EscapeProc to arg0
   */
  public void setEscapeProcessing(boolean arg0) throws SQLException {
    if (this.isClosed()) {
      throw new BQSQLException("This Statement is Closed");
    }
    this.EscapeProc = arg0;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public void setFetchDirection(int arg0) throws SQLException {
    throw new BQSQLException("Not implemented." + "setFetchDirection(int)");
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Does nothing
   *
   * @throws BQSQLException
   */
  public void setFetchSize(int arg0) throws SQLException {
    if (this.isClosed()) {
      throw new BQSQLException("Statement closed");
    }
  }

  /**
   * Sets the limit for the maximum number of bytes in a ResultSet column storing character or
   * binary values to the given number of bytes. This limit applies only to BINARY, VARBINARY,
   * LONGVARBINARY, CHAR, VARCHAR, and LONGVARCHAR fields. If the limit is exceeded, the excess data
   * is silently discarded. For maximum portability, use values greater than 256.
   *
   * @throws BQSQLException
   */
  public void setMaxFieldSize(int arg0) throws SQLException {
    this.maxFieldSize = arg0;
  }

  /** NOTE: can pass 0 or negative to set to unlimited */
  public void setMaxRows(int newMax) {
    this.resultMaxRowCount = newMax <= 0 ? Integer.MAX_VALUE - 1 : newMax;
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Not implemented yet.
   *
   * @throws BQSQLException
   */
  public void setPoolable(boolean arg0) throws SQLException {
    throw new BQSQLException("Not implemented." + "setPoolable(bool)");
  }

  public void setQueryTimeout(int seconds) throws SQLException {
    if (this.isClosed()) {
      throw new BQSQLException("This Statement is Closed");
    }
    if (seconds == 0) {
      this.querytimeout = Integer.MAX_VALUE;
    } else {
      this.querytimeout = seconds;
    }
  }

  /**
   *
   *
   *
Implementation Details:

   *
   *

   * Always throws SQLException
   *
   * @throws SQLException
   */
  public <T> T unwrap(Class<T> iface) throws SQLException {
    throw new BQSQLException("not found");
  }
}


text:
  # set default quantity (0)
  # print the list to the console
# output: a hash with its quantity

# Method to add an item to a list
# input: item name and optional quantity
# steps:add the name and quantity to the hash list that we made
# output: newly updated list

# Method to remove an item from the list
# input:item name
# steps:delete the name and quantity from the hash list
# output: newly updated list

# Method to update the quantity of an item
# input: item name with new quantity value
# steps: find the key, change the quantity value
# output: newly updated list

# Method to print a list and make it look pretty
# input: name of the hash
# steps:print out all the names and quantity of the groceries
# output: newly updated list

# INITIAL CODE:
# -------------
# Define your methods here...

# $global_variable
# CONSTANT # The same as a global variable, but your not allowed to change it (redefine it)

# @instance_variable # only avaialbe to single instance
# @@class_variable # aka an instnace variable shared by all instances of a class

# local_variable

# arguements are defined as local variables inside a method.

# def say_hello #(name)
#   # name != @name
#   puts "Hello #{@name}"
# end

# @my_name = "Michael"
# say_hello(@my_name)

# print_results(@something)

def make_list(string)
  # temp_array = string.delete(",").split(" ")
  temp_array = string.gsub(",", "").split(" ")
  temp_array.each do |item|
    $groceries[item]=0
  end
end

def print_list #(hash)
  title = "Grocery List"
  puts title
  puts "-" * title.length

  puts "There are no items in the list" if $groceries.empty?

  $groceries.each do |item, quantity|
    puts "#{item} - #{quantity}"
  end
  puts "\n"
end

def add_item(item, quantity = 1)
  # Validations
  validate_item_name(item)
  if $groceries.include?(item)
    $groceries[item] += 1
  else
    $groceries[item] = quantity
  end
  print_list #($groceries)
end

def delete_item(item)
  validate_item_name(item)
  $groceries.delete(item)
  print_list #($groceries)
end

def validate_item_name(item)
  unless item.is_a? String
    puts "Item must be a string"
    raise ArgumentError.new('Item must be a string')
  end
end

def change_quantity(item, quantity)
  add_item(item, quantity)
end

# DRIVER CODE:
# ------------
$groceries = {}
print_list

# then use methods to manipulate your list here...
make_list("apple, onions, bread")
add_item("apple", 2)
add_item("onions", 3)


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

namespace WHQ.Core.Model.WCT
{
    public class ThreadWCTInfo
    {
        public ThreadWCTInfo(bool isDeadLock, uint threadId)
        {
            IsDeadLocked = isDeadLock;
            ThreadId = threadId;
        }

        /// <summary>
        /// Specifies whether the Wait Chain is Cyclic - Deadlock
        /// </summary>
        public bool IsDeadLocked { get; private set; }
        /// <summary>
        /// OS Id of the thread
        /// </summary>
        public uint ThreadId { get; private set; }

        List<WaitChainInfoObject> _blockingObjects;

        public List<WaitChainInfoObject> WctBlockingObjects
        {
            get
            {
                if (_blockingObjects == null)
                {
                    _blockingObjects = new List<WaitChainInfoObject>();
                }
                return _blockingObjects;
            }
        }

        internal void SetInfo(WAITCHAIN_NODE_INFO[] info)
        {
            if (info != null)
            {
                foreach (var item in info)
                {
                    var block = new WaitChainInfoObject(item);
                    WctBlockingObjects.Add(block);
                }
            }
        }
    }
}