text:
package vulns

import (
	"encoding/json"
	"fmt"
	"io"
	"net/url"
	"strings"
	"time"

	"gopkg.in/yaml.v2"

	"github.com/google/osv/vulnfeeds/cves"
)

type Event struct {
	Introduced string `json:"introduced,omitempty" yaml:"introduced,omitempty"`
	Fixed      string `json:"fixed,omitempty" yaml:"fixed,omitempty"`
	Limit      string `json:"limit,omitempty" yaml:"limit,omitempty"`
}

type Affected struct {
	Package  *AffectedPackage `json:"package,omitempty"`
	Ranges   []AffectedRange  `json:"ranges" yaml:"ranges"`
	Versions []string         `json:"versions,omitempty" yaml:"versions,omitempty"`
}

type AffectedPackage struct {
	Name      string `json:"name,omitempty" yaml:"name"`
	Ecosystem string `json:"ecosystem,omitempty" yaml:"ecosystem"`
	Purl      string `json:"purl,omitempty" yaml:"purl,omitempty"`
}

type AffectedRange struct {
	Type   string  `json:"type" yaml:"type"`
	Repo   string  `json:"repo,omitempty" yaml:"repo,omitempty"`
	Events []Event `json:"events" yaml:"events"`
}

type Reference struct {
	Type string `json:"type" yaml:"type"`
	URL  string `json:"url" yaml:"url"`
}

type Vulnerability struct {
	ID         string      `json:"id" yaml:"id"`
	Summary    string      `json:"summary,omitempty" yaml:"summary,omitempty"`
	Details    string      `json:"details" yaml:"details"`
	Affected   []Affected  `json:"affected" yaml:"affected"`
	References []Reference `json:"references" yaml:"references"`
	Aliases    []string    `json:"aliases,omitempty" yaml:"aliases,omitempty"`
	Modified   string      `json:"modified" yaml:"modified"`
	Published  string      `json:"published" yaml:"published"`
}

func timestampToRFC3339(timestamp string) (string, error) {
	t, err := cves.ParseTimestamp(timestamp)
	if err != nil {
		return "", err
	}

	return t.Format(time.RFC3339), nil
}

// For a given URL, infer the OSV schema's reference type of it.
// See https://ossf.github.io/osv-schema/#references-field
// Uses the tags first before resorting to inference by shape.

func ClassifyReferenceLink(link string, tag string) string {
	switch tag {
	case "Patch":
		return "FIX"
	case "Exploit":
		return "EVIDENCE"
	case "Mailing List":
		return "ARTICLE"
	case "Issue Tracking":
		return "REPORT"
	case "Vendor Advisory", "Third Party Avisory", "VDB Entry":
		return "ADVISORY"
	}

	u, err := url.Parse(link)
	if err != nil {
		return "WEB"
	}

	pathParts := strings.Split(u.Path, "/")

	// Index 0 will always be "", so the length must be at least 2 to be relevant
	if len(pathParts) >= 2 {
		if u.Host == "github.com" {
			// Example: https://github.com/google/osv/commit/cd4e934d0527e5010e373e7fed54ef5daefba2f5
			if pathParts[len(pathParts)-2] == "commit" {
				return "FIX"
			}

			// Example: https://github.com/advisories/GHSA-fr26-qjc8-mvjx
			// Example: https://github.com/dpgaspar/Flask-AppBuilder/security/advisories/GHSA-624f-cqvr-3qw4
			if pathParts[len(pathParts)-2] == "advisories" {
				return "ADVISORY"
			}

			// Example: https://github.com/Netflix/lemur/issues/117
			if pathParts[len(pathParts)-2] == "issues" {
				return "REPORT"
			}
		}

		if u.Host == "snyk.io" {
			//Example: https://snyk.io/vuln/SNYK-PYTHON-TRYTOND-1730329
			if pathParts[1] == "vuln" {
				return "ADVISORY"
			}
		}

		if u.Host == "nvd.nist.gov" {
			//Example: https://nvd.nist.gov/vuln/detail/CVE-2021-23336
			if len(pathParts) == 4 && pathParts[1] == "vuln" && pathParts[2] == "detail" {
				return "ADVISORY"
			}
		}

		if u.Host == "www.debian.org" {
			//Example: https://www.debian.org/security/2021/dsa-4878
			if pathParts[1] == "security" {
				return "ADVISORY"
			}
		}

		if u.Host == "usn.ubuntu.com" {
			//Example: https://usn.ubuntu.com/usn/usn-4661-1
			if pathParts[1] == "usn" {
				return "ADVISORY"
			}
		}

		if u.Host == "www.ubuntu.com" {
			//Example: http://www.ubuntu.com/usn/USN-2915-2
			if pathParts[1] == "usn" {
				return "ADVISORY"
			}
		}

		if u.Host == "ubuntu.com" {
			//Example: https://ubuntu.com/security/notices/USN-5124-1
			if pathParts[1] == "security" && pathParts[2] == "notices" {
				return "ADVISORY"
			}
		}

		if u.Host == "rhn.redhat.com" {
			//Example: http://rhn.redhat.com/errata/RHSA-2016-0504.html
			if pathParts[1] == "errata" {
				return "ADVISORY"
			}
		}

		if u.Host == "access.redhat.com" {
			//Example: https://access.redhat.com/errata/RHSA-2017:1499
			if pathParts[1] == "errata" {
				return "ADVISORY"
			}
		}

		if u.Host == "security.gentoo.org" {
			//Example: https://security.gentoo.org/glsa/202003-45
			if pathParts[len(pathParts)-2] == "glsa" {
				return "ADVISORY"
			}
		}

		if u.Host == "pypi.org" {
			//Example: "https://pypi.org/project/flask"
			if pathParts[1] == "project" {
				return "PACKAGE"
			}
		}
	}

	if strings.Contains(link, "advisory") || strings.Contains(link, "advisories") {
		return "ADVISORY"
	}

	if strings.Contains(link, "bugzilla") {
		return "REPORT"
	}

	if strings.Contains(link, "blog") {
		return "ARTICLE"
	}

	return "WEB"
}

func extractAliases(id string, cve cves.CVE) []string {
	var aliases []string
	if id != cve.CVEDataMeta.ID {
		aliases = append(aliases, cve.CVEDataMeta.ID)
	}

	for _, reference := range cve.References.ReferenceData {
		u, err := url.Parse(reference.URL)
		if err == nil {
			pathParts := strings.Split(u.Path, "/")

			// Index 0 will always be "", so the length must be at least 3 here to be relevant
			if len(pathParts) >= 3 {
				if u.Host == "github.com" {
					// Example: https://github.com/advisories/GHSA-fr26-qjc8-mvjx
					// Example: https://github.com/dpgaspar/Flask-AppBuilder/security/advisories/GHSA-624f-cqvr-3qw4
					if pathParts[len(pathParts)-2] == "advisories" {
						a := pathParts[len(pathParts)-1]

						if id != a && strings.HasPrefix(a, "GHSA-") {
							aliases = append(aliases, a)
						}
					}
				}

				if u.Host == "snyk.io" {
					//Example: https://snyk.io/vuln/SNYK-PYTHON-TRYTOND-1730329
					if pathParts[1] == "vuln" {
						a := pathParts[len(pathParts)-1]

						if id != a && strings.HasPrefix(a, "SNYK-") {
							aliases = append(aliases, a)
						}
					}
				}
			}
		}
	}

	return aliases
}

type PackageInfo struct {
	PkgName      string `json:"pkg_name"`
	Ecosystem    string `json:"ecosystem"`
	PURL         string `json:"purl"`
	FixedVersion string `json:"fixed_version"`
	FixedCommit  string `json:"fixed_commit"`
	Repo         string `json:"repo"`
}

func unique[T comparable](s []T) []T {
	inResult := make(map[T]bool)
	var result []T
	for _, str := range s {
		if _, ok := inResult[str]; !ok {
			inResult[str] = true
			result = append(result, str)
		}
	}
	return result
}

// Annotates reference links based on their tags or the shape of them.
func ClassifyReferences(refs cves.CVEReferences) []Reference {
	references := []Reference{}
	for _, reference := range refs.ReferenceData {
		if len(reference.Tags) > 0 {
			for _, tag := range reference.Tags {
				references = append(references, Reference{
					Type: ClassifyReferenceLink(reference.URL, tag),
					URL:  reference.URL,
				})
			}
		} else {
			references = append(references, Reference{
				Type: ClassifyReferenceLink(reference.URL, ""),
				URL:  reference.URL,
			})
		}
	}
	return unique(references)
}

// FromCVE creates a bare minimum OSV object from a given CVEItem and id.
// Leaves affected and version fields empty to be filled in later with AddPkgInfo
func FromCVE(id string, cve cves.CVEItem) (*Vulnerability, []string) {
	v := Vulnerability{
		ID:      id,
		Details: cves.EnglishDescription(cve.CVE),
		Aliases: extractAliases(id, cve.CVE),
	}
	var err error
	var notes []string
	v.Published, err = timestampToRFC3339(cve.PublishedDate)
	if err != nil {
		notes = append(notes, fmt.Sprintf("Failed to parse published date: %v\n", err))
	}

	v.Modified, err = timestampToRFC3339(cve.LastModifiedDate)
	if err != nil {
		notes = append(notes, fmt.Sprintf("Failed to parse modified date: %v\n", err))
	}

	v.References = ClassifyReferences(cve.CVE.References)
	return &v, notes
}

// AddPkgInfo adds affected package information to the OSV vulnerability object
func (v *Vulnerability) AddPkgInfo(pkgInfo PackageInfo) {
	affected := Affected{}
	affected.Package = &AffectedPackage{
		Name:      pkgInfo.PkgName,
		Ecosystem: pkgInfo.Ecosystem,
		Purl:      pkgInfo.PURL,
	}
	if pkgInfo.FixedVersion != "" {
		versionRange := AffectedRange{
			Type: "ECOSYSTEM",
			Events: []Event{
				{Introduced: "0"},
				{Fixed: pkgInfo.FixedVersion},
			},
		}
		affected.Ranges = append(affected.Ranges, versionRange)
	}

	if pkgInfo.FixedCommit != "" {
		versionRange := AffectedRange{
			Type: "GIT",
			Repo: pkgInfo.Repo,
			Events: []Event{
				{Introduced: "0"},
				{Fixed: pkgInfo.FixedCommit},
			},
		}
		affected.Ranges = append(affected.Ranges, versionRange)
	}
	v.Affected = append(v.Affected, affected)
}

// AttachExtractedVersionInfo adds version information extracted from CVEs onto
// the affected field
func (affected *Affected) AttachExtractedVersionInfo(version cves.VersionInfo) {
	repoToCommits := map[string][]string{}
	for _, fixCommit := range version.FixCommits {
		repoToCommits[fixCommit.Repo] = append(repoToCommits[fixCommit.Repo], fixCommit.Commit)
	}

	for repo, commits := range repoToCommits {
		gitRange := AffectedRange{
			Type: "GIT",
			Repo: repo,
		}
		gitRange.Events = append(gitRange.Events, Event{Introduced: "0"})
		for _, commit := range commits {
			gitRange.Events = append(gitRange.Events, Event{Fixed: commit})
		}
		affected.Ranges = append(affected.Ranges, gitRange)
	}

	// Adding an ECOSYSTEM version range only makes sense if we have package information.
	if affected.Package == nil {
		return
	}

	versionRange := AffectedRange{
		Type: "ECOSYSTEM",
	}
	seenIntroduced := map[string]bool{}
	seenFixed := map[string]bool{}

	for _, v := range version.AffectedVersions {
		var introduced string
		if v.Introduced == "" {
			introduced = "0"
		} else {
			introduced = v.Introduced
		}

		if _, seen := seenIntroduced[introduced]; !seen {
			versionRange.Events = append(versionRange.Events, Event{
				Introduced: introduced,
			})
			seenIntroduced[introduced] = true
		}

		if _, seen := seenFixed[v.Fixed]; v.Fixed != "" && !seen {
			versionRange.Events = append(versionRange.Events, Event{
				Fixed: v.Fixed,
			})
			seenFixed[v.Fixed] = true
		}
	}
	if len(version.AffectedVersions) > 0 {
		affected.Ranges = append(affected.Ranges, versionRange)
	}
}

func FromYAML(r io.Reader) (*Vulnerability, error) {
	decoder := yaml.NewDecoder(r)
	var vuln Vulnerability
	err := decoder.Decode(&vuln)
	if err != nil {
		return nil, err
	}

	return &vuln, nil
}

func (v *Vulnerability) ToYAML(w io.Writer) error {
	encoder := yaml.NewEncoder(w)
	return encoder.Encode(v)
}

func FromJSON(r io.Reader) (*Vulnerability, error) {
	decoder := json.NewDecoder(r)
	var vuln Vulnerability
	err := decoder.Decode(&vuln)
	if err != nil {
		return nil, err
	}

	return &vuln, nil
}

func (v *Vulnerability) ToJSON(w io.Writer) error {
	encoder := json.NewEncoder(w)
	return encoder.Encode(v)
}


text:
Here you can find the C# code examples for [RabbitMQ
tutorials](http://www.rabbitmq.com/getstarted.html).

To successfully use the examples you will need a running RabbitMQ server.

## Requirements

### Requirements on Windows

You need the RabbitMQ dotnet client.

* Download [RabbitMQ .NET client](http://www.rabbitmq.com/releases/rabbitmq-dotnet-client/v3.4.4/rabbitmq-dotnet-client-3.4.4-dotnet-3.5.zip)
* Extract it and copy "RabbitMQ.Client.dll" to your working folder.

You also need to ensure your system can find the C# compiler `csc.exe`,
you may need to add `;C:\Windows\Microsoft.NET\Framework\v4.0.30319` (change .NET version
to fit your installation) to your `PATH`.

We're using the command line (start->run cmd.exe) to
compile and run the code. Alternatively you could use Visual Studio, but
due to the nature of examples we prefer the command line.

### Requirements on Linux

You need Mono and RabbitMQ dotnet client.

    sudo apt-get install mono-devel
    mkdir lib
    cd lib
    wget http://www.rabbitmq.com/releases/rabbitmq-dotnet-client/v3.4.4/rabbitmq-dotnet-client-3.4.4-dotnet-3.5.zip
    unzip rabbitmq-dotnet-client-3.4.4-dotnet-3.5.zip
    cd ..

## Code

#### [Tutorial one: "Hello World!"](http://www.rabbitmq.com/tutorial-one-dotnet.html)

##### Windows

    csc /r:"RabbitMQ.Client.dll" Send.cs
    csc /r:"RabbitMQ.Client.dll" Receive.cs

    Send.exe
    Receive.exe

##### Linux

    gmcs -r:lib/bin/RabbitMQ.Client.dll Send.cs
    gmcs -r:lib/bin/RabbitMQ.Client.dll Receive.cs

    MONO_PATH=lib/bin mono Send.exe
    MONO_PATH=lib/bin mono Receive.exe

#### [Tutorial two: Work Queues](http://www.rabbitmq.com/tutorial-two-dotnet.html)

##### Windows

    csc /r:"RabbitMQ.Client.dll" NewTask.cs
    csc /r:"RabbitMQ.Client.dll" Worker.cs

    NewTask.exe
    Worker.exe

##### Linux

    gmcs -r:lib/bin/RabbitMQ.Client.dll NewTask.cs
    gmcs -r:lib/bin/RabbitMQ.Client.dll Worker.cs

    MONO_PATH=lib/bin mono NewTask.exe
    MONO_PATH=lib/bin mono Worker.exe

#### [Tutorial three: Publish/Subscribe](http://www.rabbitmq.com/tutorial-three-dotnet.html)

##### Windows

    csc /r:"RabbitMQ.Client.dll" ReceiveLogs.cs
    csc /r:"RabbitMQ.Client.dll" EmitLog.cs

    ReceiveLogs.exe
    EmitLog.exe

##### Linux

    gmcs -r:lib/bin/RabbitMQ.Client.dll ReceiveLogs.cs
    gmcs -r:lib/bin/RabbitMQ.Client.dll EmitLog.cs

    MONO_PATH=lib/bin mono ReceiveLogs.exe
    MONO_PATH=lib/bin mono EmitLog.exe

#### [Tutorial four: Routing](http://www.rabbitmq.com/tutorial-four-dotnet.html)

##### Windows

    csc /r:"RabbitMQ.Client.dll" ReceiveLogsDirect.cs
    csc /r:"RabbitMQ.Client.dll" EmitLogDirect.cs

    ReceiveLogsDirect.exe
    EmitLogDirect.exe

##### Linux

    gmcs -r:lib/bin/RabbitMQ.Client.dll ReceiveLogsDirect.cs
    gmcs -r:lib/bin/RabbitMQ.Client.dll EmitLogDirect.cs

    MONO_PATH=lib/bin mono ReceiveLogsDirect.exe
    MONO_PATH=lib/bin mono EmitLogDirect.exe

#### [Tutorial five: Topics](http://www.rabbitmq.com/tutorial-five-dotnet.html)

##### Windows

    csc /r:"RabbitMQ.Client.dll" ReceiveLogsTopic.cs
    csc /r:"RabbitMQ.Client.dll" EmitLogTopic.cs

    ReceiveLogsTopic.exe
    EmitLogTopic.exe

##### Linux

    gmcs -r:lib/bin/RabbitMQ.Client.dll ReceiveLogsTopic.cs
    gmcs -r:lib/bin/RabbitMQ.Client.dll EmitLogTopic.cs

    MONO_PATH=lib/bin mono ReceiveLogsTopic.exe
    MONO_PATH=lib/bin mono EmitLogTopic.exe

#### [Tutorial six: RPC](http://www.rabbitmq.com/tutorial-six-dotnet.html)

##### Windows

    csc /r:"RabbitMQ.Client.dll" RPCServer.cs
    csc /r:"RabbitMQ.Client.dll" RPCClient.cs

    RPCServer.exe
    RPCClient.exe

##### Linux

    gmcs -r:lib/bin/RabbitMQ.Client.dll RPCServer.cs
    gmcs -r:lib/bin/RabbitMQ.Client.dll RPCClient.cs

    MONO_PATH=lib/bin mono RPCServer.exe
    MONO_PATH=lib/bin mono RPCClient.exe

redpajama_set_name: RedPajamaGithub


text:
User.find(:all).each do |user|
  user.plugins.create(:name => "News", :position => (user.plugins.maximum(:position) || -1) + 1)
end

page = Page.create(:title => "News",
            :link_url => "/news",
            :menu_match => "^/news.*$",
            :deletable => false,
            :position => Page.count)

RefinerySetting.find_or_set(:default_page_parts, ["Body", "Side Body"]).each do |default_page_part|
  page.parts.create(:title => default_page_part, :body => nil)
end


text:
import nltk
import sys

# First, some advanced scripting straight from the NLTK book:

class IndexedText(object):
	def __init__(self, stemmer, text):
		self._text = text
		self._stemmer = stemmer
		self._index = nltk.Index((self._stem(word), i)
								for (i, word) in enumerate(text))
	def concordance(self, word, width=40):
		key = self.stem(word)
		wc = width/4			# words of context
		for i in self._index[key]:
			lcontext = ' '.join(self._text[i-wc:i])
			rcontext = ' '.join(self,_text[i:i+wc])
			ldisplay = '%*s' % (width, lcontext[-width:])
			rdisplay = '%*s' % (width, rcontext[:width])
			print ldisplay, rdisplay
	def _stem(self, word):
		return self._stemmer.stem(word).lower()

# Now back to the part where we do things

#  So we get the word from the user:

print "Enter the word you would like to see in context:",
word = raw_input()

# We also need to choose our stemmer:

porter = nltk.PorterStemmer()

# Then we need to transform the base text using a series of steps.
# Please note this could be one line:

thefile = open('mdg.txt')
rawtext = thefile.read()
# tokens = nltk.word_tokenize(rawtext)
processedtext = nltk.corpus.
text = IndexedText(porter,tokens)

# Now we can actually look at a word:

concordstem = text.concordance(word)

print(concordstem)


text:
/*****************************************************************************
 * @(#) nsp_ioctl.h 1.34@(#)
 *****************************************************************************/

/*****************************************************************************/
/** @file nsp_ioctl.h
 *  @brief NSP2000 Device Driver IOCtl handler
 *
 * This header contains the prototype of the common IOCtl handler.
 *
 *****************************************************************************/

/*****************************************************************************
 * Revision history:
 * 04/21/03 brr   Added support for multiple memory banks.
 * 03/20/03 brr   Added debug message selector for queue manager information.
 * 09/18/02 brr   Added IOCTL codes for diagnostics & wait on request complete.
 * 07/17/02 brr   Eliminate unused ioctl codes.
 * 07/02/02 brr   Added IOCTL code for memory statistics.
 * 05/30/02 brr   Moved queue stat structure to n8_enqueue_common & removed
 *                #defines for obsolete ioctl's.
 * 05/20/02 brr   Added stat for preempted requests.
 * 05/15/02 brr   Removed obsolete Ioctl code NSP_IOCTL_QMGR_CHECK_REQ.
 * 04/03/02 spm   Removed remnants of the reverse-ioctl that the daemon
 *                formerly used (start, finish, shutdown).
 * 03/29/02 brr   Removed obsolete defines & strutures.
 * 03/29/02 hml   Added ioctl N8_IOCTL_VALIDATE_CONTEXT.
 * 03/25/02 hml   Deleted obsolete debug bits.
 * 03/22/02 hml   Added new Debug bit for displaying context.
 * 03/21/02 mmd   Added N8_QueueStatistics_t, NSP_IOCTL_QUERY_QUEUE_STATS,
 *                and N8_DBG_QUERY_QUEUE_STATS.
 * 02/18/02 brr   Added new IOCTL's for QMgr functions.
 * 01/22/02 spm   Added sys init ioctl for handling inits that need
 *                the N8 userspace daemon to be connected to the driver.
 * 01/17/02 spm   Added shutdown ioctl for handling shutdown requests
 *                from userspace (uninstall script).  Also added
 *                test ioctls for testing N8 daemon capabilities.
 * 01/15/02 spm   Added NSP_IOCTL_N8_DAEMON_START, NSP_IOCTL_N8_DAEMON_FINISH
 *                ioctls for N8 daemon support.
 * 01/02/02 hml   Modified N8_API_Parms_t structure.
 * 11/10/01 brr   Modified to support static allocations of persistant data
 *                by the driver.
 * 10/16/01 mmd   Revised debug info to a single parm - debug.
 * 09/25/01 mmd   Eliminated FPGAflag parameter.
 * 09/19/01 mmd   Creation.
 ****************************************************************************/
/** @defgroup NSP2000Driver NSP2000 Device Driver IOCtl handler
 */

#ifndef NSP_IOCTL_H
#define NSP_IOCTL_H

#include "n8_device_info.h"
#include "n8_pub_common.h"

/******************************************************************************
 * IOCTL HANDLER RESOURCES -                                                  *
 *                                                                            *
 * ParmStruct is a basic data structure used for passing paramters and        *
 * results between a user process and the ioctl handler on an ioctl call.     *
 * Each supported IOCTL code uses a different combination of the fields, so   *
 * the fields don't necessarily have any intrinsic significance.              *
 *                                                                            *
 * Three additional parameter structures are used in the same way, for some   *
 * of the legacy routines appropriated from Alpha-Data's sample driver, and   *
 * are only used in FPGA mode.                                                *
 *                                                                            *
 * The supported IOCTL codes are defined here as constants. There's no        *
 * particular significance to their actual values, beyond each constant being *
 * unique.                                                                    *
 *                                                                            *
 ******************************************************************************/

/* GENERIC IOCtl PARAMETER STRUCTURE */
typedef struct
{
     unsigned char    coretype;
     unsigned long    bitmask;
     unsigned long    timeout;
     N8_Unit_t        chip;
     unsigned char    invalid_handle;
     unsigned long    contextIndex;
     unsigned long    irqstatus;
} PARMSTRUCT_t;

/* IOCtl COMMAND CODES */
#define NSP_IOCTL_GET_DEVICE_RESOURCES 21
#define NSP_IOCTL_ALLOCATE_USER_POOL   26
#define NSP_IOCTL_ALLOCATE_BUFFER      27
#define NSP_IOCTL_FREE_BUFFER          28
#define NSP_IOCTL_MEMORY_STATS         30
#define NSP_IOCTL_WAIT_ON_INTERRUPT    31
#define NSP_IOCTL_WAIT_ON_REQUEST      32
#define NSP_IOCTL_DEBUG_MESSAGES       34

#define NSP_IOCTL_ALLOCATE_BUFFER_PK   35
#define NSP_IOCTL_FREE_BUFFER_PK       36

#define NSP_IOCTL_N8_DAEMON_SYS_INIT   39
#define NSP_IOCTL_ALLOCATE_CONTEXT     40
#define NSP_IOCTL_FREE_CONTEXT         41
#define NSP_IOCTL_QMGR_QUEUE           42
#define NSP_IOCTL_RN_QUEUE             44
#define NSP_IOCTL_RN_SET_PARMS         45
#define NSP_IOCTL_RN_GET_PARMS         46
#define NSP_IOCTL_SKS_WRITE            47
#define NSP_IOCTL_SKS_RESET_UNIT       48
#define NSP_IOCTL_SKS_ALLOCATE         49
#define NSP_IOCTL_SKS_SET_STATUS       50
#define NSP_IOCTL_QUERY_QUEUE_STATS    51
#define NSP_IOCTL_VALIDATE_CONTEXT     52
#define NSP_IOCTL_DIAGNOSTIC           53

/* CORE SELECTORS FOR IOCtl PARAMETERS */
#define N8_DAPI_PKE             1
#define N8_DAPI_RNG             2
#define N8_DAPI_EA              4
#define N8_DAPI_AMBA            8

/* DEBUG MESSAGE BIT SELECTORS */
#define N8_DBG_GENERAL            1
#define N8_DBG_IRQ                2
#define N8_DBG_BIGALLOC           4
#define N8_DBG_DISPLAY_MEMORY     8
#define N8_DBG_DISPLAY_CONTEXT    16
#define N8_DBG_DISPLAY_REGISTERS  32
#define N8_DBG_DISPLAY_QMGR       64

#endif   /* NSP_IOCTL_H */


text:
package raft

import (
	"bytes"
	"reflect"
	"testing"
	"time"

	"github.com/coreos/etcd/pkg/testutil"
	"github.com/coreos/etcd/raft/raftpb"
	"golang.org/x/net/context"
)

// TestNodeStep ensures that node.Step sends msgProp to propc chan
// and other kinds of messages to recvc chan.
func TestNodeStep(t *testing.T) {
	for i, msgn := range raftpb.MessageType_name {
		n := &node{
			propc: make(chan raftpb.Message, 1),
			recvc: make(chan raftpb.Message, 1),
		}
		msgt := raftpb.MessageType(i)
		n.Step(context.TODO(), raftpb.Message{Type: msgt})
		// Proposal goes to proc chan. Others go to recvc chan.
		if msgt == raftpb.MsgProp {
			select {
			case <-n.propc:
			default:
				t.Errorf("%d: cannot receive %s on propc chan", msgt, msgn)
			}
		} else {
			if IsLocalMsg(msgt) {
				select {
				case <-n.recvc:
					t.Errorf("%d: step should ignore %s", msgt, msgn)
				default:
				}
			} else {
				select {
				case <-n.recvc:
				default:
					t.Errorf("%d: cannot receive %s on recvc chan", msgt, msgn)
				}
			}
		}
	}
}

// Cancel and Stop should unblock Step()
func TestNodeStepUnblock(t *testing.T) {
	// a node without buffer to block step
	n := &node{
		propc: make(chan raftpb.Message),
		done:  make(chan struct{}),
	}

	ctx, cancel := context.WithCancel(context.Background())
	stopFunc := func() { close(n.done) }

	tests := []struct {
		unblock func()
		werr    error
	}{
		{stopFunc, ErrStopped},
		{cancel, context.Canceled},
	}

	for i, tt := range tests {
		errc := make(chan error, 1)
		go func() {
			err := n.Step(ctx, raftpb.Message{Type: raftpb.MsgProp})
			errc <- err
		}()
		tt.unblock()
		select {
		case err := <-errc:
			if err != tt.werr {
				t.Errorf("#%d: err = %v, want %v", i, err, tt.werr)
			}
			//clean up side-effect
			if ctx.Err() != nil {
				ctx = context.TODO()
			}
			select {
			case <-n.done:
				n.done = make(chan struct{})
			default:
			}
		case <-time.After(1 * time.Second):
			t.Fatalf("#%d: failed to unblock step", i)
		}
	}
}

// TestNodePropose ensures that node.Propose sends the given proposal to the underlying raft.
func TestNodePropose(t *testing.T) {
	msgs := []raftpb.Message{}
	appendStep := func(r *raft, m raftpb.Message) {
		msgs = append(msgs, m)
	}

	n := newNode()
	s := NewMemoryStorage()
	r := newTestRaft(1, []uint64{1}, 10, 1, s)
	go n.run(r)
	n.Campaign(context.TODO())
	for {
		rd := <-n.Ready()
		s.Append(rd.Entries)
		// change the step function to appendStep until this raft becomes leader
		if rd.SoftState.Lead == r.id {
			r.step = appendStep
			n.Advance()
			break
		}
		n.Advance()
	}
	n.Propose(context.TODO(), []byte("somedata"))
	n.Stop()

	if len(msgs) != 1 {
		t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
	}
	if msgs[0].Type != raftpb.MsgProp {
		t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
	}
	if !bytes.Equal(msgs[0].Entries[0].Data, []byte("somedata")) {
		t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, []byte("somedata"))
	}
}

// TestNodeReadIndex ensures that node.ReadIndex sends the MsgReadIndex message to the underlying raft.
// It also ensures that ReadState can be read out through ready chan.
func TestNodeReadIndex(t *testing.T) {
	msgs := []raftpb.Message{}
	appendStep := func(r *raft, m raftpb.Message) {
		msgs = append(msgs, m)
	}
	wreadIndex := uint64(1)
	wrequestCtx := []byte("somedata")

	n := newNode()
	s := NewMemoryStorage()
	r := newTestRaft(1, []uint64{1}, 10, 1, s)
	r.readState.Index = wreadIndex
	r.readState.RequestCtx = wrequestCtx
	go n.run(r)
	n.Campaign(context.TODO())
	for {
		rd := <-n.Ready()
		if rd.Index != wreadIndex {
			t.Errorf("ReadIndex = %d, want %d", rd.Index, wreadIndex)
		}

		if !bytes.Equal(rd.RequestCtx, wrequestCtx) {
			t.Errorf("RequestCtx = %v, want %v", rd.RequestCtx, wrequestCtx)
		}

		s.Append(rd.Entries)

		if rd.SoftState.Lead == r.id {
			n.Advance()
			break
		}
		n.Advance()
	}

	r.step = appendStep
	wrequestCtx = []byte("somedata2")
	n.ReadIndex(context.TODO(), wrequestCtx)
	n.Stop()

	if len(msgs) != 1 {
		t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
	}
	if msgs[0].Type != raftpb.MsgReadIndex {
		t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgReadIndex)
	}
	if !bytes.Equal(msgs[0].Entries[0].Data, wrequestCtx) {
		t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, wrequestCtx)
	}
}

// TestNodeProposeConfig ensures that node.ProposeConfChange sends the given configuration proposal
// to the underlying raft.
func TestNodeProposeConfig(t *testing.T) {
	msgs := []raftpb.Message{}
	appendStep := func(r *raft, m raftpb.Message) {
		msgs = append(msgs, m)
	}

	n := newNode()
	s := NewMemoryStorage()
	r := newTestRaft(1, []uint64{1}, 10, 1, s)
	go n.run(r)
	n.Campaign(context.TODO())
	for {
		rd := <-n.Ready()
		s.Append(rd.Entries)
		// change the step function to appendStep until this raft becomes leader
		if rd.SoftState.Lead == r.id {
			r.step = appendStep
			n.Advance()
			break
		}
		n.Advance()
	}
	cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
	ccdata, err := cc.Marshal()
	if err != nil {
		t.Fatal(err)
	}
	n.ProposeConfChange(context.TODO(), cc)
	n.Stop()

	if len(msgs) != 1 {
		t.Fatalf("len(msgs) = %d, want %d", len(msgs), 1)
	}
	if msgs[0].Type != raftpb.MsgProp {
		t.Errorf("msg type = %d, want %d", msgs[0].Type, raftpb.MsgProp)
	}
	if !bytes.Equal(msgs[0].Entries[0].Data, ccdata) {
		t.Errorf("data = %v, want %v", msgs[0].Entries[0].Data, ccdata)
	}
}

// TestBlockProposal ensures that node will block proposal when it does not
// know who is the current leader; node will accept proposal when it knows
// who is the current leader.
func TestBlockProposal(t *testing.T) {
	n := newNode()
	r := newTestRaft(1, []uint64{1}, 10, 1, NewMemoryStorage())
	go n.run(r)
	defer n.Stop()

	errc := make(chan error, 1)
	go func() {
		errc <- n.Propose(context.TODO(), []byte("somedata"))
	}()

	testutil.WaitSchedule()
	select {
	case err := <-errc:
		t.Errorf("err = %v, want blocking", err)
	default:
	}

	n.Campaign(context.TODO())
	select {
	case err := <-errc:
		if err != nil {
			t.Errorf("err = %v, want %v", err, nil)
		}
	case <-time.After(10 * time.Second):
		t.Errorf("blocking proposal, want unblocking")
	}
}

// TestNodeTick ensures that node.Tick() will increase the
// elapsed of the underlying raft state machine.
func TestNodeTick(t *testing.T) {
	n := newNode()
	s := NewMemoryStorage()
	r := newTestRaft(1, []uint64{1}, 10, 1, s)
	go n.run(r)
	elapsed := r.electionElapsed
	n.Tick()
	testutil.WaitSchedule()
	n.Stop()
	if r.electionElapsed != elapsed+1 {
		t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
	}
}

// TestNodeStop ensures that node.Stop() blocks until the node has stopped
// processing, and that it is idempotent
func TestNodeStop(t *testing.T) {
	n := newNode()
	s := NewMemoryStorage()
	r := newTestRaft(1, []uint64{1}, 10, 1, s)
	donec := make(chan struct{})

	go func() {
		n.run(r)
		close(donec)
	}()

	elapsed := r.electionElapsed
	n.Tick()
	testutil.WaitSchedule()
	n.Stop()

	select {
	case <-donec:
	case <-time.After(time.Second):
		t.Fatalf("timed out waiting for node to stop!")
	}

	if r.electionElapsed != elapsed+1 {
		t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
	}
	// Further ticks should have no effect, the node is stopped.
	n.Tick()
	if r.electionElapsed != elapsed+1 {
		t.Errorf("elapsed = %d, want %d", r.electionElapsed, elapsed+1)
	}
	// Subsequent Stops should have no effect.
	n.Stop()
}

func TestReadyContainUpdates(t *testing.T) {
	tests := []struct {
		rd       Ready
		wcontain bool
	}{
		{Ready{}, false},
		{Ready{SoftState: &SoftState{Lead: 1}}, true},
		{Ready{HardState: raftpb.HardState{Vote: 1}}, true},
		{Ready{Entries: make([]raftpb.Entry, 1, 1)}, true},
		{Ready{CommittedEntries: make([]raftpb.Entry, 1, 1)}, true},
		{Ready{Messages: make([]raftpb.Message, 1, 1)}, true},
		{Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}, true},
	}

	for i, tt := range tests {
		if g := tt.rd.containsUpdates(); g != tt.wcontain {
			t.Errorf("#%d: containUpdates = %v, want %v", i, g, tt.wcontain)
		}
	}
}

// TestNodeStart ensures that a node can be started correctly. The node should
// start with correct configuration change entries, and can accept and commit
// proposals.
func TestNodeStart(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	cc := raftpb.ConfChange{Type: raftpb.ConfChangeAddNode, NodeID: 1}
	ccdata, err := cc.Marshal()
	if err != nil {
		t.Fatalf("unexpected marshal error: %v", err)
	}
	wants := []Ready{
		{
			HardState: raftpb.HardState{Term: 1, Commit: 1, Vote: 0},
			Entries: []raftpb.Entry{
				{Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
			},
			CommittedEntries: []raftpb.Entry{
				{Type: raftpb.EntryConfChange, Term: 1, Index: 1, Data: ccdata},
			},
		},
		{
			HardState:        raftpb.HardState{Term: 2, Commit: 3, Vote: 1},
			Entries:          []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
			CommittedEntries: []raftpb.Entry{{Term: 2, Index: 3, Data: []byte("foo")}},
		},
	}
	storage := NewMemoryStorage()
	c := &Config{
		ID:              1,
		ElectionTick:    10,
		HeartbeatTick:   1,
		Storage:         storage,
		MaxSizePerMsg:   noLimit,
		MaxInflightMsgs: 256,
	}
	n := StartNode(c, []Peer{{ID: 1}})
	defer n.Stop()
	g := <-n.Ready()
	if !reflect.DeepEqual(g, wants[0]) {
		t.Fatalf("#%d: g = %+v,\n             w   %+v", 1, g, wants[0])
	} else {
		storage.Append(g.Entries)
		n.Advance()
	}

	n.Campaign(ctx)
	rd := <-n.Ready()
	storage.Append(rd.Entries)
	n.Advance()

	n.Propose(ctx, []byte("foo"))
	if g2 := <-n.Ready(); !reflect.DeepEqual(g2, wants[1]) {
		t.Errorf("#%d: g = %+v,\n             w   %+v", 2, g2, wants[1])
	} else {
		storage.Append(g2.Entries)
		n.Advance()
	}

	select {
	case rd := <-n.Ready():
		t.Errorf("unexpected Ready: %+v", rd)
	case <-time.After(time.Millisecond):
	}
}

func TestNodeRestart(t *testing.T) {
	entries := []raftpb.Entry{
		{Term: 1, Index: 1},
		{Term: 1, Index: 2, Data: []byte("foo")},
	}
	st := raftpb.HardState{Term: 1, Commit: 1}

	want := Ready{
		HardState: st,
		// commit up to index commit index in st
		CommittedEntries: entries[:st.Commit],
	}

	storage := NewMemoryStorage()
	storage.SetHardState(st)
	storage.Append(entries)
	c := &Config{
		ID:              1,
		ElectionTick:    10,
		HeartbeatTick:   1,
		Storage:         storage,
		MaxSizePerMsg:   noLimit,
		MaxInflightMsgs: 256,
	}
	n := RestartNode(c)
	defer n.Stop()
	if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
		t.Errorf("g = %+v,\n             w   %+v", g, want)
	}
	n.Advance()

	select {
	case rd := <-n.Ready():
		t.Errorf("unexpected Ready: %+v", rd)
	case <-time.After(time.Millisecond):
	}
}

func TestNodeRestartFromSnapshot(t *testing.T) {
	snap := raftpb.Snapshot{
		Metadata: raftpb.SnapshotMetadata{
			ConfState: raftpb.ConfState{Nodes: []uint64{1, 2}},
			Index:     2,
			Term:      1,
		},
	}
	entries := []raftpb.Entry{
		{Term: 1, Index: 3, Data: []byte("foo")},
	}
	st := raftpb.HardState{Term: 1, Commit: 3}

	want := Ready{
		HardState: st,
		// commit up to index commit index in st
		CommittedEntries: entries,
	}

	s := NewMemoryStorage()
	s.SetHardState(st)
	s.ApplySnapshot(snap)
	s.Append(entries)
	c := &Config{
		ID:              1,
		ElectionTick:    10,
		HeartbeatTick:   1,
		Storage:         s,
		MaxSizePerMsg:   noLimit,
		MaxInflightMsgs: 256,
	}
	n := RestartNode(c)
	defer n.Stop()
	if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
		t.Errorf("g = %+v,\n             w   %+v", g, want)
	} else {
		n.Advance()
	}

	select {
	case rd := <-n.Ready():
		t.Errorf("unexpected Ready: %+v", rd)
	case <-time.After(time.Millisecond):
	}
}

func TestNodeAdvance(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	storage := NewMemoryStorage()
	c := &Config{
		ID:              1,
		ElectionTick:    10,
		HeartbeatTick:   1,
		Storage:         storage,
		MaxSizePerMsg:   noLimit,
		MaxInflightMsgs: 256,
	}
	n := StartNode(c, []Peer{{ID: 1}})
	defer n.Stop()
	rd := <-n.Ready()
	storage.Append(rd.Entries)
	n.Advance()

	n.Campaign(ctx)
	<-n.Ready()

	n.Propose(ctx, []byte("foo"))
	select {
	case rd = <-n.Ready():
		t.Fatalf("unexpected Ready before Advance: %+v", rd)
	case <-time.After(time.Millisecond):
	}
	storage.Append(rd.Entries)
	n.Advance()
	select {
	case <-n.Ready():
	case <-time.After(100 * time.Millisecond):
		t.Errorf("expect Ready after Advance, but there is no Ready available")
	}
}

func TestSoftStateEqual(t *testing.T) {
	tests := []struct {
		st *SoftState
		we bool
	}{
		{&SoftState{}, true},
		{&SoftState{Lead: 1}, false},
		{&SoftState{RaftState: StateLeader}, false},
	}
	for i, tt := range tests {
		if g := tt.st.equal(&SoftState{}); g != tt.we {
			t.Errorf("#%d, equal = %v, want %v", i, g, tt.we)
		}
	}
}

func TestIsHardStateEqual(t *testing.T) {
	tests := []struct {
		st raftpb.HardState
		we bool
	}{
		{emptyState, true},
		{raftpb.HardState{Vote: 1}, false},
		{raftpb.HardState{Commit: 1}, false},
		{raftpb.HardState{Term: 1}, false},
	}

	for i, tt := range tests {
		if isHardStateEqual(tt.st, emptyState) != tt.we {
			t.Errorf("#%d, equal = %v, want %v", i, isHardStateEqual(tt.st, emptyState), tt.we)
		}
	}
}


text:
EXEC_DIR=$(cd $(dirname "$0") && pwd)

CMDNAME=$(basename $0); CMD=$1

########################################
# Functions
########################################
function usage() {
    cat <<EOF

Usage:
    $CMDNAME subcommand

The command line tool to deploy a RACK environment and execute an OpenStack-Native application.

Subcommand:
    deploy            Deploy a rack-api and a rack-proxy.
    image-create      Create an application image.
    run               Create an application image and then run an application.

EOF
    exit 1
}

### Deploy a rack-api and a rack-proxy
function deploy() {
    source $EXEC_DIR/lib/deploy
}

### Create an application image
function image_create() {
    source $EXEC_DIR/lib/image-create
}

### Run an application
function run() {
    source $EXEC_DIR/lib/run
}

########################################
# Source functions and configuration variables
########################################
source $EXEC_DIR/deployrc
source $EXEC_DIR/apprc
source $EXEC_DIR/lib/functions

! [ -e $EXEC_DIR/deployrc -a -e $EXEC_DIR/apprc ] && usage

########################################
# Main
########################################
trap end_process EXIT
trap 'trap - EXIT; end_process error; exit -1' HUP INT TERM

case "$CMD" in
    deploy)
        deploy
         ;;
    image-create)
        image_create
         ;;
    run)
        run
         ;;
     *)
        usage
         ;;
esac


text:
<?php

return [
    /**
     * The message entity to use
     * Default: Eye4web\ZfcUser\Pm\Entity\Message
     */
    //'messageEntity' => 'Eye4web\ZfcUser\Pm\Entity\Message',

    /**
     * The conversation entity to use
     * Default: Eye4web\ZfcUser\Pm\Entity\Conversation
     */
    //'conversationEntity' => 'Eye4web\ZfcUser\Pm\Entity\Conversation',

    /**
     * The conversation receiver entity to use
     * Default: Eye4web\ZfcUser\Pm\Entity\ConversationReceiver
     */
    //'conversationReceiverEntity' => 'Eye4web\ZfcUser\Pm\Entity\ConversationReceiver',

    /**
     * The mapper to use
     * Default: Eye4web\ZfcUser\Pm\Mapper\DoctrineORM\PmMapper
     */
    //'pmMapper' => 'Eye4web\ZfcUser\Pm\Mapper\DoctrineORM\PmMapper',

    /**
     * Sort order when reading a conversation
     * Default: DESC (newest in top)
     */
    //'messageSortOrder' => 'DESC',

    /**
     * Number of messages pr. page when reading a conversation
     * Default: 50
     */
    //'messagesPerPage' => 50,

    /**
     * Number of conversations pr. page in the list
     * Default: 20
     */
    //'conversationsPerPage' => 20,
];


text:
class Vote < ActiveRecord::Base
	belongs_to :entry
	belongs_to :user
end


text:
<?php
namespace Pyrus\PackageFile\v2;
class UsesRoleTask implements \ArrayAccess, \Iterator, \Countable
{
    protected $parent;
    protected $info;
    protected $type;
    protected $index;

    function __construct($parent, array $info, $type, $index = null)
    {
        $this->parent = $parent;
        $this->info = $info;
        $this->type = $type;
        $this->index = $index;
    }

    function current()
    {
        $info = current($this->info);
        foreach (array($this->type, 'package', 'channel', 'uri') as $key) {
            if (!array_key_exists($key, $info)) {
                $info[$key] = null;
            }
        }

        return new UsesRoleTask($this, $info, $this->type, key($this->info));
    }

    function count()
    {
        return count($this->info);
    }

    function rewind()
    {
        reset($this->info);
    }

    function key()
    {
        $info = current($this->info);
        return $info[$this->type];
    }

    function next()
    {
        return next($this->info);
    }

    function valid()
    {
        return current($this->info);
    }

    function locateRoleTask($name)
    {
        foreach ($this->info as $i => $dep) {
            if (isset($dep[$this->type]) && $dep[$this->type] == $name) {
                return $i;
            }
        }

        return false;
    }

    function offsetGet($var)
    {
        if ($this->index !== null) {
            throw new UsesRoleTask\Exception(
                'use -> operator to access properties of a uses' . $this->type);
        }

        $i = $this->locateRoleTask($var);
        if (false === $i) {
            $i = count($this->info);
            $info = array($this->type => $var, 'package' => null, 'channel' => null, 'uri' => null);
        } else {
            $info = $this->info[$i];
            foreach (array($this->type, 'package', 'channel', 'uri') as $key) {
                if (!array_key_exists($key, $this->info[$i])) {
                    $info[$key] = null;
                }
            }
        }

        return new UsesRoleTask($this, $info, $this->type, $i);
    }

    function offsetSet($var, $value)
    {
        if ($this->index !== null) {
            throw new UsesRoleTask\Exception(
                'use -> operator to access properties of a uses' . $this->type);
        }

        if (!($value instanceof UsesRoleTask)) {
            throw new UsesRoleTask\Exception(
                'Can only set uses' . $this->type . ' to a \Pyrus\PackageFile\v2\UsesRoleTask object');
        }

        if ($value->type != $this->type) {
            throw new UsesRoleTask\Exception(
                'Cannot set uses' . $this->type . ' to a uses' . $value->type . ' object');
        }

        $i = $this->locateRoleTask($var);
        if (false === $i) {
            $i = count($this->info);
        }

        $this->info[$i] = array($this->type => $var,
                                'package' => $value->package,
                                'channel' => $value->channel,
                                'uri' => $value->uri);
        $this->save();
    }

    function offsetExists($var)
    {
        if ($this->index !== null) {
            throw new UsesRoleTask\Exception(
                'use -> operator to access properties of a uses' . $this->type);
        }

        $i = $this->locateRoleTask($var);
        return $i !== false;
    }

    function offsetUnset($var)
    {
        if ($this->index !== null) {
            throw new UsesRoleTask\Exception(
                'use -> operator to access properties of a uses' . $this->type);
        }

        $i = $this->locateRoleTask($var);
        if ($i === false) {
            return;
        }

        unset($this->info[$i]);
        $this->info = array_values($this->info);
        $this->save();
    }

    function __unset($var)
    {
        if ($this->index === null) {
            throw new UsesRoleTask\Exception('use [] operator to access uses' . $this->type . 's');
        }

        if (!array_key_exists($var, $this->info)) {
            throw new UsesRoleTask\Exception(
                'Unknown variable ' . $var . ' requested, should be one of ' .
                implode(', ', array_keys($this->info))
            );
        }

        $this->info[$var] = null;
        $this->save();
    }

    function __isset($var)
    {
        if ($this->index === null) {
            throw new UsesRoleTask\Exception('use [] operator to access uses' . $this->type . 's');
        }

        if (!array_key_exists($var, $this->info)) {
            throw new UsesRoleTask\Exception(
                'Unknown variable ' . $var . ' requested, should be one of ' .
                implode(', ', array_keys($this->info))
            );
        }

        return isset($this->info[$var]);
    }

    function __set($var, $value)
    {
        return $this->__call($var, array($value));
    }

    function __call($var, $args)
    {
        if ($this->index === null) {
            throw new UsesRoleTask\Exception('use [] operator to access uses' . $this->type . 's');
        }

        if (!array_key_exists($var, $this->info)) {
            throw new UsesRoleTask\Exception('Unknown variable ' . $var . ', must be one of ' .
                            implode(', ', array_keys($this->info)));
        }

        if ($args[0] === null) {
            $this->info[$var] = null;
            $this->save();
            return $this;
        }

        if ($var === 'channel' || $var === 'package') {
            $this->info['uri'] = null;
        } elseif ($var === 'uri') {
            $this->info['channel'] = null;
            $this->info['package'] = null;
        }

        $this->info[$var] = $args[0];
        $this->save();
        return $this;
    }

    function __get($var)
    {
        if ($this->index === null) {
            throw new UsesRoleTask\Exception('use [] operator to access uses' . $this->type . 's');
        }

        if ($var === 'type') {
            return 'uses' . $this->type;
        }

        if (!array_key_exists($var, $this->info)) {
            throw new UsesRoleTask\Exception('Unknown variable ' . $var . ', must be one of ' .
                            implode(', ', array_keys($this->info)));
        }

        if (!isset($this->info[$var])) {
            return null;
        }

        return $this->info[$var];
    }

    function getInfo()
    {
        return $this->info;
    }

    function setInfo($info, $index)
    {
        foreach (array_keys($info) as $key) {
            if ($info[$key] === null) {
                unset($info[$key]);
            }
        }

        $this->info[$index] = $info;
    }

    function save()
    {
        if ($this->parent instanceof self) {
            $this->parent->setInfo($this->info, $this->index);
            $this->parent->save();
            return;
        }

        $info = $this->info;
        if (count($info) == 1) {
            $info = $info[0];
        }

        $this->parent->{'rawuses' . $this->type} = $info;
    }
}


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

    The MIT License (MIT)

    Copyright (c) 2013 Olexandr Tyshkovets <olexandr.tyshkovets@gmail.com>

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.

-->
<dataset>
    <feed_entry feed_entry_id="1"
                uuid="8h4ne2l1-b20jr-9d63ls-0cz2-lk730fnmqp1"
                author="Joshua Bloch"
                description="Effective Java. Chapter 1"
                link="http://effectivejava.com/1"
                published_date="2013-06-10"
                title="Chapter 1"
                fk_feed="1" />
</dataset>


text:
/*
 * Created on May 5, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

package edu.wustl.common.struts;

import java.io.ObjectInputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.TilesRequestProcessor;

import edu.wustl.common.util.global.Constants;
import edu.wustl.common.util.logger.Logger;

/**
 * @author kapil_kaveeshwar
 *
 * TODO To change the template for this generated type comment go to Window - Preferences - Java -
 * Code Style - Code Templates
 */
public class ApplicationRequestProcessor extends TilesRequestProcessor
{

	public ApplicationRequestProcessor()
	{
	}

	protected ActionForm processActionForm(HttpServletRequest request,
			HttpServletResponse response, ActionMapping mapping)
	{
		Logger.out.debug("contentType " + request.getContentType());
		if (request.getContentType() != null && request.getContentType().equals(Constants.HTTP_API))
		{
			try
			{
				ObjectInputStream ois = new ObjectInputStream(request.getInputStream());
				HTTPWrapperObject wrapperObject = (HTTPWrapperObject)ois.readObject();

				String operation = wrapperObject.getOperation();

				ActionForm form = wrapperObject.getForm();

				if(operation.equals(Constants.LOGIN))
				{
					request.setAttribute(Constants.OPERATION,Constants.LOGIN);
				}
				else if(operation.equals(Constants.LOGOUT))
				{
				    request.setAttribute(Constants.OPERATION,Constants.LOGOUT);
				}
				else
				{
					request.setAttribute(Constants.OPERATION,operation);
				}

				Logger.out.debug("mapping.getAttribute() " + mapping.getAttribute());

				if ("request".equals(mapping.getScope()))
				{
				    if(form !=null)
					{
				        request.setAttribute(mapping.getAttribute(), form);
					}
				}
				else
				{
					HttpSession session = request.getSession();

					if(form !=null)
					{
					    session.setAttribute(mapping.getAttribute(), form);
					}
				}
				return form;
			}
			catch (Exception e)
			{
				Logger.out.debug(e.getMessage(), e);
			}
			return null;
		}
		else
		{
			return super.processActionForm(request, response, mapping);
		}
	}

	protected void processPopulate(HttpServletRequest request, HttpServletResponse response,
			ActionForm form, ActionMapping mapping) throws ServletException
	{
		if (request.getContentType() != null && request.getContentType().equals(Constants.HTTP_API))
		{

		}
		else
		{
			super.processPopulate(request,  response, form,  mapping);
		}
	}
}


text:
package androcal.example;

import android.app.Activity;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import androcal.provider.EventsDO;
import androcal.provider.EventsDAO;
import cpp_skywell.androcal.R;

public class AddCalendarEventActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_calendar_event);
    }

    public void onStart() {
        super.onStart();
        final EditText eventNameEdit = (EditText) findViewById(R.id.txtEventName);
        final EditText startDate = (EditText) findViewById(R.id.txtDateStart);
        final EditText endDate = (EditText) findViewById(R.id.txtDateEnd);
        final EditText startTime = (EditText) findViewById(R.id.txtTimeStart);
        final EditText endTime = (EditText) findViewById(R.id.txtTimeEnd);

        startDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateDialog dialog = new DateDialog();
                dialog.setDate(startDate);
                android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
                eventNameEdit.clearFocus();
                dialog.show(ft, "DatePicker");
            }
        });
        endDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DateDialog dialog = new DateDialog();
                dialog.setDate(endDate);
                android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
                eventNameEdit.clearFocus();
                dialog.show(ft, "DatePicker");
            }
        });
        startTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimeDialog dialog = new TimeDialog();
                dialog.setEventTime(startTime);
                android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
                eventNameEdit.clearFocus();
                dialog.show(ft, "TimePicker");
            }
        });
        endTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimeDialog dialog = new TimeDialog();
                dialog.setEventTime(endTime);
                android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
                eventNameEdit.clearFocus();
                dialog.show(ft, "TimePicker");
            }
        });
        eventNameEdit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
    }

    public void onClickAddEventToCalendar(View view) {
        final EditText eventNameEdit = (EditText) findViewById(R.id.txtEventName);
        final EditText evenStartDateEdit = (EditText) findViewById(R.id.txtDateStart);
        final EditText evenStartTimeEdit = (EditText) findViewById(R.id.txtTimeStart);
        final EditText evenEndDateEdit = (EditText) findViewById(R.id.txtDateEnd);
        final EditText evenEndTimeEdit = (EditText) findViewById(R.id.txtTimeEnd);

        String eventName = eventNameEdit.getText().toString();
        String evenStart = evenStartDateEdit.getText().toString() + " " + evenStartTimeEdit.getText().toString();
        String evenEnd = evenEndDateEdit.getText().toString() + " " + evenEndTimeEdit.getText().toString();

        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm");
        try {
            Date eventStartDate = formatter.parse(evenStart);
            Date eventEndDate = formatter.parse(evenEnd);
            EventsDO event = new EventsDO();

            event.setName(eventName);
            event.setStart(eventStartDate);
            event.setEnd(eventEndDate);
            event.setRefId("");
            event.setSource(EventsDO.Source.NONE);
            event.setStatus(EventsDO.STATUS_NORMAL);
            event.setDirty(true);

//            EventsDAO eventsDAO = EventsDAOFactory.create(this.getApplicationContext());
            EventsDAO eventsDAO = new EventsDAO(this.getContentResolver());
            long rowId = eventsDAO.add(event);

            // DEBUG custom fields
//            event.setId(rowId);
//            event.setCustomValue("ckey1", "cvalue1");
//            event.setCustomValue("ckey2", "cvalue2");
//            eventsDAO.addCustomFields(event);

            showMessage(rowId, view);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void showMessage(long rowId, View view) {
        String msg = "";
        if (rowId > 0) {
            msg = "You have successfully added event!";
        } else {
            msg = "Something went wrong, please try again.";
        }
        Snackbar messageSnackbar = Snackbar.make(view, msg, Snackbar.LENGTH_SHORT);
        messageSnackbar.show();
    }

    public void hideKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Simple File Upload JS API Test Suite</title>

  <link rel="stylesheet" href="../libs/qunit/qunit.css" media="screen">

Simple File Upload JS API Test Suite

    lame test markup
    normal test markup
    awesome test markup


text:
/// <reference types="node" />
import http = require("http");
import Contracts = require("../Declarations/Contracts");
import RequestParser = require("./RequestParser");
import Tracestate = require("../Library/Tracestate");
import Traceparent = require("../Library/Traceparent");
/**
 * Helper class to read data from the requst/response objects and convert them into the telemetry contract
 */
declare class HttpRequestParser extends RequestParser {
    private static keys;
    private rawHeaders;
    private socketRemoteAddress;
    private connectionRemoteAddress;
    private legacySocketRemoteAddress;
    private userAgent;
    private sourceCorrelationId;
    private parentId;
    private operationId;
    private requestId;
    private traceparent;
    private tracestate;
    private legacyRootId;
    private correlationContextHeader;
    constructor(request: http.IncomingMessage, requestId?: string);
    onError(error: Error | string, ellapsedMilliseconds?: number): void;
    onResponse(response: http.ServerResponse, ellapsedMilliseconds?: number): void;
    getRequestTelemetry(baseTelemetry?: Contracts.Telemetry): Contracts.RequestTelemetry;
    getRequestTags(tags: {
        [key: string]: string;
    }): {
        [key: string]: string;
    };
    getOperationId(tags: {
        [key: string]: string;
    }): string;
    getOperationParentId(tags: {
        [key: string]: string;
    }): string;
    getOperationName(tags: {
        [key: string]: string;
    }): string;
    getRequestId(): string;
    getCorrelationContextHeader(): string;
    getTraceparent(): Traceparent;
    getTracestate(): Tracestate;
    getLegacyRootId(): string;
    private _getAbsoluteUrl(request);
    private _getIp();
    private _getId(name);
    /**
     * Sets this operation's operationId, parentId, requestId (and legacyRootId, if necessary) based on this operation's traceparent
     */
    private setBackCompatFromThisTraceContext();
    private parseHeaders(request, requestId?);
    static parseId(cookieValue: string): string;
}
export = HttpRequestParser;


text:
$(function(){
	var useremail;
	$(".manuactivate").on("show.bs.modal", function (event){
		var button = $(event.relatedTarget);
		var content = button.data('whatever');
		var modal = $(this);
		modal.find('.modaluseremail').text(content);
		useremail = content;
		//alert("EMAIL: "+useremail);
	});
	$("#confirmactivate").click(function(){
		//alert("DATA: "+useremail);
		$.post("admin/php/customerManage/manuactivate.php", { usermail: useremail }, function (data, textStatus){
			if(data == "Success") {
				alert("激活成功!");
				window.location.reload();
			}
		});
	});
});


text:
layout: default
---

{% if page.header.overlay_color or page.header.overlay_image or page.header.image %}
  {% include page__hero.html %}
{% elsif page.header.video.id and page.header.video.provider %}
  {% include page__hero_video.html %}
{% endif %}

{% if page.url != "/" and site.breadcrumbs %}
  {% unless paginator %}
    {% include breadcrumbs.html %}
  {% endunless %}
{% endif %}

  {% include sidebar.html %}

    {% if page.title %}<meta itemprop="headline" content="{{ page.title | markdownify | strip_html | strip_newlines | escape_once }}">{% endif %}
    {% if page.excerpt %}<meta itemprop="description" content="{{ page.excerpt | markdownify | strip_html | strip_newlines | escape_once }}">{% endif %}
    {% if page.date %}<meta itemprop="datePublished" content="{{ page.date | date: "%B %d, %Y" }}">{% endif %}
    {% if page.last_modified_at %}<meta itemprop="dateModified" content="{{ page.last_modified_at | date: "%B %d, %Y" }}">{% endif %}

BACK TO POSTS

      {% unless page.header.overlay_color or page.header.overlay_image %}

          {% if page.title %}
{{ page.title | markdownify | remove: "
" | remove: "
" }}
{% endif %}

          {% if page.author %}
            AUTHOR:  {{ page.author }}

          {% endif %}
          {% if page.last_modified_at %}
          UPDATED: <time datetime="{{ page.last_modified_at | date: "%Y-%m-%d" }}">{{ page.last_modified_at | date: "%B %d, %Y" }}</time>
         {% elsif page.date %}
           UPDATED: <time datetime="{{ page.date | date_to_xmlschema }}">{{ page.date | date: "%B %d, %Y" }}</time>
          {% endif %}
          {% if page.read_time %}
            {% include read-time.html %}
          {% endif %}

      {% endunless %}

        {{ content }}
        {% if page.link %}
{{ site.data.ui-text[site.locale].ext_link_label | default: "Direct Link" }}
{% endif %}

        {% if site.data.ui-text[site.locale].meta_label %}

{{ site.data.ui-text[site.locale].meta_label }}

        {% endif %}
        {% include page__taxonomy.html %}

      {% if page.share %}{% include social-share.html %}{% endif %}

      {% include post_pagination.html %}

    {% if site.comments.provider and page.comments %}
      {% include comments.html %}
    {% endif %}

  {% comment %}{% endcomment %}
  {% if page.id and page.related and site.related_posts.size > 0 %}

{{ site.data.ui-text[site.locale].related_label | default: "You May Also Enjoy" }}

        {% for post in site.related_posts limit:4 %}
          {% include archive-single.html type="grid" %}
        {% endfor %}

  {% endif %}


text:
<?php

namespace vakata\mail\driver;

use \vakata\mail\MailInterface;
use \vakata\mail\MailException;

/**
 * A mail helper class that stores emails on the disk instead of sending them - useful for debugging.
 */
class FileSender implements SenderInterface
{
    protected $dir;
    /**
     * Create an instance.
     * @param  string      $dir the path to save all emails to
     */
    public function __construct($dir)
    {
        $this->dir = $dir;
    }
    /**
     * Send a message.
     * @param  \vakata\mail\MailInterface $mail the message to be sent
     * @return array              array with two keys - 'good' and 'fail' - indicating successfull and failed addresses
     */
    public function send(MailInterface $mail)
    {
        $data = (string)$mail;
        if (!is_dir(realpath($this->dir))) {
            mkdir($this->dir, 0777, true);
            $this->dir = realpath($this->dir);
            if (!is_dir($this->dir)) {
                throw new MailException('Invalid mail dump dir');
            }
        }
        file_put_contents($this->dir . DIRECTORY_SEPARATOR . time() . '_' . md5($data) . '.txt', $data);
        return [
            'good' => array_merge(
                $mail->getTo(true),
                $mail->getCc(true),
                $mail->getBcc(true)
            ),
            'fail' => []
        ];
    }
}


text:
	ReLinker

[![Build Status](https://travis-ci.org/KeepSafe/ReLinker.svg?branch=master)](https://travis-ci.org/KeepSafe/ReLinker)
[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.getkeepsafe.relinker/relinker/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.getkeepsafe.relinker/relinker)
[![Release](https://img.shields.io/github/tag/KeepSafe/ReLinker.svg?label=jitpack)](https://jitpack.io/#KeepSafe/ReLinker)

A robust native library loader for Android. More information can be found in our [blog post](https://medium.com/keepsafe-engineering/the-perils-of-loading-native-libraries-on-android-befa49dce2db)

 **Min SDK:** 9

 [JavaDoc](https://jitpack.io/com/github/KeepSafe/Relinker/latest/javadoc/)

## Overview

The Android `PackageManager`'s native library loading is unreliable. Occasionally when using native libraries, you will encounter a stack trace like this:

```
java.lang.UnsatisfiedLinkError: Couldn't load stlport_shared from loader dalvik.system.PathClassLoader: findLibrary returned null
at java.lang.Runtime.loadLibrary(Runtime.java:365)
at java.lang.System.loadLibrary(System.java:535)
at com.your.app.NativeClass.<clinit>(Native.java:16)
... 63 more

Caused by: java.lang.UnsatisfiedLinkError: Library stlport_shared not found
at java.lang.Runtime.loadLibrary(Runtime.java:461)
at java.lang.System.loadLibrary(System.java:557)
at com.your.app.NativeClass.<clinit>(Native.java:16)
... 5 more
```

ReLinker fixes these issues by replacing the standard `System.loadLibrary` call with a more reliable implementation.

Note that this library fixes intermittent link errors; if you get an error every time you use your app, you may have a configuration issue. See [this StackOverflow question](http://stackoverflow.com/questions/27421134/system-loadlibrary-couldnt-find-native-library-in-my-case) for more information.

## Who needs ReLinker?

If your app includes native libraries, and your minimum SDK is below API 23 (Marshmallow), you need ReLinker.

There are a number of different bugs addressed by ReLinker; the last of these was resolved as of Marshmallow.  As long as your app's min SDK is at or above it, loading libraries via `System.loadLibrary("foo")` is safe.

## Installation

ReLinker is distributed using [MavenCentral](https://search.maven.org/artifact/com.getkeepsafe.relinker/relinker).

```groovy
   repositories {
        mavenCentral()
   }

   dependencies {
         compile 'com.getkeepsafe.relinker:relinker:x.x.x'
   }
```

If you wish, you may also use ReLinker with [jitpack](https://jitpack.io/#KeepSafe/ReLinker)

## Usage

Simply replace a call to `System.loadLibrary` like this:

```java
System.loadLibrary("mylibrary");
```

With a call to `ReLinker.loadLibrary` like this:

```java
ReLinker.loadLibrary(context, "mylibrary");
```

## Advanced Usage

### Asynchronous loading

ReLinker can load libraries asynchronously. Simply pass a `LoadListener` instance to the `loadLibrary` call:
```java
ReLinker.loadLibrary(context, "mylibrary", new ReLinker.LoadListener() {
    @Override
    public void success() { /* Yay */ }

    @Override
    public void failure(Throwable t) { /* Boo */ }
});
```

### Recursive loading

On older versions of Android, the system's library loader may fail to resolve intra-library dependencies. In this instance, ReLinker can resolve those dependencies for you. This will recursively load all libraries defined as "needed" by each library.

For example, if you have a library `libchild` that relies on `libparent`, then `libchild` will have an entry in its shared object file defining that. ReLinker will parse the shared object file and determine that `libchild` needs `libparent`. ReLinker will then proceed to load `libparent` (and any dependencies it may have) and then `libchild`.

To allow ReLinker to recursively load and resolve intra-library dependencies simply modify your `loadLibrary` call with the `recursively` modifier, like so:
```java
ReLinker.recursively().loadLibrary(context, "mylibrary");
```

### Logging

To help facilitate debugging, ReLinker can log messages to a `Logger` instance you provide:
```java
ReLinker.log(myLogger).loadLibrary(context, "mylibrary");
```

Which will log the following messages during a normal / successful execution:
```
D/ReLinker: Beginning load of mylibrary...
D/ReLinker: mylibrary was not loaded normally, re-linking...
D/ReLinker: Looking for lib/x86/libmylibrary.so in APK...
D/ReLinker: Found lib/x86/libmylibrary.so! Extracting...
D/ReLinker: mylibrary was re-linked!
```

### Versioning

In the event that your library's code is changed, it is a good idea to specify a specific version. Doing so will allow ReLinker to update the workaround library file successfully. In the case that the system handles the library loading appropriately, the version specified is not used as all library files are extracted and replaced on update or install.

To specify a version for your library simply provide it as an additional parameter for `loadLibrary` like:
```java
ReLinker.loadLibrary(context, "mylibrary", "1.0");
```

This will cause ReLinker to look for, and load `libmylibrary.so.1.0`. Subsequent version updates will automatically clean up all other library versions.

## Sample application

See the sample application under `sample/` for a quick demo.

## Acknowledgements

Special thanks to [Jeff Young](https://github.com/tenoversix) for the awesome logo!

## License

    Copyright 2015 - 2016 Keepsafe Software 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.


text:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** @author  John Miller
 *  @version 1.2
 *  @date    Fri Sep 25 15:05:06 EDT 2009
 *  @see     LICENSE (MIT style license file).
 */

package scalation.util

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `Error` trait is used to report errors showing the class and method within
 *  which the error or flaw occurred.  For performance reasons, 'getClass' is
 *  commented out.  Uncomment to include this information.
 */
trait Error
{
    /** Name of the class where the error occurred
     */
//  private val className = getClass.getSimpleName ()

    /** Use `EasyWriter` to make it easy to switch from standard out to a (log) file
     */
//  private val ew = new EasyWriter ("util", "error")

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Toggle output destination from default of (log) file to standard output. etc.
     */
//  def toggle () { ew.toggle () }

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Show the flaw by printing the error message.
     *  @param method   the method where the error occurred
     *  @param message  the error message
     */
    final def flaw (method: String, message: String)
    {
//      ew.println ("ERROR @ " + className + "." + method +  ": " + message)
//      ew.println ("ERROR @ " + method +  ": " + message)
        println ("ERROR @ " + method +  ": " + message)
    } // flaw

} // Error trait


text:
package com.asy.vectordrawables;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

/**
 * Class Description.
 *
 * @author asanchezyu@gmail.com.
 * @version 1.0.
 * @since 11/5/16.
 */
public class ComparisionActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_comparision);

    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialLayout="@layout/widget_trigger_layout"
    android:minHeight="40dp"
    android:minWidth="40dp"
    android:resizeMode="vertical"
    android:widgetCategory="home_screen|keyguard"
    android:updatePeriodMillis="1800000" />


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

namespace ValkyrieWorkflowEngineLibrary.StepHandler
{
    public class ValkProcessorStepHandler
    {
		protected string _HandlesStep = "";
		public string HandlesStep { get { return _HandlesStep; } private set { } }
        public virtual void HandleStep(ref ValkQueueWFMessage WFMessage)
        {
			//Default behavior.  Please override and do something useful instead.
            WFMessage.Command = ValkQueueWFMessage.WFCommand.WFC_COMPLETE;
            //Console.WriteLine("Default Behavior: Autocompleting step");
        }
    }
}


text:
class Bueller
  # Gemspec related error
  class GemspecError < StandardError
  end

  class VersionYmlError < StandardError
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_test_widget"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.cky.learnandroiddetails.TestWidgetAct">

    <com.cky.learnandroiddetails.widget.CleanableEditText
        android:id="@+id/etClearEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableRight="@mipmap/input_icon_close"
        android:background="@null"/>

    <Button
        android:layout_below="@+id/etClearEditText"
        android:id="@+id/btnShowPopWindow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ShowPopUp"/>
</RelativeLayout>


text:
package cmwell.ctrl.checkers

import cmwell.ctrl.config.Config
import cmwell.ctrl.controllers.WebserverController
import cmwell.util.http.{SimpleHttpClient => Http}
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent.duration.FiniteDuration

/**
  * Created by michael on 12/3/14.
  */
object WebChecker extends Checker with RestarterChecker with LazyLogging {

  override val storedStates: Int = 10

  override def restartAfter: FiniteDuration = 10.minutes

  override def doRestart: Unit = {
    WebserverController.restart
    logger.warn("Webservice was restarted.")
  }

  private val req = s"http://${Config.webAddress}:${Config.webPort}"

  override def check: Future[ComponentState] = {
    val res = Http.get(req)
    val startTime = System.currentTimeMillis()
    res
      .map { x =>
        val now = System.currentTimeMillis()
        if (x.status < 400 || x.status == 503) WebOk((now - startTime).toInt)
        else {
          logger.warn(s"WebChecker.check: got a bad response when GET $req. response = $x")
          WebBadCode(x.status, (now - startTime).toInt)
        }
      }
      .recover {
        case _: Throwable =>
          WebDown()
      }
  }
}


text:
using System;
using System.Runtime.CompilerServices;

namespace System.Runtime.CompilerServices
{
#if PROJECTN
    [AttributeUsage(AttributeTargets.Field)]
    internal sealed class BoundAttribute : Attribute { }

    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Method)]
    public sealed class BoundsCheckingAttribute : Attribute { }
#endif
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using ZEDFramework.Collection.Infrastructure.Validation.Attributes;

namespace ZEDFramework.Collection.Infrastructure.Validation
{
    public static class Validation
    {
        internal static string ValidateFieldHtmlValidation(object obj, PropertyInfo property)
        {
            string responseCode = string.Empty;
            try
            {
                FieldHtmlValidation customAttribute = property.GetCustomAttribute<FieldHtmlValidation>();
                if (customAttribute == null)
                {
                    return responseCode;
                }
                if (property.PropertyType == typeof(string))
                {
                    string str2 = (string)property.GetValue(obj);
                    if (string.IsNullOrWhiteSpace(str2))
                    {
                        return responseCode;
                    }
                    if (Regex.IsMatch(str2, @"<(.|\n)*?>"))
                    {
                        responseCode = customAttribute.ResponseCode;
                    }
                }
            }
            catch
            {
                throw;
            }
            return responseCode;
        }

        internal static string ValidateFieldLength(object obj, PropertyInfo property)
        {
            string responseCode = string.Empty;
            try
            {
                int? nullable;
                FieldLength customAttribute = property.GetCustomAttribute<FieldLength>();
                if (customAttribute == null)
                {
                    return responseCode;
                }
                if (property.PropertyType != typeof(string))
                {
                    throw new ArgumentException("TypeOf Not String!");
                }
                string str2 = property.GetValue(obj) as string;
                if (string.IsNullOrEmpty(str2))
                {
                    return responseCode;
                }
                if ((!customAttribute.MaxLength.HasValue && customAttribute.MinLength.HasValue) && ((str2.Length < (nullable = customAttribute.MinLength).GetValueOrDefault()) && nullable.HasValue))
                {
                    responseCode = customAttribute.ResponseCode;
                }
                if ((!customAttribute.MinLength.HasValue && customAttribute.MaxLength.HasValue) && (str2.Length > customAttribute.MaxLength.Value))
                {
                    responseCode = customAttribute.ResponseCode;
                }
                if ((customAttribute.MinLength.HasValue && (str2.Length < customAttribute.MinLength.Value)) || (customAttribute.MaxLength.HasValue && (str2.Length > customAttribute.MaxLength.Value)))
                {
                    responseCode = customAttribute.ResponseCode;
                }
            }
            catch
            {
                throw;
            }
            return responseCode;
        }

        internal static string ValidateFieldNotEmptyGuid(object obj, PropertyInfo property)
        {
            string responseCode = string.Empty;
            try
            {
                FieldNotEmptyGuid customAttribute = property.GetCustomAttribute<FieldNotEmptyGuid>();
                if (customAttribute == null)
                {
                    return responseCode;
                }
                if (property.PropertyType == typeof(Guid))
                {
                    Guid guid2 = (Guid)property.GetValue(obj);
                    if (guid2 == Guid.Empty)
                    {
                        responseCode = customAttribute.ResponseCode;
                    }
                }
            }
            catch
            {
                throw;
            }
            return responseCode;
        }

        internal static string ValidateFieldNotZero(object obj, PropertyInfo property)
        {
            string responseCode = string.Empty;
            try
            {
                FieldNotZero customAttribute = property.GetCustomAttribute<FieldNotZero>();
                if (customAttribute == null)
                {
                    return responseCode;
                }
                if (property.PropertyType == typeof(int))
                {
                    int num = (int)property.GetValue(obj);
                    if (num <= 0)
                    {
                        responseCode = customAttribute.ResponseCode;
                    }
                    return responseCode;
                }
                if (property.PropertyType == typeof(decimal))
                {
                    decimal num2 = (decimal)property.GetValue(obj);
                    if (num2 <= 0M)
                    {
                        responseCode = customAttribute.ResponseCode;
                    }
                }
            }
            catch
            {
                throw;
            }
            return responseCode;
        }

        internal static string ValidateFieldRequired(object obj, PropertyInfo property)
        {
            string responseCode = string.Empty;
            try
            {
                FieldRequired customAttribute = property.GetCustomAttribute<FieldRequired>();
                if (customAttribute == null)
                {
                    return responseCode;
                }
                if (property.PropertyType != typeof(string))
                {
                    throw new ArgumentException("TypeOf Not String!");
                }
                string str2 = property.GetValue(obj) as string;
                if (string.IsNullOrWhiteSpace(str2))
                {
                    responseCode = customAttribute.ResponseCode;
                }
            }
            catch
            {
                throw;
            }
            return responseCode;
        }
    }
}


text:
<?php

namespace OroCRM\Bundle\CampaignBundle\Tests\Selenium;

use Oro\Bundle\TestFrameworkBundle\Test\Selenium2TestCase;
use OroCRM\Bundle\CampaignBundle\Tests\Selenium\Pages\Campaigns;

/**
 * Class Campaign Test
 *
 * @package OroCRM\Bundle\CampaignBundle\Tests\Selenium
 * {@inheritdoc}
 */
class CampaignTest extends Selenium2TestCase
{
    /**
     * @return string
     */
    public function testCreate()
    {
        $campaignCode = 'Campaign_' . mt_rand();

        $login = $this->login();
        /** @var Campaigns $login */
        $login->openCampaigns('OroCRM\Bundle\CampaignBundle')
            ->add()
            ->assertTitle('Create Campaign - Campaigns - Marketing')
            ->setName($campaignCode)
            ->setCode($campaignCode)
            ->save()
            ->assertMessage('Campaign saved')
            ->assertTitle("{$campaignCode} - Campaigns - Marketing");

        return $campaignCode;
    }

    /**
     * @depends testCreate
     * @param $campaignCode
     * @return string
     */
    public function testUpdate($campaignCode)
    {
        $newСampaignCode = substr('Update_' . $campaignCode, 0, 20);

        $login = $this->login();
        /** @var Campaigns $login */
        $login->openCampaigns('OroCRM\Bundle\CampaignBundle')
            ->filterBy('Code', $campaignCode)
            ->open(array($campaignCode))
            ->edit()
            ->assertTitle($campaignCode . ' - Edit - Campaigns - Marketing')
            ->setCode($newСampaignCode)
            ->save()
            ->assertMessage('Campaign saved')
            ->assertTitle("{$campaignCode} - Campaigns - Marketing")
            ->close();

        return $newСampaignCode;
    }

    /**
     * @depends testUpdate
     * @param $campaignCode
     */
    public function testDelete($campaignCode)
    {
        $login = $this->login();
        /** @var Campaigns $login */
        $login->openCampaigns('OroCRM\Bundle\CampaignBundle')
            ->filterBy('Code', $campaignCode)
            ->deleteEntity(array($campaignCode))
            ->assertMessage('Item deleted');

        /** @var Campaigns $login */
        $login = $login->openCampaigns('OroCRM\Bundle\CampaignBundle');
        if ($login->getRowsCount() > 0) {
            $login->filterBy('Code', $campaignCode)
                ->assertNoDataMessage('No entity was found to match your search');
        }
    }
}


text:
package org.jasig.cas.support.oauth.web;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;

import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Principal;
import org.jasig.cas.support.oauth.CentralOAuthService;
import org.jasig.cas.support.oauth.InvalidParameterException;
import org.jasig.cas.support.oauth.OAuthConstants;
import org.jasig.cas.support.oauth.OAuthUtils;
import org.jasig.cas.support.oauth.personal.PersonalAccessToken;
import org.jasig.cas.support.oauth.token.AccessToken;
import org.jasig.cas.support.oauth.token.InvalidTokenException;
import org.jasig.cas.support.oauth.token.TokenType;
import org.jasig.cas.ticket.InvalidTicketException;
import org.jasig.cas.ticket.ServiceTicket;
import org.jasig.cas.validation.Assertion;

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

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * The OAuth 2.0 "Profile" controller.
 *
 * This controller handles requests that ask for the profile (identifier, attributes and scopes) of the principal
 * associated with a given access token.
 *
 * @author Jerome Leleu
 * @author Michael Haselton
 * @author Longze Chen
 * @since 3.5.0
 */
public final class OAuth20ProfileController extends AbstractController {

    /** Log instance for logging events, info, warnings, errors, etc. */
    private static final Logger LOGGER = LoggerFactory.getLogger(OAuth20ProfileController.class);

    /** The CAS OAuth authorization service. */
    private final CentralOAuthService centralOAuthService;

    /** The primary CAS authentication service. */
    private final CentralAuthenticationService centralAuthenticationService;

    /**
     * Instantiates a new {@link OAuth20ProfileController}.
     *
     * @param centralOAuthService the CAS OAuth service
     * @param centralAuthenticationService the primary CAS authentication service
     */
    public OAuth20ProfileController(
            final CentralOAuthService centralOAuthService,
            final CentralAuthenticationService centralAuthenticationService
    ) {
        this.centralOAuthService = centralOAuthService;
        this.centralAuthenticationService = centralAuthenticationService;
    }

    @Override
    protected ModelAndView handleRequestInternal(
            final HttpServletRequest request,
            final HttpServletResponse response
    ) throws Exception {

        // Verify that all required OAuth 2.0 parameters are provided.
        final String prefixedBearerToken = request.getHeader(OAuthConstants.AUTHORIZATION_HEADER);
        LOGGER.debug("{} : {}", OAuthConstants.BEARER_TOKEN, prefixedBearerToken);
        String accessTokenId = request.getParameter(OAuthConstants.ACCESS_TOKEN);
        LOGGER.debug("{} : {}", OAuthConstants.ACCESS_TOKEN, accessTokenId);
        try {
            accessTokenId = verifyRequest(accessTokenId, prefixedBearerToken);
        } catch (final InvalidParameterException e) {
            return OAuthUtils.writeJsonError(
                    response,
                    OAuthConstants.INVALID_REQUEST,
                    e.getMessage(),
                    HttpStatus.SC_BAD_REQUEST
            );
        }

        // Verify and retrieve the access token. The token can be OAuth-granted by authorization or CAS-granted by
        // authentication. It can also be an OSF-generated PERSONAL access token, which does not exist in the token
        // registry (i.e. CAS database) the first time it is used.
        AccessToken accessToken;
        try {
            accessToken = centralOAuthService.getToken(accessTokenId, AccessToken.class);
        } catch (final InvalidTokenException e) {
            // If not found, check if it is an PERSONAL access token.
            final PersonalAccessToken personalAccessToken = centralOAuthService.getPersonalAccessToken(accessTokenId);
            if (personalAccessToken != null) {
                accessToken = centralOAuthService.grantPersonalAccessToken(personalAccessToken);
            } else {
                LOGGER.error("Could not get Access Token [{}]", accessTokenId);
                return OAuthUtils.writeJsonError(
                        response,
                        OAuthConstants.UNAUTHORIZED_REQUEST,
                        OAuthConstants.INVALID_ACCESS_TOKEN_DESCRIPTION,
                        HttpStatus.SC_UNAUTHORIZED
                );
            }
        }

        // Retrieve the principal id and released attributes associated with the access token.
        final Principal principal;
        final Map<String, Object> attributeMap = new HashMap<>();
        if (accessToken.getType() == TokenType.PERSONAL) {
            // PERSONAL access tokens do not have an OAuth registered service. Thus no attributes can be released.
            // TODO: Need to grant a service ticket here if we would like keep stats on ticket usage.
            principal = accessToken.getTicketGrantingTicket().getAuthentication().getPrincipal();
        } else {
            // Retrieve an existing or grant a new service ticket.
            final ServiceTicket serviceTicket;
            if (accessToken.getType() == TokenType.OFFLINE) {
                // OFFLINE access tokens are granted with a service ticket. Thus just use it here.
                serviceTicket = accessToken.getServiceTicket();
            } else {
                // Both ONLINE and CAS access tokens are granted with a ticket granting ticket and an associated
                // registered service. Thus, must grant a new service ticket here using the TGT and the service.
                serviceTicket = centralAuthenticationService
                        .grantServiceTicket(accessToken.getTicketGrantingTicket().getId(), accessToken.getService()
                );
            }
            // Validate the service ticket, and apply service specific attribute release policy
            final Assertion assertion;
            try {
                assertion = centralAuthenticationService
                        .validateServiceTicket(serviceTicket.getId(), serviceTicket.getService());
            } catch (final InvalidTicketException e) {
                LOGGER.error(
                        "Could not validate Service Ticket [{}] of Access Token [{}] ",
                        serviceTicket.getId(),
                        accessToken.getId()
                );
                return OAuthUtils.writeJsonError(
                        response,
                        OAuthConstants.UNAUTHORIZED_REQUEST,
                        OAuthConstants.INVALID_ACCESS_TOKEN_DESCRIPTION,
                        HttpStatus.SC_UNAUTHORIZED
                );
            }
            // Retrieve principal and attributes from the service ticket validation assertion.
            principal = assertion.getPrimaryAuthentication().getPrincipal();
            for (final Map.Entry<String, Object> attribute : principal.getAttributes().entrySet()) {
                attributeMap.put(attribute.getKey(), attribute.getValue());
            }
        }

        // Build and return the response.
        final ObjectMapper mapper = new ObjectMapper();
        final Map<String, Object> map = new HashMap<>();
        map.put(OAuthConstants.PRINCIPAL_ID, principal.getId());
        if (attributeMap.size() > 0) {
            map.put(OAuthConstants.PRINCIPAL_ATTRIBUTES, attributeMap);
        }
        final Set<String> scopes = accessToken.getScopes();
        if (scopes.size() > 0) {
            map.put(OAuthConstants.SCOPE, accessToken.getScopes());
        }
        final String result = mapper.writeValueAsString(map);
        LOGGER.debug("result : {}", result);
        response.setContentType("application/json");
        return OAuthUtils.writeText(response, result, HttpStatus.SC_OK);
    }

    /**
     * Verify that all required OAuth 2.0 parameters are provided.
     *
     * @param accessTokenId the access token id
     * @param prefixedBearerToken the prefixed bearer token provided by the HTTP Authorization header
     * @return the access token id
     * @throws InvalidParameterException with the name of the invalid parameter
     */
    private String verifyRequest(
            final String accessTokenId,
            final String prefixedBearerToken
    ) throws InvalidParameterException {

        // An access token must be provided via either the request body or the HTTP "Authorization" header.
        if (StringUtils.isBlank(accessTokenId)) {
            if (StringUtils.isNotBlank(prefixedBearerToken)
                    && prefixedBearerToken.startsWith(OAuthConstants.BEARER_TOKEN + " ")
            ) {
                return prefixedBearerToken.substring(OAuthConstants.BEARER_TOKEN.length() + 1);
            } else {
                LOGGER.debug(OAuthConstants.MISSING_ACCESS_TOKEN_DESCRIPTION);
                throw new InvalidParameterException(OAuthConstants.ACCESS_TOKEN);
            }
        } else {
            return accessTokenId;
        }
    }
}


text:
#pragma strict
@script RequireComponent(NetworkView)

public class ArtifactPillar extends MonoBehaviour
{
	public var artifact : int;

	//TODO GAME BALANCE
	@Range(0, 1)
	public var startingInfluence : float = 0.25;

	private var influence : Influence = null;

	public function Start()
	{
		influence = new Influence(startingInfluence, artifact);
	}

	public function getArtifact() : int { return influence.getArtifact(); }
	public function getInfluence() : float { return influence.getInfluence(); }

	@RPC
	public function lostArtifact()
	{
		influence.setInfluence(0.0);
	}

}


text:
import { Component, OnInit } from '@angular/core';
import { PizzaService } from './shared/pizza.service';

@Component({
  selector: 'pizza-root',
  template: `
Anzahl an Pizzen: {{pizzas?.length}}
  `
})
export class AppComponent implements OnInit {
  public pizzas: Object[];

  constructor(
    private pizzaService: PizzaService
  ) { }

  ngOnInit() {
    this.pizzaService
      .getPizza()
      .subscribe((pizzas: Object[]) => this.pizzas = pizzas);
  }

}