text:
package cz.ladicek.annDocuGen.annotationProcessor.view;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.Resources;
import com.google.gson.Gson;
import cz.ladicek.annDocuGen.annotationProcessor.gson.GsonHolder;
import cz.ladicek.annDocuGen.annotationProcessor.model.DocumentationData;

import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

public class DocumentationWriter {
    private final DocumentationData documentationData;
    private final DocumentationDataView documentationDataView;
    private final FileCreator fileCreator;
    private final Gson gson;

    public DocumentationWriter(DocumentationData documentationData, FileCreator fileCreator) {
        this.documentationData = documentationData;
        this.documentationDataView = new DocumentationDataView(documentationData);
        this.fileCreator = fileCreator;
        this.gson = GsonHolder.instance;
    }

    public void write() throws IOException {
        copyStaticAsset("thirdparty/bootstrap.css");
        copyStaticAsset("style.css");

        copyStaticAsset("thirdparty/jquery.js");
        copyStaticAsset("thirdparty/typeahead.js");

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        ImmutableMap<String, Object> staticContext = ImmutableMap.<String, Object>builder()
                .put("now", dateFormat.format(new Date()))
                .build();

        MustacheFactory mustache = new DefaultMustacheFactory();

        {
            Mustache template = mustache.compile("index.mustache");
            Writer writer = fileCreator.newWriter("index.html");
            try {
                generateIndex(template, writer, staticContext);
            } finally {
                writer.close();
            }
        }

        Mustache template = mustache.compile("class.mustache");
        for (DocumentedClassView documentedClass : documentationDataView.documentedClasses()) {
            Writer writer = fileCreator.newWriter(documentedClass.fullName() + ".html");
            try {
                template.execute(writer, new Object[] {documentedClass, staticContext});
            } finally {
                writer.close();
            }
        }

        generateData();
    }

    private void copyStaticAsset(String filePath) throws IOException {
        OutputStream outputStream = fileCreator.newOutputStream(filePath);
        try {
            URL url = Resources.getResource(DocumentationWriter.class, "/" + filePath);
            Resources.copy(url, outputStream);
        } finally {
            outputStream.close();
        }
    }

    private void generateIndex(Mustache template, Writer out, ImmutableMap<String, Object> staticContext) {
        List<DocumentedClassView> units = new ArrayList<DocumentedClassView>();
        List<DocumentedClassView> services = new ArrayList<DocumentedClassView>();
        for (DocumentedClassView clazz : documentationDataView.documentedClasses()) {
            if (clazz.isUnit()) {
                units.add(clazz);
            } else {
                services.add(clazz);
            }
        }
        Collections.sort(units, DocumentedClassView.SIMPLE_NAME_COMPARATOR);
        Collections.sort(services, DocumentedClassView.SIMPLE_NAME_COMPARATOR);

        ImmutableMap<String, Object> context = ImmutableMap.<String, Object>builder()
                .put("title", "Index")
                .put("units", units)
                .put("services", services)
                .put("searchData", generateSearchData())
                .putAll(staticContext)
                .build();
        template.execute(out, context);
    }

    private String generateSearchData() {
        List<SearchData> searchData = new ArrayList<SearchData>();
        for (DocumentedClassView documentedClassView : documentationDataView.documentedClasses()) {
            searchData.add(new SearchData(documentedClassView));
        }

        StringWriter writer = new StringWriter();
        gson.toJson(searchData, writer);
        return writer.getBuffer().toString();
    }

    private void generateData() throws IOException {
        Writer writer = fileCreator.newWriter("data.json");
        try {
            gson.toJson(documentationDataView, writer);
        } finally {
            writer.close();
        }

        writer = fileCreator.newWriter("raw-data.json");
        try {
            gson.toJson(documentationData, writer);
        } finally {
            writer.close();
        }
    }
}


text:
using NUnit.Framework;
using Symbooglix;
using System;

namespace SymbooglixLibTests
{
    [TestFixture()]
    public class FunctionAsAxiom : SymbooglixTest
    {
        [Test()]
        public void TestCase()
        {
            p = LoadProgramFrom("programs/functionAsAxiom.bpl");
            e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
            var counter = new TerminationCounter();
            counter.Connect(e);
            e.Run(GetMain(p));

            Assert.AreEqual(1, counter.Sucesses);
            Assert.AreEqual(0, counter.NumberOfFailures);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

{% include head.html %}

{{ site.name }}

{{ site.description }}

            {% if site.github %}

            {% endif %} {% if site.twitter %}

            {% endif %} {% if site.linkedin %}

            {% endif %} {% if site.pinterest %}

            {% endif %} {% if site.facebook %}

            {% endif %}

        {{ content }}


text:
import React from 'react';
import { blissComponent } from 're-app/lib/decorators';
import './BlessedComponent.less';

@blissComponent
export default class BlessedComponent extends React.Component {
	render() {
		const {
			getBlissModuleClassName: bm, // eslint-disable-line
			getBlissElementClassName: be, // eslint-disable-line
			} = this.props;
		// ... or use shortcuts directly
		// const {bm, be} = this.props;
		return (

					Header

						Content 1

						Content 2

						Content 3 (last)

					Footer

		);
	}
}


text:
#pragma once

#include "../core/system.h"

namespace overdrive {
	namespace app {
		/*
		 * Conceptually an 'application' is very similar to an engine subsystem,
		 * only it can assume that all engine subsystems have been initialized already.
		 * This exists in an attempt to separate 'application logic' from 'library logic'
		 */

		class Application:
			public core::System
		{
		public:
			Application(const std::string& name);

			virtual void initialize() = 0;
			virtual void update() = 0;
			virtual void shutdown() = 0;
		};
	}
}


text:
from django.views.generic import ListView
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

# Local Django imports
from user.decorators import is_health_professional
from prescription.models import Prescription

class ListFavoritePrescription(ListView):
    '''
        View for list favorite prescriptions in database.
    '''
    template_name = 'list_favorite_prescriptions.html'
    context_object_name = 'list_favorite_prescriptions'
    model = Prescription
    paginate_by = 20
    ordering = ['-date_created']

    @method_decorator(login_required)
    @method_decorator(is_health_professional)
    def dispatch(self, *args, **kwargs):
        return super(ListFavoritePrescription, self).dispatch(*args, **kwargs)

    def get_queryset(self):
        return self.model.objects.filter(health_professional=self.request.user, is_favorite=True)


text:
package roachpb

import (
	"bytes"
	"fmt"
	"strings"

	"github.com/pkg/errors"

	"github.com/cockroachdb/cockroach/pkg/util/hlc"
)

//go:generate go run -tags gen-batch gen_batch.go

// SetActiveTimestamp sets the correct timestamp at which the request is to be
// carried out. For transactional requests, ba.Timestamp must be zero initially
// and it will be set to txn.OrigTimestamp. For non-transactional requests, if
// no timestamp is specified, nowFn is used to create and set one.
func (ba *BatchRequest) SetActiveTimestamp(nowFn func() hlc.Timestamp) error {
	if ba.Txn == nil {
		// When not transactional, allow empty timestamp and  use nowFn instead.
		if ba.Timestamp.Equal(hlc.ZeroTimestamp) {
			ba.Timestamp.Forward(nowFn())
		}
	} else if !ba.Timestamp.Equal(hlc.ZeroTimestamp) {
		return errors.New("transactional request must not set batch timestamp")
	} else {
		// Always use the original timestamp for reads and writes, even
		// though some intents may be written at higher timestamps in the
		// event of a WriteTooOldError.
		ba.Timestamp = ba.Txn.OrigTimestamp
	}
	return nil
}

// UpdateTxn updates the batch transaction from the supplied one in
// a copy-on-write fashion, i.e. without mutating an existing
// Transaction struct.
func (ba *BatchRequest) UpdateTxn(otherTxn *Transaction) {
	if otherTxn == nil {
		return
	}
	if ba.Txn == nil {
		ba.Txn = otherTxn
		return
	}
	clonedTxn := ba.Txn.Clone()
	clonedTxn.Update(otherTxn)
	ba.Txn = &clonedTxn
}

// IsConsistencyRelated returns whether the batch consists of a single
// ComputeChecksum or CheckConsistency request.
func (ba *BatchRequest) IsConsistencyRelated() bool {
	if !ba.IsSingleRequest() {
		return false
	}
	_, ok1 := ba.GetArg(ComputeChecksum)
	_, ok2 := ba.GetArg(CheckConsistency)
	return ok1 || ok2
}

// IsFreeze returns whether the batch consists of a single ChangeFrozen request.
func (ba *BatchRequest) IsFreeze() bool {
	if !ba.IsSingleRequest() {
		return false
	}
	_, ok := ba.GetArg(ChangeFrozen)
	return ok
}

// IsLeaseRequest returns whether the batch consists of a single RequestLease
// request. Note that TransferLease requests return false.
// RequestLease requests are special because they're the only type of requests a
// non-lease-holder can propose.
func (ba *BatchRequest) IsLeaseRequest() bool {
	if !ba.IsSingleRequest() {
		return false
	}
	_, ok := ba.GetArg(RequestLease)
	return ok
}

// IsAdmin returns true iff the BatchRequest contains an admin request.
func (ba *BatchRequest) IsAdmin() bool {
	return ba.hasFlag(isAdmin)
}

// IsWrite returns true iff the BatchRequest contains a write.
func (ba *BatchRequest) IsWrite() bool {
	return ba.hasFlag(isWrite)
}

// IsReadOnly returns true if all requests within are read-only.
func (ba *BatchRequest) IsReadOnly() bool {
	return len(ba.Requests) > 0 && !ba.hasFlag(isWrite|isAdmin)
}

// IsReverse returns true iff the BatchRequest contains a reverse request.
func (ba *BatchRequest) IsReverse() bool {
	return ba.hasFlag(isReverse)
}

// IsPossibleTransaction returns true iff the BatchRequest contains
// requests that can be part of a transaction.
func (ba *BatchRequest) IsPossibleTransaction() bool {
	return ba.hasFlag(isTxn)
}

// IsTransactionWrite returns true iff the BatchRequest contains a txn write.
func (ba *BatchRequest) IsTransactionWrite() bool {
	return ba.hasFlag(isTxnWrite)
}

// IsSingleRequest returns true iff the BatchRequest contains a single request.
func (ba *BatchRequest) IsSingleRequest() bool {
	return len(ba.Requests) == 1
}

// IsNonKV returns true iff all of the requests in the batch have the non-KV
// flag set.
func (ba *BatchRequest) IsNonKV() bool {
	for _, union := range ba.Requests {
		if (union.GetInner().flags() & isNonKV) == 0 {
			return false
		}
	}
	return true
}

// IsSingleSkipLeaseCheckRequest returns true iff the batch contains a single
// request, and that request has the skipLeaseCheck flag set.
func (ba *BatchRequest) IsSingleSkipLeaseCheckRequest() bool {
	return ba.IsSingleRequest() && ba.hasFlag(skipLeaseCheck)
}

// GetPrevLeaseForLeaseRequest returns the previous lease, at the time
// of proposal, for a request lease or transfer lease request. If the
// batch does not contain a single lease request, this method will panic.
func (ba *BatchRequest) GetPrevLeaseForLeaseRequest() *Lease {
	return ba.Requests[0].GetInner().(leaseRequestor).prevLease()
}

// hasFlag returns true iff one of the requests within the batch contains the
// specified flag.
func (ba *BatchRequest) hasFlag(flag int) bool {
	for _, union := range ba.Requests {
		if (union.GetInner().flags() & flag) != 0 {
			return true
		}
	}
	return false
}

// GetArg returns a request of the given type if one is contained in the
// Batch. The request returned is the first of its kind, with the exception
// of EndTransaction, where it examines the very last request only.
func (ba *BatchRequest) GetArg(method Method) (Request, bool) {
	// when looking for EndTransaction, just look at the last entry.
	if method == EndTransaction {
		if length := len(ba.Requests); length > 0 {
			if req := ba.Requests[length-1].GetInner(); req.Method() == EndTransaction {
				return req, true
			}
		}
		return nil, false
	}

	for _, arg := range ba.Requests {
		if req := arg.GetInner(); req.Method() == method {
			return req, true
		}
	}
	return nil, false
}

func (br *BatchResponse) String() string {
	var str []string
	str = append(str, fmt.Sprintf("(err: %v)", br.Error))
	for _, union := range br.Responses {
		str = append(str, fmt.Sprintf("%T", union.GetInner()))
	}
	return strings.Join(str, ", ")
}

// IntentSpanIterate calls the passed method with the key ranges of the
// transactional writes contained in the batch. Usually the key spans
// contained in the requests are used, but when a response contains a
// ResumeSpan the ResumeSpan is subtracted from the request span to provide a
// more minimal span of keys affected by the request.
func (ba *BatchRequest) IntentSpanIterate(br *BatchResponse, fn func(key, endKey Key)) {
	for i, arg := range ba.Requests {
		req := arg.GetInner()
		if !IsTransactionWrite(req) {
			continue
		}
		h := req.Header()
		if br != nil {
			resumeSpan := br.Responses[i].GetInner().Header().ResumeSpan
			// If a resume span exists we need to cull the span.
			if resumeSpan != nil {
				if bytes.Equal(resumeSpan.Key, h.Key) {
					if bytes.Equal(resumeSpan.EndKey, h.EndKey) {
						// Nothing was written.
						continue
					}
					fn(resumeSpan.EndKey, h.EndKey)
				} else {
					fn(h.Key, resumeSpan.Key)
				}
				continue
			}
		}
		fn(h.Key, h.EndKey)
	}
}

// Combine implements the Combinable interface. It combines each slot of the
// given request into the corresponding slot of the base response. The number
// of slots must be equal and the respective slots must be combinable.
// On error, the receiver BatchResponse is in an invalid state.
// TODO(tschottdorf): write tests.
func (br *BatchResponse) Combine(otherBatch *BatchResponse) error {
	if len(otherBatch.Responses) != len(br.Responses) {
		return errors.New("unable to combine batch responses of different length")
	}
	for i, l := 0, len(br.Responses); i < l; i++ {
		valLeft := br.Responses[i].GetInner()
		valRight := otherBatch.Responses[i].GetInner()
		cValLeft, lOK := valLeft.(combinable)
		cValRight, rOK := valRight.(combinable)
		if lOK && rOK {
			if err := cValLeft.combine(cValRight); err != nil {
				return err
			}
			continue
		}
		// If our slot is a NoopResponse, then whatever the other batch has is
		// the result. Note that the result can still be a NoopResponse, to be
		// filled in by a future Combine().
		if _, ok := valLeft.(*NoopResponse); ok {
			br.Responses[i] = otherBatch.Responses[i]
		}
	}
	br.Txn.Update(otherBatch.Txn)
	br.CollectedSpans = append(br.CollectedSpans, otherBatch.CollectedSpans...)
	return nil
}

// Add adds a request to the batch request. It's a convenience method;
// requests may also be added directly into the slice.
func (ba *BatchRequest) Add(requests ...Request) {
	for _, args := range requests {
		ba.Requests = append(ba.Requests, RequestUnion{})
		ba.Requests[len(ba.Requests)-1].MustSetInner(args)
	}
}

// Add adds a response to the batch response. It's a convenience method;
// responses may also be added directly.
func (br *BatchResponse) Add(reply Response) {
	br.Responses = append(br.Responses, ResponseUnion{})
	br.Responses[len(br.Responses)-1].MustSetInner(reply)
}

// Methods returns a slice of the contained methods.
func (ba *BatchRequest) Methods() []Method {
	var res []Method
	for _, arg := range ba.Requests {
		res = append(res, arg.GetInner().Method())
	}
	return res
}

// Split separates the requests contained in a batch so that each subset of
// requests can be executed by a Store (without changing order). In particular,
// Admin requests are always singled out and mutating requests separated from
// reads. The boolean parameter indicates whether EndTransaction should be
// special-cased: If false, an EndTransaction request will never be split into
// a new chunk (otherwise, it is treated according to its flags). This allows
// sending a whole transaction in a single Batch when addressing a single
// range.
func (ba BatchRequest) Split(canSplitET bool) [][]RequestUnion {
	compatible := func(method Method, exFlags, newFlags int) bool {
		// If no flags are set so far, everything goes.
		if exFlags == 0 || (!canSplitET && method == EndTransaction) {
			return true
		}
		if (newFlags & isAlone) != 0 {
			return false
		}
		// Otherwise, the flags below must remain the same with the new
		// request added.
		//
		// Note that we're not checking isRead: The invariants we're
		// enforcing are that a batch can't mix non-writes with writes.
		// Checking isRead would cause ConditionalPut and Put to conflict,
		// which is not what we want.
		const mask = isWrite | isAdmin | isReverse
		return (mask & exFlags) == (mask & newFlags)
	}
	var parts [][]RequestUnion
	for len(ba.Requests) > 0 {
		part := ba.Requests
		var gFlags int
		for i, union := range ba.Requests {
			args := union.GetInner()
			flags := args.flags()
			method := args.Method()
			// Regardless of flags, a NoopRequest is always compatible.
			if method == Noop {
				continue
			}
			if !compatible(method, gFlags, flags) {
				part = ba.Requests[:i]
				break
			}
			gFlags |= flags
		}
		parts = append(parts, part)
		ba.Requests = ba.Requests[len(part):]
	}
	return parts
}

// String gives a brief summary of the contained requests and keys in the batch.
// TODO(tschottdorf): the key range is useful information, but requires `keys`.
// See #2198.
func (ba BatchRequest) String() string {
	var str []string
	if ba.Txn != nil {
		str = append(str, fmt.Sprintf("[txn: %s]", ba.Txn.Short()))
	}
	for count, arg := range ba.Requests {
		// Limit the strings to provide just a summary. Without this limit
		// a log message with a BatchRequest can be very long.
		if count >= 20 && count < len(ba.Requests)-5 {
			if count == 20 {
				str = append(str, fmt.Sprintf("... %d skipped ...", len(ba.Requests)-25))
			}
			continue
		}
		req := arg.GetInner()
		if _, ok := req.(*NoopRequest); ok {
			str = append(str, req.Method().String())
		} else {
			h := req.Header()
			str = append(str, fmt.Sprintf("%s [%s,%s)", req.Method(), h.Key, h.EndKey))
		}
	}
	return strings.Join(str, ", ")
}

// TODO(marc): we should assert
// var _ security.RequestWithUser = &BatchRequest{}
// here, but we need to break cycles first.

// GetUser implements security.RequestWithUser.
// KV messages are always sent by the node user.
func (*BatchRequest) GetUser() string {
	// TODO(marc): we should use security.NodeUser here, but we need to break cycles first.
	return "node"
}

// SetNewRequest increases the internal sequence counter of this batch request.
// The sequence counter is used for replay and reordering protection. At the
// Store, a sequence counter less than or equal to the last observed one incurs
// a transaction restart (if the request is transactional).
func (ba *BatchRequest) SetNewRequest() {
	if ba.Txn != nil {
		txn := *ba.Txn
		txn.Sequence++
		ba.Txn = &txn
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>C-Index</title>
<meta name="date" content="2013-07-02">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

A B C D E F G H I L M N O P R S T U W

C

clear() - Method in class com.palamida.util.collect.RankList

clear() - Method in class com.palamida.util.collect.Skiplist

clear() - Method in class com.palamida.util.collect.SkiplistSet

clear() - Method in class com.palamida.util.collect.Treelist

clear() - Method in class com.palamida.util.collect.TreeQueue

Removes all of the elements from this queue.

clear() - Method in class com.palamida.util.collect.TreeSet

clone() - Method in class com.palamida.util.collect.RankList

Returns a shallow copy of this RankList.

clone() - Method in class com.palamida.util.collect.Skiplist

Returns a shallow copy of this Skiplist.

clone() - Method in class com.palamida.util.collect.SkiplistSet

Returns a shallow copy of this SkiplistSet.

clone() - Method in class com.palamida.util.collect.Treelist

Returns a shallow copy of this Treelist.

clone() - Method in class com.palamida.util.collect.TreeQueue

Returns a shallow copy of this TreeQueue.

clone() - Method in class com.palamida.util.collect.TreeSet

Returns a shallow copy of this TreeSet.

com.palamida.util.base - package com.palamida.util.base

Basic utilities.

com.palamida.util.collect - package com.palamida.util.collect

This package contains interfaces, implementations, and other utilities for
 working with Collections and Maps.

com.palamida.util.io - package com.palamida.util.io

Static utilities for working with
 Files, and system-dependent tasks.

com.palamida.util.swing - package com.palamida.util.swing

Static utilities for working with Java Swing.

comparator() - Method in class com.palamida.util.collect.Skiplist

Returns the comparator used to order the elements in this list.

comparator() - Method in class com.palamida.util.collect.SkiplistSet

Returns the comparator used to order the elements in this set.

comparator() - Method in interface com.palamida.util.collect.SortedCollection

Returns the comparator used to order the elements in this collection.

comparator() - Method in class com.palamida.util.collect.Treelist

Returns the comparator used to order the elements in this list.

comparator() - Method in class com.palamida.util.collect.TreeQueue

Returns the comparator used to order the elements in this deque.

comparator() - Method in class com.palamida.util.collect.TreeSet

Returns the comparator used to order the elements in this set.

concat(ListIterator<E>...) - Static method in class com.palamida.util.collect.MoreIterators

Combines multiple list iterators into a single ListIterator.

contains(T[], Object) - Static method in class com.palamida.util.base.MoreArrays

Returns true if the specified array contains the given element,
 false otherwise.

contains(Object) - Method in class com.palamida.util.collect.Skiplist

contains(Object) - Method in class com.palamida.util.collect.SkiplistSet

contains(Object) - Method in class com.palamida.util.collect.Treelist

contains(Object) - Method in class com.palamida.util.collect.TreeQueue

contains(Object) - Method in class com.palamida.util.collect.TreeSet

create() - Static method in class com.palamida.util.collect.RankList

Creates a new RankList.

create(Iterable<? extends E>) - Static method in class com.palamida.util.collect.RankList

Creates a new RankList containing the elements of the specified
 Iterable.

create() - Method in class com.palamida.util.collect.Skiplist.Builder

Builds an empty Skiplist using the previously specified
 comparator.

create(Iterable<? extends T>) - Method in class com.palamida.util.collect.Skiplist.Builder

Builds a new Skiplist using the previously specified
 comparator, and having the given initial elements.

create() - Static method in class com.palamida.util.collect.Skiplist

Creates a new Skiplist that orders its elements according to
 their natural ordering.

create() - Static method in class com.palamida.util.collect.SkiplistSet

Creates a new SkiplistSet that orders its elements according to
 their natural ordering.

create(Comparator<? super E>) - Static method in class com.palamida.util.collect.SkiplistSet

Creates a new SkiplistSet that uses the specified comparator to
 order its elements.

create(Collection<? extends E>) - Static method in class com.palamida.util.collect.SkiplistSet

Creates a new SkiplistSet containing the specified initial
 elements.

create() - Method in class com.palamida.util.collect.Treelist.Builder

Builds an empty Treelist using the previously specified
 comparator.

create(Iterable<? extends T>) - Method in class com.palamida.util.collect.Treelist.Builder

Builds a new Treelist using the previously specified
 comparator, and having the given initial elements.

create() - Static method in class com.palamida.util.collect.Treelist

Creates a new Treelist that orders its elements according to
 their natural ordering.

create() - Method in class com.palamida.util.collect.TreeQueue.Builder

Builds an empty TreeQueue using the previously specified
 options.

create(Iterable<? extends T>) - Method in class com.palamida.util.collect.TreeQueue.Builder

Builds a new TreeQueue using the previously specified
 options, and having the given initial elements.

create() - Static method in class com.palamida.util.collect.TreeQueue

Creates a new unbounded TreeQueue that orders its elements
 according to their natural ordering.

create() - Static method in class com.palamida.util.collect.TreeSet

Creates a new TreeSet that orders its elements according to their
 natural ordering.

create(Comparator<? super E>) - Static method in class com.palamida.util.collect.TreeSet

Creates a new TreeSet that uses the specified comparator to order
 its elements.

create(Iterable<? extends E>) - Static method in class com.palamida.util.collect.TreeSet

Creates a new TreeSet containing the specified initial elements.

createParentDirs(File) - Static method in class com.palamida.util.io.MoreFiles

Creates any necessary but nonexistent parent directories of the specified
 file.

A B C D E F G H I L M N O P R S T U W

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
<?php

namespace Clients\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Debug\Debug;
use Zend\Db\Sql\Where;

class LinkTable {

    protected $tableGateway;

    public function __construct(TableGateway $tableGateway) {
        $this->tableGateway = $tableGateway;
    }

    public function saveLink(Link $link) {
//                              Debug::dump($link->website);exit;
        $data = array(
            'date' => $link->date,
            'url' => $link->url,
            'website_id' => $link->website_id,
        );

        $id = (int) $link->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
        } else {
            if ($this->getLink($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Link ID does not exist');
            }
        }
    }

    public function fetchAll() {
        $resultSet = $this->tableGateway->select();
        $resultSet->buffer();
        return $resultSet;
    }

    public function getLink($id) {
        $id = (int) $id;
        $rowset = $this->tableGateway->select(array('id' => $id));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $id");
        }
        return $row;
    }

    public function getLinkWebsite($id) {
        $id = (int) $id;
        $rowset = $this->tableGateway->select(array('website_id' => $id));
         $rowset->buffer();
//        print_r($rowset);exit;
//        $row = $rowset->current();
//        if (!$rowset) {
//            throw new \Exception("Could not find row $id");
//        }
        return $rowset;
    }

    public function getLinkByEmail($linkEmail) {
        $rowset = $this->tableGateway->select(array('email' =>
            $linkEmail));
        $row = $rowset->current();
        if (!$row) {
            throw new \Exception("Could not find row $linkEmail");
        }
        return $row;
    }

    public function deleteLink($id) {
        $this->tableGateway->delete(array('id' => $id));
    }

    public function deleteLinkClient($id) {
        $this->tableGateway->delete(array('clients_id' => $id));
    }

    public function dateRange($from, $till, $website_id) {
        $where = new Where();
        $where->equalTo('website_id', $website_id);
        $where->between('date', $from, $till);
//        $where->greaterThanOrEqualTo('date', $from);
//        $where->lessThanOrEqualTo('date', $till);
        $resultSet = $this->tableGateway->select($where);
//        print_r($resultSet);
//        exit;
        $resultSet->buffer();
        return $resultSet;
    }
    public function alldateRange($from, $till) {
        $where = new Where();
        $where->between('date', $from, $till);
//        $where->greaterThanOrEqualTo('date', $from);
//        $where->lessThanOrEqualTo('date', $till);
        $resultSet = $this->tableGateway->select($where);
//        print_r($resultSet);
//        exit;
        $resultSet->buffer();
        return $resultSet;
    }

}


text: export * from './inputs.component';


text:
package my.interest.tamil.rest.resources.exception;

import javax.ws.rs.WebApplicationException;

/**
 * <p>
 * </p>
 *
 * @author velsubra
 */
public class ResourceException extends RuntimeException {
    public ResourceException(String message) {
        super(message);
    }
}


text:
package com.evolveum.midpoint.schema;

import java.util.Collection;
import java.util.List;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;

import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilitiesType;
import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType;
import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.*;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Element;

import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.JAXBUtil;
import com.evolveum.midpoint.util.exception.SchemaException;

/**
 * @author semancik
 *
 */
public class CapabilityUtil {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static <T extends CapabilityType> T getCapability(Collection<Object> capabilities, Class<T> capabilityClass) {
        if (capabilities == null) {
            return null;
        }
        for (Object cap : capabilities) {
            if (cap instanceof JAXBElement) {
                JAXBElement element = (JAXBElement) cap;
                if (capabilityClass.isAssignableFrom(element.getDeclaredType())) {
                    return (T) element.getValue();
                }
            } else if (capabilityClass.isAssignableFrom(cap.getClass())) {
                return (T) cap;
            }
        }
        return null;
    }

    public static boolean isCapabilityEnabled(Object capability) {
        if (capability == null) {
            return false;
        }
        if (capability instanceof JAXBElement<?>) {
            capability = ((JAXBElement<?>)capability).getValue();
        }

        if (capability instanceof CapabilityType) {
            return CapabilityUtil.isCapabilityEnabled((CapabilityType)capability);
        } else if (capability instanceof Element) {
            return CapabilityUtil.isCapabilityEnabled((Element)capability);
        } else {
            throw new IllegalArgumentException("Unexpected capability type "+capability.getClass());
        }
    }

    private static boolean isCapabilityEnabled(Element capability) {
        if (capability == null) {
            return false;
        }
        ObjectFactory capabilitiesObjectFactory = new ObjectFactory();
        QName enabledElementName = capabilitiesObjectFactory.createEnabled(true).getName();
        Element enabledElement = DOMUtil.getChildElement(capability, enabledElementName);
        return enabledElement == null || Boolean.parseBoolean(enabledElement.getTextContent());
    }

    public static <T extends CapabilityType> boolean isCapabilityEnabled(T capability) {
        if (capability == null) {
            return false;
        }
        if (capability.isEnabled() == null) {
            return true;
        }
        return capability.isEnabled();
    }

    public static Object getCapabilityWithSameElementName(List<Object> capabilities, Object capability) {
        if (capabilities == null) {
            return false;
        }
        QName capabilityElementName = JAXBUtil.getElementQName(capability);
        for (Object cap: capabilities) {
            QName capElementName = JAXBUtil.getElementQName(cap);
            if (capabilityElementName.equals(capElementName)) {
                return cap;
            }
        }
        return null;
    }

    public static boolean containsCapabilityWithSameElementName(List<Object> capabilities, Object capability) {
        return getCapabilityWithSameElementName(capabilities, capability) != null;
    }

    public static String getCapabilityDisplayName(Object capability) {
        // TODO: look for schema annotation
        String className;
        if (capability instanceof JAXBElement) {
            className = ((JAXBElement) capability).getDeclaredType().getSimpleName();
        } else {
            className = capability.getClass().getSimpleName();
        }
        if (className.endsWith("CapabilityType")) {
            return className.substring(0, className.length() - "CapabilityType".length());
        }
        return className;
    }

    public static boolean isPasswordReturnedByDefault(CredentialsCapabilityType capability) {
        if (capability == null) {
            return false;
        }
        PasswordCapabilityType password = capability.getPassword();
        if (password == null) {
            return false;
        }
        if (password.isReturnedByDefault() == null) {
            return true;
        }
        return password.isReturnedByDefault();
    }

    public static boolean isActivationStatusReturnedByDefault(ActivationCapabilityType capability) {
        if (capability == null) {
            return false;
        }
        ActivationStatusCapabilityType statusCap = getEffectiveActivationStatus(capability);
        if (statusCap == null) {
            return false;
        }
        if (statusCap.isReturnedByDefault() == null) {
            return true;
        }
        return statusCap.isReturnedByDefault();
    }

    public static boolean isActivationLockoutStatusReturnedByDefault(ActivationCapabilityType capability) {
        if (capability == null) {
            return false;
        }
        ActivationLockoutStatusCapabilityType statusCap = capability.getLockoutStatus();
        if (statusCap == null) {
            return false;
        }
        if (statusCap.isReturnedByDefault() == null) {
            return true;
        }
        return statusCap.isReturnedByDefault();
    }

    public static boolean isActivationValidFromReturnedByDefault(ActivationCapabilityType capability) {
        if (capability == null) {
            return false;
        }
        ActivationValidityCapabilityType valCap = capability.getValidFrom();
        if (valCap == null) {
            return false;
        }
        if (valCap.isReturnedByDefault() == null) {
            return true;
        }
        return valCap.isReturnedByDefault();
    }

    public static boolean isActivationValidToReturnedByDefault(ActivationCapabilityType capability) {
        if (capability == null) {
            return false;
        }
        ActivationValidityCapabilityType valCap = capability.getValidTo();
        if (valCap == null) {
            return false;
        }
        if (valCap.isReturnedByDefault() == null) {
            return true;
        }
        return valCap.isReturnedByDefault();
    }

    @SuppressWarnings("unchecked")
    public static CapabilityType asCapabilityType(Object capabilityObject) {
        return capabilityObject instanceof CapabilityType ?
                (CapabilityType) capabilityObject :
                ((JAXBElement<? extends CapabilityType>) capabilityObject).getValue();
    }

    public static void fillDefaults(@NotNull CapabilityType capability) {
        if (capability.isEnabled() == null) {
            capability.setEnabled(true);
        }
        if (capability instanceof ActivationCapabilityType) {
            ActivationCapabilityType act = ((ActivationCapabilityType) capability);
            if (act.getStatus() == null) {
                ActivationStatusCapabilityType st = new ActivationStatusCapabilityType();
                act.setStatus(st);
                st.setEnabled(false);                // TODO check if all midPoint code honors this flag!
                st.setReturnedByDefault(false);
                st.setIgnoreAttribute(true);
            } else {
                ActivationStatusCapabilityType st = act.getStatus();
                st.setEnabled(def(st.isEnabled(), true));
                st.setReturnedByDefault(def(st.isReturnedByDefault(), true));
                st.setIgnoreAttribute(def(st.isIgnoreAttribute(), true));
            }
            if (act.getLockoutStatus() == null) {
                ActivationLockoutStatusCapabilityType st = new ActivationLockoutStatusCapabilityType();
                act.setLockoutStatus(st);
                st.setEnabled(false);
                st.setReturnedByDefault(false);
                st.setIgnoreAttribute(true);
            } else {
                ActivationLockoutStatusCapabilityType st = act.getLockoutStatus();
                st.setEnabled(def(st.isEnabled(), true));
                st.setReturnedByDefault(def(st.isReturnedByDefault(), true));
                st.setIgnoreAttribute(def(st.isIgnoreAttribute(), true));
            }
            if (act.getValidFrom() == null) {
                ActivationValidityCapabilityType vf = new ActivationValidityCapabilityType();
                act.setValidFrom(vf);
                vf.setEnabled(false);
                vf.setReturnedByDefault(false);
            } else {
                ActivationValidityCapabilityType vf = act.getValidFrom();
                vf.setEnabled(def(vf.isEnabled(), true));
                vf.setReturnedByDefault(def(vf.isReturnedByDefault(), true));
            }
            if (act.getValidTo() == null) {
                ActivationValidityCapabilityType vt = new ActivationValidityCapabilityType();
                act.setValidTo(vt);
                vt.setEnabled(false);
                vt.setReturnedByDefault(false);
            } else {
                ActivationValidityCapabilityType vt = act.getValidTo();
                vt.setEnabled(def(vt.isEnabled(), true));
                vt.setReturnedByDefault(def(vt.isReturnedByDefault(), true));
            }
        } else if (capability instanceof CredentialsCapabilityType) {
            CredentialsCapabilityType cred = ((CredentialsCapabilityType) capability);
            if (cred.getPassword() == null) {
                PasswordCapabilityType pc = new PasswordCapabilityType();
                cred.setPassword(pc);
                pc.setEnabled(false);
                pc.setReturnedByDefault(false);
            } else {
                PasswordCapabilityType pc = cred.getPassword();
                pc.setEnabled(def(pc.isEnabled(), true));
                pc.setReturnedByDefault(def(pc.isReturnedByDefault(), true));
            }
        }
    }

    private static Boolean def(Boolean originalValue, boolean defaultValue) {
        return originalValue != null ? originalValue : defaultValue;
    }

    public static <T extends CapabilityType> T getEffectiveCapability(CapabilitiesType capabilitiesType, Class<T> capabilityClass) {
        if (capabilitiesType == null) {
            return null;
        }
        if (capabilitiesType.getConfigured() != null) {
            T configuredCapability = CapabilityUtil.getCapability(capabilitiesType.getConfigured().getAny(), capabilityClass);
            if (configuredCapability != null) {
                return configuredCapability;
            }
            // No configured capability entry, fallback to native capability
        }
        if (capabilitiesType.getNative() != null) {
            T nativeCapability = CapabilityUtil.getCapability(capabilitiesType.getNative().getAny(), capabilityClass);
            if (nativeCapability != null) {
                return nativeCapability;
            }
        }
        return null;
    }

    public static ActivationStatusCapabilityType getEffectiveActivationStatus(ActivationCapabilityType act) {
        if (act != null && act.getStatus() != null && !Boolean.FALSE.equals(act.getStatus().isEnabled())) {
            return act.getStatus();
        } else {
            return null;
        }
    }

    public static ActivationValidityCapabilityType getEffectiveActivationValidFrom(ActivationCapabilityType act) {
        if (act != null && act.getValidFrom() != null && !Boolean.FALSE.equals(act.getValidFrom().isEnabled())) {
            return act.getValidFrom();
        } else {
            return null;
        }
    }

    public static ActivationValidityCapabilityType getEffectiveActivationValidTo(ActivationCapabilityType act) {
        if (act != null && act.getValidTo() != null && !Boolean.FALSE.equals(act.getValidTo().isEnabled())) {
            return act.getValidTo();
        } else {
            return null;
        }
    }

    public static ActivationLockoutStatusCapabilityType getEffectiveActivationLockoutStatus(ActivationCapabilityType act) {
        if (act != null && act.getLockoutStatus() != null && !Boolean.FALSE.equals(act.getLockoutStatus().isEnabled())) {
            return act.getLockoutStatus();
        } else {
            return null;
        }
    }

    public static <T extends CapabilityType>  boolean hasNativeCapability(CapabilitiesType capabilities, Class<T> capabilityClass) {
        if (capabilities == null) {
            return false;
        }
        CapabilityCollectionType nativeCaps = capabilities.getNative();
        if (nativeCaps == null) {
            return false;
        }
        return getCapability(nativeCaps.getAny(), capabilityClass) != null;
    }

    public static <T extends CapabilityType>  boolean hasConfiguredCapability(CapabilitiesType capabilities, Class<T> capabilityClass) {
        if (capabilities == null) {
            return false;
        }
        CapabilityCollectionType configuredCaps = capabilities.getConfigured();
        if (configuredCaps == null) {
            return false;
        }
        return getCapability(configuredCaps.getAny(), capabilityClass) != null;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="gaia3d.persistence.ConverterMapper">

	<!-- converter job 총 건수 -->
	<select id="getConverterJobTotalCount" parameterType="converterJob" resultType="long">
		/* getConverterJobTotalCount */
		SELECT COUNT(converter_job_id)
		FROM converter_job
		WHERE data_group_target = 'user'
		<if test="userId != null and userId != ''">
			AND user_id = #{userId}
		</if>
		<if test="status != null and status != ''">
			AND status = #{status}
		</if>
		<if test="searchWord != null and searchWord != '' and searchValue != null and searchValue != '' and searchOption == '0'.toString()">
			AND ${searchWord} = #{searchValue}
		</if>
		<if test="searchWord != null and searchWord != '' and searchValue != null and searchValue != '' and searchOption == '1'.toString()">
			AND ${searchWord} LIKE '%' || #{searchValue} || '%'
		</if>
		<if test="startDate != null and startDate != ''">
			<![CDATA[
			AND insert_date >= TO_TIMESTAMP(#{startDate}, 'YYYYMMDDHH24MISSUS')
			]]>
		</if>
		<if test="endDate != null and endDate != ''">
			<![CDATA[
			AND insert_date <= TO_TIMESTAMP(#{endDate}, 'YYYYMMDDHH24MISSUS')
			]]>
		</if>
	</select>

	<!-- converter job file 총 건수 -->
	<select id="getConverterJobFileTotalCount" parameterType="converterJobFile" resultType="long">
		/* getConverterJobFileTotalCount */
		SELECT COUNT(X.*)
		FROM (
			SELECT A.*, B.file_name
			FROM converter_job_file A, upload_data_file B
			WHERE A.upload_data_file_id = B.upload_data_file_id
			<if test="userId != null and userId != ''">
					AND A.user_id = #{userId}
			</if>
			<if test="status != null and status != ''">
					AND A.status = #{status}
			</if>
			<if test="searchWord != null and searchWord != '' and searchValue != null and searchValue != '' and searchOption == '0'.toString()">
					AND B.${searchWord} = #{searchValue}
			</if>
			<if test="searchWord != null and searchWord != '' and searchValue != null and searchValue != '' and searchOption == '1'.toString()">
					AND B.${searchWord} LIKE '%' || #{searchValue} || '%'
			</if>
			<if test="startDate != null and startDate != ''">
				<![CDATA[
						AND A.insert_date >= TO_TIMESTAMP(#{startDate}, 'YYYYMMDDHH24MISSUS')
			]]>
			</if>
			<if test="endDate != null and endDate != ''">
				<![CDATA[
						AND A.insert_date <= TO_TIMESTAMP(#{endDate}, 'YYYYMMDDHH24MISSUS')
			]]>
			</if>
			<if test="converterJobId != null">
					AND A.converter_job_id = #{converterJobId}
			</if>
			<choose>
				<when test="orderWord != null and orderWord != '' and orderValue != null and orderValue != ''">
					ORDER BY A.${orderWord} ${orderValue}
				</when>
				<otherwise>
					ORDER BY A.insert_date DESC, A.converter_job_id DESC
				</otherwise>
			</choose>
		) X
	</select>

	<!-- converter job 목록 -->
	<select id="getListConverterJob" parameterType="converterJob" resultType="converterJob">
		/* getListConverterJob */
		SELECT X.*,
		(SELECT COUNT(converter_job_file_id) FROM converter_job_file WHERE converter_job_id = X.converter_job_id) AS converter_file_count
		FROM (
		SELECT A.*
		FROM converter_job A
		WHERE data_group_target = 'user'
		<if test="userId != null and userId != ''">
			AND user_id = #{userId}
		</if>
		<if test="status != null and status != ''">
			AND A.status = #{status}
		</if>
		<if test="searchWord != null and searchWord != '' and searchValue != null and searchValue != '' and searchOption == '0'.toString()">
			AND A.${searchWord} = #{searchValue}
		</if>
		<if test="searchWord != null and searchWord != '' and searchValue != null and searchValue != '' and searchOption == '1'.toString()">
			AND A.${searchWord} LIKE '%' || #{searchValue} || '%'
		</if>
		<if test="startDate != null and startDate != ''">
			<![CDATA[
				AND A.insert_date >= TO_TIMESTAMP(#{startDate}, 'YYYYMMDDHH24MISSUS')
				]]>
		</if>
		<if test="endDate != null and endDate != ''">
			<![CDATA[
				AND A.insert_date <= TO_TIMESTAMP(#{endDate}, 'YYYYMMDDHH24MISSUS')
				]]>
		</if>
		<choose>
			<when test="orderWord != null and orderWord != '' and orderValue != null and orderValue != ''">
				ORDER BY A.${orderWord} ${orderValue}
			</when>
			<otherwise>
				ORDER BY A.insert_date DESC, A.converter_job_id DESC
			</otherwise>
		</choose>
		OFFSET #{offset} LIMIT #{limit}
		) X
	</select>

	<!-- converter job file 목록 -->
	<select id="getListConverterJobFile" parameterType="converterJobFile" resultType="converterJobFile">
		/* getListConverterJobFile */
		SELECT X.*
		FROM (
			SELECT A.*, B.file_name
			FROM converter_job_file A, upload_data_file B
			WHERE A.upload_data_file_id = B.upload_data_file_id
				<if test="userId != null and userId != ''">
					AND A.user_id = #{userId}
				</if>
				<if test="status != null and status != ''">
					AND A.status = #{status}
				</if>
				<if test="searchWord != null and searchWord != '' and searchValue != null and searchValue != '' and searchOption == '0'.toString()">
					AND B.${searchWord} = #{searchValue}
				</if>
				<if test="searchWord != null and searchWord != '' and searchValue != null and searchValue != '' and searchOption == '1'.toString()">
					AND B.${searchWord} LIKE '%' || #{searchValue} || '%'
				</if>
				<if test="startDate != null and startDate != ''">
					<![CDATA[
						AND A.insert_date >= TO_TIMESTAMP(#{startDate}, 'YYYYMMDDHH24MISSUS')
						]]>
				</if>
				<if test="endDate != null and endDate != ''">
					<![CDATA[
						AND A.insert_date <= TO_TIMESTAMP(#{endDate}, 'YYYYMMDDHH24MISSUS')
						]]>
				</if>
				<if test="converterJobId != null">
				AND A.converter_job_id = #{converterJobId}
				</if>
			<choose>
				<when test="orderWord != null and orderWord != '' and orderValue != null and orderValue != ''">
					ORDER BY A.${orderWord} ${orderValue}
				</when>
				<otherwise>
					ORDER BY A.insert_date DESC, A.converter_job_id DESC
				</otherwise>
			</choose>
			OFFSET #{offset} LIMIT #{limit}
		) X
	</select>

	<!-- 데이터 변환 파일 목록 -->
	<select id="getListConverterJobFileByConverterJob" parameterType="converterJob" resultType="converterJobFile">
		/* getListConverterJobFileByConverterJob */
		SELECT *
		FROM converter_job_file
		WHERE converter_job_id = #{converterJobId}
		<if test="userId != null and userId != ''">
			AND user_id = #{userId}
		</if>
	</select>

	<!-- converter job 등록 -->
	<insert id="insertConverterJob" parameterType="converterJob">
		/* insertConverterJob */
		<selectKey keyProperty="converterJobId" resultType="long" order="BEFORE">
			SELECT NEXTVAL('converter_job_seq')
		</selectKey>
		INSERT INTO converter_job(
		converter_job_id, upload_data_id, data_group_target, user_id, title, usf, converter_template, y_axis_up, file_count,
		<if test="status != null and status != ''">
			status,
		</if>
		error_code
		) VALUES (
		#{converterJobId}, #{uploadDataId}, #{dataGroupTarget}, #{userId}, #{title}, #{usf}, #{converterTemplate}, #{yAxisUp}, #{fileCount},
		<if test="status != null and status != ''">
			#{status},
		</if>
		#{errorCode}
		)
	</insert>

	<!-- converter job file 등록 -->
	<insert id="insertConverterJobFile" parameterType="converterJobFile">
		/* insertConverterJobFile */
		<selectKey keyProperty="converterJobFileId" resultType="long" order="BEFORE">
			SELECT NEXTVAL('converter_job_file_seq')
		</selectKey>
		INSERT INTO converter_job_file(
		converter_job_file_id, converter_job_id, upload_data_id, upload_data_file_id, data_group_id, user_id,
		<if test="status != null and status != ''">
			status,
		</if>
		error_code
		) VALUES (
		#{converterJobFileId}, #{converterJobId}, #{uploadDataId}, #{uploadDataFileId}, #{dataGroupId}, #{userId},
		<if test="status != null and status != ''">
			#{status},
		</if>
		#{errorCode}
		)
	</insert>

	<!-- converter job -->
	<update id="updateConverterJob" parameterType="converterJob">
		/* updateConverterJob */
		UPDATE converter_job
		SET
		<if test="title != null and title != ''">
			title = #{title},
		</if>
		<if test="status != null and status != ''">
			status = #{status},
		</if>
		<if test="converterTemplate != null and converterTemplate != ''">
			converter_type = #{converterTemplate},
		</if>
		<if test="usf != null">
			usf = #{usf},
		</if>
		<if test="yAxisUp != null">
			y_axis_up = #{yAxisUp},
		</if>
		<if test="errorCode != null and errorCode != ''">
			error_code = #{errorCode},
		</if>
		update_date = now()
		WHERE converter_job_id = #{converterJobId}
		<if test="userId != null and userId != ''">
			AND user_id = #{userId}
		</if>
	</update>

	<!-- converter job file -->
	<update id="updateConverterJobFile" parameterType="converterJobFile">
		/* updateConverterJobFile */
		UPDATE converter_job_file
		<set>
			<if test="status != null and status != ''">
				status = #{status},
			</if>
			<if test="errorCode != null and errorCode != ''">
				error_code = #{errorCode},
			</if>
		</set>
		WHERE converter_job_file_id = #{converterJobFileId}
		<if test="userId != null and userId != ''">
			AND user_id = #{userId}
		</if>
	</update>
</mapper>


text:
package org.codelibs.elasticsearch.ja.analysis;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.ja.tokenattributes.PartOfSpeechAttribute;
import org.codelibs.analysis.ja.PosConcatenationFilter;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.analysis.AbstractTokenFilterFactory;
import org.elasticsearch.index.analysis.Analysis;

public class PosConcatenationFilterFactory extends AbstractTokenFilterFactory {

    private final Set<String> posTags = new HashSet<>();

    public PosConcatenationFilterFactory(final IndexSettings indexSettings, final Environment environment, final String name, final Settings settings) {
        super(indexSettings, name, settings);

        final List<String> tagList = Analysis.getWordList(environment, settings, "tags");
        if (tagList != null) {
            posTags.addAll(tagList);
        }
    }

    @Override
    public TokenStream create(final TokenStream tokenStream) {
        final PartOfSpeechAttribute posAtt = tokenStream.addAttribute(PartOfSpeechAttribute.class);
        return new PosConcatenationFilter(tokenStream, posTags, () -> posAtt.getPartOfSpeech());
    }
}


text:
class StateDef < ActiveRecord::Base
  belongs_to :module_def
  #has_many   :transition_defs, :foreign_key => :from_state_id

  #serialize  :view_form
end


text:
using Xunit;

namespace IharBury.Algorithms.Tests
{
    public class Point2DInt16Tests
    {
        [Fact]
        public void PointOnTheLineIsNotToTheLeft()
        {
            var point = new Point2DInt16(3, 3);
            var backPoint = new Point2DInt16(1, 1);
            var forwardPoint = new Point2DInt16(2, 2);
            Assert.False(point.IsToTheLeftOf(backPoint, forwardPoint));
        }

        [Fact]
        public void WhenAPointIsToTheLeftItIsDetected()
        {
            var point = new Point2DInt16(3, 3);
            var backPoint = new Point2DInt16(1, 1);
            var forwardPoint = new Point2DInt16(1, 2);
            Assert.True(point.IsToTheLeftOf(backPoint, forwardPoint));
        }

        [Fact]
        public void WhenAPointIsToTheRightItIsNotToTheLeft()
        {
            var point = new Point2DInt16(3, 3);
            var backPoint = new Point2DInt16(1, 1);
            var forwardPoint = new Point2DInt16(2, 1);
            Assert.False(point.IsToTheLeftOf(backPoint, forwardPoint));
        }
    }
}


text:
#include "Common.h"

class StreamReader
{
public:
	StreamReader(std::istream &stream)
		:m_Stream(stream)
	{
	}

	virtual ~StreamReader()
	{
	}

	template<typename T>
	void Read(T *object)
	{
		Read(object,sizeof(T));
	}

	template<typename T>
	void Read(T *object, size_t len)
	{
		m_Stream.read(reinterpret_cast<char*>(object),len);
	}

	void SetPosition(size_t pos)
	{
		m_Stream.seekg(pos);
	}

	size_t GetPosition()
	{
		return m_Stream.tellg();
	}

	std::istream &GetStream()
	{
		return m_Stream;
	}

	void Align(size_t alignment = 4)
	{
		int pos = GetPosition();
		if(pos % alignment)
			SetPosition( pos + alignment - pos%alignment );
	}

protected:
	std::istream &m_Stream;
};

#endif


text:
/* global tavJS, HTMLFormElement, Object */

/**
 * Get run tests in form (HTMLFormElement)
 * @author Helio de Paula Nogueira <helio.nogueir@gmail.com>
 * @version 1.0.0
 *
 * @param {formObject} formObject HTMLFormElement
 * @returns {Array} Results of validate
 */
tavJS.test.run = function (formObject) {
    var test = new Object();
    try {
        if (formObject instanceof HTMLFormElement) {
            var index = 0;
            var rowSet = new Array();
            // Data
            tavJS.import('core/data');
            for (var i = 0, element; (element = formObject.elements[i++]); ) {
                var row = tavJS.data.get(element);
                if (null !== row) {
                    rowSet[index++] = row;
                }
            }
            // Validate
            tavJS.import('core/validate');
            test.validate = tavJS.validate.test(rowSet);
        }
    } catch (ex) {
        console.log(ex);
    }
    return test;
};


text:
const L = require('../leaflet.js');
const layer = require('./Layer.js');
const utils = require('../utils');

export class LeafletVelocityModel extends layer.LeafletLayerModel {
  defaults() {
    return {
      ...super.defaults(),
      _view_name: 'LeafletVelocityView',
      _model_name: 'LeafletVelocityModel',
      displayValues: true,
      displayOptions: {
        velocityType: 'Global Wind',
        position: 'bottomleft',
        emptyString: 'No velocity data',
        angleConvention: 'bearingCW',
        displayPosition: 'bottomleft',
        displayEmptyString: 'No velocity data',
        speedUnit: 'kt'
      },
      data: [],
      minVelocity: 0,
      maxVelocity: 10,
      velocityScale: 0.005,
      colorScale: []
    };
  }
}

export class LeafletVelocityView extends layer.LeafletLayerView {
  create_obj() {
    var options = this.get_options();
    options.data = this.model.get('data');
    this.obj = L.velocityLayer(options);
  }

  model_events() {
    super.model_events();
    this.listenTo(
      this.model,
      'change:data',
      function() {
        const data = this.model.get('data');
        this.obj.setData(data);
      },
      this
    );
    // Separate display_options from the options to perform a shallow copy.
    var key = 'display_options';
    this.listenTo(
      this.model,
      'change:' + key,
      function() {
        var options = {};
        options[utils.camel_case(key)] = { ...this.model.get(key) };
        L.setOptions(this.obj, options);
      },
      this
    );
  }
}


text:
import pytest

import numpy as np

from scipy import sparse
from scipy.sparse import csgraph
from scipy.linalg import eigh

from sklearn.manifold import SpectralEmbedding
from sklearn.manifold._spectral_embedding import _graph_is_connected
from sklearn.manifold._spectral_embedding import _graph_connected_component
from sklearn.manifold import spectral_embedding
from sklearn.metrics.pairwise import rbf_kernel
from sklearn.metrics import normalized_mutual_info_score
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.utils.extmath import _deterministic_vector_sign_flip
from sklearn.utils._testing import assert_array_almost_equal
from sklearn.utils._testing import assert_array_equal

# non centered, sparse centers to check the
centers = np.array([
    [0.0, 5.0, 0.0, 0.0, 0.0],
    [0.0, 0.0, 4.0, 0.0, 0.0],
    [1.0, 0.0, 0.0, 5.0, 1.0],
])
n_samples = 1000
n_clusters, n_features = centers.shape
S, true_labels = make_blobs(n_samples=n_samples, centers=centers,
                            cluster_std=1., random_state=42)

def _assert_equal_with_sign_flipping(A, B, tol=0.0):
    """ Check array A and B are equal with possible sign flipping on
    each columns"""
    tol_squared = tol ** 2
    for A_col, B_col in zip(A.T, B.T):
        assert (np.max((A_col - B_col) ** 2) <= tol_squared or
                np.max((A_col + B_col) ** 2) <= tol_squared)

def test_sparse_graph_connected_component():
    rng = np.random.RandomState(42)
    n_samples = 300
    boundaries = [0, 42, 121, 200, n_samples]
    p = rng.permutation(n_samples)
    connections = []

    for start, stop in zip(boundaries[:-1], boundaries[1:]):
        group = p[start:stop]
        # Connect all elements within the group at least once via an
        # arbitrary path that spans the group.
        for i in range(len(group) - 1):
            connections.append((group[i], group[i + 1]))

        # Add some more random connections within the group
        min_idx, max_idx = 0, len(group) - 1
        n_random_connections = 1000
        source = rng.randint(min_idx, max_idx, size=n_random_connections)
        target = rng.randint(min_idx, max_idx, size=n_random_connections)
        connections.extend(zip(group[source], group[target]))

    # Build a symmetric affinity matrix
    row_idx, column_idx = tuple(np.array(connections).T)
    data = rng.uniform(.1, 42, size=len(connections))
    affinity = sparse.coo_matrix((data, (row_idx, column_idx)))
    affinity = 0.5 * (affinity + affinity.T)

    for start, stop in zip(boundaries[:-1], boundaries[1:]):
        component_1 = _graph_connected_component(affinity, p[start])
        component_size = stop - start
        assert component_1.sum() == component_size

        # We should retrieve the same component mask by starting by both ends
        # of the group
        component_2 = _graph_connected_component(affinity, p[stop - 1])
        assert component_2.sum() == component_size
        assert_array_equal(component_1, component_2)

def test_spectral_embedding_two_components(seed=36):
    # Test spectral embedding with two components
    random_state = np.random.RandomState(seed)
    n_sample = 100
    affinity = np.zeros(shape=[n_sample * 2, n_sample * 2])
    # first component
    affinity[0:n_sample,
             0:n_sample] = np.abs(random_state.randn(n_sample, n_sample)) + 2
    # second component
    affinity[n_sample::,
             n_sample::] = np.abs(random_state.randn(n_sample, n_sample)) + 2

    # Test of internal _graph_connected_component before connection
    component = _graph_connected_component(affinity, 0)
    assert component[:n_sample].all()
    assert not component[n_sample:].any()
    component = _graph_connected_component(affinity, -1)
    assert not component[:n_sample].any()
    assert component[n_sample:].all()

    # connection
    affinity[0, n_sample + 1] = 1
    affinity[n_sample + 1, 0] = 1
    affinity.flat[::2 * n_sample + 1] = 0
    affinity = 0.5 * (affinity + affinity.T)

    true_label = np.zeros(shape=2 * n_sample)
    true_label[0:n_sample] = 1

    se_precomp = SpectralEmbedding(n_components=1, affinity="precomputed",
                                   random_state=np.random.RandomState(seed))
    embedded_coordinate = se_precomp.fit_transform(affinity)
    # Some numpy versions are touchy with types
    embedded_coordinate = \
        se_precomp.fit_transform(affinity.astype(np.float32))
    # thresholding on the first components using 0.
    label_ = np.array(embedded_coordinate.ravel() < 0, dtype="float")
    assert normalized_mutual_info_score(
        true_label, label_) == pytest.approx(1.0)

@pytest.mark.parametrize("X", [S, sparse.csr_matrix(S)],
                         ids=["dense", "sparse"])
def test_spectral_embedding_precomputed_affinity(X, seed=36):
    # Test spectral embedding with precomputed kernel
    gamma = 1.0
    se_precomp = SpectralEmbedding(n_components=2, affinity="precomputed",
                                   random_state=np.random.RandomState(seed))
    se_rbf = SpectralEmbedding(n_components=2, affinity="rbf",
                               gamma=gamma,
                               random_state=np.random.RandomState(seed))
    embed_precomp = se_precomp.fit_transform(rbf_kernel(X, gamma=gamma))
    embed_rbf = se_rbf.fit_transform(X)
    assert_array_almost_equal(
        se_precomp.affinity_matrix_, se_rbf.affinity_matrix_)
    _assert_equal_with_sign_flipping(embed_precomp, embed_rbf, 0.05)

def test_precomputed_nearest_neighbors_filtering():
    # Test precomputed graph filtering when containing too many neighbors
    n_neighbors = 2
    results = []
    for additional_neighbors in [0, 10]:
        nn = NearestNeighbors(
            n_neighbors=n_neighbors + additional_neighbors).fit(S)
        graph = nn.kneighbors_graph(S, mode='connectivity')
        embedding = SpectralEmbedding(random_state=0, n_components=2,
                                      affinity='precomputed_nearest_neighbors',
                                      n_neighbors=n_neighbors
                                      ).fit(graph).embedding_
        results.append(embedding)

    assert_array_equal(results[0], results[1])

@pytest.mark.parametrize("X", [S, sparse.csr_matrix(S)],
                         ids=["dense", "sparse"])
def test_spectral_embedding_callable_affinity(X, seed=36):
    # Test spectral embedding with callable affinity
    gamma = 0.9
    kern = rbf_kernel(S, gamma=gamma)
    se_callable = SpectralEmbedding(n_components=2,
                                    affinity=(
                                        lambda x: rbf_kernel(x, gamma=gamma)),
                                    gamma=gamma,
                                    random_state=np.random.RandomState(seed))
    se_rbf = SpectralEmbedding(n_components=2, affinity="rbf",
                               gamma=gamma,
                               random_state=np.random.RandomState(seed))
    embed_rbf = se_rbf.fit_transform(X)
    embed_callable = se_callable.fit_transform(X)
    assert_array_almost_equal(
        se_callable.affinity_matrix_, se_rbf.affinity_matrix_)
    assert_array_almost_equal(kern, se_rbf.affinity_matrix_)
    _assert_equal_with_sign_flipping(embed_rbf, embed_callable, 0.05)

# TODO: Remove when pyamg does replaces sp.rand call with np.random.rand
# https://github.com/scikit-learn/scikit-learn/issues/15913
@pytest.mark.filterwarnings(
    "ignore:scipy.rand is deprecated:DeprecationWarning:pyamg.*")
# TODO: Remove when pyamg removes the use of np.float
@pytest.mark.filterwarnings(
    "ignore:`np.float` is a deprecated alias:DeprecationWarning:pyamg.*")
def test_spectral_embedding_amg_solver(seed=36):
    # Test spectral embedding with amg solver
    pytest.importorskip('pyamg')

    se_amg = SpectralEmbedding(n_components=2, affinity="nearest_neighbors",
                               eigen_solver="amg", n_neighbors=5,
                               random_state=np.random.RandomState(seed))
    se_arpack = SpectralEmbedding(n_components=2, affinity="nearest_neighbors",
                                  eigen_solver="arpack", n_neighbors=5,
                                  random_state=np.random.RandomState(seed))
    embed_amg = se_amg.fit_transform(S)
    embed_arpack = se_arpack.fit_transform(S)
    _assert_equal_with_sign_flipping(embed_amg, embed_arpack, 1e-5)

    # same with special case in which amg is not actually used
    # regression test for #10715
    # affinity between nodes
    row = [0, 0, 1, 2, 3, 3, 4]
    col = [1, 2, 2, 3, 4, 5, 5]
    val = [100, 100, 100, 1, 100, 100, 100]

    affinity = sparse.coo_matrix((val + val, (row + col, col + row)),
                                 shape=(6, 6)).toarray()
    se_amg.affinity = "precomputed"
    se_arpack.affinity = "precomputed"
    embed_amg = se_amg.fit_transform(affinity)
    embed_arpack = se_arpack.fit_transform(affinity)
    _assert_equal_with_sign_flipping(embed_amg, embed_arpack, 1e-5)

# TODO: Remove filterwarnings when pyamg does replaces sp.rand call with
# np.random.rand:
# https://github.com/scikit-learn/scikit-learn/issues/15913
@pytest.mark.filterwarnings(
    "ignore:scipy.rand is deprecated:DeprecationWarning:pyamg.*")
# TODO: Remove when pyamg removes the use of np.float
@pytest.mark.filterwarnings(
    "ignore:`np.float` is a deprecated alias:DeprecationWarning:pyamg.*")
def test_spectral_embedding_amg_solver_failure():
    # Non-regression test for amg solver failure (issue #13393 on github)
    pytest.importorskip('pyamg')
    seed = 36
    num_nodes = 100
    X = sparse.rand(num_nodes, num_nodes, density=0.1, random_state=seed)
    upper = sparse.triu(X) - sparse.diags(X.diagonal())
    sym_matrix = upper + upper.T
    embedding = spectral_embedding(sym_matrix,
                                   n_components=10,
                                   eigen_solver='amg',
                                   random_state=0)

    # Check that the learned embedding is stable w.r.t. random solver init:
    for i in range(3):
        new_embedding = spectral_embedding(sym_matrix,
                                           n_components=10,
                                           eigen_solver='amg',
                                           random_state=i + 1)
        _assert_equal_with_sign_flipping(embedding, new_embedding, tol=0.05)

@pytest.mark.filterwarnings("ignore:the behavior of nmi will "
                            "change in version 0.22")
def test_pipeline_spectral_clustering(seed=36):
    # Test using pipeline to do spectral clustering
    random_state = np.random.RandomState(seed)
    se_rbf = SpectralEmbedding(n_components=n_clusters,
                               affinity="rbf",
                               random_state=random_state)
    se_knn = SpectralEmbedding(n_components=n_clusters,
                               affinity="nearest_neighbors",
                               n_neighbors=5,
                               random_state=random_state)
    for se in [se_rbf, se_knn]:
        km = KMeans(n_clusters=n_clusters, random_state=random_state)
        km.fit(se.fit_transform(S))
        assert_array_almost_equal(
            normalized_mutual_info_score(
                km.labels_,
                true_labels), 1.0, 2)

def test_spectral_embedding_unknown_eigensolver(seed=36):
    # Test that SpectralClustering fails with an unknown eigensolver
    se = SpectralEmbedding(n_components=1, affinity="precomputed",
                           random_state=np.random.RandomState(seed),
                           eigen_solver="<unknown>")
    with pytest.raises(ValueError):
        se.fit(S)

def test_spectral_embedding_unknown_affinity(seed=36):
    # Test that SpectralClustering fails with an unknown affinity type
    se = SpectralEmbedding(n_components=1, affinity="<unknown>",
                           random_state=np.random.RandomState(seed))
    with pytest.raises(ValueError):
        se.fit(S)

def test_connectivity(seed=36):
    # Test that graph connectivity test works as expected
    graph = np.array([[1, 0, 0, 0, 0],
                      [0, 1, 1, 0, 0],
                      [0, 1, 1, 1, 0],
                      [0, 0, 1, 1, 1],
                      [0, 0, 0, 1, 1]])
    assert not _graph_is_connected(graph)
    assert not _graph_is_connected(sparse.csr_matrix(graph))
    assert not _graph_is_connected(sparse.csc_matrix(graph))
    graph = np.array([[1, 1, 0, 0, 0],
                      [1, 1, 1, 0, 0],
                      [0, 1, 1, 1, 0],
                      [0, 0, 1, 1, 1],
                      [0, 0, 0, 1, 1]])
    assert _graph_is_connected(graph)
    assert _graph_is_connected(sparse.csr_matrix(graph))
    assert _graph_is_connected(sparse.csc_matrix(graph))

def test_spectral_embedding_deterministic():
    # Test that Spectral Embedding is deterministic
    random_state = np.random.RandomState(36)
    data = random_state.randn(10, 30)
    sims = rbf_kernel(data)
    embedding_1 = spectral_embedding(sims)
    embedding_2 = spectral_embedding(sims)
    assert_array_almost_equal(embedding_1, embedding_2)

def test_spectral_embedding_unnormalized():
    # Test that spectral_embedding is also processing unnormalized laplacian
    # correctly
    random_state = np.random.RandomState(36)
    data = random_state.randn(10, 30)
    sims = rbf_kernel(data)
    n_components = 8
    embedding_1 = spectral_embedding(sims,
                                     norm_laplacian=False,
                                     n_components=n_components,
                                     drop_first=False)

    # Verify using manual computation with dense eigh
    laplacian, dd = csgraph.laplacian(sims, normed=False,
                                      return_diag=True)
    _, diffusion_map = eigh(laplacian)
    embedding_2 = diffusion_map.T[:n_components]
    embedding_2 = _deterministic_vector_sign_flip(embedding_2).T

    assert_array_almost_equal(embedding_1, embedding_2)

def test_spectral_embedding_first_eigen_vector():
    # Test that the first eigenvector of spectral_embedding
    # is constant and that the second is not (for a connected graph)
    random_state = np.random.RandomState(36)
    data = random_state.randn(10, 30)
    sims = rbf_kernel(data)
    n_components = 2

    for seed in range(10):
        embedding = spectral_embedding(sims,
                                       norm_laplacian=False,
                                       n_components=n_components,
                                       drop_first=False,
                                       random_state=seed)

        assert np.std(embedding[:, 0]) == pytest.approx(0)
        assert np.std(embedding[:, 1]) > 1e-3

# TODO: Remove in 1.1
@pytest.mark.parametrize("affinity", ["precomputed",
                                      "precomputed_nearest_neighbors"])
def test_spectral_embedding_pairwise_deprecated(affinity):
    se = SpectralEmbedding(affinity=affinity)
    msg = r"Attribute _pairwise was deprecated in version 0\.24"
    with pytest.warns(FutureWarning, match=msg):
        se._pairwise


text:
import httpretty
import json

from formspree import settings
from formspree.app import DB
from formspree.forms.helpers import HASH
from formspree.users.models import User, Email
from formspree.forms.models import Form, Submission

from formspree_test_case import FormspreeTestCase
from utils import parse_confirmation_link_sent

class TestFormCreationFromDashboard(FormspreeTestCase):

    @httpretty.activate
    def test_form_creation(self):
        httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json')

        # register user
        r = self.client.post('/register',
            data={'email': 'colorado@springs.com',
                  'password': 'banana'}
        )
        self.assertEqual(r.status_code, 302)
        self.assertEqual(1, User.query.count())

        # fail to create form
        r = self.client.post('/forms',
            headers={'Content-type': 'application/json'},
            data={'email': 'hope@springs.com'}
        )
        self.assertEqual(r.status_code, 402)
        self.assertIn('error', json.loads(r.data))
        self.assertEqual(0, Form.query.count())

        # upgrade user manually
        user = User.query.filter_by(email='colorado@springs.com').first()
        user.upgraded = True
        DB.session.add(user)
        DB.session.commit()

        # successfully create form
        r = self.client.post('/forms',
            headers={'Accept': 'application/json', 'Content-type': 'application/json'},
            data=json.dumps({'email': 'hope@springs.com'})
        )
        resp = json.loads(r.data)
        self.assertEqual(r.status_code, 200)
        self.assertIn('submission_url', resp)
        self.assertIn('hashid', resp)
        form_endpoint = resp['hashid']
        self.assertIn(resp['hashid'], resp['submission_url'])
        self.assertEqual(1, Form.query.count())
        self.assertEqual(Form.query.first().id, Form.get_with_hashid(resp['hashid']).id)

        # post to form
        r = self.client.post('/' + form_endpoint,
            headers={'Referer': 'http://testsite.com'},
            data={'name': 'bruce'}
        )
        self.assertIn("sent an email confirmation", r.data)
        self.assertIn('confirm+your+email', httpretty.last_request().body)
        self.assertEqual(1, Form.query.count())

        # confirm form
        form = Form.query.first()
        self.client.get('/confirm/%s:%s' % (HASH(form.email, str(form.id)), form.hashid))
        self.assertTrue(Form.query.first().confirmed)

        # Make sure that it marks the first form as AJAX
        self.assertTrue(Form.query.first().uses_ajax)

        # check captcha disabling
        self.assertFalse(Form.query.first().captcha_disabled)
        r = self.client.get('/forms/' + form_endpoint + '/toggle-recaptcha',
            headers={'Referer': settings.SERVICE_URL})
        self.assertTrue(Form.query.first().captcha_disabled)
        r = self.client.get('/forms/' + form_endpoint + '/toggle-recaptcha',
            headers={'Referer': settings.SERVICE_URL})
        self.assertFalse(Form.query.first().captcha_disabled)

        # send 5 forms (monthly limits should not apply to the upgraded user)
        self.assertEqual(settings.MONTHLY_SUBMISSIONS_LIMIT, 2)
        for i in range(5):
            r = self.client.post('/' + form_endpoint,
                headers={'Referer': 'testsite.com'},
                data={'name': 'ana',
                      'submission': '__%s__' % i}
            )
        form = Form.query.first()
        self.assertEqual(form.counter, 5)
        self.assertEqual(form.get_monthly_counter(), 5)
        self.assertIn('ana', httpretty.last_request().body)
        self.assertIn('__4__', httpretty.last_request().body)
        self.assertNotIn('You+are+past+our+limit', httpretty.last_request().body)

        # try (and fail) to submit from a different host
        r = self.client.post('/' + form_endpoint,
            headers={'Referer': 'bad.com'},
            data={'name': 'usurper'}
        )
        self.assertEqual(r.status_code, 403)
        self.assertIn('ana', httpretty.last_request().body) # no more data is sent to sendgrid
        self.assertIn('__4__', httpretty.last_request().body)

    @httpretty.activate
    def test_form_creation_with_a_registered_email(self):
        httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json')

        # register user
        r = self.client.post('/register',
            data={'email': 'user@testsite.com',
                  'password': 'banana'}
        )
        # upgrade user manually
        user = User.query.filter_by(email='user@testsite.com').first()
        user.upgraded = True
        DB.session.add(user)
        DB.session.commit()

        httpretty.reset()
        httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json')

        # create form without providing an url should not send verification email
        r = self.client.post('/forms',
            headers={'Accept': 'application/json', 'Content-type': 'application/json'},
            data=json.dumps({'email': 'email@testsite.com'})
        )
        self.assertEqual(httpretty.has_request(), False)

        # create form without a confirmed email should send a verification email
        r = self.client.post('/forms',
            headers={'Accept': 'application/json', 'Content-type': 'application/json'},
            data=json.dumps({'email': 'email@testsite.com',
                             'url': 'https://www.testsite.com/contact.html'})
        )
        resp = json.loads(r.data)
        self.assertEqual(resp['confirmed'], False)
        self.assertEqual(httpretty.has_request(), True)
        self.assertIn('Confirm+email', httpretty.last_request().body)
        self.assertIn('www.testsite.com%2Fcontact.html', httpretty.last_request().body)

        # manually verify an email
        email = Email()
        email.address = 'owned-by@testsite.com'
        email.owner_id = user.id
        DB.session.add(email)
        DB.session.commit()

        # create a form with the verified email address
        r = self.client.post('/forms',
            headers={'Accept': 'application/json', 'Content-type': 'application/json'},
            data=json.dumps({'email': 'owned-by@testsite.com',
                             'url': 'https://www.testsite.com/about.html'})
        )
        resp = json.loads(r.data)
        self.assertEqual(resp['confirmed'], True)
        self.assertIn('www.testsite.com%2Fcontact.html', httpretty.last_request().body) # same as the last, means no new request was made

        # should have three created forms in the end
        self.assertEqual(Form.query.count(), 3)

    @httpretty.activate
    def test_sitewide_forms(self):
        httpretty.register_uri(httpretty.GET,
                               'http://mysite.com/formspree-verify.txt',
                               body=u'other_email@forms.com\nmyüñìćõð€email@email.com',
                               status=200)
        httpretty.register_uri(httpretty.GET,
                               'http://www.naive.com/formspree-verify.txt',
                               body=u'myüñìćõð€email@email.com',
                               status=200)

        # register user
        r = self.client.post('/register',
            data={'email': 'user@testsite.com',
                  'password': 'banana'}
        )
        # upgrade user manually
        user = User.query.filter_by(email='user@testsite.com').first()
        user.upgraded = True
        DB.session.add(user)
        DB.session.commit()

        # manually verify an email
        email = Email()
        email.address = u'myüñìćõð€email@email.com'
        email.owner_id = user.id
        DB.session.add(email)
        DB.session.commit()

        # create a sitewide form with the verified email address
        r = self.client.post('/forms',
            headers={'Accept': 'application/json', 'Content-type': 'application/json'},
            data=json.dumps({'email': u'myüñìćõð€email@email.com',
                             'url': 'http://mysite.com',
                             'sitewide': 'true'})
        )
        resp = json.loads(r.data)

        self.assertEqual(httpretty.has_request(), True)
        self.assertEqual(resp['confirmed'], True)

        self.assertEqual(1, Form.query.count())
        forms = Form.query.all()
        form = forms[0]
        self.assertEqual(form.sitewide, True)
        self.assertEqual(form.host, 'mysite.com')

        # submit form
        httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json')

        r = self.client.post('/' + form.hashid,
            headers = {'Referer': 'http://www.mysite.com/hipopotamo', 'content-type': 'application/json'},
            data=json.dumps({'name': 'alice'})
        )
        self.assertIn('alice', httpretty.last_request().body)

        self.client.post('/' + form.hashid,
            headers = {'Referer': 'http://mysite.com/baleia/urso?w=2', 'content-type': 'application/json'},
            data=json.dumps({'name': 'maria'})
        )
        self.assertIn('maria', httpretty.last_request().body)

        self.client.post('/' + form.hashid,
            headers = {'Referer': 'http://mysite.com/', 'content-type': 'application/json'},
            data=json.dumps({'name': 'laura'})
        )
        self.assertIn('laura', httpretty.last_request().body)

        # another form, now with a www prefix that will be stripped
        r = self.client.post('/forms',
            headers={'Accept': 'application/json', 'Content-type': 'application/json'},
            data=json.dumps({'email': u'myüñìćõð€email@email.com',
                             'url': 'http://www.naive.com',
                             'sitewide': 'true'})
        )
        resp = json.loads(r.data)

        self.assertEqual(httpretty.has_request(), True)
        self.assertEqual(resp['confirmed'], True)

        self.assertEqual(2, Form.query.count())
        forms = Form.query.all()
        form = forms[1]
        self.assertEqual(form.sitewide, True)
        self.assertEqual(form.host, 'naive.com')

        # submit form
        httpretty.register_uri(httpretty.POST, 'https://api.sendgrid.com/api/mail.send.json')

        r = self.client.post('/' + form.hashid,
            headers={'Referer': 'http://naive.com/hipopotamo', 'content-type': 'application/json'},
            data=json.dumps({'name': 'alice'})
        )
        self.assertIn('alice', httpretty.last_request().body)

        self.client.post('/' + form.hashid,
            headers={'Referer': 'http://www.naive.com/baleia/urso?w=2', 'content-type': 'application/json'},
            data=json.dumps({'name': 'maria'})
        )
        self.assertIn('maria', httpretty.last_request().body)

        self.client.post('/' + form.hashid,
            headers={'Referer': 'http://www.naive.com/', 'content-type': 'application/json'},
            data=json.dumps({'name': 'laura'})
        )
        self.assertIn('laura', httpretty.last_request().body)

        # create a different form with the same email address, now using unprefixed url
        r = self.client.post('/forms',
            headers={'Accept': 'application/json', 'Content-type': 'application/json'},
            data=json.dumps({'email': u'myüñìćõð€email@email.com',
                             'url': 'mysite.com',
                             'sitewide': 'true'})
        )
        resp = json.loads(r.data)


text:
"""Base class to load data into data warehouse"""
#pylint: disable=relative-import
#pylint: disable=too-many-function-args
#pylint: disable=too-many-arguments
#pylint: disable=abstract-class-instantiated

from etl_framework.loaders.PostgreSqlLoader import PostgreSqlLoader
from etl_framework.loader_mixins.BufferMixin import BufferMixin

class PostgreSqlBufferedLoader(PostgreSqlLoader, BufferMixin):
    """loads data into database"""

    def load_buffered(self):

        # NOTE this is specific to SQL loaders,
        # so this class could be renamed SqlBufferedLoader
        self.datastore.run_statement(
            self.config.get_sql_statement(),
            multiple_values=self._buffered_values,
            commit=True
        )

    def load(self, values):
        """stuff"""

        self.write_to_buffer(values)


text:
package com.intellij.javascript;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.MutableLookupElement;
import com.intellij.lang.javascript.JSTokenTypes;
import com.intellij.lang.javascript.JavaScriptSupportLoader;
import com.intellij.lang.javascript.psi.*;
import com.intellij.lang.parameterInfo.*;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.ResolveResult;
import com.intellij.psi.search.searches.DefinitionsScopedSearch;
import com.intellij.psi.tree.IElementType;
import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.ContainerUtil;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.*;

/**
 * @author Maxim.Mossienko
 */
public class JSParameterInfoHandler implements ParameterInfoHandlerWithTabActionSupport<JSArgumentList, JSFunction, JSExpression>
{
	private static final Set<Class<?>> ourArgumentListAllowedParentClassesSet = ContainerUtil.<Class<?>>newHashSet(JSCallExpression.class);

	@Override
	public boolean couldShowInLookup()
	{
		return true;
	}

	@Override
	public Object[] getParametersForLookup(final LookupElement item, final ParameterInfoContext context)
	{
		if(!(item instanceof MutableLookupElement))
		{
			return null;
		}

		PsiElement element = item.getPsiElement();
		if(element instanceof JSFunction)
		{
			final JSFunction originalFunction = (JSFunction) element;
			final List<JSFunction> lookupItems = new ArrayList<JSFunction>();
			Set<String> availableSignatures = new HashSet<String>();

			for(PsiElement el : DefinitionsScopedSearch.search(originalFunction))
			{
				doAddSignature(lookupItems, availableSignatures, el);
			}

			if(lookupItems.size() == 0)
			{
				lookupItems.add(originalFunction);
			}

			return lookupItems.toArray(new Object[lookupItems.size()]);
		}

		return ArrayUtil.EMPTY_OBJECT_ARRAY;
	}

	private static void doAddSignature(final List<JSFunction> lookupItems, final Set<String> availableSignatures, final PsiElement el)
	{
		if(el instanceof JSFunction)
		{
			final JSFunction function = (JSFunction) el;
			final JSParameterList parameterList = function.getParameterList();

			if(parameterList != null)
			{
				final String typedSignature = buildSignature(parameterList.getParameters(), false, -1).text;
				final String untypedSignature = buildSignature(parameterList.getParameters(), true, -1).text;

				if(!availableSignatures.contains(typedSignature) && !availableSignatures.contains(untypedSignature))
				{
					lookupItems.add(function);
					availableSignatures.add(typedSignature);
					availableSignatures.add(untypedSignature);
				}
			}
		}
	}

	@Override
	public JSArgumentList findElementForParameterInfo(final CreateParameterInfoContext context)
	{
		JSArgumentList argList = findArgumentList(context.getFile(), context.getOffset());

		if(argList != null)
		{
			return fillSignaturesForArgumentList(context, argList);
		}
		return argList;
	}

	@Nullable
	public static JSArgumentList findArgumentList(final PsiFile file, final int offset)
	{
		JSArgumentList argList = ParameterInfoUtils.findParentOfType(file, offset, JSArgumentList.class);
		if(argList == null)
		{
			final JSCallExpression callExpression = ParameterInfoUtils.findParentOfType(file, offset, JSCallExpression.class);
			if(callExpression != null)
			{
				argList = callExpression.getArgumentList();
			}
		}
		return argList;
	}

	@Nullable
	private static JSArgumentList fillSignaturesForArgumentList(final CreateParameterInfoContext context, final @Nonnull JSArgumentList argList)
	{
		final PsiElement psiElement = argList.getParent();
		if(!(psiElement instanceof JSCallExpression))
		{
			return null;
		}

		final JSCallExpression parent = (JSCallExpression) psiElement;
		final JSExpression methodExpression = parent.getMethodExpression();

		if(methodExpression instanceof JSReferenceExpression)
		{
			final ResolveResult[] resolveResults = ((JSReferenceExpression) methodExpression).multiResolve(true);

			if(resolveResults.length > 0)
			{
				List<JSFunction> items = new ArrayList<JSFunction>(resolveResults.length);
				Set<String> availableSignatures = new HashSet<String>();

				for(ResolveResult r : resolveResults)
				{
					PsiElement element = r.getElement();
					if(element instanceof JSProperty)
					{
						element = ((JSProperty) element).getValue();
					}

					doAddSignature(items, availableSignatures, element);
				}

				context.setItemsToShow(ArrayUtil.toObjectArray(items));
				return argList;
			}
		}
		else if(methodExpression instanceof JSSuperExpression)
		{
			final PsiElement clazz = methodExpression.getReference().resolve();
			if(clazz instanceof JSFunction)
			{
				context.setItemsToShow(new Object[]{clazz});
				return argList;
			}
		}
		return null;
	}

	@Override
	public void showParameterInfo(@Nonnull final JSArgumentList element, final CreateParameterInfoContext context)
	{
		context.showHint(element, element.getTextOffset(), this);
	}

	@Override
	public JSArgumentList findElementForUpdatingParameterInfo(final UpdateParameterInfoContext context)
	{
		return findArgumentList(context.getFile(), context.getOffset());
	}

	@Override
	public void updateParameterInfo(@Nonnull final JSArgumentList o, final UpdateParameterInfoContext context)
	{
		if(context.getParameterOwner() != o)
		{
			context.removeHint();
			return;
		}
		final int currentParameterIndex = ParameterInfoUtils.getCurrentParameterIndex(o.getNode(), context.getOffset(), JSTokenTypes.COMMA);
		context.setCurrentParameter(currentParameterIndex);
	}

	@Override
	public void updateUI(final JSFunction p, final ParameterInfoUIContext context)
	{
		final JSParameterList parameterList = p.getParameterList();
		final JSParameter[] params = parameterList != null ? parameterList.getParameters() : new JSParameter[0];
		final int currentParameterIndex = context.getCurrentParameterIndex() >= 0 ? context.getCurrentParameterIndex() : params.length;
		final JSParameter parameter = currentParameterIndex < params.length ? params[currentParameterIndex] : null;

		final SignatureInfo signatureInfo = buildSignature(params, false, currentParameterIndex);
		final String name = signatureInfo.text;

		final String currentParameterSignature = parameter != null ? getSignatureForParameter(parameter, false) : null;
		int highlightStart = parameter != null ? signatureInfo.selectedParameterStart : 0;
		int highlightEnd = parameter != null ? highlightStart + currentParameterSignature.length() : 0;
		context.setupUIComponentPresentation(name, highlightStart, highlightEnd, false, false, false, context.getDefaultParameterColor());
	}

	private static class SignatureInfo
	{
		String text;
		int selectedParameterStart = -1;
	}

	private static
	@Nonnull
	SignatureInfo buildSignature(final JSParameter[] params, final boolean skipType, int selectedParameterIndex)
	{
		SignatureInfo info = new SignatureInfo();
		if(params.length > 0)
		{
			StringBuilder result = new StringBuilder();
			for(int i = 0; i < params.length; ++i)
			{
				if(result.length() > 0)
				{
					result.append(", ");
				}
				if(selectedParameterIndex == i)
				{
					info.selectedParameterStart = result.length();
				}
				result.append(getSignatureForParameter(params[i], skipType));
			}

			info.text = result.toString();
		}
		else
		{
			info.text = CodeInsightBundle.message("parameter.info.no.parameters");
		}
		return info;
	}

	public static String getSignatureForParameter(final JSParameter p, boolean skipType)
	{
		final String s = skipType ? null : p.getTypeString();

		if(s != null && s.length() > 0)
		{
			final boolean ecmal4 = p.getContainingFile().getLanguage() == JavaScriptSupportLoader.ECMA_SCRIPT_L4;
			String result;

			if(ecmal4)
			{
				if(p.isRest())
				{
					result = "...";
				}
				else
				{
					result = p.getName() + ":" + s;
				}
			}
			else
			{
				result = "[" + s + "] " + p.getName();
			}
			final String initializerText = p.getInitializerText();
			if(initializerText != null)
			{
				result += " = " + initializerText;
			}
			return result;
		}
		return p.getName();
	}

	@Override
	@Nonnull
	public JSExpression[] getActualParameters(@Nonnull final JSArgumentList jsArgumentList)
	{
		return jsArgumentList.getArguments();
	}

	@Override
	@Nonnull
	public IElementType getActualParameterDelimiterType()
	{
		return JSTokenTypes.COMMA;
	}

	@Override
	@Nonnull
	public IElementType getActualParametersRBraceType()
	{
		return JSTokenTypes.RBRACE;
	}

	@Override
	@Nonnull
	public Set<Class<?>> getArgumentListAllowedParentClasses()
	{
		return ourArgumentListAllowedParentClassesSet;
	}

	@Nonnull
	@Override
	public Set<? extends Class<?>> getArgListStopSearchClasses()
	{
		return Collections.emptySet();
	}

	@Override
	@Nonnull
	public Class<JSArgumentList> getArgumentListClass()
	{
		return JSArgumentList.class;
	}
}


text:
module Doorkeeper
  VERSION = "4.2.6".freeze
end


text:
var fb = window.fb || {};
var config = window.config || {};

if (typeof fb.init === 'undefined') {
  (function() {

    fb.isEnabled = false;
    var initialized = false;

    fb.init = function(callback) {
      if (initialized) {
        callback();
        return;
      }
      initialized = true;
      var req = utils.config.load('/contacts/config.json');

      req.onload = function(configData) {
        if (configData.facebookEnabled === true) {
          fb.isEnabled = true;
        }

        fb.operationsTimeout = config.operationsTimeout =
                                                  configData.operationsTimeout;
        fb.logLevel = configData.logLevel || 'none';
        fb.syncPeriod = configData.facebookSyncPeriod || 24;
        fb.testToken = configData.testToken;

        callback();
      };

      req.onerror = function(code) {
        window.console.error('Contacts: Error while checking if FB is enabled',
                             code);
      };
    };
  })();
}


text:
<!DOCTYPE html>
<title>Nimi's page</title>

<link type="text/css" rel="stylesheet" href="stylesheets/default.css"/>
<link type="text/css" rel="stylesheet" href="stylesheets/blog.css"/>

<!DOCTYPE html>

Hello DBC!

About me

Blog

Portfolio

Contact info