text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Bootstrap, from Twitter</title>
    <meta name="description" content="">
    <meta name="author" content="">

    <link href="../bootstrap.css" rel="stylesheet">
    <link href="assets/css/docs.css" rel="stylesheet">
    <link href="assets/js/google-code-prettify/prettify.css" rel="stylesheet">

    <link rel="shortcut icon" type="image/x-icon" href="assets/ico/favicon.ico">
    <link rel="apple-touch-icon" href="assets/ico/bootstrap-apple-57x57.png">
    <link rel="apple-touch-icon" sizes="72x72" href="assets/ico/bootstrap-apple-72x72.png">
    <link rel="apple-touch-icon" sizes="114x114" href="assets/ico/bootstrap-apple-114x114.png">

Bootstrap JS

Overview

Modals

Dropdown

ScrollSpy

Buttons

Tabs

Twipsy

Popover

Alerts

Javascript for Bootstrap

            Bring Bootstrap's components to life with new, custom plugins that work with jQuery and Ender.

← Back to Bootstrap home

Modals bootstrap-modal.js

Our Modal plugin is a super slim take on the traditional modal js plugin, taking special care to include only the bare functionality that we require here at twitter.

          Download

Using bootstrap-modal

$('#my-modal').modal(options)

Options

               Name
               type
               default
               description

               backdrop
               boolean, string
               false
               Includes a modal-backdrop element. Set backdrop to "static" if you do not want the modal closed when the backdrop is clicked.

               keyboard
               boolean
               false
               Closes the modal when escape key is pressed

               show
               boolean
               false
               Opens modal on class initialization

Markup

You can activate modals on your page easily without having to write a single line of javascript. Just give an element a data-controls-modal attribute which corresponds to a modal element id, and when clicked, it will launch your modal. To add modal options, just include them as data attributes as well.

<a class="btn" data-controls-modal="my-modal" data-backdrop="static" >Launch Modal</a>

Notice If you want your modal to animate in and out, just add a .fade class to your .modal element (refer to the demo to see this in action).

Methods

.modal(options)

Activates your content as a modal. Accepts an optional options object.

$('#my-modal').modal({
  keyboard: true
})

.modal('toggle')

Manually toggles a modal.

$('#my-modal').modal('toggle')

.modal('show')

Manually opens a modal.

$('#my-modal').modal('show')

.modal('hide')

Manually hides a modal.

$('#my-modal').modal('hide')

.modal(true)

Returns an elements modal class instance.

$('#my-modal').modal(true)

Notice Alternatively, this can be retrieved with $().data('modal').

Events

Bootstrap's modal class exposes a few events for hooking into modal functionality.

               Event
               Description

               show
               This event fires immediately when the show instance method is called.

               shown
               This event is fired when the modal has been made visible to the user (will wait for css transitions to complete).

               hide
               This event is fired immediately when the hide instance method has been called.

               hidden
               This event is fired when the modal has finished being hidden from the user (will wait for css transitions to complete).

$('#my-modal').bind('hidden', function () {
  // do something ...
})

Demo

              ×

Modal Heading

One fine body…

              Primary
              Secondary

          <button data-controls-modal="modal-from-dom" data-backdrop="true" data-keyboard="true" class="btn danger">Launch Modal</button>

Dropdown bootstrap-dropdown.js

This plugin is for adding dropdown interaction to the bootstrap topbar or tabbed navigations.

          Download

Using bootstrap-dropdown.js

$('#topbar').dropdown()

Markup

To quickly add dropdown functionality to any nav element, use the data-dropdown attribute. Any valid bootstrap dropdown will automatically be activated.

<ul class="tabs">
  <li class="active"><a href="#">Home</a></li>
  <li class="dropdown" data-dropdown="dropdown" >
    <a href="#" class="dropdown-toggle">Dropdown</a>
    <ul class="dropdown-menu">
      <li><a href="#">Secondary link</a></li>
      <li><a href="#">Something else here</a></li>
      <li class="divider"></li>
      <li><a href="#">Another link</a></li>
    </ul>
  </li>
</ul>

Notice If your ui has several dropdowns, consider adding the data-dropdown attribute to a more significant container element like .tabs or .topbar.

Methods

$().dropdown()

          A programatic api for activating menus for a given topbar or tabbed navigation.

Demo

Project Name

Link

Link

                  <form action="">
                    <input type="text" placeholder="Search" />
                  </form>

                      Dropdown 1

Secondary link

Something else here

Another link

                      Dropdown 2

Secondary link

Something else here

Another link

ScrollSpy bootstrap-scrollspy.js

This plugin is for adding the scrollspy (auto updating nav) interaction to the bootstrap topbar.

          Download

Using bootstrap-scrollspy.js

$('#topbar').scrollSpy()

Markup

To easily add scrollspy behavior to your nav, just add the data-scrollspy attribute to the .topbar.

<div class="topbar" data-scrollspy="scrollspy" >...</div>

Methods

$().scrollSpy()

          Auto activates navigation buttons by users scroll position.

$('body > .topbar').scrollSpy()

Notice Topbar anchor tags must have resolvable id targets. For example, a <a href="#home">home</a> must correspond to something in the dom like <div id="home"></div>.

.scrollSpy('refresh')

The scrollspy caches nav buttons and section coordinates for performance. If you need to update this cache (likely if you have dynamic content) just call this refresh method. If you used the data attribute to define your scrollspy, just call refresh on the body.

$('body').scrollSpy('refresh')

Demo

Checkout the the topbar navigation on this page.

Buttons bootstrap-buttons.js

This plugin offers additional functionality for managing button state.

          Download

Using bootstrap-buttons.js

$('.tabs').button()

Methods

$().button('toggle')

Toggles push state. Gives btn the look that it's been activated.

Notice You can enable auto toggling of a button by using the data-toggle attribute.

<button class="btn" data-toggle="toggle" >...</button>

$().button('loading')

Sets button state to loading - disables button and swaps text to loading text. Loading text should be defined on the button element using the data attribute data-loading-text.

<button class="btn" data-loading-text="loading stuff..." >...</button>

$().button('reset')

Resets button state - swaps text to original text.

$().button(string)

Resets button state - swaps text to any data defined text state.

<button class="btn" data-complete-text="finished!" >...</button>
<script>
  $('.btn').button('complete')
</scrip>

Demo

          <button id="fat-btn" data-loading-text="loading..." class="btn danger">Loading Demo</button>
          <button class="btn" data-toggle="toggle">Toggle Demo</button>

Tabs bootstrap-tabs.js

This plugin adds quick, dynamic tab and pill functionality.

          Download

Using bootstrap-tabs.js

$('.tabs').tabs()

Markup

You can activate a tab or pill navigation without writing any javascript by simply giving them a data-tabs or data-pills attribute.

 <ul class="tabs" data-tabs="tabs" >...</ul>

Methods

$().tabs or $().pills

            Activates tab and pill functionality for a given container. Tab links should reference IDs in the document.

<ul class="tabs">
  <li class="active"><a href="#home">Home</a></li>
  <li><a href="#profile">Profile</a></li>
  <li><a href="#messages">Messages</a></li>
  <li><a href="#settings">Settings</a></li>
</ul>

<div class="pill-content">
  <div class="active" id="home">...</div>
  <div id="profile">...</div>
  <div id="messages">...</div>
  <div id="settings">...</div>
</div>

<script>
  $.domReady(function () {
    $('.tabs').tabs()
  })
</script>

Events

					     Event
					     Description

					     change
					     This event fires on tab change. Use event.target and event.relatedTarget to target the active tab and the previous active tab respectively.

$('.tabs a').bind('change', function (e) {
  e.target // activated tab
  e.relatedTarget // previous tab
})

Demo

Home

Profile

Messages

Settings

              Dropdown

@fat

@mdo

Raw denim you probably haven't heard of them jean shorts Austin. Nesciunt tofu stumptown aliqua, retro synth master cleanse. Mustache cliche tempor, williamsburg carles vegan helvetica. Reprehenderit butcher retro keffiyeh dreamcatcher synth. Cosby sweater eu banh mi, qui irure terry richardson ex squid. Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel, butcher voluptate nisi qui.

Food truck fixie locavore, accusamus mcsweeney's marfa nulla single-origin coffee squid. Exercitation +1 labore velit, blog sartorial PBR leggings next level wes anderson artisan four loko farm-to-table craft beer twee. Qui photo booth letterpress, commodo enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl cillum PBR. Homo nostrud organic, assumenda labore aesthetic magna delectus mollit. Keytar helvetica VHS salvia yr, vero magna velit sapiente labore stumptown. Vegan fanny pack odio cillum wes anderson 8-bit, sustainable jean shorts beard ut DIY ethical culpa terry richardson biodiesel. Art party scenester stumptown, tumblr butcher vero sint qui sapiente accusamus tattooed echo park.

Banksy do proident, brooklyn photo booth delectus sunt artisan sed organic exercitation eiusmod four loko. Quis tattooed iphone esse aliqua. Master cleanse vero fixie mcsweeney's. Ethical portland aute, irony food truck pitchfork lomo eu anim. Aesthetic blog DIY, ethical beard leggings tofu consequat whatever cardigan nostrud. Helvetica you probably haven't heard of them carles, marfa veniam occaecat lomo before they sold out in shoreditch scenester sustainable thundercats. Consectetur tofu craft beer, mollit brunch fap echo park pitchfork mustache dolor.

Sunt qui biodiesel mollit officia, fanny pack put a bird on it thundercats seitan squid ad wolf bicycle rights blog. Et aute readymade farm-to-table carles 8-bit, nesciunt nulla etsy adipisicing organic ea. Master cleanse mollit high life, next level Austin nesciunt american apparel twee mustache adipisicing reprehenderit hoodie portland irony. Aliqua tofu quinoa +1 commodo eiusmod. High life williamsburg cupidatat twee homo leggings. Four loko vinyl DIY consectetur nisi, marfa retro keffiyeh vegan. Fanny pack viral retro consectetur gentrify fap.

Etsy mixtape wayfarers, ethical wes anderson tofu before they sold out mcsweeney's organic lomo retro fanny pack lo-fi farm-to-table readymade. Messenger bag gentrify pitchfork tattooed craft beer, iphone skateboard locavore carles etsy salvia banksy hoodie helvetica. DIY synth PBR banksy irony. Leggings gentrify squid 8-bit cred pitchfork. Williamsburg banh mi whatever gluten-free, carles pitchfork biodiesel fixie etsy retro mlkshk vice blog. Scenester cred you probably haven't heard of them, vinyl craft beer blog stumptown. Pitchfork sustainable tofu synth chambray yr.

Trust fund seitan letterpress, keytar raw denim keffiyeh etsy art party before they sold out master cleanse gluten-free squid scenester freegan cosby sweater. Fanny pack portland seitan DIY, art party locavore wolf cliche high life echo park Austin. Cred vinyl keffiyeh DIY salvia PBR, banh mi before they sold out farm-to-table VHS viral locavore cosby sweater. Lomo wolf viral, mustache readymade thundercats keffiyeh craft beer marfa ethical. Wolf salvia freegan, sartorial keffiyeh echo park vegan.

Twipsy bootstrap-twipsy.js

Based on the excellent jQuery.tipsy plugin written by Jason Frame; twipsy is an updated version, which doesn't rely on images, uses css3 for animations, and data-attributes for title storage!

          Download

Using bootstrap-twipsy.js

$('#example').twipsy(options)

Options

               Name
               type
               default
               description

               animate
               boolean
               true
               apply a css fade transition to the tooltip

               delayIn
               number
               0
               delay before showing tooltip (ms)

               delayOut
               number
               0
               delay before hiding tooltip (ms)

               fallback
               string
               ''
               text to use when no tooltip title is present

               placement
               string
               'above'
               how to position the tooltip - above | below | left | right

               html
               boolean
               false
               allows html content within tooltip

               live
               boolean
               false
               use event delegation instead of individual event handlers

               offset
               number
               0
               pixel offset of tooltip from target element

               title
               string, function
               'title'
               attribute or method for retrieving title text

               trigger
               string
               'hover'
               how tooltip is triggered - hover | focus | manual

               template
               string
               [default markup]
               the html template used for rendering a twipsy

Notice Individual twipsy instance options can alternatively be specified through the use of data attributes.

<a href="#" data-placement="below" rel='twipsy' title='Some title text'>text</a>

Methods

$().twipsy(options)

Attaches a twipsy handler to an element collection.

.twipsy('show')

Reveals an elements twipsy.

$('#element').twipsy('show')

.twipsy('hide')

Hides an elements twipsy.

$('#element').twipsy('hide')

.twipsy(true)

Returns an elements twipsy class instance.

$('#element').twipsy(true)

Notice Alternatively, this can be retrieved with $().data('twipsy').

Demo

Tight pants next level keffiyeh you probably haven't heard of them. Photo booth beard raw denim letterpress vegan messenger bag stumptown. Farm-to-table seitan, mcsweeney's fixie sustainable quinoa 8-bit american apparel have a terry richardson vinyl chambray. Beard stumptown, cardigans banh mi lomo thundercats. Tofu biodiesel williamsburg marfa, four loko mcsweeney's cleanse vegan chambray. A really ironic artisan whatever keytar, scenester farm-to-table banksy Austin twitter handle freegan cred raw denim single-origin coffee viral.

Popovers bootstrap-popover.js

The popover plugin provides a simple interface for adding popovers to your application. It extends the bootstrap-twipsy.js plugin, so be sure to grab that file as well when including popovers in your project!

Notice You must include the bootstrap-twipsy.js file before bootstrap-popover.js.

          Download

Using bootstrap-popover.js

$('#example').popover(options)

Options

               Name
               type
               default
               description

               animate
               boolean
               true
               apply a css fade transition to the tooltip

               delayIn
               number
               0
               delay before showing tooltip (ms)

               delayOut
               number
               0
               delay before hiding tooltip (ms)

               fallback
               string
               ''
               text to use when no tooltip title is present

               placement
               string
               'right'
               how to position the tooltip - above | below | left | right

               html
               boolean
               false
               allows html content within tooltip

               live
               boolean
               false
               use event delegation instead of individual event handlers

               offset
               number
               0
               pixel offset of tooltip from target element

               title
               string, function
               'title'
               attribute or method for retrieving title text

               content
               string, function
               'data-content'
               attribute or method for retrieving content text.

               trigger
               string
               'hover'
               how tooltip is triggered - hover | focus | manual

               template
               string
               [default markup]
               the html template used for rendering a popover

Notice Individual popover instance options can alternatively be specified through the use of data attributes.

<a data-placement="below" href="#" class="btn danger" rel="popover">text</a>

Methods

$().popover(options)

Initializes popovers for an element collection.

.popover('show')

Reveals an elements popover.

$('#element').popover('show')

.popover('hide')

Hides an elements popover.

$('#element').popover('hide')

Demo

          hover for popover

Alerts bootstrap-alerts.js

The alert plugin is a super tiny class for adding close functionality to alerts.

          Download

Using bootstrap-alerts.js

$(".alert-message").alert()

Markup

Just add a data-alert attribute to your alert messages to automatically give them close functionality.

Options

               Name
               type
               default
               description

               selector
               string
               '.close'
               What selector to target for closing an alert.

Methods

$().alert()

Wraps all alerts with close functionality. To have your alerts animate out when closed, make sure they have the .fade and .in class already applied to them.

.alert('close')

Closes an alert.

$(".alert-message").alert('close')

Demo

            ×

Holy guacamole! Best check yo self, you're not looking too good.

            ×

Oh snap! You got an error! Change this and that and try again. Duis mollis, est non commodo luctus, nisi erat porttitor ligula, eget lacinia odio sem nec elit. Cras mattis consectetur purus sit amet fermentum.

              Take this action Or do this

Back to top

          Designed and built with all the love in the world @twitter by @mdo and @fat.

          Licensed under the Apache License v2.0.


text:
using System;

/// <summary>
/// This code demonstrates the Facade pattern as a MortgageApplication
/// object which provides a simplified interface to a large subsystem
/// of classes measuring the creditworthyness of an applicant.
/// </summary>
namespace Facade.Demonstration
{
    /// <summary>
    /// Facade Design Pattern.
    /// </summary>
    class Client
    {
        /// <summary>
        /// Entry point into console application.
        /// </summary>
        static void Main()
        {
            //TODO
        }
    }

    /// <summary>
    /// The 'Facade' class
    /// </summary>
    class CollegeLoan
    {
        private Bank _bank = new Bank();
        private Loan _loan = new Loan();
        private Credit _credit = new Credit();

        public bool IsEligible(Student stud, int amount)
        {
            Console.WriteLine("{0} applies for {1:C} loan\n",
              stud.Name, amount);

            bool eligible = true;

            // Verify creditworthyness of applicant
            if (!_bank.HasSufficientSavings(stud, amount))
            {
                eligible = false;
            }
            else if (!_loan.HasNoBadLoans(stud))
            {
                eligible = false;
            }
            else if (!_credit.HasGoodCredit(stud))
            {
                eligible = false;
            }

            return eligible;
        }
    }

    /// <summary>
    /// The 'Subsystem ClassA' class
    /// </summary>
    class Bank
    {
        public bool HasSufficientSavings(Student c, int amount)
        {
            Console.WriteLine("Verify bank for " + c.Name);
            return true;
        }
    }

    /// <summary>
    /// The 'Subsystem ClassB' class
    /// </summary>
    class Credit
    {
        public bool HasGoodCredit(Student c)
        {
            Console.WriteLine("Verify credit for " + c.Name);
            return true;
        }
    }

    /// <summary>
    /// The 'Subsystem ClassC' class
    /// </summary>
    class Loan
    {
        public bool HasNoBadLoans(Student c)
        {
            Console.WriteLine("Verify loans for " + c.Name);
            return true;
        }
    }

    /// <summary>
    /// Student class
    /// </summary>
    class Student
    {
        private string _name;

        // Constructor
        public Student(string name)
        {
            this._name = name;
        }

        // Gets the name
        public string Name
        {
            get { return _name; }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
module OSC
  class AddressPattern
    def initialize(pattern)
      @pattern = pattern

      generate_regex_from_pattern
    end

    def match?(address)
      !!(@re.nil? || @re.match(address))
    end

    private

    def generate_regex_from_pattern
      case @pattern
      when nil
        @re = @pattern
      when Regexp
        @re = @pattern
      when String
        # i'm unsure what this does
        # @pattern.gsub!(/[.^(|)]/, '\\1')

        # handles osc single char wildcard matching
        @pattern.gsub!(/\?/, '[^/]')

        # handles ** - used in creating osc routers
        # TODO: turns out the OSC 1.1 spec says that we shoudl use "//"
        # this will be implemented in the next major release of this gem
        #@pattern.gsub!(/\*\*/, '.*' )

        # handles osc * - 0 or more matching
        @pattern.gsub!(/\*[^\*]/, '[^/]*')

        # handles [!] matching
        @pattern.gsub!(/\[!/, '[^')

        # handles {} matching
        @pattern.gsub!(/\{/, '(')
        @pattern.gsub!(/,/, '|')
        @pattern.gsub!(/\}/, ')')

        # keeps from matching before the begining of the pattern
        @pattern.gsub!(/\A/, '\A')

        # keeps from matching beyond the end,
        # eg. pattern /hi does not match /hidden
        @pattern.gsub!(/\z/, '\z')

        @re = Regexp.new(@pattern)
      else
        raise(ArgumentError, 'invalid pattern')
      end
    end
  end
end


text:
package plugin

import (
	"bytes"
	"compress/zlib"
	"context"
	"fmt"
	"io/ioutil"
	"reflect"
	"testing"

	"github.com/golang/protobuf/proto"
	"github.com/golang/protobuf/ptypes"
	"github.com/kolide/osquery-go/gen/osquery"

	fspb "github.com/google/fleetspeak/fleetspeak/src/common/proto/fleetspeak"
	ospb "github.com/google/fleetspeak/fleetspeak/src/osquery/proto/fleetspeak_osquery"
)

func decode(t ospb.CompressionType, b []byte) ([]byte, error) {
	switch t {
	case ospb.CompressionType_UNCOMPRESSED:
		return b, nil
	case ospb.CompressionType_ZCOMPRESSION:
		r, err := zlib.NewReader(bytes.NewReader(b))
		if err != nil {
			return nil, err
		}
		defer r.Close()
		return ioutil.ReadAll(r)
	}
	return nil, fmt.Errorf("unknown compression type: %d", t)
}

func TestDistributed(t *testing.T) {
	toOSQuery := make(chan *fspb.Message, 5)
	fromOSQuery := make(chan *fspb.Message, 20)

	dist := MakeDistributed("testDistributed", toOSQuery, fromOSQuery)
	for _, tc := range []struct {
		name string

		// The queries to throw at the extension as if they came through FS.
		inQueries []*ospb.Queries
		// What getQueries should return to osquery, after inQ are sent to the extension.
		wantGet osquery.ExtensionPluginResponse

		// What results should be given using writeResults after getQueries.
		inResults []osquery.ExtensionPluginRequest
		// What rows are expected to be sent back to FS, for each query.
		wantRows map[string]*ospb.Rows
	}{
		{
			name: "basic",
			inQueries: []*ospb.Queries{{
				Queries: map[string]string{"basic": "SELECT * FROM foobar"},
			}},
			wantGet: osquery.ExtensionPluginResponse{
				{"results": `{"queries":{"basic":"SELECT * FROM foobar"}}`},
			},
			inResults: []osquery.ExtensionPluginRequest{
				{"action": "writeResults", "results": `{"queries":{"basic":[{"iso_8601":"2017-07-10T22:08:40Z"}]}, "statuses":{"basic":"0"}}`},
			},
			wantRows: map[string]*ospb.Rows{"basic": {Rows: []*ospb.Row{{Row: map[string]string{"iso_8601": "2017-07-10T22:08:40Z"}}}}},
		},
		{
			name: "multi-query",
			inQueries: []*ospb.Queries{
				{Queries: map[string]string{
					"multi1": "SELECT name FROM foobar WHERE idx=1",
					"multi2": "SELECT name FROM foobar WHERE idx=2"}},
				{Queries: map[string]string{
					"multi3": "SELECT name FROM foobar WHERE idx=3",
					"multi4": "SELECT name FROM foobar WHERE idx=4"}},
			},
			wantGet: osquery.ExtensionPluginResponse{
				{"results": `{"queries":{"multi1":"SELECT name FROM foobar WHERE idx=1","multi2":"SELECT name FROM foobar WHERE idx=2","multi3":"SELECT name FROM foobar WHERE idx=3","multi4":"SELECT name FROM foobar WHERE idx=4"}}`},
			},
			inResults: []osquery.ExtensionPluginRequest{
				{"action": "writeResults", "results": `{"queries":{"multi1":[{"name":"client1"}], "multi2":[{"name":"client2"}], "multi3":[{"name":"client3"}], "multi4":[{"name":"client4"}]}, "statuses":{"multi1":"0","multi2":"0","multi3":"0","multi4":"0"}}`},
			},
			wantRows: map[string]*ospb.Rows{
				"multi1": {Rows: []*ospb.Row{{Row: map[string]string{"name": "client1"}}}},
				"multi2": {Rows: []*ospb.Row{{Row: map[string]string{"name": "client2"}}}},
				"multi3": {Rows: []*ospb.Row{{Row: map[string]string{"name": "client3"}}}},
				"multi4": {Rows: []*ospb.Row{{Row: map[string]string{"name": "client4"}}}},
			},
		},
		{
			name: "multi-results",
			inQueries: []*ospb.Queries{{
				Queries: map[string]string{"basic": "SELECT * FROM foobar"},
			}},
			wantGet: osquery.ExtensionPluginResponse{
				{"results": `{"queries":{"basic":"SELECT * FROM foobar"}}`},
			},
			inResults: []osquery.ExtensionPluginRequest{
				{"action": "writeResults", "results": `{"queries":{"basic":[{"iso_8601":"2017-07-10T22:08:40Z"}, {"iso_8601":"2017-07-10T22:08:41Z"}, {"iso_8601":"2017-07-10T22:08:42Z"}]}, "statuses":{"basic":"0"}}`},
			},
			wantRows: map[string]*ospb.Rows{"basic": {Rows: []*ospb.Row{
				{Row: map[string]string{"iso_8601": "2017-07-10T22:08:40Z"}},
				{Row: map[string]string{"iso_8601": "2017-07-10T22:08:41Z"}},
				{Row: map[string]string{"iso_8601": "2017-07-10T22:08:42Z"}},
			}}},
		},
	} {
		serviceName := fmt.Sprintf("TestService-%s", tc.name)
		for _, q := range tc.inQueries {
			data, err := ptypes.MarshalAny(q)
			if err != nil {
				t.Errorf("%s: Failed to marshal ospb.Queries: %v", tc.name, err)
			}
			toOSQuery <- &fspb.Message{
				Source:      &fspb.Address{ServiceName: serviceName},
				MessageType: "Queries",
				Data:        data,
			}
		}
		res := dist.Call(context.Background(), osquery.ExtensionPluginRequest{"action": "getQueries"})
		if (*res.Status != osquery.ExtensionStatus{Code: 0, Message: "OK"}) {
			t.Errorf("%s: Unexpected ExtensionStatus, wanted OK, got: %v", tc.name, res.Status)
			continue
		}
		if !reflect.DeepEqual(res.Response, tc.wantGet) {
			t.Errorf("%s: Unexpected Response attributed, wanted %v, got %v.", tc.name, tc.wantGet, res.Response)
			continue
		}
		for _, r := range tc.inResults {
			res := dist.Call(context.Background(), r)
			if (*res.Status != osquery.ExtensionStatus{Code: 0, Message: "OK"}) {
				t.Errorf("%s: Unexpected ExtensionStatus, wanted OK, got: %v", tc.name, res.Status)
				continue
			}
		}
	L:
		for {
			var msg *fspb.Message
			select {
			case msg = <-fromOSQuery:
			default:
				break L
			}

			if !proto.Equal(msg.Destination, &fspb.Address{ServiceName: serviceName}) {
				t.Errorf("%s: Unexpected Destination, wanted %v, got %v", tc.name, &fspb.Address{ServiceName: serviceName}, msg.Destination)
			}
			if msg.MessageType != "DistributedResult" {
				t.Errorf("%s: Unexpected MessageType, wanted DistributedResult, got %s", tc.name, msg.MessageType)
			}
			var qr ospb.QueryResults
			if err := ptypes.UnmarshalAny(msg.Data, &qr); err != nil {
				t.Errorf("%s: Error unmarshalling data as QueryResults: %v", tc.name, err)
				continue
			}
			b, err := decode(qr.Compress, qr.Rows)
			if err != nil {
				t.Errorf("%s: Error decoding Rows: %v", tc.name, err)
			}
			var rows ospb.Rows
			if err := proto.Unmarshal(b, &rows); err != nil {
				t.Errorf("%s: Unable to unmarshal rows: %v", tc.name, err)
				continue
			}
			if !proto.Equal(&rows, tc.wantRows[qr.QueryName]) {
				t.Errorf("%s: Unexpected rows returned for %s, wanted %+v, got %+v", tc.name, qr.QueryName, tc.wantRows[qr.QueryName].String(), rows.String())
			}
			delete(tc.wantRows, qr.QueryName)
		}
		if len(tc.wantRows) > 0 {
			t.Errorf("Did not receive all expected rows, still waiting for: %v", tc.wantRows)
		}
	}
}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;

namespace UserInterface {
    [AddComponentMenu(NamingHelper.Tabbar.Name, 3)]
    public class GMTabbar : ToggleGroup {
        /// <summary>
        /// If activated the tabbar checks if more than one tab is currently open and then automatically opens the
        /// first or - if set - default tab. This should be deactivated if the behaviour is handled from outside.
        /// </summary>
        public bool deactivateDefaultOnEnableBehaviour;
        public bool activateNewTabsOnAdd = true;
        public bool registerInactiveTabsOnStart = true;
        public GMTab defaultTab;

        private List<GMTab> tabs = new List<GMTab>();
        public List<GMTab> Tabs => tabs;

        private GMTab activeTab;

        private List<Action> valueChangedListeners = new List<Action>();

        protected override void Start() {
            base.Start();

            //Register all tabs that are children of this tabbar
            GMTab[] tabs = GetComponentsInChildren<GMTab>(registerInactiveTabsOnStart);

            foreach (GMTab tab in tabs) {
                //Only register Tabs that are not child to another tab
                if (tab.transform.parent.GetComponentInParent<GMTab>() == null) {
                    RegisterTab(tab);
                }
            }

            if (!allowSwitchOff && !deactivateDefaultOnEnableBehaviour) ActivateCustomDefaultTab();
        }

        protected override void OnEnable()
        {
            base.OnEnable();

            if (!deactivateDefaultOnEnableBehaviour && !allowSwitchOff)
            {
                //activate custom or first tab
                ActivateCustomDefaultTab();
            }
        }

        public void ActivateFirstTab() {
            if (tabs.Count > 0) {
                GMTab firstTab = tabs.FirstOrDefault();

                if (firstTab != null)
                {
                    ActivateTab(firstTab);
                }
                else
                {
                    ActivateTab(tabs[0]);
                }
            }
        }

        public void ActivateCustomDefaultTab() {
            if (defaultTab != null) {
                if (tabs.Contains(defaultTab)) {
                    ActivateTab(defaultTab);
                } else {
                    ActivateFirstTab();
                }
            } else {
                ActivateFirstTab();
            }
        }

        public void ActivateLastTab() {
            if (tabs.Count > 0) {
                ActivateTab(tabs[tabs.Count - 1]);
            }
        }

        /// <summary>
        /// Activates the index of the tab by. Used by management view
        /// </summary>
        /// <param name="index">Index.</param>
        public void ActivateTabByIndex(int index) {
            GMTab tab = tabs[index];

            if (tab != null) {
                ActivateTab(tab);
            } else {
                ActivateFirstTab();
            }
        }

        public void ActivateTab(GMTab tab) {
            //Deactivate all tabs and activate new tab
            foreach (GMTab _tab in tabs) {
                if (_tab == tab) {
                    _tab.isOn = true;
                } else {
                    _tab.isOn = false;
                }

                _tab.UpdateColors();
            }
        }

        public void DeactivateTab(GMTab tab) {
            if (activeTab == tab) {
                tab.isOn = false;
                activeTab = null;

                OnValueChanged();
            }
        }

        /// <summary>
        /// Returns 0 if tab is not registered
        /// </summary>
        /// <param name="tab"></param>
        /// <returns></returns>
        public int GetIndexOfTab(GMTab tab) {
            if (tabs.Contains(tab)) {
                return tabs.IndexOf(tab);
            } else {
                return 0;
            }
        }

        /// <summary>
        /// Adds a new tab to the tabbar.
        /// </summary>
        /// <param name="tab">Tab.</param>
        public void RegisterTab(GMTab tab)
        {
            if (!tabs.Contains(tab)) tabs.Add(tab);
            tab.Initialize(this);
            RegisterToggle(tab);

            if (activateNewTabsOnAdd) {
                ActivateTab(tab);
            }
        }

        public void RemoveTab(GMTab tab, bool destroy = false)
        {
            //activate tab in front
            int index = tabs.IndexOf(tab);

            if (index > 0 && tabs.Count > 0) {
                ActivateTabByIndex(index - 1);
            }

            //Remove tab
            tabs.Remove(tab);
            UnregisterToggle(tab);
            if (destroy) Destroy(tab.gameObject);
        }

        public GMTab GetActiveTab()
        {
            return activeTab;
        }

        /// <summary>
        /// This method should only be used by a Tab to register itself as active.
        /// </summary>
        public void SetAsActiveTab(GMTab tab)
        {
            activeTab = tab;
            OnValueChanged();
        }

        void OnValueChanged() {
            foreach(Action listener in valueChangedListeners) {
                listener();
            }
        }

        public void AddValueChangedListener(Action callback) {
            if (!valueChangedListeners.Contains(callback)) {
                valueChangedListeners.Add(callback);
            }
        }

        public void RemoveValueChangedListener(Action callback) {
            if (valueChangedListeners.Contains(callback)) {
                valueChangedListeners.Remove(callback);
            }
        }

        public void SetOrderForTab(GMTab tab, int index) {
            tab.transform.SetSiblingIndex(index);
            tabs.Remove(tab);
            tabs.Insert(Mathf.Clamp(index, 0, tabs.Count - 2), tab);
        }
    }
}


text: SELECT setval('people_id_seq', 1000);


text:
#ifdef GAMEPAD_EXPORTS
#define GAMEPAD_API __declspec(dllexport)
#else
#define GAMEPAD_API __declspec(dllimport)
#endif

// external for DLL
extern "C" GAMEPAD_API void __stdcall gpInit(void);
extern "C" GAMEPAD_API void __stdcall gpDeInit(void);
extern "C" GAMEPAD_API void __stdcall gpUpdateAllControllers(void);
extern "C" GAMEPAD_API int  __stdcall gpMaxControllersCount(void);
extern "C" GAMEPAD_API void __stdcall gpSetUseDeadZone(bool status);
extern "C" GAMEPAD_API bool __stdcall gpIsUsingDeadZone(void);

extern "C" GAMEPAD_API bool __stdcall gpIsConnected(int index);

extern "C" GAMEPAD_API bool __stdcall gpIsButton_DPAD_UP(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_DPAD_DOWN(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_DPAD_LEFT(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_DPAD_RIGHT(int index);

extern "C" GAMEPAD_API bool __stdcall gpIsButton_START(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_BACK(int index);

extern "C" GAMEPAD_API bool __stdcall gpIsButton_A(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_B(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_X(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_Y(int index);

extern "C" GAMEPAD_API bool __stdcall gpIsButton_LEFT_THUMB(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_RIGHT_THUMB(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_LEFT_SHOULDER(int index);
extern "C" GAMEPAD_API bool __stdcall gpIsButton_RIGHT_SHOULDER(int index);

extern "C" GAMEPAD_API int __stdcall gpLeftTriggerValue(int index);
extern "C" GAMEPAD_API int __stdcall gpRightTriggerValue(int index);
extern "C" GAMEPAD_API int __stdcall gpLeftThumbXValue(int index);
extern "C" GAMEPAD_API int __stdcall gpLeftThumbYValue(int index);
extern "C" GAMEPAD_API int __stdcall gpRightThumbXValue(int index);
extern "C" GAMEPAD_API int __stdcall gpRightThumbYValue(int index);


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace WlToolsLib.Producer
{
    public class Producer
    {
    }
}


text:
package guru.nidi.loader.use.jsonschema;

import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import guru.nidi.loader.basic.ClassPathLoader;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import static org.junit.Assert.assertTrue;

public class JsonSchemaTest {
    private final ClassPathLoader loader = new ClassPathLoader("guru/nidi/loader");

    @Test
    public void jsonSchemaWithLoader() throws IOException, ProcessingException {
        final JsonSchemaFactory factory = LoaderUriDownloader.createJsonSchemaFactory(loader);
        assertTrue(validate(factory).isSuccess());
    }

    @Test(expected = ProcessingException.class)
    public void jsonSchemaWithoutLoader() throws IOException, ProcessingException {
        final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
        validate(factory);
    }

    private ProcessingReport validate(JsonSchemaFactory factory) throws ProcessingException, IOException {
        final JsonSchema jsonSchema = factory.getJsonSchema(JsonLoader.fromReader(new InputStreamReader(loader.fetchResource("ref.json", -1), "utf-8")));
        return jsonSchema.validate(JsonLoader.fromReader(new StringReader("\"blu\"")));
    }
}


text:
'use strict';

const   async = require('async'),
        fs = require('fs'),
        format = require('pg-format'),
        inherits = require('util').inherits,
        path = require('path'),
        {Pool} = require('pg').native,
        _ = require('lodash');

const Table = require('../classes/table');

const required_settings = ['user', 'password', 'host', 'database'];
const DEFAULT_MODELS_PATH = 'models';

/**
 * Create a new database instance
 *
 * @param settings
 * @constructor
 */
class DB {

    /**
     * Prepare the connection string for the PG connection, and create table objects
     * The connections are actually made with each query from node-postgres connections pool
     * to prevent single-connection bottleneck
     */
    connect(brest, settings, callback) {

        const missing_settings = _.difference(required_settings, _.keys(settings));
        if (missing_settings.length > 0) {
          return callback({error: 'Brest-pg missing settings', missing: missing_settings});
        }
        this.settings = settings;
        this.tables = {};
        this.pg = new Pool(this.settings);

        this.pg.on('error', err => {
          brest.emit('error', err);
        });

        const modelPath = path.join(path.dirname(require.main.filename), this.settings.models || DEFAULT_MODELS_PATH);

        async.waterfall([

            /**
             * @param {Function} next
             */
            next => {
                fs.stat(modelPath, err => {
                    if (err) {
                        console.log(`[WARNING] can't access models path ${modelPath}. Starting with no custom model support`);
                        this.customModels = false;
                    } else {
                        this.customModels = true;
                    }
                    next();
                });
            },

          /**
           * @param {Function} next(err, tables)
           */
          next => {
                this.query(`
                            SELECT table_name
                            FROM information_schema.tables
                            WHERE table_catalog = %L AND table_schema NOT IN ('pg_catalog', 'information_schema')
                            ORDER BY table_schema, table_name;`, settings.database, next);
            },

            /**
             * Initializing table models
             * @param {Array} tables
             * @param {Function} next
             */
            (tables, next) => {
                async.eachSeries(tables, (table, next_table) => {

                    const table_name = table.table_name;

                    async.waterfall([

                      table_next => {
                          if (this.customModels) {
                              const customFile = path.join(modelPath, `${table_name}.js`);
                              fs.stat(customFile, err => {
                                  if (err) { //No custom model
                                      table_next(null, Table);
                                  } else { //Custom model exists
                                      table_next(null, require(customFile));
                                  }
                              });
                          } else { //No custom models, use generic class
                              table_next(null, Table);
                          }
                      },

                      (TableModel, table_next) => {
                            this.tables[table_name] = new TableModel(this, table_name);
                            this.tables[table_name].init(table_next);
                        },

                      table_next => {
                          this.tables[table_name].updatePersistent(table_next);
                      }

                    ], next_table);

                }, (err) => next(err));
            }

        ], callback);
    }

    /**
     * Perform singular query with optional params array.
     * Use (http://www.postgresql.org/docs/9.3/static/functions-string.html#FUNCTIONS-STRING-FORMAT) to format
     * the query string
     * @param {String} query
     * @param {Array} [params]
     * @param {Function} callback
     */
    query(query, params, callback) {

        if (_.isFunction(params)) {
            callback = params;
            params = [];
        }

        this.pg.connect((err, client, release) => {
            if (err) {
                return callback(err);
            }

            const results = [];

            if (!_.isArray(params)) params = [params];
            const formatted_query = format(query, ...params);
            if (this.settings.log) console.log(`\n[QUERY]: \n${formatted_query}`);

            client.query(formatted_query, (err, res) => {
              release();
              callback(err, res.rows);
            });

            return {
              raw_query: query,
              formatted_query,
              params
            }
        });
    }

    /**
     * Query a single row
     * @param {String} query
     * @param {Array} params
     * @param {Function} callback
     */
    row (query, params, callback) {
        if (_.isFunction(params)) {
            callback = params;
            params = [];
        }

        return this.query(query, params, (err, res) => {
            if (err) return callback(err);
            callback(null, res[0]);
        });
    }

    /**
     * Inject filters into the formatted query
     * @param {String} query
     * @param {Object} filters
     * @param {Object} filterQueries
     * @returns {String}
     */
    injectFilters (query, filters, filterQueries) {
        const injections = {};
        const used = {};

        _.each(filters, (value, filter) => {

            if (filterQueries[filter]) {

                //Preprocess value if needed
                if (filterQueries[filter]._pre) {
                    value = filterQueries[filter]._pre(value);
                }

                _.each(filterQueries[filter], (injection, place) => {

                    if (place[0] !== "_"){ //We use underscored keys for handlers

                        if (!used[place]) used[place] = [];

                        if (used[place].indexOf(injection) === -1){
                            used[place].push(injection);

                            value = [value];
                            const formatted_injection = format(injection, ...value);
                            if (injections[place]) injections[place] += ` ${formatted_injection}`;
                            else injections[place] = formatted_injection;
                        }
                    }
                });

            }
        });

        _.each(injections, (injection, key) => {
            query = query.replace("{{"+key+"}}", " "+injection);
        });

        return query.replace(/({{.*?}})*/g,"");
    }

    /**
     * Return table object for the given table (if exists)
     * @param table
     * @returns {*}
     */
    table (table) {
        if (_.isEmpty(this.tables[table])) throw new Error(`Attempted to request non-existing table "${table}"`);
        return this.tables[table];
    }

}

module.exports = DB;


text:
"""
    Event Module - Controllers

    http://eden.sahanafoundation.org/wiki/BluePrintScenario
"""

module = request.controller
resourcename = request.function

if not settings.has_module(module):
    raise HTTP(404, body="Module disabled: %s" % module)

# -----------------------------------------------------------------------------
def index():
    """ Module's Home Page """

    return s3db.cms_index(module, alt_function="index_alt")

# -----------------------------------------------------------------------------
def index_alt():
    """
        Module homepage for non-Admin users when no CMS content found
    """

    # Just redirect to the list of Events
    s3_redirect_default(URL(f="event"))

# -----------------------------------------------------------------------------
def create():
    """ Redirect to event/create """
    redirect(URL(f="event", args="create"))

# -----------------------------------------------------------------------------
def event():
    """
        RESTful CRUD controller
    """

    # Pre-process
    def prep(r):
        if r.interactive:
            if r.component:
                if r.component.name == "req":
                    if r.method != "update" and r.method != "read":
                        # Hide fields which don't make sense in a Create form
                        # inc list_create (list_fields over-rides)
                        s3db.req_create_form_mods()

            elif r.method != "update" and r.method != "read":
                # Create or ListCreate
                r.table.closed.writable = r.table.closed.readable = False

            elif r.method == "update":
                # Can't change details after event activation
                table = r.table
                table.exercise.writable = False
                table.exercise.comment = None
                table.start_date.writable = False

        return True
    s3.prep = prep

    return s3_rest_controller(rheader = s3db.event_rheader)

# -----------------------------------------------------------------------------
def event_type():
    """
        RESTful CRUD controller
    """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def incident_type():
    """
        RESTful CRUD controller
    """

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def incident():
    """
        RESTful CRUD controller
    """

    # Pre-process
    def prep(r):
        if r.interactive or r.representation == "aadata":
            if r.component:
                if r.component.alias == "assign":
                    if not r.method:
                        r.method = "assign"
                    if r.method == "assign":
                        r.custom_action = s3db.hrm_AssignMethod(component="assign")
                if r.component_name == "config":
                    s3db.configure("gis_config",
                                   deletable = False,
                                   )
                    s3.crud.submit_button = T("Update")
                elif r.component_name in ("asset", "human_resource", "organisation", "site"):
                    s3.crud.submit_button = T("Assign")
                    s3.crud_labels["DELETE"] = T("Remove")
                #else:
                #    s3.crud.submit_button = T("Assign")
                #    s3.crud_labels["DELETE"] = T("Remove")

            elif r.method != "update" and r.method != "read":
                # Create or ListCreate
                r.table.closed.writable = r.table.closed.readable = False

            elif r.method == "update":
                # Can't change details after event activation
                table = r.table
                table.scenario_id.writable = False
                table.exercise.writable = False
                table.exercise.comment = None
                table.zero_hour.writable = False

        return True
    s3.prep = prep

    # Post-process
    def postp(r, output):

        if r.interactive:
            if r.component:
                if r.component.name == "human_resource":
                    #update_url = URL(c="hrm", f="human_resource", args=["[id]"])
                    #s3_action_buttons(r, update_url=update_url)
                    s3_action_buttons(r)
                    if "msg" in settings.modules:
                        s3base.S3CRUD.action_button(url = URL(f="compose",
                                                              vars = {"hrm_id": "[id]"}),
                                                    _class = "action-btn send",
                                                    label = str(T("Send Notification")))
        return output
    s3.postp = postp

    output = s3_rest_controller(rheader = s3db.event_rheader)
    return output

# -----------------------------------------------------------------------------
def incident_report():
    """
        RESTful CRUD controller
    """

    def prep(r):
        if r.http == "GET":
            if r.method in ("create", "create.popup"):
                # Lat/Lon from Feature?
                # @ToDo: S3PoIWidget() instead to pickup the passed Lat/Lon/WKT
                field = r.table.location_id
                lat = get_vars.get("lat", None)
                if lat is not None:
                    lon = get_vars.get("lon", None)
                    if lon is not None:
                        form_vars = Storage(lat = float(lat),
                                            lon = float(lon),
                                            )
                        form = Storage(vars=form_vars)
                        s3db.gis_location_onvalidation(form)
                        id = s3db.gis_location.insert(**form_vars)
                        field.default = id
                # WKT from Feature?
                wkt = get_vars.get("wkt", None)
                if wkt is not None:
                    form_vars = Storage(wkt = wkt,
                                        )
                    form = Storage(vars = form_vars)
                    s3db.gis_location_onvalidation(form)
                    id = s3db.gis_location.insert(**form_vars)
                    field.default = id

        return True
    s3.prep = prep

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def resource():
    """
        RESTful CRUD controller
    """

    def prep(r):
        if r.interactive:
            if r.method in ("create", "update"):
                table = r.table
                if r.method == "create":
                    # Enable Location field
                    field = table.location_id
                    field.readable = field.writable = True

                get_vars = r.get_vars
                # Context from a Profile page?"
                #location_id = get_vars.get("(location)", None)
                #if location_id:
                #    field = table.location_id
                #    field.default = location_id
                #    field.readable = field.writable = False
                incident_id = get_vars.get("~.(incident)", None)
                if incident_id:
                    field = table.incident_id
                    field.default = incident_id
                    field.readable = field.writable = False
        return True
    s3.prep = prep

    return s3_rest_controller()

# -----------------------------------------------------------------------------
def person():
    """ Person controller for AddPersonWidget """

    def prep(r):
        if r.representation != "s3json":
            # Do not serve other representations here
            return False
        else:
            current.xml.show_ids = True
        return True
    s3.prep = prep

    return s3_rest_controller("pr", "person")

# -----------------------------------------------------------------------------
def compose():
    """ Send message to people/teams """

    vars = request.vars

    if "hrm_id" in vars:
        id = vars.hrm_id
        fieldname = "hrm_id"
        table = s3db.pr_person
        htable = s3db.hrm_human_resource
        pe_id_query = (htable.id == id) & \
                      (htable.person_id == table.id)
        title = T("Send a message to this person")
    else:
        session.error = T("Record not found")
        redirect(URL(f="index"))

    pe = db(pe_id_query).select(table.pe_id,
                                limitby=(0, 1)).first()
    if not pe:
        session.error = T("Record not found")
        redirect(URL(f="index"))

    pe_id = pe.pe_id

    # Get the individual's communications options & preference
    table = s3db.pr_contact
    contact = db(table.pe_id == pe_id).select(table.contact_method,
                                              orderby="priority",
                                              limitby=(0, 1)).first()
    if contact:
        s3db.msg_outbox.contact_method.default = contact.contact_method
    else:
        session.error = T("No contact method found")
        redirect(URL(f="index"))

    # URL to redirect to after message sent
    url = URL(c=module,
              f="compose",
              vars={fieldname: id})

    # Create the form
    output = msg.compose(recipient = pe_id,
                         url = url)

    output["title"] = title
    response.view = "msg/compose.html"
    return output

# END =========================================================================


text:
package com.amazonaws.services.elasticmapreduce.model;

/**
 *

 * Describes the status of the job flow.
 *

 */
public class JobFlowExecutionStatusDetail {

    /**
     * The state of the job flow.
     *

     * Constraints:

     * Allowed Values: COMPLETED, FAILED, TERMINATED, RUNNING, SHUTTING_DOWN, STARTING, WAITING, BOOTSTRAPPING
     */
    private String state;

    /**
     * The creation date and time of the job flow.
     */
    private java.util.Date creationDateTime;

    /**
     * The start date and time of the job flow.
     */
    private java.util.Date startDateTime;

    /**
     * The date and time when the job flow was ready to start running
     * bootstrap actions.
     */
    private java.util.Date readyDateTime;

    /**
     * The completion date and time of the job flow.
     */
    private java.util.Date endDateTime;

    /**
     * Description of the job flow last changed state.
     *

     * Constraints:

     * Length: 0 - 10280

     * Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*

     */
    private String lastStateChangeReason;

    /**
     * Default constructor for a new JobFlowExecutionStatusDetail object.  Callers should use the
     * setter or fluent setter (with...) methods to initialize this object after creating it.
     */
    public JobFlowExecutionStatusDetail() {}

    /**
     * Constructs a new JobFlowExecutionStatusDetail object.
     * Callers should use the setter or fluent setter (with...) methods to
     * initialize any additional object members.
     *
     * @param state The state of the job flow.
     * @param creationDateTime The creation date and time of the job flow.
     */
    public JobFlowExecutionStatusDetail(String state, java.util.Date creationDateTime) {
        this.state = state;
        this.creationDateTime = creationDateTime;
    }

    /**
     * The state of the job flow.
     *

     * Constraints:

     * Allowed Values: COMPLETED, FAILED, TERMINATED, RUNNING, SHUTTING_DOWN, STARTING, WAITING, BOOTSTRAPPING
     *
     * @return The state of the job flow.
     *
     * @see JobFlowExecutionState
     */
    public String getState() {
        return state;
    }

    /**
     * The state of the job flow.
     *

     * Constraints:

     * Allowed Values: COMPLETED, FAILED, TERMINATED, RUNNING, SHUTTING_DOWN, STARTING, WAITING, BOOTSTRAPPING
     *
     * @param state The state of the job flow.
     *
     * @see JobFlowExecutionState
     */
    public void setState(String state) {
        this.state = state;
    }

    /**
     * The state of the job flow.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Allowed Values: COMPLETED, FAILED, TERMINATED, RUNNING, SHUTTING_DOWN, STARTING, WAITING, BOOTSTRAPPING
     *
     * @param state The state of the job flow.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     *
     * @see JobFlowExecutionState
     */
    public JobFlowExecutionStatusDetail withState(String state) {
        this.state = state;
        return this;
    }

    /**
     * The creation date and time of the job flow.
     *
     * @return The creation date and time of the job flow.
     */
    public java.util.Date getCreationDateTime() {
        return creationDateTime;
    }

    /**
     * The creation date and time of the job flow.
     *
     * @param creationDateTime The creation date and time of the job flow.
     */
    public void setCreationDateTime(java.util.Date creationDateTime) {
        this.creationDateTime = creationDateTime;
    }

    /**
     * The creation date and time of the job flow.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param creationDateTime The creation date and time of the job flow.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public JobFlowExecutionStatusDetail withCreationDateTime(java.util.Date creationDateTime) {
        this.creationDateTime = creationDateTime;
        return this;
    }

    /**
     * The start date and time of the job flow.
     *
     * @return The start date and time of the job flow.
     */
    public java.util.Date getStartDateTime() {
        return startDateTime;
    }

    /**
     * The start date and time of the job flow.
     *
     * @param startDateTime The start date and time of the job flow.
     */
    public void setStartDateTime(java.util.Date startDateTime) {
        this.startDateTime = startDateTime;
    }

    /**
     * The start date and time of the job flow.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param startDateTime The start date and time of the job flow.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public JobFlowExecutionStatusDetail withStartDateTime(java.util.Date startDateTime) {
        this.startDateTime = startDateTime;
        return this;
    }

    /**
     * The date and time when the job flow was ready to start running
     * bootstrap actions.
     *
     * @return The date and time when the job flow was ready to start running
     *         bootstrap actions.
     */
    public java.util.Date getReadyDateTime() {
        return readyDateTime;
    }

    /**
     * The date and time when the job flow was ready to start running
     * bootstrap actions.
     *
     * @param readyDateTime The date and time when the job flow was ready to start running
     *         bootstrap actions.
     */
    public void setReadyDateTime(java.util.Date readyDateTime) {
        this.readyDateTime = readyDateTime;
    }

    /**
     * The date and time when the job flow was ready to start running
     * bootstrap actions.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param readyDateTime The date and time when the job flow was ready to start running
     *         bootstrap actions.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public JobFlowExecutionStatusDetail withReadyDateTime(java.util.Date readyDateTime) {
        this.readyDateTime = readyDateTime;
        return this;
    }

    /**
     * The completion date and time of the job flow.
     *
     * @return The completion date and time of the job flow.
     */
    public java.util.Date getEndDateTime() {
        return endDateTime;
    }

    /**
     * The completion date and time of the job flow.
     *
     * @param endDateTime The completion date and time of the job flow.
     */
    public void setEndDateTime(java.util.Date endDateTime) {
        this.endDateTime = endDateTime;
    }

    /**
     * The completion date and time of the job flow.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param endDateTime The completion date and time of the job flow.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public JobFlowExecutionStatusDetail withEndDateTime(java.util.Date endDateTime) {
        this.endDateTime = endDateTime;
        return this;
    }

    /**
     * Description of the job flow last changed state.
     *

     * Constraints:

     * Length: 0 - 10280

     * Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*

     *
     * @return Description of the job flow last changed state.
     */
    public String getLastStateChangeReason() {
        return lastStateChangeReason;
    }

    /**
     * Description of the job flow last changed state.
     *

     * Constraints:

     * Length: 0 - 10280

     * Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*

     *
     * @param lastStateChangeReason Description of the job flow last changed state.
     */
    public void setLastStateChangeReason(String lastStateChangeReason) {
        this.lastStateChangeReason = lastStateChangeReason;
    }

    /**
     * Description of the job flow last changed state.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *

     * Constraints:

     * Length: 0 - 10280

     * Pattern: [\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*

     *
     * @param lastStateChangeReason Description of the job flow last changed state.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public JobFlowExecutionStatusDetail withLastStateChangeReason(String lastStateChangeReason) {
        this.lastStateChangeReason = lastStateChangeReason;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("State: " + state + ", ");
        sb.append("CreationDateTime: " + creationDateTime + ", ");
        sb.append("StartDateTime: " + startDateTime + ", ");
        sb.append("ReadyDateTime: " + readyDateTime + ", ");
        sb.append("EndDateTime: " + endDateTime + ", ");
        sb.append("LastStateChangeReason: " + lastStateChangeReason + ", ");
        sb.append("}");
        return sb.toString();
    }

}


text:
name: Problem with the module
about: If you have a problem, bug, or enhancement with the module.
---
<!--
    Your feedback and support is greatly appreciated, thanks for contributing!

    Please provide information regarding your issue under each header below.
    Write N/A under any headers that do not apply to your issue, or if the
    information is not available.

    NOTE! Sensitive information should be obfuscated.

    PLEASE KEEP THE HEADERS.

    You may remove this comment block, and the other comment blocks,
    but please keep the headers.
-->
#### Details of the scenario you tried and the problem that is occurring

#### Steps to reproduce the problem

#### Expected behavior

#### Current behavior

#### Suggested solution to the issue

#### The operating system the target node is running

#### Version and build of PowerShell the target node is running
<!--
    To help with this information, please run this command:
    $PSVersionTable
-->

#### Version of the module that was used
<!--
    To help with this information, please run this command:
    Get-Module -Name 'DscResource.DocGenerator' -ListAvailable | ft Name,Version,Path
-->


text:
package com.example.simon.if26.chat.models;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Locale;

public class Contact {

    public static final int MODEL_ID = 0;
    public static final String KEY_ID = "id";
    public static final String KEY_CONTACT = "contact";
    public static final String KEY_CONTACTS = "contacts";
    public static final String KEY_LAST_NAME = "last_name";
    public static final String KEY_FIRST_NAME = "first_name";
    public static final String KEY_EMAIL = "email";
    public static final String KEY_MESSAGE = "message";

    private int _id;
    private String _lastname;
    private String _firstname;
    private String _email;
    private ArrayList<Message> _messages;

    public Contact() {
        this._messages = new ArrayList<Message>();
    }

    public Contact(JSONObject json) {
        try {
            this.setId(json.getInt(KEY_ID));
            this.setLastname(json.getJSONObject(KEY_CONTACT).getString(KEY_LAST_NAME));
            this.setFirstname(json.getJSONObject(KEY_CONTACT).getString(KEY_FIRST_NAME));
            this.setEmail(json.getJSONObject(KEY_CONTACT).getString(KEY_EMAIL));
            this.setLastMessage(json.getJSONObject(KEY_MESSAGE));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public Contact(int id, String lastname, String firstname, String email,
                   ArrayList<Message> messages) {
        super();
        this._id = id;
        this._lastname = lastname;
        this._firstname = firstname;
        this._email = email;
        this._messages = messages;
    }

    public static ArrayList<Contact> fromJSON(JSONArray arr) {
        ArrayList<Contact> contacts = new ArrayList<Contact>();

        for (int i = 0; i < arr.length(); i++) {
            try {
                contacts.add(new Contact(arr.getJSONObject(i)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        return contacts;
    }

    public int getId() {
        return _id;
    }

    public Contact setId(int id) {
        this._id = id;
        return this;
    }

    public String getLastname() {
        return _lastname;
    }

    public Contact setLastname(String lastname) {
        this._lastname = lastname;
        return this;
    }

    public String getFirstname() {
        return _firstname;
    }

    public Contact setFirstname(String firstname) {
        this._firstname = firstname;
        return this;
    }

    public String getEmail() {
        return _email;
    }

    public Contact setEmail(String email) {
        this._email = email;
        return this;
    }

    public ArrayList<Message> getMessages() {
        if (this._messages == null) {
            this._messages = new ArrayList<Message>();
        }
        return _messages;
    }

    public Contact setMessages(ArrayList<Message> messages) {
        this._messages = messages;
        return this;
    }

    public Contact setLastMessage(JSONObject json) {
        Message lastMessage = null;

        try {
            lastMessage = new Message(
                    json.getString("message"),
                    json.getString("date"),
                    this,
                    json.getBoolean("sent"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        this.getMessages().add(this.getMessages().size() == 0 ? 0 : this.getMessages().size() - 1, lastMessage);

        return this;
    }

    @Override
    public String toString() {
        return this._id + " " +
                this._firstname + " " +
                this._lastname + " " +
                this._email + " " +
                this._messages.toString();
    }

    public CharSequence getFullname() {
        return this.getFirstname() + " " + this.getLastname().toUpperCase(Locale.FRANCE);
    }

    public Message getLastmessage() {
        return this.getMessages().get(this.getMessages().size() - 1);
    }

}


text:
package com.snowplowanalytics.snowplow.storage.kinesis.redshift.writer

import java.io.{BufferedOutputStream, File, FileOutputStream, PrintWriter}
import java.sql.{SQLException, Connection}
import java.util.Properties
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.ReentrantLock
import java.util.zip.GZIPOutputStream
import javax.sql.DataSource

import com.amazonaws.auth.AWSCredentialsProvider
import com.amazonaws.regions.{RegionUtils, Region, Regions}
import com.amazonaws.services.cloudwatch.AmazonCloudWatchClient
import com.amazonaws.services.cloudwatch.model.{StandardUnit, MetricDatum, PutMetricDataRequest}
import com.amazonaws.services.kinesis.connectors.KinesisConnectorConfiguration
import com.amazonaws.services.s3.AmazonS3Client
import com.amazonaws.services.s3.model.ObjectMetadata
import com.amazonaws.util.StringInputStream
import com.digdeep.util.concurrent.ThreadOnce
import com.snowplowanalytics.snowplow.storage.kinesis.redshift.TableWriter
import org.apache.commons.logging.LogFactory
import scaldi.Injector

import scala.collection.mutable
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.language.implicitConversions
import scala.language.postfixOps
import scala.util.Try
import scaldi.{Injector, Injectable}
import Injectable._

abstract class BaseCopyTableWriter(dataSource:DataSource, table: String)(implicit injector: Injector) extends CopyTableWriter {
  private val log = LogFactory.getLog(classOf[BaseCopyTableWriter])
  lazy val s3Manifest: String = createManifest
  lazy val bufferFileInterm: File = File.createTempFile(table + "_interm", ".tsv.gz")
  lazy val bufferFile: File = File.createTempFile(table, ".tsv.gz")
  private val props = inject[Properties]
  var batchCount: Int = 0
  var pending: Future[Unit] = null
  val updateInProgress = new AtomicBoolean()
  val threadOnce = new ThreadOnce()

  var bufferFileStream: PrintWriter = null
  def write(values: Array[String]): Unit = {
    write(values.map(f => if (f == null) "" else f).mkString("\t"))
  }
  def write(value: String): Unit = {
    // 1. Write record to a file (create if necessary)
    // 2. Check if flush is necessary
    // 2.1 If yes, execute Redshift flush, truncate the file
    val file = getBufferFile
    file.println(value)
    batchCount += 1
    if (isFlushRequired) {
      flush()
    }
  }
  def requiresJsonParsing: Boolean = false

  def beforeFlushToRedshift():Int = {
    if (bufferFileStream != null) {
      bufferFileStream.flush()
      bufferFileStream.close()
      bufferFileStream = null
    }
    if (bufferFile != null && bufferFile.exists()) bufferFile.delete()
    if (bufferFileInterm != null && bufferFileInterm.exists() && bufferFile != null) bufferFileInterm.renameTo(bufferFile)
    val res = batchCount
    batchCount = 0
    if (bufferFile.exists()) {
      res
    } else {
      0
    }
  }

  def isUpdateInProgress(takeLock: Boolean = false): Boolean = !updateInProgress.compareAndSet(false, takeLock)

  def flush(): Unit = {
    if (isUpdateInProgress(true)) { // Note: this sets the flag to true essentially taking a lock
      threadOnce.callOnce(log.warn(s"Ignoring flush on $table - there is a flush in progress"))
      return
    }
    threadOnce.reset()
    log.info("Flushing events")
    val flushCount = beforeFlushToRedshift()
    val start = System.currentTimeMillis()
    pending = Future {
      var retryCount = 0
      var connection: Connection = null
      while (retryCount < 5) {
        try {
          connection = TableWriter.getConnection(dataSource)
          onFlushToRedshift(flushCount, start, Some(connection))
          retryCount = 5
        }
        catch {
          case se: SQLException =>
            log.error(s"SQLException flushing $table - retry $retryCount", se)
            retryCount += 1
            Thread.sleep(Math.round(1000 * Math.pow(4, retryCount)))
          case e:Throwable =>
            log.error(s"Non-database exception flushing $table", e)
            retryCount = 5 // break
        } finally {
          try {
            if (connection != null) connection.close()
          } catch {
            case t: Throwable =>
              log.error("Exception closing connection", t)
          }
        }
      }
    }
    pending onComplete {
      case _ =>
        pending = null
        updateInProgress.set(false)
        updateInProgress.synchronized {
          updateInProgress.notifyAll()
        }
    }
  }

  def onFlushToRedshift(flushCount: Int, start:Long, con: Option[Connection])

  def isFlushRequired: Boolean = false

  def getBufferFile: PrintWriter = {
    if (bufferFileStream == null) {
      bufferFileStream = new PrintWriter(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(bufferFileInterm, false))))
    }
    bufferFileStream
  }
  def close() = {
    waitForPending()

    log.info(s"Closing writer for $table")
    if (bufferFileStream != null) {
      waitForPending()
      flush()
    }
    waitForPending()

    if (bufferFileStream != null) {
      bufferFileStream.close()
    }
    if (!props.containsKey("dontDeleteTempFiles")) {
      if (bufferFile != null && bufferFile.exists()) {
        bufferFile.delete()
      }
      if (bufferFileInterm != null && bufferFileInterm.exists()) {
        bufferFileInterm.delete()
      }
    }
  }

  protected def waitForPending(msg: Option[String] = None): Unit = {
    updateInProgress.synchronized {
      while (isUpdateInProgress()) {
        log.info(msg.getOrElse("Waiting for pending flush to complete"))
        updateInProgress.wait(60000)
      }
    }
  }

  def createManifest: String = {
    val s3client = new AmazonS3Client(inject[AWSCredentialsProvider])
    s3client.setRegion(RegionUtils.getRegion(inject[Properties].getProperty(KinesisConnectorConfiguration.PROP_REGION_NAME)))
    val endPoint = props.getProperty("sshEndpoint")
    val username = props.getProperty("sshUsername")
    val s3Folder = props.getProperty("sshS3Bucket")
    val manifest = "{ \n\n    \"entries\": [ \n\t    {\"endpoint\":\"" + endPoint + "\", \n           " +
      "\"command\": \"cat " + bufferFile.getAbsolutePath + "\",\n           \"mandatory\":true, \n           \"username\": \"" + username + "\"} \n     ] \n}"
    val stream: StringInputStream = new StringInputStream(manifest)
    val metadata: ObjectMetadata = new ObjectMetadata()
    metadata.setContentLength(stream.available())
    s3client.putObject(s3Folder, table, stream, metadata)
    s"s3://$s3Folder/$table"
  }

}


text:
#ifndef SYMBOL_H
#define SYMBOL_H

#include "name_storage.h"
#include "growable_vector.h"
#include "sparse_array.h"
#include "format_flags.h"
#include "op_types.h"

#include <bfd.h>
#include <stdint.h>

#include <list>

class extra_images;

/// for storing sample counts
typedef sparse_array<u32, count_type> count_array_t;

/// A simple container for a fileno:linenr location.
struct file_location {
	file_location() : linenr(0) {}
	/// empty if not valid.
	debug_name_id filename;
	/// 0 means invalid or code is generated internally by the compiler
	unsigned int linenr;

	bool operator<(file_location const & rhs) const {
		// Note we sort on filename id not on string
		return filename < rhs.filename ||
		  (filename == rhs.filename && linenr < rhs.linenr);
	}
};

/// associate vma address with a file location and a samples count
struct sample_entry {
	sample_entry() : vma(0) {}
	/// From where file location comes the samples
	file_location file_loc;
	/// From where virtual memory address comes the samples
	bfd_vma vma;
	/// the samples count
	count_array_t counts;
};

/// associate a symbol with a file location, samples count and vma address
class symbol_entry {
public:
	symbol_entry() : size(0) {}
	virtual ~symbol_entry() {}

	/// which image this symbol belongs to
	image_name_id image_name;
	/// owning application name: identical to image name if profiling
	/// session did not separate samples for shared libs or if image_name
	/// is not a shared lib
	image_name_id app_name;
	// index into the op_bfd symbol table
	size_t sym_index;
	/// file location, vma and cumulated samples count for this symbol
	sample_entry sample;
	/// name of symbol
	symbol_name_id name;
	/// symbol size as calculated by op_bfd, start of symbol is sample.vma
	size_t size;

	/**
	 * @param fl  input hint
	 *
	 * combine fl with the calculated hint. It's theoretically possible
	 * that we get a symbol where its samples pass the border line, but
	 * the start is below it, but the the hint is only used for formatting
	 */
	column_flags output_hint(column_flags fl) const;
	uint64_t spu_offset;
	image_name_id embedding_filename;
};

/// a collection of sorted symbols
typedef std::vector<symbol_entry const *> symbol_collection;

/**
 * The public data for call-graph symbols. Each caller/callee has
 * the sample counts replaced with the relevant arc counts, whilst
 * the cg_symbol retains its self count.
 */
class cg_symbol : public symbol_entry {
public:
	cg_symbol(symbol_entry const & sym) : symbol_entry(sym) {}

	typedef std::vector<symbol_entry> children;

	/// all callers of this symbol
	children callers;
	/// total count of callers
	count_array_t total_caller_count;

	/// all symbols called by this symbol
	children callees;
	/// total count of callees
	count_array_t total_callee_count;
};

/// a collection of sorted callgraph symbol objects
typedef std::list<cg_symbol> cg_collection_objs;

/// for storing diff %ages
typedef growable_vector<double> diff_array_t;

/**
 * Data for a diffed symbol.
 */
struct diff_symbol : public symbol_entry  {
	diff_symbol(symbol_entry const & sym) : symbol_entry(sym) {}

	/// diff %age values for each profile class
	diff_array_t diffs;
};

/// a collection of diffed symbols
typedef std::vector<diff_symbol> diff_collection;

bool has_sample_counts(count_array_t const & counts, size_t lo, size_t hi);
std::string const & get_image_name(image_name_id id,
				   image_name_storage::image_name_type type,
				   extra_images const & extra);

#endif /* !SYMBOL_H */


text:
#include <aws/forecast/model/CreateDatasetImportJobRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::ForecastService::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

CreateDatasetImportJobRequest::CreateDatasetImportJobRequest() :
    m_datasetImportJobNameHasBeenSet(false),
    m_datasetArnHasBeenSet(false),
    m_dataSourceHasBeenSet(false),
    m_timestampFormatHasBeenSet(false),
    m_timeZoneHasBeenSet(false),
    m_useGeolocationForTimeZone(false),
    m_useGeolocationForTimeZoneHasBeenSet(false),
    m_geolocationFormatHasBeenSet(false),
    m_tagsHasBeenSet(false)
{
}

Aws::String CreateDatasetImportJobRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_datasetImportJobNameHasBeenSet)
  {
   payload.WithString("DatasetImportJobName", m_datasetImportJobName);

  }

  if(m_datasetArnHasBeenSet)
  {
   payload.WithString("DatasetArn", m_datasetArn);

  }

  if(m_dataSourceHasBeenSet)
  {
   payload.WithObject("DataSource", m_dataSource.Jsonize());

  }

  if(m_timestampFormatHasBeenSet)
  {
   payload.WithString("TimestampFormat", m_timestampFormat);

  }

  if(m_timeZoneHasBeenSet)
  {
   payload.WithString("TimeZone", m_timeZone);

  }

  if(m_useGeolocationForTimeZoneHasBeenSet)
  {
   payload.WithBool("UseGeolocationForTimeZone", m_useGeolocationForTimeZone);

  }

  if(m_geolocationFormatHasBeenSet)
  {
   payload.WithString("GeolocationFormat", m_geolocationFormat);

  }

  if(m_tagsHasBeenSet)
  {
   Array<JsonValue> tagsJsonList(m_tags.size());
   for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex)
   {
     tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize());
   }
   payload.WithArray("Tags", std::move(tagsJsonList));

  }

  return payload.View().WriteReadable();
}

Aws::Http::HeaderValueCollection CreateDatasetImportJobRequest::GetRequestSpecificHeaders() const
{
  Aws::Http::HeaderValueCollection headers;
  headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "AmazonForecast.CreateDatasetImportJob"));
  return headers;

}


text:
/* pbkdf2-hmac-sha1.c
 *
 * PKCS #5 PBKDF2 used with HMAC-SHA1, see RFC 2898.
 */

/* nettle, low-level cryptographics library
 *
 * Copyright (C) 2012 Simon Josefsson
 *
 * The nettle library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at your
 * option) any later version.
 *
 * The nettle library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
 * License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with the nettle library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02111-1301, USA.
 */

#if HAVE_CONFIG_H
# include "config.h"
#endif

#include "pbkdf2.h"

#include "hmac.h"

void
pbkdf2_hmac_sha1 (unsigned key_length, const uint8_t *key,
		  unsigned iterations,
		  unsigned salt_length, const uint8_t *salt,
		  unsigned length, uint8_t *dst)
{
  struct hmac_sha1_ctx sha1ctx;

  hmac_sha1_set_key (&sha1ctx, key_length, key);
  PBKDF2 (&sha1ctx, hmac_sha1_update, hmac_sha1_digest,
	  SHA1_DIGEST_SIZE, iterations, salt_length, salt, length, dst);
}


text:
#include <dbobjects/factory/TableFactoryTest.h>

#include <dbobjects/common/Database.h>
#include <dbobjects/factory/Table.h>
#include <dbobjects/psql/Table.h>

void
TableFactoryTest::initTestCase()
{

}

void
TableFactoryTest::cleanupTestCase()
{

}

void
TableFactoryTest::createTableTest()
{
    using namespace DbObjects;

    QString tableName("artists");
    QString schemaName("vtunes");

    Common::Database *dbInst = Common::Database::instance();
    QVERIFY(0 != dbInst);

//    Common::DbSchema *schema = dbInst->findSchema(schemaName);
//    QVERIFY(0 != schema);

    dbInst->setSqlDriver("QPSQL");
    QVERIFY(0 != dynamic_cast<Psql::Table*>(Factory::Table::createTable(tableName, schemaName)));

    // \todo update this check as for psql when more RDBMS are supported
    dbInst->setSqlDriver("QMYSQL");
    QVERIFY(0 == Factory::Table::createTable(tableName, schemaName));

    dbInst->setSqlDriver("QIODBC");
    QVERIFY(0 == Factory::Table::createTable(tableName, schemaName));

    dbInst->setSqlDriver("QSQLITE");
    QVERIFY(0 == Factory::Table::createTable(tableName, schemaName));

    dbInst->setSqlDriver("NODRV");
    QVERIFY(0 == Factory::Table::createTable(tableName, schemaName));
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
    <jdbc-connection-pool name="company_pool" allow-non-component-callers="false" associate-with-thread="false"
                          connection-creation-retry-attempts="0"
                          connection-creation-retry-interval-in-seconds="10"
                          connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0"
                          connection-validation-method="auto-commit" datasource-classname="org.apache.derby.jdbc.ClientDataSource"
                          fail-all-connections="false" idle-timeout-in-seconds="300" is-connection-validation-required="false"
                          is-isolation-level-guaranteed="true" lazy-connection-association="false"
                          lazy-connection-enlistment="false" match-connections="false"
                          max-connection-usage-count="0" max-pool-size="32"
                          max-wait-time-in-millis="60000" non-transactional-connections="false"
                          pool-resize-quantity="2" res-type="javax.sql.DataSource"
                          statement-timeout-in-seconds="-1" steady-pool-size="8"
                          validate-atmost-once-period-in-seconds="0" wrap-jdbc-objects="false">
        <property name="serverName" value="localhost"/>
        <property name="portNumber" value="1527"/>
        <property name="databaseName" value="company"/>
        <property name="User" value="APP"/>
        <property name="Password" value="APP"/>
        <property name="driverClass" value="org.apache.derby.jdbc.ClientDriver"/>
        <property name="createDatabase" value="create"/>
    </jdbc-connection-pool>
    <jdbc-resource enabled="true" jndi-name="java:app/jdbc/company" object-type="user" pool-name="company_pool"/>
</resources>


text:
import {CSS} from '#build/bento-base-carousel-1.0.css';

import {BaseElement as BentoCarousel} from '#bento/components/bento-base-carousel/1.0/base-element';
import {adoptStyles} from '#bento/util/unit-helpers';

import {subscribe, unsubscribe} from '#core/context';
import {htmlFor} from '#core/dom/static-template';

import {defineBentoElement} from '#preact/bento-ce';
import {CanRender} from '#preact/contextprops';

describes.realWin('bento-base-carousel:1.0', {amp: false}, (env) => {
  let win;
  let html;
  let element;

  function readContextProp(element, prop) {
    return new Promise((resolve) => {
      const handler = (value) => {
        resolve(value);
        unsubscribe(element, [prop], handler);
      };
      subscribe(element, [prop], handler);
    });
  }

  beforeEach(async () => {
    win = env.win;
    html = htmlFor(win.document);
    element = html`
      <bento-base-carousel visible-count="1">

      </bento-base-carousel>
    `;
    defineBentoElement('bento-base-carousel', BentoCarousel, win);
    adoptStyles(win, CSS);
    win.document.body.appendChild(element);
    await element.getApi();
  });

  it('should render slides', async () => {
    const slides = element.children;

    expect(slides.length).to.equal(5);
    expect(slides[0].getAttribute('src')).to.have.equal(
      '/examples/bind/shirts/blue.jpg'
    );
    expect(slides[1].getAttribute('src')).to.have.equal(
      '/examples/bind/shirts/brown.jpg'
    );
    expect(slides[2].getAttribute('src')).to.have.equal(
      '/examples/bind/shirts/navy.jpg'
    );
    expect(slides[3].getAttribute('src')).to.have.equal(
      '/examples/bind/shirts/wine.jpg'
    );
    expect(slides[4].getAttribute('src')).to.have.equal(
      '/examples/bind/shirts/dark-green.jpg'
    );

    expect(await readContextProp(slides[0], CanRender)).to.be.true;
    expect(await readContextProp(slides[1], CanRender)).to.be.false;
    expect(await readContextProp(slides[2], CanRender)).to.be.false;
    expect(await readContextProp(slides[3], CanRender)).to.be.false;
    expect(await readContextProp(slides[4], CanRender)).to.be.false;
  });
});


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe "RspecCheckAuth" do

  it "should require a checking block" do
    lambda { CheckAuth.checking_block }.should raise_error("CheckAuth#checking_block needs defining")
  end

  it "should call the checking block when one is set" do
    CheckAuth.checking_block do
      raise "I'm in the block!"
    end

    lambda { CheckAuth.checking_block }.should raise_error("I'm in the block!")
  end

  it "should add an action with default formats" do
    expect_request_for(:route, :html)
    expect_request_for(:route, :xml)

    expect_output_for(:html, [:"route_html"])
    expect_output_for(:xml, [:"route_xml"])

    CheckAuth.for do |c|
      c.add :route
    end
  end

  it "should add an action with custom params" do
    expect_request_for :route, :html, :some => :fields
    expect_request_for :route, :xml, :some => :fields

    expect_output_for :html, [:route_html]
    expect_output_for :xml, [:route_xml]

    CheckAuth.for do |c|
      c.add :route, :some => :fields
    end
  end

  it "should add an action with custom formats" do
    expect_request_for :route, :html
    expect_request_for :route, :json
    expect_request_for :route, :fart

    expect_output_for :html, [:route_html]
    expect_output_for :json, [:route_json]
    expect_output_for :fart, [:route_fart]

    CheckAuth.for do |c|
      c.add :route, :format => [:html, :json, :fart]
    end
  end

  it "should add an action with custom params and custom formats" do
    expect_request_for :route, :html, :some => :fields
    expect_request_for :route, :json, :some => :fields
    expect_request_for :route, :fart, :some => :fields

    expect_output_for :html, [:route_html]
    expect_output_for :json, [:route_json]
    expect_output_for :fart, [:route_fart]

    CheckAuth.for do |c|
      c.add :route, :format => [:html, :json, :fart], :some => :fields
    end
  end

  it "should add standard resource routes in one line" do
    expect_requests_for_resource_actions

    expect_output_for(:html, [:index_html, :new_html, :create_html, :edit_html, :show_html, :update_html, :destroy_html])
    expect_output_for(:xml, [:index_xml, :new_xml, :create_xml, :edit_xml, :show_xml, :update_xml, :destroy_xml])

    CheckAuth.for do |c|
      c.resource_actions
    end
  end

  it "should ignore resources it's been told to" do
    expect_request_for :index, :html
    expect_request_for :index, :xml

    expect_output_for(:html, [:index_html])
    expect_output_for(:xml, [:index_xml])

    CheckAuth.for do |c|
      c.resource_actions :except => [:new, :show, :edit, :update, :create, :destroy]
    end
  end

  it "should only expect resources it's been told to" do
    expect_request_for :index, :html
    expect_request_for :index, :xml

    expect_output_for(:html, [:index_html])
    expect_output_for(:xml, [:index_xml])

    CheckAuth.for do |c|
      c.resource_actions :only => :index
    end
  end

  it "should add standard resource routes with extra params" do
    expect_requests_for_resource_actions :some => :fields

    expect_output_for(:html, [:index_html, :new_html, :create_html, :edit_html, :show_html, :update_html, :destroy_html])
    expect_output_for(:xml, [:index_xml, :new_xml, :create_xml, :edit_xml, :show_xml, :update_xml, :destroy_xml])

    CheckAuth.for do |c|
      c.resource_actions :some => :fields
    end
  end

  it "should add standard resource routes with extra formats" do
    expect_requests_for_resource_actions({}, [:html, :json, :fart])

    expect_output_for(:html, [:index_html, :new_html, :create_html, :edit_html, :show_html, :update_html, :destroy_html])
    expect_output_for(:json, [:index_json, :new_json, :create_json, :edit_json, :show_json, :update_json, :destroy_json])
    expect_output_for(:fart, [:index_fart, :new_fart, :create_fart, :edit_fart, :show_fart, :update_fart, :destroy_fart])

    CheckAuth.for do |c|
      c.resource_actions :format => [:html, :json, :fart]
    end
  end

  it "should add standard resource routes with extra params and extra formats" do
    expect_requests_for_resource_actions({:some => :fields}, [:html, :json, :fart])

    expect_output_for(:html, [:index_html, :new_html, :create_html, :edit_html, :show_html, :update_html, :destroy_html])
    expect_output_for(:json, [:index_json, :new_json, :create_json, :edit_json, :show_json, :update_json, :destroy_json])
    expect_output_for(:fart, [:index_fart, :new_fart, :create_fart, :edit_fart, :show_fart, :update_fart, :destroy_fart])

    CheckAuth.for do |c|
      c.resource_actions :format => [:html, :json, :fart], :some => :fields
    end
  end

  private

  def expect_requests_for_resource_actions options={}, formats=[:html, :xml]
    formats.each do |f|
      expect_request_for(:index, f, options)
      expect_request_for(:new, f, options)
      expect_request_for(:create, f, options)
      expect_request_for(:edit, f, options.merge(:id => "some_id"))
      expect_request_for(:show, f, options.merge(:id => "some_id"))
      expect_request_for(:update, f, options.merge(:id => "some_id"))
      expect_request_for(:destroy, f, options.merge(:id => "some_id"))
    end
  end

  def expect_request_for action, format, options={}
    CheckAuth::Request.should_receive(:new).with(action, format, options).and_return(:"#{action}_#{format}")
  end

  def expect_output_for format, actions=[]
    CheckAuth::Output.should_receive(:generate_steps_for).with(format, actions)
  end
end