text:
require 'spec_helper'
require './spec/api_docs/image_hack'

resource "Users" do
  let(:user) { users(:admin) }
  let(:other_user) { users(:the_collaborator) }

  before do
    log_in user
  end

  get "/users" do
    pagination

    example_request "Get a list of users" do
      status.should == 200
    end
  end

  post "/users" do
    parameter :username, "Username"
    parameter :password, "Password - required unless LDAP authentication is enabled on the server"
    parameter :first_name, "First Name"
    parameter :last_name, "Last Name"
    parameter :email, "E-mail"
    parameter :title, "Title"
    parameter :dept, "Department"
    parameter :notes, "Notes"
    parameter :admin, "Make the user an admin. (Only allowed if the authenticated user is an admin)"

    required_parameters :username, :first_name, :last_name, :email

    let(:username) { "cookiemonster" }
    let(:first_name) { "Cookie" }
    let(:last_name) { "Monster" }
    let(:email) { "cookie@monster.com" }
    let(:password) { "secret" }
    let(:title) { "Chief Cookie Officer" }
    let(:dept) { "jar" }
    let(:notes) { "great" }

    example_request "Create a user" do
      status.should == 201
    end
  end

  get "/users/:id" do
    parameter :id, "Id of a user"

    required_parameters :id

    let(:id) { other_user.id }

    example_request "Get a user" do
      status.should == 200
    end
  end

  put "/users/:id" do
    parameter :id, "Id of a user"
    parameter :first_name, "First Name"
    parameter :last_name, "Last Name"
    parameter :email, "E-mail"
    parameter :title, "Title"
    parameter :dept, "Department"
    parameter :notes, "Notes"
    parameter :admin, "Make the user an admin. (Only allowed if the authenticated user is an admin)"

    required_parameters :id, :first_name, :last_name, :email

    let(:id) { other_user.id }
    let(:first_name) { "Big" }
    let(:last_name) { "Bird" }
    let(:email) { "cookie@monster1.com" }
    let(:title) { "Cookie manager1" }
    let(:dept) { "jar1" }
    let(:notes) { "great1" }
    let(:admin) { "true" }

    example_request "Update a user's details" do
      status.should == 200
    end
  end

  delete "/users/:id" do
    parameter :id, "Id of a user"

    required_parameters :id

    let(:id) { other_user.id }

    example_request "Delete a user" do
      status.should == 200
    end
  end

  get "/users/ldap" do
    parameter :username, "Username"
    required_parameters :username

    let(:username) { other_user.username }

    before do
      stub(LdapClient).search.with_any_args { [other_user.attributes] }
    end

    example_request "Search for an LDAP user" do
      explanation "This method only works if LDAP is enabled on the server"
      status.should == 200
    end
  end

  post "/users/:user_id/image" do
    parameter :user_id, "Id of a user"
    parameter :files, "Image file"

    required_parameters :user_id

    let(:user_id) { user.to_param }
    let(:files) { [Rack::Test::UploadedFile.new(File.expand_path("spec/fixtures/small2.png", Rails.root), "image/png")] }

    example_request "Update a user's profile image" do
      status.should == 200
    end
  end

  get "/users/:user_id/image" do
    let(:user_id) { users(:owner).to_param }

    parameter :user_id, "Id of a user"
    parameter :style, "Size of image ( original, icon )"

    required_parameters :user_id

    example_request "Get a user's profile image" do
      status.should == 200
    end
  end
end


text:
#include "capu/os/Windows/Console.h"

namespace capu
{
    const uint8_t capu::os::Console::Colors[] = {
        0x0C, // RED
        0x01, // BLUE
        0x0A, // GREEN
        0x0E, // YELLOW
        0x0F, // WHITE
        0x0B, // AQUA
    };

    HANDLE os::Console::m_event = INVALID_HANDLE_VALUE;
    os::LightweightMutex os::Console::interruptMutex;

    capu::status_t os::Console::ReadOneCharacter(HANDLE fileHandle, char& buffer)
    {
        char readBuffer;
        DWORD bytesRead = 0;
        const DWORD numberOfBytesToRead = 1;
        const BOOL ret = ReadFile(fileHandle, &readBuffer, numberOfBytesToRead, &bytesRead, NULL);
        if (ret)
        {
            if (0 == bytesRead)
            {
                return CAPU_EOF;
            }
            buffer = readBuffer;
            return CAPU_OK;
        }
        else
        {
            const DWORD error = GetLastError();
            if (ERROR_INVALID_HANDLE == error)
            {
                return CAPU_EOF;
            }
            else
            {
                return CAPU_ERROR;
            }
        }
    }

    HANDLE os::Console::GetInterruptEventHandle()
    {
        return m_event;
    }

    void os::Console::SetEventHandle(HANDLE eventHandle)
    {
        m_event = eventHandle;
    }

    void os::Console::InitializeInterruptEvent()
    {
        HANDLE previouslyCreatedEventHandle = GetInterruptEventHandle();
        if (previouslyCreatedEventHandle == INVALID_HANDLE_VALUE)
        {
            HANDLE createdEventHandle = CreateEvent(NULL, FALSE, FALSE, NULL);
            SetEventHandle(createdEventHandle);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
#ifndef PGUT_SPI_H
#define PGUT_SPI_H

#include "executor/spi.h"

#if PG_VERSION_NUM < 80400

extern int SPI_execute_with_args(const char *src, int nargs, Oid *argtypes,
	Datum *values, const char *nulls, bool read_only, long tcount);

#endif

extern void execute(int expected, const char *sql);
extern void execute_plan(int expected, SPIPlanPtr plan, Datum *values, const char *nulls);
extern void execute_with_format(int expected, const char *format, ...)
__attribute__((format(printf, 2, 3)));
extern void execute_with_args(int expected, const char *src, int nargs, Oid argtypes[], Datum values[], const bool nulls[]);
extern void execute_with_format_args(int expected, const char *format, int nargs, Oid argtypes[], Datum values[], const bool nulls[], ...)
__attribute__((format(printf, 2, 7)));

#endif   /* PGUT_SPI_H */


text:
<!DOCTYPE html>

<link rel="stylesheet" type="text/css" href="/commons/Client/styles.css"/>

Feature and Quality Matrix

In this window, you can filter, sort or compare the optimal variants from your model.

Mouse over a cell to observe the concrete unique clafer names and values.

Press <image src="/commons/Client/images/checkbox_empty.bmp"> to add a require(once) or eliminate(twice) filter.

Press <input type="submit" value="Distinct"> to fade out any features that are uniform across the table. Press <input type="submit" value="Normal"> to restore the initial view.

Press <input type="submit" value="Reset"> to clear any filters you may have active.

Click on the column headers to pick a variant for comparison.

Type a clafer name into the Search box to search for a clafer by name.

Expand or collapse clafer trees using by clicking on arrows close to the clafer names.

Return to Welcome page


text:
package integration

import (
	"errors"
	"fmt"
	goruntime "runtime"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	runtime "k8s.io/cri-api/pkg/apis/runtime/v1"
)

// Test to verify for a container ID
func TestContainerStats(t *testing.T) {
	t.Logf("Create a pod config and run sandbox container")
	sb, sbConfig := PodSandboxConfigWithCleanup(t, "sandbox1", "stats")

	EnsureImageExists(t, pauseImage)

	t.Logf("Create a container config and run container in a pod")
	containerConfig := ContainerConfig(
		"container1",
		pauseImage,
		WithTestLabels(),
		WithTestAnnotations(),
	)
	cn, err := runtimeService.CreateContainer(sb, containerConfig, sbConfig)
	require.NoError(t, err)
	defer func() {
		assert.NoError(t, runtimeService.RemoveContainer(cn))
	}()
	require.NoError(t, runtimeService.StartContainer(cn))
	defer func() {
		assert.NoError(t, runtimeService.StopContainer(cn, 10))
	}()

	t.Logf("Fetch stats for container")
	var s *runtime.ContainerStats
	require.NoError(t, Eventually(func() (bool, error) {
		s, err = runtimeService.ContainerStats(cn)
		if err != nil {
			return false, err
		}
		if s.GetWritableLayer().GetUsedBytes().GetValue() != 0 {
			return true, nil
		}
		return false, nil
	}, time.Second, 30*time.Second))

	t.Logf("Verify stats received for container %q", cn)
	testStats(t, s, containerConfig)
}

// Test to verify if the consumed stats are correct.
func TestContainerConsumedStats(t *testing.T) {
	t.Logf("Create a pod config and run sandbox container")
	sb, sbConfig := PodSandboxConfigWithCleanup(t, "sandbox1", "stats")

	testImage := GetImage(ResourceConsumer)
	EnsureImageExists(t, testImage)

	t.Logf("Create a container config and run container in a pod")
	containerConfig := ContainerConfig(
		"container1",
		testImage,
		WithTestLabels(),
		WithTestAnnotations(),
	)
	cn, err := runtimeService.CreateContainer(sb, containerConfig, sbConfig)
	require.NoError(t, err)
	defer func() {
		assert.NoError(t, runtimeService.RemoveContainer(cn))
	}()
	require.NoError(t, runtimeService.StartContainer(cn))
	defer func() {
		assert.NoError(t, runtimeService.StopContainer(cn, 10))
	}()

	t.Logf("Fetch initial stats for container")
	var s *runtime.ContainerStats
	require.NoError(t, Eventually(func() (bool, error) {
		s, err = runtimeService.ContainerStats(cn)
		if err != nil {
			return false, err
		}
		if s.GetMemory().GetWorkingSetBytes().GetValue() > 0 {
			return true, nil
		}
		return false, nil
	}, time.Second, 30*time.Second))

	initialMemory := s.GetMemory().GetWorkingSetBytes().GetValue()
	t.Logf("Initial container memory consumption is %f MB. Consume 100 MB and expect the reported stats to increase accordingly", float64(initialMemory)/(1024*1024))

	// consume 100 MB memory for 30 seconds.
	var command []string
	if goruntime.GOOS == "windows" {
		// -d: Leak and touch memory in specified MBs
		// -c: Count of number of objects to allocate
		command = []string{"testlimit.exe", "-accepteula", "-d", "25", "-c", "4"}
	} else {
		command = []string{"stress", "-m", "1", "--vm-bytes", "100M", "--vm-hang", "0", "-t", "30"}
	}

	go func() {
		_, _, err = runtimeService.ExecSync(cn, command, 30*time.Second)
	}()

	require.NoError(t, Eventually(func() (bool, error) {
		s, err = runtimeService.ContainerStats(cn)
		if err != nil {
			return false, err
		}
		if s.GetMemory().GetWorkingSetBytes().GetValue() > initialMemory+100*1024*1024 {
			return true, nil
		}
		return false, nil
	}, time.Second, 30*time.Second))
}

// Test to verify filtering without any filter
func TestContainerListStats(t *testing.T) {
	var (
		stats []*runtime.ContainerStats
		err   error
	)
	t.Logf("Create a pod config and run sandbox container")
	sb, sbConfig := PodSandboxConfigWithCleanup(t, "running-pod", "statsls")

	EnsureImageExists(t, pauseImage)

	t.Logf("Create a container config and run containers in a pod")
	containerConfigMap := make(map[string]*runtime.ContainerConfig)
	for i := 0; i < 3; i++ {
		cName := fmt.Sprintf("container%d", i)
		containerConfig := ContainerConfig(
			cName,
			pauseImage,
			WithTestLabels(),
			WithTestAnnotations(),
		)
		cn, err := runtimeService.CreateContainer(sb, containerConfig, sbConfig)
		require.NoError(t, err)
		containerConfigMap[cn] = containerConfig
		defer func() {
			assert.NoError(t, runtimeService.RemoveContainer(cn))
		}()
		require.NoError(t, runtimeService.StartContainer(cn))
		defer func() {
			assert.NoError(t, runtimeService.StopContainer(cn, 10))
		}()
	}

	t.Logf("Fetch all container stats")
	require.NoError(t, Eventually(func() (bool, error) {
		stats, err = runtimeService.ListContainerStats(&runtime.ContainerStatsFilter{})
		if err != nil {
			return false, err
		}
		for _, s := range stats {
			if s.GetWritableLayer().GetUsedBytes().GetValue() == 0 {
				return false, nil
			}
		}
		return true, nil
	}, time.Second, 30*time.Second))

	t.Logf("Verify all container stats")
	for _, s := range stats {
		testStats(t, s, containerConfigMap[s.GetAttributes().GetId()])
	}
}

// Test to verify filtering given a specific container ID
// TODO Convert the filter tests into table driven tests and unit tests
func TestContainerListStatsWithIdFilter(t *testing.T) {
	var (
		stats []*runtime.ContainerStats
		err   error
	)
	t.Logf("Create a pod config and run sandbox container")
	sb, sbConfig := PodSandboxConfigWithCleanup(t, "running-pod", "statsls")

	EnsureImageExists(t, pauseImage)

	t.Logf("Create a container config and run containers in a pod")
	containerConfigMap := make(map[string]*runtime.ContainerConfig)
	for i := 0; i < 3; i++ {
		cName := fmt.Sprintf("container%d", i)
		containerConfig := ContainerConfig(
			cName,
			pauseImage,
			WithTestLabels(),
			WithTestAnnotations(),
		)
		cn, err := runtimeService.CreateContainer(sb, containerConfig, sbConfig)
		containerConfigMap[cn] = containerConfig
		require.NoError(t, err)
		defer func() {
			assert.NoError(t, runtimeService.RemoveContainer(cn))
		}()
		require.NoError(t, runtimeService.StartContainer(cn))
		defer func() {
			assert.NoError(t, runtimeService.StopContainer(cn, 10))
		}()
	}

	t.Logf("Fetch container stats for each container with Filter")
	for id := range containerConfigMap {
		require.NoError(t, Eventually(func() (bool, error) {
			stats, err = runtimeService.ListContainerStats(
				&runtime.ContainerStatsFilter{Id: id})
			if err != nil {
				return false, err
			}
			if len(stats) != 1 {
				return false, errors.New("unexpected stats length")
			}
			if stats[0].GetWritableLayer().GetUsedBytes().GetValue() != 0 {
				return true, nil
			}
			return false, nil
		}, time.Second, 30*time.Second))

		t.Logf("Verify container stats for %s", id)
		for _, s := range stats {
			require.Equal(t, s.GetAttributes().GetId(), id)
			testStats(t, s, containerConfigMap[id])
		}
	}
}

// Test to verify filtering given a specific Sandbox ID. Stats for
// all the containers in a pod should be returned
func TestContainerListStatsWithSandboxIdFilter(t *testing.T) {
	var (
		stats []*runtime.ContainerStats
		err   error
	)
	t.Logf("Create a pod config and run sandbox container")
	sb, sbConfig := PodSandboxConfigWithCleanup(t, "running-pod", "statsls")

	EnsureImageExists(t, pauseImage)

	t.Logf("Create a container config and run containers in a pod")
	containerConfigMap := make(map[string]*runtime.ContainerConfig)
	for i := 0; i < 3; i++ {
		cName := fmt.Sprintf("container%d", i)
		containerConfig := ContainerConfig(
			cName,
			pauseImage,
			WithTestLabels(),
			WithTestAnnotations(),
		)
		cn, err := runtimeService.CreateContainer(sb, containerConfig, sbConfig)
		containerConfigMap[cn] = containerConfig
		require.NoError(t, err)
		defer func() {
			assert.NoError(t, runtimeService.RemoveContainer(cn))
		}()
		require.NoError(t, runtimeService.StartContainer(cn))
		defer func() {
			assert.NoError(t, runtimeService.StopContainer(cn, 10))
		}()
	}

	t.Logf("Fetch container stats for each container with Filter")
	require.NoError(t, Eventually(func() (bool, error) {
		stats, err = runtimeService.ListContainerStats(
			&runtime.ContainerStatsFilter{PodSandboxId: sb})
		if err != nil {
			return false, err
		}
		if len(stats) != 3 {
			return false, errors.New("unexpected stats length")
		}

		for _, containerStats := range stats {
			// Wait for stats on all containers, not just the first one in the list.
			if containerStats.GetWritableLayer().GetUsedBytes().GetValue() == 0 {
				return false, nil
			}
		}
		return true, nil
	}, time.Second, 45*time.Second))
	// TODO(claudiub): Reduce the timer above to 30 seconds once Windows flakiness has been addressed.
	t.Logf("Verify container stats for sandbox %q", sb)
	for _, s := range stats {
		testStats(t, s, containerConfigMap[s.GetAttributes().GetId()])
	}
}

// Test to verify filtering given a specific container ID and
// sandbox ID
func TestContainerListStatsWithIdSandboxIdFilter(t *testing.T) {
	var (
		stats []*runtime.ContainerStats
		err   error
	)
	t.Logf("Create a pod config and run sandbox container")
	sb, sbConfig := PodSandboxConfigWithCleanup(t, "running-pod", "statsls")

	EnsureImageExists(t, pauseImage)

	t.Logf("Create container config and run containers in a pod")
	containerConfigMap := make(map[string]*runtime.ContainerConfig)
	for i := 0; i < 3; i++ {
		cName := fmt.Sprintf("container%d", i)
		containerConfig := ContainerConfig(
			cName,
			pauseImage,
			WithTestLabels(),
			WithTestAnnotations(),
		)
		cn, err := runtimeService.CreateContainer(sb, containerConfig, sbConfig)
		containerConfigMap[cn] = containerConfig
		require.NoError(t, err)
		defer func() {
			assert.NoError(t, runtimeService.RemoveContainer(cn))
		}()
		require.NoError(t, runtimeService.StartContainer(cn))
		defer func() {
			assert.NoError(t, runtimeService.StopContainer(cn, 10))
		}()
	}
	t.Logf("Fetch container stats for sandbox ID and container ID filter")
	for id, config := range containerConfigMap {
		require.NoError(t, Eventually(func() (bool, error) {
			stats, err = runtimeService.ListContainerStats(
				&runtime.ContainerStatsFilter{Id: id, PodSandboxId: sb})
			if err != nil {
				return false, err
			}
			if len(stats) != 1 {
				return false, errors.New("unexpected stats length")
			}
			if stats[0].GetWritableLayer().GetUsedBytes().GetValue() != 0 {
				return true, nil
			}
			return false, nil
		}, time.Second, 30*time.Second))
		t.Logf("Verify container stats for sandbox %q and container %q filter", sb, id)
		for _, s := range stats {
			testStats(t, s, config)
		}
	}

	t.Logf("Fetch container stats for sandbox truncID and container truncID filter ")
	for id, config := range containerConfigMap {
		require.NoError(t, Eventually(func() (bool, error) {
			stats, err = runtimeService.ListContainerStats(
				&runtime.ContainerStatsFilter{Id: id[:3], PodSandboxId: sb[:3]})
			if err != nil {
				return false, err
			}
			if len(stats) != 1 {
				return false, fmt.Errorf("expected only one stat, but got %v", stats)
			}
			if stats[0].GetWritableLayer().GetUsedBytes().GetValue() != 0 {
				return true, nil
			}
			return false, nil
		}, time.Second, 30*time.Second))
		t.Logf("Verify container stats for sandbox %q and container %q filter", sb, id)
		for _, s := range stats {
			testStats(t, s, config)
		}
	}
}

// TODO make this as options to use for dead container tests
func testStats(t *testing.T,
	s *runtime.ContainerStats,
	config *runtime.ContainerConfig,
) {
	require.NotEmpty(t, s.GetAttributes().GetId())
	require.NotEmpty(t, s.GetAttributes().GetMetadata())
	require.NotEmpty(t, s.GetAttributes().GetAnnotations())
	require.Equal(t, s.GetAttributes().GetLabels(), config.Labels)
	require.Equal(t, s.GetAttributes().GetAnnotations(), config.Annotations)
	require.Equal(t, s.GetAttributes().GetMetadata().Name, config.Metadata.Name)
	require.NotEmpty(t, s.GetAttributes().GetLabels())
	require.NotEmpty(t, s.GetCpu().GetTimestamp())
	require.NotEmpty(t, s.GetCpu().GetUsageCoreNanoSeconds().GetValue())
	require.NotEmpty(t, s.GetMemory().GetTimestamp())
	require.NotEmpty(t, s.GetMemory().GetWorkingSetBytes().GetValue())
	require.NotEmpty(t, s.GetWritableLayer().GetTimestamp())
	require.NotEmpty(t, s.GetWritableLayer().GetFsId().GetMountpoint())
	require.NotEmpty(t, s.GetWritableLayer().GetUsedBytes().GetValue())

	// Windows does not collect inodes stats.
	if goruntime.GOOS != "windows" {
		require.NotEmpty(t, s.GetWritableLayer().GetInodesUsed().GetValue())
	}
}


text:
Testing
=======

testing first repo,I probably delete this later


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

class VideoDocument : MultimediaDocument
{
    public int? FrameRate { get; protected set; }

    public override void LoadProperty(string key, string value)
    {
        base.LoadProperty(key, value);
        if (key == "framerate")
        {
            this.FrameRate = int.Parse(value);
        }
    }

    public override void SaveAllProperties(IList<KeyValuePair<string, object>> output)
    {
        base.SaveAllProperties(output);
        output.Add(new KeyValuePair<string, object>("framerate", this.FrameRate));
    }

    public override string ToString()
    {
        return "VideoDocument[" + PropertiesToString() + "]";
    }
}


text:
require 'nokogiri'

module Feed2Email
  class OPMLReader
    def initialize(io)
      @io = io
    end

    def urls
      Nokogiri::XML(data).css('opml body outline').map {|outline|
        outline['xmlUrl']
      }.compact
    end

    private

    attr_reader :io

    def data
      io.read
    end
  end
end


text:
    Copyright 2012 PayPerks Inc.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

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

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

10gen-mms-agent-ubuntu
======================

Tools for running mms-agent on Ubuntu

Presently we have:

## Upstart Script
* This is known to work at least on Ubuntu 12's upstart, version 1.5.
* Drop into /etc/init to have mms-agent started on boot and restarted whenever required.  Logging goes to /var/log/upstart/ or to /var/log/syslog.
* Assumes a dedicated user has been setup to run the agent

## Ubuntu Packaging Files
Drop the contents of the latest & greatest mms-agent into opt/mongo-mms-agent/ and then you can build them into a package with:

    dpkg-deb --build mongo-mms-agent_1.0-5

It's best to leave your api & secret keys out and add them upon installation.

Creates a user/group 'mongomms' to run the agent as.  UID/GID 510.

Potential improvements:
* Install settings.py to /etc and have the daemon look for it there
* Prompt on attented dpkg installations for api & secret keys
* Version with debian-friendly init script


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 2.5.1//EN" "http://google-web-toolkit.googlecode.com/svn/tags/2.5.1/distro-source/core/src/gwt-module.dtd">
<module>
	<inherits name="com.google.gwt.user.User" />
	<inherits name="com.google.gwt.json.JSON" />

	<source path="client"/>
</module>


text:
package com.vividsolutions.jts.geom.util;

import com.vividsolutions.jts.geom.*;

/**
 * A visitor to {@link Geometry} elements which can
 * be short-circuited by a given condition
 *
 * @version 1.7
 */
public abstract class ShortCircuitedGeometryVisitor
{
  private boolean isDone = false;

  public ShortCircuitedGeometryVisitor() {
  }

  public void applyTo(Geometry geom) {
    for (int i = 0; i < geom.getNumGeometries() && ! isDone; i++) {
      Geometry element = geom.getGeometryN(i);
      if (! (element instanceof GeometryCollection)) {
        visit(element);
        if (isDone()) {
          isDone = true;
          return;
        }
      }
      else
        applyTo(element);
    }
  }

  protected abstract void visit(Geometry element);

  protected abstract boolean isDone();
}


text:
cordova.define('cordova/plugin_list', function(require, exports, module) {
module.exports = [
    {
        "file": "plugins/cordova-plugin-whitelist/whitelist.js",
        "id": "cordova-plugin-whitelist.whitelist",
        "runs": true
    },
    {
        "file": "plugins/cordova-plugin-device-orientation/www/CompassError.js",
        "id": "cordova-plugin-device-orientation.CompassError",
        "clobbers": [
            "CompassError"
        ]
    },
    {
        "file": "plugins/cordova-plugin-device-orientation/www/CompassHeading.js",
        "id": "cordova-plugin-device-orientation.CompassHeading",
        "clobbers": [
            "CompassHeading"
        ]
    },
    {
        "file": "plugins/cordova-plugin-device-orientation/www/compass.js",
        "id": "cordova-plugin-device-orientation.compass",
        "clobbers": [
            "navigator.compass"
        ]
    }
];
module.exports.metadata =
// TOP OF METADATA
{
    "cordova-plugin-whitelist": "1.0.0",
    "cordova-plugin-device-orientation": "1.0.0"
}
// BOTTOM OF METADATA
});


text:
module GroupSupervisionsExtension
  def current
    in_progress.first
  end
end


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE259_Hard_Coded_Password__w32_wchar_t_54e.c
Label Definition File: CWE259_Hard_Coded_Password__w32.label.xml
Template File: sources-sink-54e.tmpl.c
*/
/*
 * @description
 * CWE: 259 Use of Hard-coded Password
 * BadSource:  Use a hardcoded password
 * GoodSource: Read the password from the console
 * Sink:
 *    BadSink : Authenticate the user using LogonUserW()
 * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#define PASSWORD L"ABCD1234!"

#include <windows.h>
#pragma comment(lib, "advapi32.lib")

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

void CWE259_Hard_Coded_Password__w32_wchar_t_54e_badSink(wchar_t * password)
{
    {
        HANDLE pHandle;
        wchar_t * username = L"User";
        wchar_t * domain = L"Domain";
        /* POTENTIAL FLAW: Attempt to login user with password from the source (which may be hardcoded) */
        if (LogonUserW(
                    username,
                    domain,
                    password,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE259_Hard_Coded_Password__w32_wchar_t_54e_goodG2BSink(wchar_t * password)
{
    {
        HANDLE pHandle;
        wchar_t * username = L"User";
        wchar_t * domain = L"Domain";
        /* POTENTIAL FLAW: Attempt to login user with password from the source (which may be hardcoded) */
        if (LogonUserW(
                    username,
                    domain,
                    password,
                    LOGON32_LOGON_NETWORK,
                    LOGON32_PROVIDER_DEFAULT,
                    &pHandle) != 0)
        {
            printLine("User logged in successfully.");
            CloseHandle(pHandle);
        }
        else
        {
            printLine("Unable to login.");
        }
    }
}

#endif /* OMITGOOD */


text:
extern crate regex;

pub mod parse;
pub mod namesp;


text:
package org.pentaho.di.trans.steps.salesforceinput;

import java.util.List;

import org.pentaho.di.core.CheckResult;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.row.value.ValueMetaDate;
import org.pentaho.di.core.row.value.ValueMetaFactory;
import org.pentaho.di.core.row.value.ValueMetaInteger;
import org.pentaho.di.core.row.value.ValueMetaString;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.salesforce.SalesforceConnectionUtils;
import org.pentaho.di.trans.steps.salesforce.SalesforceStepMeta;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;

@Step(
    id = "SalesforceInput",
    i18nPackageName = "org.pentaho.di.trans.steps.salesforceinput",
    name = "SalesforceInput.TypeLongDesc.SalesforceInput",
    description = "SalesforceInput.TypeTooltipDesc.SalesforceInput",
    categoryDescription = "i18n:org.pentaho.di.trans.step:BaseStep.Category.Input",
    image = "SFI.svg",
    documentationUrl = "Products/Data_Integration/Transformation_Step_Reference/Salesforce_Input" )
public class SalesforceInputMeta extends SalesforceStepMeta {
  public static String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

  private static Class<?> PKG = SalesforceInputMeta.class; // for i18n purposes, needed by Translator2!!

  /** Flag indicating that we should include the generated SQL in the output */
  private boolean includeSQL;

  /** The name of the field in the output containing the generated SQL */
  private String sqlField;

  /** Flag indicating that we should include the server Timestamp in the output */
  private boolean includeTimestamp;

  /** The name of the field in the output containing the server Timestamp */
  private String timestampField;

  /** Flag indicating that we should include the filename in the output */
  private boolean includeTargetURL;

  /** The name of the field in the output containing the filename */
  private String targetURLField;

  /** Flag indicating that we should include the module in the output */
  private boolean includeModule;

  /** The name of the field in the output containing the module */
  private String moduleField;

  /** Flag indicating that a deletion date field should be included in the output */
  private boolean includeDeletionDate;

  /** The name of the field in the output containing the deletion Date */
  private String deletionDateField;

  /** Flag indicating that a row number field should be included in the output */
  private boolean includeRowNumber;

  /** The name of the field in the output containing the row number */
  private String rowNumberField;

  /** The condition */
  private String condition;

  /** The maximum number or lines to read */
  private String rowLimit;

  /** The fields to return... */
  private SalesforceInputField[] inputFields;

  /** option: specify query **/
  private boolean specifyQuery;

  // ** query entered by user **/
  private String query;

  private int nrFields;

  private String readTo;
  private String readFrom;

  /** records filter */
  private int recordsFilter;

  /** Query all records including deleted ones **/
  private boolean queryAll;

  public SalesforceInputMeta() {
    super(); // allocate BaseStepMeta
  }

  /**
   * @return Returns the input fields.
   */
  public SalesforceInputField[] getInputFields() {
    return inputFields;
  }

  /**
   * @param inputFields
   *          The input fields to set.
   */
  public void setInputFields( SalesforceInputField[] inputFields ) {
    this.inputFields = inputFields;
  }

  /**
   * @return Returns the query.
   */
  public String getQuery() {
    return query;
  }

  /**
   * @param query
   *          The query to set.
   */
  public void setQuery( String query ) {
    this.query = query;
  }

  /**
   * @return Returns the specifyQuery.
   */
  public boolean isSpecifyQuery() {
    return specifyQuery;
  }

  /**
   * @param specifyQuery
   *          The specifyQuery to set.
   */
  public void setSpecifyQuery( boolean specifyQuery ) {
    this.specifyQuery = specifyQuery;
  }

  /**
   * @return Returns the queryAll.
   */
  public boolean isQueryAll() {
    return queryAll;
  }

  /**
   * @param queryAll
   *          The queryAll to set.
   */
  public void setQueryAll( boolean value ) {
    this.queryAll = value;
  }

  /**
   * @return Returns the condition.
   */
  public String getCondition() {
    return condition;
  }

  /**
   * @param condition
   *          The condition to set.
   */
  public void setCondition( String condition ) {
    this.condition = condition;
  }

  /**
   * @param TargetURLField
   *          The TargetURLField to set.
   */
  public void setTargetURLField( String TargetURLField ) {
    this.targetURLField = TargetURLField;
  }

  /**
   * @param sqlField
   *          The sqlField to set.
   */
  public void setSQLField( String sqlField ) {
    this.sqlField = sqlField;
  }

  /**
   * @param timestampField
   *          The timestampField to set.
   */
  public void setTimestampField( String timestampField ) {
    this.timestampField = timestampField;
  }

  /**
   * @param ModuleField
   *          The ModuleField to set.
   */
  public void setModuleField( String module_field ) {
    this.moduleField = module_field;
  }

  public int getRecordsFilter() {
    return recordsFilter;
  }

  public void setRecordsFilter( int recordsFilter ) {
    this.recordsFilter = recordsFilter;
  }

  /**
   * @return Returns the includeTargetURL.
   */
  public boolean includeTargetURL() {
    return includeTargetURL;
  }

  /**
   * @return Returns the includeSQL.
   */
  public boolean includeSQL() {
    return includeSQL;
  }

  /**
   * @param includeSQL
   *          to set.
   */
  public void setIncludeSQL( boolean includeSQL ) {
    this.includeSQL = includeSQL;
  }

  /**
   * @return Returns the includeTimestamp.
   */
  public boolean includeTimestamp() {
    return includeTimestamp;
  }

  /**
   * @param includeTimestamp
   *          to set.
   */
  public void setIncludeTimestamp( boolean includeTimestamp ) {
    this.includeTimestamp = includeTimestamp;
  }

  /**
   * @return Returns the includeModule.
   */
  public boolean includeModule() {
    return includeTargetURL;
  }

  /**
   * @param includeTargetURL
   *          The includeTargetURL to set.
   */
  public void setIncludeTargetURL( boolean includeTargetURL ) {
    this.includeTargetURL = includeTargetURL;
  }

  /**
   * @param includeModule
   *          The includeModule to set.
   */
  public void setIncludeModule( boolean includemodule ) {
    this.includeModule = includemodule;
  }

  /**
   * @return Returns the includeRowNumber.
   */
  public boolean includeRowNumber() {
    return includeRowNumber;
  }

  /**
   * @param includeRowNumber
   *          The includeRowNumber to set.
   */
  public void setIncludeRowNumber( boolean includeRowNumber ) {
    this.includeRowNumber = includeRowNumber;
  }

  /**
   * @return Returns the includeDeletionDate.
   */
  public boolean includeDeletionDate() {
    return includeDeletionDate;
  }

  /**
   * @param includeDeletionDate
   *          The includeDeletionDate to set.
   */
  public void setIncludeDeletionDate( boolean includeDeletionDate ) {
    this.includeDeletionDate = includeDeletionDate;
  }

  /**
   * @return Returns the rowLimit.
   */
  public String getRowLimit() {
    return rowLimit;
  }

  /**
   * @param rowLimit
   *          The rowLimit to set.
   */
  public void setRowLimit( String rowLimit ) {
    this.rowLimit = rowLimit;
  }

  /**
   * @return Returns the rowNumberField.
   */
  public String getRowNumberField() {
    return rowNumberField;
  }

  /**
   * @return Returns the deletionDateField.
   */
  public String getDeletionDateField() {
    return deletionDateField;
  }

  /**
   * @param value
   *          the deletionDateField to set.
   */
  public void setDeletionDateField( String value ) {
    this.deletionDateField = value;
  }

  /**
   * @return Returns the targetURLField.
   */
  public String getTargetURLField() {
    return targetURLField;
  }

  /**
   * @return Returns the readFrom.
   */
  public String getReadFrom() {
    return readFrom;
  }

  /**
   * @param readFrom
   *          the readFrom to set.
   */
  public void setReadFrom( String readFrom ) {
    this.readFrom = readFrom;
  }

  /**
   * @return Returns the readTo.
   */
  public String getReadTo() {
    return readTo;
  }

  /**
   * @param readTo
   *          the readTo to set.
   */
  public void setReadTo( String readTo ) {
    this.readTo = readTo;
  }

  /**
   * @return Returns the sqlField.
   */
  public String getSQLField() {
    return sqlField;
  }

  /**
   * @return Returns the timestampField.
   */
  public String getTimestampField() {
    return timestampField;
  }

  /**
   * @return Returns the moduleField.
   */
  public String getModuleField() {
    return moduleField;
  }

  /**
   * @param rowNumberField
   *          The rowNumberField to set.
   */
  public void setRowNumberField( String rowNumberField ) {
    this.rowNumberField = rowNumberField;
  }

  public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
    super.loadXML( stepnode, databases, metaStore );
    readData( stepnode );
  }

  public Object clone() {
    SalesforceInputMeta retval = (SalesforceInputMeta) super.clone();

    int nrFields = inputFields.length;

    retval.allocate( nrFields );

    for ( int i = 0; i < nrFields; i++ ) {
      if ( inputFields[i] != null ) {
        retval.inputFields[i] = (SalesforceInputField) inputFields[i].clone();
      }
    }

    return retval;
  }

  public String getXML() {
    StringBuilder retval = new StringBuilder( super.getXML() );
    retval.append( "    " ).append( XMLHandler.addTagValue( "condition", getCondition() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "specifyQuery", isSpecifyQuery() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "query", getQuery() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "include_targeturl", includeTargetURL() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "targeturl_field", getTargetURLField() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "include_module", includeModule() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "module_field", getModuleField() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "include_rownum", includeRowNumber() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "include_deletion_date", includeDeletionDate() ) );

    retval.append( "    " ).append( XMLHandler.addTagValue( "deletion_date_field", getDeletionDateField() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "rownum_field", getRowNumberField() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "include_sql", includeSQL() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "sql_field", getSQLField() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "include_Timestamp", includeTimestamp() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "timestamp_field", getTimestampField() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "read_from", getReadFrom() ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "read_to", getReadTo() ) );
    retval.append( "    " ).append(
      XMLHandler
        .addTagValue( "records_filter", SalesforceConnectionUtils.getRecordsFilterCode( getRecordsFilter() ) ) );
    retval.append( "    " ).append( XMLHandler.addTagValue( "queryAll", isQueryAll() ) );

    retval.append( "    " ).append( XMLHandler.openTag( "fields" ) ).append( Const.CR );
    for ( SalesforceInputField field : inputFields ) {
      retval.append( field.getXML() );
    }
    retval.append( "    " ).append( XMLHandler.closeTag( "fields" ) ).append( Const.CR );
    retval.append( "    " ).append( XMLHandler.addTagValue( "limit", getRowLimit() ) );

    return retval.toString();
  }

  private void readData( Node stepnode ) throws KettleXMLException {
    try {
      setCondition( XMLHandler.getTagValue( stepnode, "condition" ) );
      setQuery( XMLHandler.getTagValue( stepnode, "query" ) );
      setSpecifyQuery( "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "specifyQuery" ) ) );
      setIncludeTargetURL( "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "include_targeturl" ) ) );
      setTargetURLField( XMLHandler.getTagValue( stepnode, "targeturl_field" ) );
      setIncludeModule( "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "include_module" ) ) );
      setModuleField( XMLHandler.getTagValue( stepnode, "module_field" ) );
      setIncludeRowNumber( "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "include_rownum" ) ) );
      setIncludeDeletionDate( "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "include_deletion_date" ) ) );
      setRowNumberField( XMLHandler.getTagValue( stepnode, "rownum_field" ) );
      setDeletionDateField( XMLHandler.getTagValue( stepnode, "deletion_date_field" ) );

      setIncludeSQL( "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "include_sql" ) ) );
      setSQLField( XMLHandler.getTagValue( stepnode, "sql_field" ) );
      setIncludeTimestamp( "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "include_Timestamp" ) ) );
      setTimestampField( XMLHandler.getTagValue( stepnode, "timestamp_field" ) );
      setReadFrom( XMLHandler.getTagValue( stepnode, "read_from" ) );
      setReadTo( XMLHandler.getTagValue( stepnode, "read_to" ) );
      setRecordsFilter(
        SalesforceConnectionUtils.getRecordsFilterByCode( Const.NVL( XMLHandler.getTagValue(
          stepnode, "records_filter" ), "" ) ) );
      setQueryAll( "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "queryAll" ) ) );

      Node fields = XMLHandler.getSubNode( stepnode, "fields" );
      int nrFields = XMLHandler.countNodes( fields, "field" );

      allocate( nrFields );

      for ( int i = 0; i < nrFields; i++ ) {
        Node fnode = XMLHandler.getSubNodeByNr( fields, "field", i );
        SalesforceInputField field = new SalesforceInputField( fnode );
        inputFields[i] = field;
      }
      // Is there a limit on the number of rows we process?
      setRowLimit( XMLHandler.getTagValue( stepnode, "limit" ) );
    } catch ( Exception e ) {
      throw new KettleXMLException( "Unable to load step info from XML", e );
    }
  }

  public void allocate( int nrfields ) {
    setInputFields( new SalesforceInputField[nrfields] );
  }

  public int getNrFields() {
    return nrFields;
  }

  public void setDefault() {
    super.setDefault();
    setIncludeDeletionDate( false );
    setQueryAll( false );
    setReadFrom( "" );
    setReadTo( "" );
    nrFields = 0;
    setSpecifyQuery( false );
    setQuery( "" );
    setCondition( "" );
    setIncludeTargetURL( false );
    setTargetURLField( "" );
    setIncludeModule( false );
    setModuleField( "" );
    setIncludeRowNumber( false );
    setRowNumberField( "" );
    setDeletionDateField( "" );
    setIncludeSQL( false );
    setSQLField( "" );
    setIncludeTimestamp( false );
    setTimestampField( "" );
    allocate( 0 );

    setRowLimit( "0" );
  }

  public void getFields( RowMetaInterface r, String name, RowMetaInterface[] info, StepMeta nextStep,
    VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
    int i;
    for ( i = 0; i < inputFields.length; i++ ) {
      SalesforceInputField field = inputFields[i];

      int type = field.getType();
      if ( type == ValueMetaInterface.TYPE_NONE ) {
        type = ValueMetaInterface.TYPE_STRING;
      }
      try {
        ValueMetaInterface v =
          ValueMetaFactory.createValueMeta( space.environmentSubstitute( field.getName() ), type );
        v.setLength( field.getLength() );
        v.setPrecision( field.getPrecision() );
        v.setOrigin( name );
        v.setConversionMask( field.getFormat() );
        v.setDecimalSymbol( field.getDecimalSymbol() );
        v.setGroupingSymbol( field.getGroupSymbol() );
        v.setCurrencySymbol( field.getCurrencySymbol() );
        r.addValueMeta( v );
      } catch ( Exception e ) {
        throw new KettleStepException( e );
      }
    }

    if ( includeTargetURL && !Utils.isEmpty( targetURLField ) ) {
      ValueMetaInterface v = new ValueMetaString( space.environmentSubstitute( targetURLField ) );
      v.setLength( 250 );
      v.setPrecision( -1 );
      v.setOrigin( name );
      r.addValueMeta( v );
    }
    if ( includeModule && !Utils.isEmpty( moduleField ) ) {
      ValueMetaInterface v = new ValueMetaString( space.environmentSubstitute( moduleField ) );
      v.setLength( 250 );
      v.setPrecision( -1 );
      v.setOrigin( name );
      r.addValueMeta( v );
    }

    if ( includeSQL && !Utils.isEmpty( sqlField ) ) {
      ValueMetaInterface v = new ValueMetaString( space.environmentSubstitute( sqlField ) );
      v.setLength( 250 );
      v.setPrecision( -1 );
      v.setOrigin( name );
      r.addValueMeta( v );
    }
    if ( includeTimestamp && !Utils.isEmpty( timestampField ) ) {
      ValueMetaInterface v = new ValueMetaDate( space.environmentSubstitute( timestampField ) );
      v.setOrigin( name );
      r.addValueMeta( v );
    }

    if ( includeRowNumber && !Utils.isEmpty( rowNumberField ) ) {
      ValueMetaInterface v = new ValueMetaInteger( space.environmentSubstitute( rowNumberField ) );
      v.setLength( ValueMetaInterface.DEFAULT_INTEGER_LENGTH, 0 );
      v.setOrigin( name );
      r.addValueMeta( v );
    }
    if ( includeDeletionDate && !Utils.isEmpty( deletionDateField ) ) {
      ValueMetaInterface v = new ValueMetaDate( space.environmentSubstitute( deletionDateField ) );
      v.setOrigin( name );
      r.addValueMeta( v );
    }

  }

  public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases ) throws KettleException {
    super.readRep( rep, metaStore, id_step, databases );
    try {
      // H.kawaguchi Add 19-01-2009
      setCondition( rep.getStepAttributeString( id_step, "condition" ) );
      // H.kawaguchi Add 19-01-2009
      setQuery( rep.getStepAttributeString( id_step, "query" ) );
      setSpecifyQuery( rep.getStepAttributeBoolean( id_step, "specifyQuery" ) );
      setIncludeTargetURL( rep.getStepAttributeBoolean( id_step, "include_targeturl" ) );
      setTargetURLField( rep.getStepAttributeString( id_step, "targeturl_field" ) );
      setIncludeModule( rep.getStepAttributeBoolean( id_step, "include_module" ) );
      setModuleField( rep.getStepAttributeString( id_step, "module_field" ) );
      setIncludeRowNumber( rep.getStepAttributeBoolean( id_step, "include_rownum" ) );
      setIncludeDeletionDate( rep.getStepAttributeBoolean( id_step, "include_deletion_date" ) );
      setRowNumberField( rep.getStepAttributeString( id_step, "rownum_field" ) );
      setDeletionDateField( rep.getStepAttributeString( id_step, "deletion_date_field" ) );
      setIncludeSQL( rep.getStepAttributeBoolean( id_step, "include_sql" ) );
      setSQLField( rep.getStepAttributeString( id_step, "sql_field" ) );
      setIncludeTimestamp( rep.getStepAttributeBoolean( id_step, "include_Timestamp" ) );
      setTimestampField( rep.getStepAttributeString( id_step, "timestamp_field" ) );
      setRowLimit( rep.getStepAttributeString( id_step, "limit" ) );
      setReadFrom( rep.getStepAttributeString( id_step, "read_from" ) );
      setReadTo( rep.getStepAttributeString( id_step, "read_to" ) );
      setRecordsFilter(
        SalesforceConnectionUtils.getRecordsFilterByCode( Const.NVL( rep.getStepAttributeString(
          id_step, "records_filter" ), "" ) ) );
      setQueryAll( rep.getStepAttributeBoolean( id_step, "queryAll" ) );

      int nrFields = rep.countNrStepAttributes( id_step, "field_name" );

      allocate( nrFields );

      for ( int i = 0; i < nrFields; i++ ) {
        SalesforceInputField field = new SalesforceInputField();
        field.readRep( rep, metaStore, id_step, i );
        inputFields[i] = field;
      }
    } catch ( Exception e ) {
      throw new KettleException( BaseMessages.getString(
        PKG, "SalesforceInputMeta.Exception.ErrorReadingRepository" ), e );
    }
  }

  public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step ) throws KettleException {
    super.saveRep( rep, metaStore, id_transformation, id_step );
    try {
      // H.kawaguchi Add 19-01-2009
      rep.saveStepAttribute( id_transformation, id_step, "condition", getCondition() );
      // H.kawaguchi Add 19-01-2009
      rep.saveStepAttribute( id_transformation, id_step, "query", getQuery() );
      rep.saveStepAttribute( id_transformation, id_step, "specifyQuery", isSpecifyQuery() );

      rep.saveStepAttribute( id_transformation, id_step, "include_targeturl", includeTargetURL() );
      rep.saveStepAttribute( id_transformation, id_step, "targeturl_field", getTargetURLField() );
      rep.saveStepAttribute( id_transformation, id_step, "include_module", includeModule() );
      rep.saveStepAttribute( id_transformation, id_step, "module_field", getModuleField() );
      rep.saveStepAttribute( id_transformation, id_step, "include_rownum", includeRowNumber() );
      rep.saveStepAttribute( id_transformation, id_step, "include_deletion_date", includeDeletionDate() );

      rep.saveStepAttribute( id_transformation, id_step, "include_sql", includeSQL() );
      rep.saveStepAttribute( id_transformation, id_step, "sql_field", getSQLField() );
      rep.saveStepAttribute( id_transformation, id_step, "include_Timestamp", includeTimestamp() );
      rep.saveStepAttribute( id_transformation, id_step, "timestamp_field", getTimestampField() );
      rep.saveStepAttribute( id_transformation, id_step, "rownum_field", getRowNumberField() );
      rep.saveStepAttribute( id_transformation, id_step, "deletion_date_field", getDeletionDateField() );

      rep.saveStepAttribute( id_transformation, id_step, "limit", getRowLimit() );
      rep.saveStepAttribute( id_transformation, id_step, "read_from", getReadFrom() );
      rep.saveStepAttribute( id_transformation, id_step, "read_to", getReadTo() );
      rep.saveStepAttribute( id_transformation, id_step, "records_filter", SalesforceConnectionUtils
        .getRecordsFilterCode( getRecordsFilter() ) );
      rep.saveStepAttribute( id_transformation, id_step, "queryAll", isQueryAll() );

      for ( int i = 0; i < inputFields.length; i++ ) {
        SalesforceInputField field = inputFields[i];
        field.saveRep( rep, metaStore, id_transformation, id_step, i );
      }
    } catch ( Exception e ) {
      throw new KettleException( BaseMessages.getString(
        PKG, "SalesforceInputMeta.Exception.ErrorSavingToRepository", "" + id_step ), e );
    }
  }

  public void check( List<CheckResultInterface> remarks, TransMeta transMeta, StepMeta stepMeta,
    RowMetaInterface prev, String[] input, String[] output, RowMetaInterface info, VariableSpace space,
    Repository repository, IMetaStore metaStore ) {
    super.check( remarks, transMeta, stepMeta, prev, input, output, info, space, repository, metaStore );
    CheckResult cr;

    // See if we get input...
    if ( input != null && input.length > 0 ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoInputExpected" ), stepMeta );
    } else {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoInput" ), stepMeta );
    }
    remarks.add( cr );

    // check return fields
    if ( getInputFields().length == 0 ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoFields" ), stepMeta );
    } else {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_OK, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.FieldsOk" ), stepMeta );
    }
    remarks.add( cr );

    // check additional fields
    if ( includeTargetURL() && Utils.isEmpty( getTargetURLField() ) ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoTargetURLField" ), stepMeta );
      remarks.add( cr );
    }
    if ( includeSQL() && Utils.isEmpty( getSQLField() ) ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoSQLField" ), stepMeta );
      remarks.add( cr );
    }
    if ( includeModule() && Utils.isEmpty( moduleField ) ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoModuleField" ), stepMeta );
      remarks.add( cr );
    }
    if ( includeTimestamp() && Utils.isEmpty( getTimestampField() ) ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoTimestampField" ), stepMeta );
      remarks.add( cr );
    }
    if ( includeRowNumber() && Utils.isEmpty( getRowNumberField() ) ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoRowNumberField" ), stepMeta );
      remarks.add( cr );
    }
    if ( includeDeletionDate() && Utils.isEmpty( getDeletionDateField() ) ) {
      cr =
        new CheckResult( CheckResult.TYPE_RESULT_ERROR, BaseMessages.getString(
          PKG, "SalesforceInputMeta.CheckResult.NoDeletionDateField" ), stepMeta );
      remarks.add( cr );
    }
  }

  public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int cnr,
    TransMeta transMeta, Trans trans ) {
    return new SalesforceInput( stepMeta, stepDataInterface, cnr, transMeta, trans );
  }

  public StepDataInterface getStepData() {
    return new SalesforceInputData();
  }
}


text:
# Java - Domo API SDK
[![Download](https://api.bintray.com/packages/domoinc/domo-java-sdk/domo-java-sdk/images/download.svg) ](https://bintray.com/domoinc/domo-java-sdk/domo-java-sdk/_latestVersion)
[![License](http://img.shields.io/badge/license-MIT-blue.svg?style=flat)](http://www.opensource.org/licenses/MIT)
[![CircleCI](https://circleci.com/gh/domoinc/domo-java-sdk.svg?style=svg)](https://circleci.com/gh/domoinc/domo-java-sdk)
[![Coverage Status](https://img.shields.io/coveralls/domoinc/domo-java-sdk.svg?style=flat)](https://coveralls.io/r/domoinc/domo-java-sdk?branch=master)

### About

* The Domo API SDK is the simplest way to automate your Domo instance
* The SDK streamlines the API programming experience, allowing you to significantly reduce your written code
* This package is published to [bintray jcenter](https://bintray.com/domoinc/domo-java-sdk/domo-java-sdk/_latestVersion)

### Features:
- DataSet and Personalized Data Policy (PDP) Management
    - Use DataSets for fairly static data sources that only require occasional updates via data replacement
    - Add Personalized Data Policies (PDPs) to DataSets (hide sensitive data from groups of users)
    - Docs: https://developer.domo.com/docs/domo-apis/data
- Stream Management
    - A Domo Stream is a specialized upload pipeline pointing to a single Domo DataSet
    - Use Streams for massive, constantly changing, or rapidly growing data sources
    - Streams support accelerated uploading via parallel data uploads
    - Docs: https://developer.domo.com/docs/domo-apis/stream-apis
- User Management
    - Create, update, and remove users
    - Major use case: LDAP/Active Directory synchronization
    - Docs: https://developer.domo.com/docs/domo-apis/users
- Group Management
    - Create, update, and remove groups of users
    - Docs: https://developer.domo.com/docs/domo-apis/group-apis
- Account Management
    - Create, update, and remove accounts
    - Docs: https://developer.domo.com/docs/domo-apis/accounts-api-reference

### Setup

The SDK can be added to your project in three ways:

It is currently hosted via bintray and JCenter (It will be in Maven central eventually):
```groovy
repositories {
    maven {
        url  "http://dl.bintray.com/domoinc/domo-java-sdk"
    }
}
```

Maven:

```xml
<dependency>
  <groupId>com.domo</groupId>
  <artifactId>domo-java-sdk-all</artifactId>
  <version>0.4.3</version>
</dependency>
```

Gradle:

```groovy
compile 'com.domo:domo-java-sdk-all:0.4.3'
```

Classic Jar Import:
- Clone this repository
- Using a Bash Terminal, navigate to the cloned repository folder
- Create the Jar files via the Bash command `./gradlew publishToMavenLocal`
- The Jars will be located in `domo-java-sdk-all/build/libs/`
- Copy the Jars to your project folder, and add them to your build path

### Usage
* See the [Client Test File](https://github.com/domoinc/domo-java-sdk/blob/master/domo-java-sdk-all/src/test/java/com/domo/sdk/ClientTest.java) for full usage and examples.
* Create an API Client on the [Domo Developer Portal](https://developer.domo.com/)
* Use your API Client id/secret to instantiate a DomoClient()
* Multiple API Clients can be used by instantiating multiple Domo Clients
* Authentication with the Domo API is handled automatically by the SDK
* If you encounter a 'Not Allowed' error, this is a permissions issue. Please speak with your Domo Administrator.

```java
public class Example {

    public void domoSDKUsage() {

        //Build an SDK configuration
        Config config = Config.with()
                .clientId("MY_CLIENT_ID")
                .clientSecret("MY_CLIENT_SECRET")
                .apiHost("api.domo.com")
                .useHttps(true)
                .scope(USER, DATA)
                .httpLoggingLevel(HttpLoggingInterceptor.Level.BODY)
                .build();

        //Create an instance of the SDK Client
        DomoClient domo = DomoClient.create(config);

        //Manage DataSets
        DataSetClient datasets = domo.dataSetClient();
        datasets.create();

        //Manage Streams
        StreamClient streams = domo.streamClient();
        streams.create();

        //Manage Users
        UserClient users = domo.userClient();
        users.create();

        //Manage User Groups
        GroupClient groups = domo.groupClient();
        groups.create();
    }
}
```

##### Snapshots

You can use snapshot versions through [JitPack](https://jitpack.io):

* Go to [JitPack project page](https://jitpack.io/#domoinc/domo-java-sdk)
* Select `Commits` section and click `Get it` on commit you want to use (top one - the most recent)
* Follow displayed instruction: add repository and change dependency (NOTE: due to JitPack convention artifact group will be different)

[![java lib generator](http://img.shields.io/badge/Powered%20by-%20Java%20lib%20generator-green.svg?style=flat-square)](https://github.com/xvik/generator-lib-java)


text:
package org.mycontroller.standalone.restclient;

import java.io.IOException;

import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.ext.Provider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jeeva Kandasamy (jkandasa)
 * @since 0.0.3
 */
@Provider
public class ResponseLogger implements ClientResponseFilter {
    private static final Logger _logger = LoggerFactory.getLogger(ResponseLogger.class);

    @Override
    public void filter(ClientRequestContext clientRequestContext, ClientResponseContext clientResponseContext)
            throws IOException {
        if (_logger.isTraceEnabled()) {
            _logger.trace("Response [Headers:{}, Status:{}]",
                    clientResponseContext.getHeaders(),
                    clientResponseContext.getStatus());
        }
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Routing.Constraints;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;

namespace MVCWeb
{
    public class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // IMPORTANT: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

            // Attribute routing.
            config.MapHttpAttributeRoutes();

            // Convention-based routing.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { RouteParameter.Optional });

//                constraints: new CompoundRouteConstraint({
//                    new BoolRouteConstraint().IfNotNull(null)
//});

            //config.Routes.MapHttpRoute(
            //    name: "DefaultApiByAction",
            //    routeTemplate: "api/{controller}/{action}/{id}",
            //    defaults: new { id = RouteParameter.Optional },
            //    constraints: new { HttpVerbs.Post }
            //    );

            config.EnsureInitialized();
        }
    }
}


text:
<?php

namespace backend\modules\location;

class Location extends \yii\base\Module
{
    public $controllerNamespace = 'backend\modules\location\controllers';

    public function init()
    {
        parent::init();
        $this->layoutPath='@backend/views/layouts';
        $this->layout='column2';
        // custom initialization code goes here
    }
}


text:
import pytest
import numpy
import random as rand

@pytest.fixture
def fixed_seed():
    rand.seed(0)
    numpy.random.seed(0)


text:
using namespace SourceKit;
using namespace swift;
using namespace swift::index;

static UIdent KindImportModuleClang("source.lang.swift.import.module.clang");
static UIdent KindImportModuleSwift("source.lang.swift.import.module.swift");

static UIdent getUIDForDependencyKind(bool isClangModule) {
  return isClangModule ? KindImportModuleClang : KindImportModuleSwift;
}

class SKIndexDataConsumer : public IndexDataConsumer {
public:
  SKIndexDataConsumer(IndexingConsumer &C) : impl(C) {}

private:
  void failed(StringRef error) override { impl.failed(error); }

  void warning(StringRef warning) override {
    LOG_WARN_FUNC(warning);
  }

  bool enableWarnings() override {
    return Logger::isLoggingEnabledForLevel(Logger::Level::Warning);
  }

  bool recordHash(StringRef hash, bool isKnown) override {
    return impl.recordHash(hash, isKnown);
  }

  bool startDependency(StringRef name, StringRef path, bool isClangModule,
                       bool isSystem, StringRef hash) override {
    auto kindUID = getUIDForDependencyKind(isClangModule);
    return impl.startDependency(kindUID, name, path, isSystem, hash);
  }

  bool finishDependency(bool isClangModule) override {
    return impl.finishDependency(getUIDForDependencyKind(isClangModule));
  }

  Action startSourceEntity(const IndexSymbol &symbol) override {
    if (symbol.symInfo.Kind == SymbolKind::Parameter)
      return Skip;

    // report any parent relations to this reference
    if (symbol.roles & (SymbolRoleSet)SymbolRole::RelationBaseOf) {
      withEntityInfo(symbol, [this](const EntityInfo &info) {
        return impl.recordRelatedEntity(info);
      });
    }

    // filter out references with invalid locations
    if (symbol.roles & (SymbolRoleSet)SymbolRole::Reference &&
        (symbol.line == 0 || symbol.column == 0))
      return Skip;

    // start the entity (ref or def)
    if (!withEntityInfo(symbol, [this](const EntityInfo &info) {
        return impl.startSourceEntity(info);
    })) return Abort;

    // report relations this occurrence has
    for (auto Relation: symbol.Relations) {
      if (Relation.roles & (SymbolRoleSet)SymbolRole::RelationOverrideOf) {
        if (!withEntityInfo(Relation, [this](const EntityInfo &info) {
          return impl.recordRelatedEntity(info);
        })) return Abort;
      }
    }
    return Continue;
  }

  bool finishSourceEntity(SymbolInfo symInfo, SymbolRoleSet roles) override {
    bool isRef = roles & (unsigned)SymbolRole::Reference;
    auto UID = SwiftLangSupport::getUIDForSymbol(symInfo, isRef);
    return impl.finishSourceEntity(UID);
  }

  template <typename F>
  bool withEntityInfo(const IndexSymbol &symbol, F func) {
    EntityInfo info;
    bool isRef = symbol.roles & (unsigned)SymbolRole::Reference;
    bool isImplicit = symbol.roles & (unsigned)SymbolRole::Implicit;

    info.Kind = SwiftLangSupport::getUIDForSymbol(symbol.symInfo, isRef);
    info.Name = isImplicit? "" : symbol.name;
    info.USR = symbol.USR;
    info.Group = symbol.group;
    info.Line = symbol.line;
    info.Column = symbol.column;
    info.ReceiverUSR = symbol.getReceiverUSR();
    info.IsDynamic = symbol.roles & (unsigned)SymbolRole::Dynamic;
    info.IsTestCandidate = symbol.symInfo.Properties & SymbolProperty::UnitTest;
    std::vector<UIdent> uidAttrs;
    if (!isRef) {
      uidAttrs =
        SwiftLangSupport::UIDsFromDeclAttributes(symbol.decl->getAttrs());
      info.Attrs = uidAttrs;
    }
    return func(info);
  }

  template <typename F>
  bool withEntityInfo(const IndexRelation &relation, F func) {
    EntityInfo info;
    bool isRef = (relation.roles & (unsigned)SymbolRole::Reference) ||
      (relation.roles & (unsigned)SymbolRole::RelationOverrideOf);
    info.Kind = SwiftLangSupport::getUIDForSymbol(relation.symInfo, isRef);
    info.Name = relation.name;
    info.USR = relation.USR;
    info.Group = relation.group;
    info.IsDynamic = relation.roles & (unsigned)SymbolRole::Dynamic;
    info.IsTestCandidate = relation.symInfo.Properties & SymbolProperty::UnitTest;
    std::vector<UIdent> uidAttrs;
    if (!isRef) {
      uidAttrs =
      SwiftLangSupport::UIDsFromDeclAttributes(relation.decl->getAttrs());
      info.Attrs = uidAttrs;
    }
    return func(info);
  }

private:
  IndexingConsumer &impl;
};

static void indexModule(llvm::MemoryBuffer *Input,
                        StringRef ModuleName,
                        StringRef Hash,
                        IndexingConsumer &IdxConsumer,
                        CompilerInstance &CI,
                        ArrayRef<const char *> Args) {
  ASTContext &Ctx = CI.getASTContext();
  std::unique_ptr<SerializedModuleLoader> Loader;
  ModuleDecl *Mod = nullptr;
  if (ModuleName == Ctx.StdlibModuleName.str()) {
    Mod = Ctx.getModule({ {Ctx.StdlibModuleName, SourceLoc()} });
  } else {
    Loader = SerializedModuleLoader::create(Ctx);
    auto Buf = std::unique_ptr<llvm::MemoryBuffer>(
        llvm::MemoryBuffer::getMemBuffer(Input->getBuffer(),
                                         Input->getBufferIdentifier()));

    // FIXME: These APIs allocate memory on the ASTContext, meaning it may not
    // be freed for a long time.
    Mod = ModuleDecl::create(Ctx.getIdentifier(ModuleName), Ctx);
    // Indexing is not using documentation now, so don't open the module
    // documentation file.
    // FIXME: refactor the frontend to provide an easy way to figure out the
    // correct filename here.
    auto FUnit = Loader->loadAST(*Mod, None, std::move(Buf), nullptr);

    // FIXME: Not knowing what went wrong is pretty bad. loadModule() should be
    // more modular, rather than emitting diagnostics itself.
    if (!FUnit) {
      IdxConsumer.failed("failed to load module");
      return;
    }

    Mod->setHasResolvedImports();
  }

  // Setup a typechecker for protocol conformance resolving.
  (void)createTypeChecker(Ctx);

  SKIndexDataConsumer IdxDataConsumer(IdxConsumer);
  index::indexModule(Mod, Hash, IdxDataConsumer);
}

//===----------------------------------------------------------------------===//
// IndexSource
//===----------------------------------------------------------------------===//

template <typename Str>
static void initTraceInfoImpl(trace::SwiftInvocation &SwiftArgs,
                              StringRef InputFile,
                              ArrayRef<Str> Args) {
  llvm::raw_string_ostream OS(SwiftArgs.Args.Arguments);
  interleave(Args, [&OS](StringRef arg) { OS << arg; }, [&OS] { OS << ' '; });
  SwiftArgs.Args.PrimaryFile = InputFile;
}

void trace::initTraceInfo(trace::SwiftInvocation &SwiftArgs,
                          StringRef InputFile,
                          ArrayRef<const char *> Args) {
  initTraceInfoImpl(SwiftArgs, InputFile, Args);
}

void trace::initTraceInfo(trace::SwiftInvocation &SwiftArgs,
                          StringRef InputFile,
                          ArrayRef<std::string> Args) {
  initTraceInfoImpl(SwiftArgs, InputFile, Args);
}

void SwiftLangSupport::indexSource(StringRef InputFile,
                                   IndexingConsumer &IdxConsumer,
                                   ArrayRef<const char *> OrigArgs,
                                   StringRef Hash) {
  std::string Error;
  auto InputBuf = ASTMgr->getMemoryBuffer(InputFile, Error);
  if (!InputBuf) {
    IdxConsumer.failed(Error);
    return;
  }

  StringRef Filename = llvm::sys::path::filename(InputFile);
  StringRef FileExt = llvm::sys::path::extension(Filename);

  bool IsModuleIndexing = (FileExt == ".swiftmodule" || FileExt == ".pcm");
  CompilerInstance CI;
  // Display diagnostics to stderr.
  PrintingDiagnosticConsumer PrintDiags;
  CI.addDiagnosticConsumer(&PrintDiags);

  // Add -disable-typo-correction, since the errors won't be captured in the
  // response, and it can be expensive to do typo-correction when there are many
  // errors, which is common in indexing.
  SmallVector<const char *, 16> Args(OrigArgs.begin(), OrigArgs.end());
  Args.push_back("-Xfrontend");
  Args.push_back("-disable-typo-correction");

  CompilerInvocation Invocation;
  bool Failed = true;
  if (IsModuleIndexing) {
    Failed = getASTManager()->initCompilerInvocationNoInputs(
        Invocation, Args, CI.getDiags(), Error);
  } else {
    Failed = getASTManager()->initCompilerInvocation(
        Invocation, Args, CI.getDiags(), InputFile, Error);
  }
  if (Failed) {
    IdxConsumer.failed(Error);
    return;
  }

  if (IsModuleIndexing) {
    if (CI.setup(Invocation))
      return;
    bool IsClangModule = (FileExt == ".pcm");
    if (IsClangModule) {
      IdxConsumer.failed("Clang module files are not supported");
      return;
    }

    indexModule(InputBuf.get(), llvm::sys::path::stem(Filename),
                Hash, IdxConsumer, CI, Args);
    return;
  }

  if (!Invocation.getFrontendOptions().InputsAndOutputs.hasInputs()) {
    IdxConsumer.failed("no input filenames specified");
    return;
  }

  if (CI.setup(Invocation))
    return;

  trace::TracedOperation TracedOp(trace::OperationKind::IndexSource);
  if (TracedOp.enabled()) {
    trace::SwiftInvocation SwiftArgs;
    trace::initTraceInfo(SwiftArgs, InputFile, Args);
    TracedOp.start(SwiftArgs);
  }

  CI.performSema();

  // NOTE: performSema() may end up with some gruesome error preventing it from
  // setting primary file correctly
  if (!CI.getPrimarySourceFile()) {
    IdxConsumer.failed("no primary source file found");
    return;
  }

  // Setup a typechecker for protocol conformance resolving.
  (void)createTypeChecker(CI.getASTContext());

  SKIndexDataConsumer IdxDataConsumer(IdxConsumer);
  index::indexSourceFile(CI.getPrimarySourceFile(), Hash, IdxDataConsumer);
}


text:
'''
Created on 17/05/2012

@author: piranna
'''

try:
    from collections import OrderedDict
except ImportError:
    OrderedDict = None

if OrderedDict:
    class Cache(OrderedDict):
        """Cache with LRU algorithm using an OrderedDict as basis
        """
        def __init__(self, maxsize=100):
            OrderedDict.__init__(self)

            self._maxsize = maxsize

        def __getitem__(self, key, *args, **kwargs):
            # Get the key and remove it from the cache, or raise KeyError
            value = OrderedDict.__getitem__(self, key)
            del self[key]

            # Insert the (key, value) pair on the front of the cache
            OrderedDict.__setitem__(self, key, value)

            # Return the value from the cache
            return value

        def __setitem__(self, key, value, *args, **kwargs):
            # Key was inserted before, remove it so we put it at front later
            if key in self:
                del self[key]

            # Too much items on the cache, remove the least recent used
            elif len(self) >= self._maxsize:
                self.popitem(False)

            # Insert the (key, value) pair on the front of the cache
            OrderedDict.__setitem__(self, key, value, *args, **kwargs)

else:
    class Cache(dict):
        """Cache that reset when gets full
        """
        def __init__(self, maxsize=100):
            dict.__init__(self)

            self._maxsize = maxsize

        def __setitem__(self, key, value, *args, **kwargs):
            # Reset the cache if we have too much cached entries and start over
            if len(self) >= self._maxsize:
                self.clear()

            # Insert the (key, value) pair on the front of the cache
            dict.__setitem__(self, key, value, *args, **kwargs)

def memoize_generator(func):
    """Memoize decorator for generators

    Store `func` results in a cache according to their arguments as 'memoize'
    does but instead this works on decorators instead of regular functions.
    Obviusly, this is only useful if the generator will always return the same
    values for each specific parameters...
    """
    cache = Cache()

    def wrapped_func(*args, **kwargs):
#        params = (args, kwargs)
        params = (args, tuple(sorted(kwargs.items())))

        # Look if cached
        try:
            cached = cache[params]

        # Not cached, exec and store it
        except KeyError:
            cached = []

            for item in func(*args, **kwargs):
                cached.append(item)
                yield item

            cache[params] = cached

        # Cached, yield its items
        else:
            for item in cached:
                yield item

    return wrapped_func


text:
@interface THJAlertController : UIAlertController

+ (instancetype)THJAlertControllerWithTitle:(NSString *)title
                                    message:(NSString *)message
                             preferredStyle:(UIAlertControllerStyle)preferredStyle;

- (void)show;

@end


text:
package cmd

import (
	"fmt"

	"github.com/TheThingsNetwork/go-account-lib/account"
	"github.com/TheThingsNetwork/ttn/ttnctl/util"
	"github.com/howeyc/gopass"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var userRegisterCmd = &cobra.Command{
	Use:   "register [username] [e-mail]",
	Short: "Register",
	Long:  `ttnctl user register allows you to register a new user in the account server`,
	Example: `$ ttnctl user register yourname your@email.org
Password: <entering password>
  INFO Registered user
  WARN You might have to verify your email before you can login
`,
	Run: func(cmd *cobra.Command, args []string) {
		assertArgsLength(cmd, args, 2, 2)

		username := args[0]
		email := args[1]
		fmt.Print("Password: ")
		password, err := gopass.GetPasswd()
		if err != nil {
			ctx.Fatal(err.Error())
		}
		acc := account.New(viper.GetString("auth-server")).WithHeader("User-Agent", util.GetUserAgent())
		err = acc.RegisterUser(username, email, string(password))
		if err != nil {
			ctx.WithError(err).Fatal("Could not register user")
		}
		ctx.Info("Registered user")
		ctx.Warn("You might have to verify your email before you can login")
	},
}

func init() {
	userCmd.AddCommand(userRegisterCmd)
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

    <link rel="stylesheet" href="https://code.getmdl.io/1.2.1/material.indigo-pink.min.css">

    <link rel="stylesheet" type="text/css" href="admin.css">
    <title></title>

Add Head Of Department

      <form action="#">

    <input class="mdl-textfield__input" type="password" id="repassword">
    Secret Key

    <input class="mdl-textfield__input" type="text" id="username">
    Username

    <input class="mdl-textfield__input" type="text" id="name">
    Full Name

    <input class="mdl-textfield__input" type="password" id="password">
    Password

    <input class="mdl-textfield__input" type="password" id="repassword">
    Repeat Password

        <button class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect mdl-button--accent">
  Register
</button>
      </form>


text:
"""Tests for projectq.libs.math_constantmath.py."""

import pytest

import projectq.libs.math
from projectq import MainEngine
from projectq.backends import Simulator
from projectq.cengines import AutoReplacer, DecompositionRuleSet, InstructionFilter
from projectq.libs.math import AddConstant, AddConstantModN, MultiplyByConstantModN
from projectq.ops import All, BasicMathGate, ClassicalInstructionGate, Measure, X
from projectq.setups.decompositions import qft2crandhadamard, swap2cnot

def init(engine, quint, value):
    for i in range(len(quint)):
        if ((value >> i) & 1) == 1:
            X | quint[i]

def no_math_emulation(eng, cmd):
    if isinstance(cmd.gate, BasicMathGate):
        return False
    if isinstance(cmd.gate, ClassicalInstructionGate):
        return True
    try:
        return len(cmd.gate.matrix) == 2
    except AttributeError:
        return False

@pytest.fixture
def eng():
    return MainEngine(
        backend=Simulator(),
        engine_list=[AutoReplacer(rule_set), InstructionFilter(no_math_emulation)],
    )

rule_set = DecompositionRuleSet(modules=[projectq.libs.math, qft2crandhadamard, swap2cnot])

@pytest.mark.parametrize(
    'gate', (AddConstantModN(-1, 6), MultiplyByConstantModN(-1, 6), MultiplyByConstantModN(4, 4)), ids=str
)
def test_invalid(eng, gate):
    qureg = eng.allocate_qureg(4)
    init(eng, qureg, 4)

    with pytest.raises(ValueError):
        gate | qureg
        eng.flush()

def test_adder(eng):
    qureg = eng.allocate_qureg(4)
    init(eng, qureg, 4)

    AddConstant(3) | qureg

    assert 1.0 == pytest.approx(abs(eng.backend.cheat()[1][7]))

    init(eng, qureg, 7)  # reset
    init(eng, qureg, 2)

    # check for overflow -> should be 15+2 = 1 (mod 16)
    AddConstant(15) | qureg
    assert 1.0 == pytest.approx(abs(eng.backend.cheat()[1][1]))

    All(Measure) | qureg

def test_modadder(eng):
    qureg = eng.allocate_qureg(4)
    init(eng, qureg, 4)

    AddConstantModN(3, 6) | qureg

    assert 1.0 == pytest.approx(abs(eng.backend.cheat()[1][1]))

    init(eng, qureg, 1)  # reset
    init(eng, qureg, 7)

    AddConstantModN(10, 13) | qureg
    assert 1.0 == pytest.approx(abs(eng.backend.cheat()[1][4]))

    All(Measure) | qureg

def test_modmultiplier(eng):
    qureg = eng.allocate_qureg(4)
    init(eng, qureg, 4)

    MultiplyByConstantModN(3, 7) | qureg

    assert 1.0 == pytest.approx(abs(eng.backend.cheat()[1][5]))

    init(eng, qureg, 5)  # reset
    init(eng, qureg, 7)

    MultiplyByConstantModN(4, 13) | qureg
    assert 1.0 == pytest.approx(abs(eng.backend.cheat()[1][2]))

    All(Measure) | qureg


text:
class Admin::MenuItemsController < Admin::BaseController

  helper :pages

  before_filter :sub_query_filter

  active_scaffold :menu_items do |config|
    config.label = "Navigation Menu Items"
    config.list.sorting = {:position => :asc}
    #override to set display order
    config.list.columns   = [:name, :menu, :children, :link_type_desc,  :position, :visible]
    config.update.columns = [:name, :parent, :menu, :position, :conditions, :link_type, :link_url, :visible]
    config.create.columns = [:name, :parent, :menu, :position, :conditions, :link_type, :link_url, :visible]
    #
    config.columns[:parent].form_ui = :select
    config.columns[:menu].form_ui   = :select
    config.columns[:position].inplace_edit = true

    config.columns[:children].label = 'Sub Menus'
    config.columns[:children].association.reverse = :parent
    config.columns[:children].includes = nil
    #
    config.subform.columns.exclude :link_type, :link_url, :children, :menu
  end

  def link_type_controller
    menu_item = MenuItem.find_or_initialize_by_id(params[:id])
    menu_type = params[:type]
    #
    render :update do |page|
      page.replace_html "link_url_#{menu_item.id}", render_link_url_controller(menu_item, menu_type)
    end
  end

  protected

  #activeScaffold override to display only top level menu items when in list mode
  #children can be accessed as a nested form when clicking on the children column
  def conditions_for_collection
    'menu_items.parent_id is null' if params[:nested].blank?
  end

  def sub_query_filter
    unless params[:nested].blank?
      active_scaffold_config.list.columns.exclude [:menu, :children]
      active_scaffold_config.update.columns.exclude [:menu, :children]
      active_scaffold_config.create.columns.exclude [:menu, :children]
    else
      active_scaffold_config.list.columns.add [:menu]
      active_scaffold_config.update.columns.add [:menu]
      active_scaffold_config.create.columns.add [:menu]
    end
  end

end