text:
ITEM.Name = "M9 Bayonet Knife" .. " | " .. "Marble Fade"
ITEM.Price = 20000
ITEM.Model = "models/weapons/w_csgo_m9.mdl"
ITEM.Skin = 13
ITEM.WeaponClass = "csgo_m9_marblefade"

function ITEM:OnEquip(ply)
	ply:Give(self.WeaponClass)
end

function ITEM:OnBuy(ply)
	ply:Give(self.WeaponClass)
	ply:SelectWeapon(self.WeaponClass)
end

function ITEM:OnSell(ply)
	ply:StripWeapon(self.WeaponClass)
end

function ITEM:OnHolster(ply)
	ply:StripWeapon(self.WeaponClass)
end

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Ukr. bot. Zh. 60(2): 126 (2003)

#### Original name
Xanthoria weberi S.Y. Kondr. & Kärnefelt

### Remarks
null


text:
module GeoWorks
  # Attributes and methods for basic geospatial metadata used by Works
  module BasicGeoMetadata
    extend ActiveSupport::Concern

    included do
      apply_schema ::GeoWorks::BasicGeoMetadataRequired,
                   ActiveFedora::SchemaIndexingStrategy.new(
                     ActiveFedora::Indexers::GlobalIndexer.new(
                       [:stored_searchable, :facetable, :symbol]
                     )
                   )
      apply_schema ::GeoWorks::BasicGeoMetadataOptional,
                   ActiveFedora::SchemaIndexingStrategy.new(
                     ActiveFedora::Indexers::GlobalIndexer.new(
                       [:stored_searchable, :facetable, :symbol]
                     )
                   )
    end
  end
end


text:
package rendergold

import (
	"html/template"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/go-martini/martini"
	"github.com/martini-contrib/render"
	"github.com/yosssi/gold"
)

func TestRenderHTML(t *testing.T) {
	// Case when r.g.ParseFile returns an error.
	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	opt := Options{
		Directory:       "test",
		Func:            nil,
		Charset:         defaultCharset,
		HTMLContentType: render.ContentHTML,
	}
	r := renderer{res, req, opt, compiledCharset(opt), gold.NewGenerator(false).SetBaseDir(opt.Directory)}
	r.HTML(http.StatusOK, "notExistTemplate", nil)
	if res.Code != http.StatusInternalServerError {
		t.Errorf("invalid HTTP status code [actual: %d][expected: %d]", res.Code, http.StatusInternalServerError)
	}

	// Case when t.Execute returns an error.
	res = httptest.NewRecorder()
	req, _ = http.NewRequest("GET", "/", nil)
	opt = Options{
		Directory:       "test",
		Func:            nil,
		Charset:         defaultCharset,
		HTMLContentType: render.ContentHTML,
	}
	r = renderer{res, req, opt, compiledCharset(opt), gold.NewGenerator(false).SetBaseDir(opt.Directory)}
	r.HTML(http.StatusOK, "0002", "Test")
	if res.Code != http.StatusInternalServerError {
		t.Errorf("invalid HTTP status code [actual: %d][expected: %d]", res.Code, http.StatusInternalServerError)
	}

	// Case when no error occurs (with no HTMLOptions).
	res = httptest.NewRecorder()
	req, _ = http.NewRequest("GET", "/", nil)
	opt = Options{
		Directory:       "test",
		Func:            nil,
		Charset:         defaultCharset,
		HTMLContentType: render.ContentHTML,
	}
	r = renderer{res, req, opt, compiledCharset(opt), gold.NewGenerator(false).SetBaseDir(opt.Directory)}
	r.HTML(http.StatusOK, "0001", nil)
	if res.Code != http.StatusOK {
		t.Errorf("invalid HTTP status code [actual: %d][expected: %d]", res.Code, http.StatusOK)
	}

	// Case when no error occurs (with HTMLOptions).
	res = httptest.NewRecorder()
	req, _ = http.NewRequest("GET", "/", nil)
	opt = Options{
		Directory:       "test",
		Func:            nil,
		Charset:         defaultCharset,
		HTMLContentType: render.ContentHTML,
	}
	r = renderer{res, req, opt, compiledCharset(opt), gold.NewGenerator(false).SetBaseDir(opt.Directory)}
	r.HTML(http.StatusOK, "0001", nil, render.HTMLOptions{Layout: "0001" + NameContentDelim + "html"})
	if res.Code != http.StatusOK {
		t.Errorf("invalid HTTP status code [actual: %d][expected: %d]", res.Code, http.StatusOK)
	}
}

func TestRenderRedirect(t *testing.T) {
	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	opt := Options{
		Directory:       defaultDirectory,
		Func:            nil,
		Charset:         defaultCharset,
		HTMLContentType: render.ContentHTML,
	}
	r := renderer{res, req, opt, compiledCharset(opt), gold.NewGenerator(false).SetBaseDir(opt.Directory)}
	r.Redirect("https://github.com", http.StatusMovedPermanently)
	if res.Code != http.StatusMovedPermanently {
		t.Errorf("invalid HTTP status code [actual: %d][expected: %d]", res.Code, http.StatusMovedPermanently)
	}
}

func TestRenderer(t *testing.T) {
	opt := Options{
		Directory: "test",
		Func: template.FuncMap{
			"testFunc": func() string { return "test" },
		},
		Charset:         defaultCharset,
		HTMLContentType: render.ContentHTML,
	}
	Renderer(opt)

	// Test via a Martini context.
	m := martini.Classic()
	m.Use(Renderer(opt))
	m.Get("/", func(r Render) {
		r.HTML(http.StatusOK, "0001", nil)
	})
	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/", nil)
	m.ServeHTTP(res, req)
	if res.Code != http.StatusOK {
		t.Errorf("invalid HTTP status code [actual: %d][expected: %d]", res.Code, http.StatusOK)
	}
}


text:
#import <Cocoa/Cocoa.h>
#import "USParser.h"

@class USSchema;
@class USMessage;

@interface USParser (Messages)

- (void)processMessageElement:(NSXMLElement *)el schema:(USSchema *)schema;
- (void)processMessageChildElement:(NSXMLElement *)el message:(USMessage *)message;
- (void)processPartElement:(NSXMLElement *)el message:(USMessage *)message;

@end


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

namespace Gale.Db
{
    public interface IEntityTable
    {
    }

    public interface IEntityTable<T>
    {
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Xaml;

namespace Microsoft.VisualStudio.LanguageServices.Xaml.Implementation.LanguageServer.Extensions
{
    internal static class SolutionExtensions
    {
        public static IEnumerable<Project> GetXamlProjects(this Solution solution)
            => solution.Projects.Where(p => p.Language == StringConstants.XamlLanguageName);
    }
}


text:
package io.atomix.protocols.gossip;

import com.google.common.annotations.Beta;
import io.atomix.primitive.PrimitiveManagementService;
import io.atomix.primitive.protocol.GossipProtocol;
import io.atomix.primitive.protocol.PrimitiveProtocol;
import io.atomix.primitive.protocol.counter.CounterDelegate;
import io.atomix.primitive.protocol.counter.CounterProtocol;
import io.atomix.primitive.protocol.set.NavigableSetDelegate;
import io.atomix.primitive.protocol.set.NavigableSetProtocol;
import io.atomix.primitive.protocol.set.SetDelegate;
import io.atomix.primitive.protocol.set.SortedSetDelegate;
import io.atomix.primitive.protocol.value.ValueDelegate;
import io.atomix.primitive.protocol.value.ValueProtocol;
import io.atomix.protocols.gossip.counter.CrdtCounterDelegate;
import io.atomix.protocols.gossip.set.CrdtNavigableSetDelegate;
import io.atomix.protocols.gossip.set.CrdtSetDelegate;
import io.atomix.protocols.gossip.value.CrdtValueDelegate;
import io.atomix.utils.serializer.Serializer;

/**
 * Conflict-free Replicated Data Types (CRDT) protocol.
 */
@Beta
public class CrdtProtocol implements GossipProtocol, CounterProtocol, NavigableSetProtocol, ValueProtocol {
  public static final Type TYPE = new Type();

  /**
   * Returns an instance of the CRDT protocol with the default configuration.
   *
   * @return an instance of the CRDT protocol with the default configuration
   */
  public static CrdtProtocol instance() {
    return new CrdtProtocol(new CrdtProtocolConfig());
  }

  /**
   * Returns a new CRDT protocol builder.
   *
   * @return a new CRDT protocol builder
   */
  public static CrdtProtocolBuilder builder() {
    return new CrdtProtocolBuilder(new CrdtProtocolConfig());
  }

  /**
   * CRDT protocol type.
   */
  public static final class Type implements PrimitiveProtocol.Type<CrdtProtocolConfig> {
    private static final String NAME = "crdt";

    @Override
    public String name() {
      return NAME;
    }

    @Override
    public CrdtProtocolConfig newConfig() {
      return new CrdtProtocolConfig();
    }

    @Override
    public PrimitiveProtocol newProtocol(CrdtProtocolConfig config) {
      return new CrdtProtocol(config);
    }
  }

  protected final CrdtProtocolConfig config;

  protected CrdtProtocol(CrdtProtocolConfig config) {
    this.config = config;
  }

  @Override
  public PrimitiveProtocol.Type type() {
    return TYPE;
  }

  @Override
  public CounterDelegate newCounterDelegate(String name, PrimitiveManagementService managementService) {
    return new CrdtCounterDelegate(name, config, managementService);
  }

  @Override
  public <E> SetDelegate<E> newSetDelegate(String name, Serializer serializer, PrimitiveManagementService managementService) {
    return new CrdtSetDelegate<>(name, serializer, config, managementService);
  }

  @Override
  public <E> SortedSetDelegate<E> newSortedSetDelegate(String name, Serializer serializer, PrimitiveManagementService managementService) {
    return new CrdtNavigableSetDelegate<>(name, serializer, config, managementService);
  }

  @Override
  public <E> NavigableSetDelegate<E> newNavigableSetDelegate(String name, Serializer serializer, PrimitiveManagementService managementService) {
    return new CrdtNavigableSetDelegate<>(name, serializer, config, managementService);
  }

  @Override
  public ValueDelegate newValueDelegate(String name, Serializer serializer, PrimitiveManagementService managementService) {
    return new CrdtValueDelegate(name, serializer, config, managementService);
  }
}


text:
package scala.meta
package internal

import scala.language.implicitConversions
import org.scalameta.default._
import org.scalameta.unreachable
import org.scalameta.invariants._
import org.scalameta.show._
import scala.collection.mutable
import scala.{Seq => _}
import scala.collection.immutable.Seq
import scala.{meta => api}
import scala.meta.internal.ast._
import scala.meta.internal.prettyprinters._

package object semantic {
  implicit class XtensionHygieneDebug(debug: org.scalameta.debug.Debug.type) {
    def hygiene = sys.props("hygiene.debug") != null
  }

  implicit class XtensionAttributedTree[T <: api.Tree](tree: T) {
    def requireAttributed(): Unit = {
      val offenders = mutable.ListBuffer[(Tree, List[String])]()
      def traverse(tree: Tree, path: List[String]): Unit = {
        def check(tree: Tree): Boolean = {
          def checkEnv(tree: Tree): Boolean = tree.internalEnv.map(_ match {
            case Environment.Zero => true
            case _ => false
          }).getOrElse(true)

          def checkDenot(tree: Tree): Boolean = tree.internalDenot.map(_ match {
            case Denotation.Single(Prefix.Zero, _) =>
              true
            case Denotation.Single(Prefix.Type(prefix: Tree), _) =>
              traverse(prefix, path :+ "Denotation")
              true
            case Denotation.Multi(Prefix.Zero, _) =>
              true
            case Denotation.Multi(Prefix.Type(prefix: Tree), _) =>
              traverse(prefix, path :+ "Denotation")
              true
            case _ =>
              false
          }).getOrElse(true)

          def checkTyping(tree: Tree): Boolean = tree.internalTyping.map(_ match {
            case Typing.Recursive => true
            case Typing.Nonrecursive(_) => true
            case _ => false
          }).getOrElse(true)

          def checkExpansion(tree: Tree): Boolean = tree.internalExpansion.map(_ match {
            case Expansion.Identity => true
            case Expansion.Desugaring(_) => true
            case _ => false
          }).getOrElse(true)

          checkEnv(tree) && checkDenot(tree) && checkTyping(tree) && checkExpansion(tree)
        }
        def loop(x: Any): Unit = x match {
          case x: Tree => traverse(x, path :+ tree.productPrefix)
          case x: Seq[_] => x.foreach(loop)
          case x: Some[_] => loop(x.get)
          case x => // do nothing
        }
        if (!check(tree)) offenders += ((tree, path))
        tree.productIterator.toList.map(loop)
      }
      traverse(tree.require[Tree], Nil)
      if (offenders.nonEmpty) {
        val grouped = offenders.groupBy(_._1.productPrefix).toList.sortBy(_._1)
        def commaCommaAnd[T](list: List[T]): String = list.init.mkString(", ") + (if (list.length == 1) "" else " and ") + list.last
        // The problem is caused by 6 Idents that are either unattributed or erroneous:
        val offenderSummary = commaCommaAnd(grouped.map{ case (k, v) => s"${v.length} $k${if (v.length == 1) "" else "s"}" })
        // 1: _ (... CaseDef > Bind > UnApply > Typed > Ident)
        // 2: _ (...  DefDef > Match > CaseDef > Bind > Ident)
        // ...
        val offenderPrintout = grouped.flatMap(_._2).map({ case (tree, path) =>
          var prefix = tree.toString.replace("\n", " ")
          if (prefix.length > 60) prefix = prefix.take(60) + "..."
          val s_path = path.mkString(" > ")
          var suffix = if (s_path.length <= 40) s_path else "... " + s_path.takeRight(40)
          if (suffix != "") suffix = s" ($suffix)"
          s"$prefix$suffix"
        }).zipWithIndex.map{ case (s, i) => s"${i + 1}: $s" }.mkString("\n")
        sys.error(s"""
          |scala.meta tree is not fully attributed,
          |because $offenderSummary ${if (offenders.length == 1) "doesn't" else "don't"} have denotations:
          |$offenderPrintout
          |The tree that has caused problems is printed out below in its entirety:
          |$tree
          |${tree.show[Attributes]}
        """.stripMargin)
      }
    }

    def inheritAttrs(other: Tree): T = {
      def areCompatible = (
        !(tree.internalDenot.isEmpty ^ other.internalDenot.isEmpty) &&
        !(tree.internalTyping.isEmpty ^ other.internalTyping.isEmpty)
      )
      if (!areCompatible) sys.error(s"${tree.productPrefix} can't inherit attrs from ${other.productPrefix}")
      val result = tree match {
        case tree: Term.Name => tree.withAttrs(other.internalDenot.get, other.internalTyping.get)
        case tree: Ctor.Name => tree.withAttrs(other.internalDenot.get, other.internalTyping.get)
        case tree: Name => tree.withAttrs(other.internalDenot.get)
        case tree: Term => tree.withAttrs(other.internalTyping.get)
        case tree: Term.Param => tree.withAttrs(other.internalTyping.get)
        case _ => tree // do nothing
      }
      result.asInstanceOf[T]
    }
  }

  trait TypingLike { def typing: Typing }
  object TypingLike {
    implicit def typeIsTypingLike(tpe: => api.Type.Arg): TypingLike = new TypingLike { def typing = Typing.Nonrecursive(tpe) }
    implicit def typingIsTypingLike(typing0: Typing): TypingLike = new TypingLike { def typing = typing0 }
  }

  trait ExpansionLike { def expansion: Expansion }
  object ExpansionLike {
    implicit def termIsExpansionLike(term: api.Term): ExpansionLike = new ExpansionLike { def expansion = Expansion.Desugaring(term) }
    implicit def expansionIsExpansionLike(expansion0: Expansion): ExpansionLike = new ExpansionLike { def expansion = expansion0 }
  }
}


text:
#include "FL.h"

int main(int argc, char **argv) {

    char *pos = NULL;
    char fileExtension[10];
    int nbins = 216;
    int k = 60;

    if (argc!=4){
        printf("Usage: <image1.[pgm/ppm]> <image2.[pgm/ppm]> <image3.[pgm/ppm]>\n");
        exit(-1);
    }

    FeatureVector **featureMatrix = (FeatureVector **)calloc(1,sizeof(FeatureVector *));
    for (int i = 0; i < 3; ++i) {
        pos = strrchr(argv[i+1],'.') + 1;
        sscanf(pos,"%s",fileExtension);

        if (strcmp(fileExtension,"pgm")==0){
            GrayImage *grayImage = readGrayImage(argv[i+1]);
            Histogram *hist = GrayHistogram(grayImage,nbins);
            FeatureVector *vec1 = createFeatureVector(hist);
            FeatureVector *vec2 = getMorphologicalPdf(grayImage,k);
            featureMatrix[i] =  mergeFeatureVectors(vec1,vec2);
            destroyGrayImage(&grayImage);
            destroyFeatureVector(&vec1);
            destroyFeatureVector(&vec2);
            DestroyHistogram(&hist);
        } else if(strcmp(fileExtension,"ppm")==0){ /* ppm */
            ColorImage *colorImage = readColorImage(argv[i+1]);
            Histogram *hist = ColorHistogram(colorImage,nbins);
            FeatureVector *vec1 = createFeatureVector(hist);
            FeatureVector *vec2 = getMorphologicalPdf(colorImage,k);
            featureMatrix[i] = mergeFeatureVectors(vec1,vec2);
            destroyColorImage(&colorImage);
            destroyFeatureVector(&vec1);
            destroyFeatureVector(&vec2);
            DestroyHistogram(&hist);
        }else{
            printf("Invalide image format: %s\n",fileExtension);
        }
        printf("feature vector da imagem %d computado\n",i);
        printf("\n");
    }

    wirteFeatureVectors(featureMatrix,3, "fv2.txt");
    FeatureVector* vec1 = circularCrossCorrelation1D(featureMatrix[0],featureMatrix[1],false);
    FeatureVector* vec2 = circularCrossCorrelation1D(featureMatrix[0],featureMatrix[2],false);
    FeatureVector* vec3 = circularCrossCorrelation1D(featureMatrix[0],featureMatrix[0],false);

    for (int i = 0; i < 3; ++i) {
        destroyFeatureVector(&featureMatrix[i]);
    }
    FeatureVector **correlations = (FeatureVector **)calloc(3,sizeof(FeatureVector *));
    correlations[0] = vec1;
    correlations[1] = vec2;
    correlations[2] = vec3;
    wirteFeatureVectors(correlations,3, "R_xy.txt");

    //free(pos);
    return 0;

}


text:
TOOLS=/nfs/hn46/xiaolonw/pose_cnncode/caffe-3dnormal_joint_pose/build/tools

GLOG_logtostderr=1 $TOOLS/finetune_net.bin   /nfs/hn46/xiaolonw/pose_cnncode/caffe-3dnormal_joint_pose/posescript/pose_flic_lecun_mode2/pose_solver.prototxt /nfs/hn38/users/xiaolonw/pose_models/flic_coarse_lecun_mode2/pose__iter_30000


text:
Open a terminal window.

Clone the davinci-units repo:
```
git clone git://github.com/geometryzen/davinci-units.git
```

Change to the repo directory:
```
cd davinci-units
```

Install NPM:
```
npm install
```
to install the tooling dependencies (For this you need to have [Node.js](http://nodejs.org) installed).

Install JSPM:
```
jspm install
```
to install JSPM, used for testing.

Install TypeScript definitions:
```
tsd install
```
to install TypeScript definitions for Jasmine used in testing.

## Building

```
grunt
```
to compile the source using the TypeScript compiler (For this you need to have [TypeScript](http://www.typescriptlang.org) installed) and to package the individual files into a single JavaScript file.

## Making Changes

Make your changes to the TypeScript files in the _src_ directory. Do not edit the files in the _dist_ directory, these files will be generated.

## Testing

```
grunt test
```

## Versioning

```
src/davinci-units/config.ts
package.json
```

## Git

```
git add --all
git commit -m '...'
git tag -a major.minor.patch -m '...'
git push origin master --tags
npm publish
```


text:
package labels

import (
	"fmt"
	"sort"
	"strings"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
)

// Selector represents a label selector.
type Selector interface {
	// Matches returns true if this selector matches the given set of labels.
	Matches(Labels) bool

	// Empty returns true if this selector does not restrict the selection space.
	Empty() bool

	// RequiresExactMatch allows a caller to introspect whether a given selector
	// requires a single specific label to be set, and if so returns the value it
	// requires.
	// TODO: expand this to be more general
	RequiresExactMatch(label string) (value string, found bool)

	// String returns a human readable string that represents this selector.
	String() string
}

// Everything returns a selector that matches all labels.
func Everything() Selector {
	return andTerm{}
}

type hasTerm struct {
	label, value string
}

func (t *hasTerm) Matches(ls Labels) bool {
	return ls.Get(t.label) == t.value
}

func (t *hasTerm) Empty() bool {
	return false
}

func (t *hasTerm) RequiresExactMatch(label string) (value string, found bool) {
	if t.label == label {
		return t.value, true
	}
	return "", false
}

func (t *hasTerm) String() string {
	return fmt.Sprintf("%v=%v", t.label, t.value)
}

type notHasTerm struct {
	label, value string
}

func (t *notHasTerm) Matches(ls Labels) bool {
	return ls.Get(t.label) != t.value
}

func (t *notHasTerm) Empty() bool {
	return false
}

func (t *notHasTerm) RequiresExactMatch(label string) (value string, found bool) {
	return "", false
}

func (t *notHasTerm) String() string {
	return fmt.Sprintf("%v!=%v", t.label, t.value)
}

type andTerm []Selector

func (t andTerm) Matches(ls Labels) bool {
	for _, q := range t {
		if !q.Matches(ls) {
			return false
		}
	}
	return true
}

func (t andTerm) Empty() bool {
	if t == nil {
		return true
	}
	if len([]Selector(t)) == 0 {
		return true
	}
	for i := range t {
		if !t[i].Empty() {
			return false
		}
	}
	return true
}

func (t andTerm) RequiresExactMatch(label string) (string, bool) {
	if t == nil || len([]Selector(t)) == 0 {
		return "", false
	}
	for i := range t {
		if value, found := t[i].RequiresExactMatch(label); found {
			return value, found
		}
	}
	return "", false
}

func (t andTerm) String() string {
	var terms []string
	for _, q := range t {
		terms = append(terms, q.String())
	}
	return strings.Join(terms, ",")
}

// Operator represents a key's relationship
// to a set of values in a Requirement.
// TODO: Should also represent key's existence.
type Operator int

const (
	IN Operator = iota + 1
	NOT_IN
)

// LabelSelector only not named 'Selector' due
// to name conflict until Selector is deprecated.
type LabelSelector struct {
	Requirements []Requirement
}

type Requirement struct {
	key       string
	operator  Operator
	strValues util.StringSet
}

func (r *Requirement) Matches(ls Labels) bool {
	switch r.operator {
	case IN:
		return r.strValues.Has(ls.Get(r.key))
	case NOT_IN:
		return !r.strValues.Has(ls.Get(r.key))
	default:
		return false
	}
}

func (sg *LabelSelector) Matches(ls Labels) bool {
	for _, req := range sg.Requirements {
		if !req.Matches(ls) {
			return false
		}
	}
	return true
}

func try(selectorPiece, op string) (lhs, rhs string, ok bool) {
	pieces := strings.Split(selectorPiece, op)
	if len(pieces) == 2 {
		return pieces[0], pieces[1], true
	}
	return "", "", false
}

// SelectorFromSet returns a Selector which will match exactly the given Set. A
// nil Set is considered equivalent to Everything().
func SelectorFromSet(ls Set) Selector {
	if ls == nil {
		return Everything()
	}
	items := make([]Selector, 0, len(ls))
	for label, value := range ls {
		items = append(items, &hasTerm{label: label, value: value})
	}
	if len(items) == 1 {
		return items[0]
	}
	return andTerm(items)
}

// ParseSelector takes a string representing a selector and returns an
// object suitable for matching, or an error.
func ParseSelector(selector string) (Selector, error) {
	parts := strings.Split(selector, ",")
	sort.StringSlice(parts).Sort()
	var items []Selector
	for _, part := range parts {
		if part == "" {
			continue
		}
		if lhs, rhs, ok := try(part, "!="); ok {
			items = append(items, &notHasTerm{label: lhs, value: rhs})
		} else if lhs, rhs, ok := try(part, "=="); ok {
			items = append(items, &hasTerm{label: lhs, value: rhs})
		} else if lhs, rhs, ok := try(part, "="); ok {
			items = append(items, &hasTerm{label: lhs, value: rhs})
		} else {
			return nil, fmt.Errorf("invalid selector: '%s'; can't understand '%s'", selector, part)
		}
	}
	if len(items) == 1 {
		return items[0], nil
	}
	return andTerm(items), nil
}


text:
package goweb

/*
	RouteManager
*/

// Manages routes and matching
type RouteManager struct {
	routes []*Route
}

// Creates a route that maps the specified path to the specified controller
// along with any optional RouteMatcherFunc modifiers
func (manager *RouteManager) Map(path string, controller Controller, matcherFuncs ...RouteMatcherFunc) *Route {

	// create the route (from the path)
	route := makeRouteFromPath(path)

	// set the controller
	route.Controller = controller

	// set the matcher funcs
	route.MatcherFuncs = matcherFuncs

	// add the new route to the default
	manager.AddRoute(route)

	// return the new route
	return route

}

func (manager *RouteManager) MapFunc(path string, contorllerFunction func(*Context), matcherFuncs ...RouteMatcherFunc) *Route {

	// create the route (from the path)
	route := makeRouteFromPath(path)

	// set the controller
	route.Controller = ControllerFunc(contorllerFunction)

	// set the matcher funcs
	route.MatcherFuncs = matcherFuncs

	// add the new route to the default
	manager.AddRoute(route)

	// return the new route
	return route

}

// Adds a route to the manager
func (manager *RouteManager) AddRoute(route *Route) {
	manager.routes = append(manager.routes, route)
}

// Clears all routes
func (manager *RouteManager) ClearRoutes() {
	manager.routes = make([]*Route, 0)
}

// Default instance of the RouteManager
var DefaultRouteManager *RouteManager = new(RouteManager)


text:
FactoryGirl.define do
  factory :resource do
    sequence :name do |n|
      "Resource #{n}"
    end

    category "project"
    manifest "{}"

    factory :findable_resource do
      readme "findable resource with some information"
    end

    factory :unfindable_resource do
      readme "don't find me!"
    end
  end
end


text:
package org.apache.ignite.loadtests.hashmap;

import org.apache.ignite.cache.store.*;
import org.apache.ignite.configuration.*;
import org.apache.ignite.internal.processors.cache.*;
import org.apache.ignite.internal.processors.cache.datastructures.*;
import org.apache.ignite.internal.processors.cache.dr.*;
import org.apache.ignite.internal.processors.cache.jta.*;
import org.apache.ignite.internal.processors.cache.query.*;
import org.apache.ignite.internal.processors.cache.query.continuous.*;
import org.apache.ignite.internal.processors.cache.store.*;
import org.apache.ignite.internal.processors.cache.transactions.*;
import org.apache.ignite.internal.processors.cache.version.*;
import org.apache.ignite.internal.processors.plugin.*;
import org.apache.ignite.testframework.junits.*;

import java.util.*;

import static org.apache.ignite.testframework.junits.GridAbstractTest.*;

/**
 * Cache test context.
 */
public class GridCacheTestContext<K, V> extends GridCacheContext<K, V> {
    /**
     * @param ctx Context.
     * @throws Exception If failed.
     */
    @SuppressWarnings("NullableProblems")
    public GridCacheTestContext(GridTestKernalContext ctx) throws Exception {
        super(
            ctx,
            new GridCacheSharedContext<>(
                ctx,
                new IgniteTxManager(),
                new GridCacheVersionManager(),
                new GridCacheMvccManager(),
                new GridCacheDeploymentManager<K, V>(),
                new GridCachePartitionExchangeManager<K, V>(),
                new GridCacheIoManager(),
                new CacheNoopJtaManager(),
                null
            ),
            defaultCacheConfiguration(),
            CacheType.USER,
            true,
            true,
            new GridCacheEventManager(),
            new GridCacheSwapManager(false),
            new CacheOsStoreManager(null, new CacheConfiguration()),
            new GridCacheEvictionManager(),
            new GridCacheLocalQueryManager<K, V>(),
            new CacheContinuousQueryManager(),
            new GridCacheAffinityManager(),
            new CacheDataStructuresManager(),
            new GridCacheTtlManager(),
            new GridOsCacheDrManager(),
            new CacheOsConflictResolutionManager<K, V>(),
            new CachePluginManager(ctx, new CacheConfiguration())
        );

        store().initialize(null, new IdentityHashMap<CacheStore, ThreadLocal>());
    }
}


text:
package io.github.luizgrp.sectionedrecyclerviewadapter;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;

/*
 * Unit tests for SectionParameters
 */
@SuppressWarnings({"PMD.MethodNamingConventions"})
public class SectionParametersTest {

    @Rule
    public final ExpectedException expectedException = ExpectedException.none();

    @Test
    public void givenValidParameters_whenBuild_thenSucceeds() {
        // Given
        final int itemId = 1;
        final int footerId = 3;
        final int loadingId = 5;
        final int emptyId = 6;

        // When
        SectionParameters sectionParameters = SectionParameters.builder()
                .itemResourceId(itemId)
                .headerViewWillBeProvided()
                .footerResourceId(footerId)
                .failedViewWillBeProvided()
                .loadingResourceId(loadingId)
                .emptyResourceId(emptyId)
                .build();

        // Then
        assertThat(sectionParameters.itemResourceId, is(itemId));
        assertThat(sectionParameters.itemViewWillBeProvided, is(false));
        assertThat(sectionParameters.headerResourceId, is(nullValue()));
        assertThat(sectionParameters.headerViewWillBeProvided, is(true));
        assertThat(sectionParameters.footerResourceId, is(footerId));
        assertThat(sectionParameters.footerViewWillBeProvided, is(false));
        assertThat(sectionParameters.failedResourceId, is(nullValue()));
        assertThat(sectionParameters.failedViewWillBeProvided, is(true));
        assertThat(sectionParameters.loadingResourceId, is(loadingId));
        assertThat(sectionParameters.loadingViewWillBeProvided, is(false));
        assertThat(sectionParameters.emptyResourceId, is(emptyId));
        assertThat(sectionParameters.emptyViewWillBeProvided, is(false));
    }

    @Test
    public void givenNoMandatoryItemParameter_whenBuild_thenThrowsException() {
        // Expect exception
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("Either itemResourceId or itemViewWillBeProvided must be set");

        // When
        SectionParameters.builder()
                .build();
    }

    @Test
    public void givenConflictingItemParameters_whenBuild_thenThrowsException() {
        // Given
        final int itemId = 1;

        // Expect exception
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("itemResourceId and itemViewWillBeProvided cannot both be set");

        // When
        SectionParameters.builder()
                .itemResourceId(itemId)
                .itemViewWillBeProvided()
                .build();
    }

    @Test
    public void givenConflictingHeaderParameters_whenBuild_thenThrowsException() {
        // Given
        final int itemId = 1;
        final int headerId = 3;

        // Expect exception
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("headerResourceId and headerViewWillBeProvided cannot both be set");

        // When
        SectionParameters.builder()
                .itemResourceId(itemId)
                .headerViewWillBeProvided()
                .headerResourceId(headerId)
                .build();
    }

    @Test
    public void givenConflictingFooterParameters_whenBuild_thenThrowsException() {
        // Given
        final int itemId = 1;
        final int footerId = 3;

        // Expect exception
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("footerResourceId and footerViewWillBeProvided cannot both be set");

        // When
        SectionParameters.builder()
                .itemResourceId(itemId)
                .footerResourceId(footerId)
                .footerViewWillBeProvided()
                .build();
    }

    @Test
    public void givenConflictingLoadingParameters_whenBuild_thenThrowsException() {
        // Given
        final int itemId = 1;
        final int loadingId = 5;

        // Expect exception
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("loadingResourceId and loadingViewWillBeProvided cannot both be set");

        // When
        SectionParameters.builder()
                .itemResourceId(itemId)
                .loadingResourceId(loadingId)
                .loadingViewWillBeProvided()
                .build();
    }

    @Test
    public void givenConflictingFailedParameters_whenBuild_thenThrowsException() {
        // Given
        final int itemId = 1;
        final int failedId = 6;

        // Expect exception
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("failedResourceId and failedViewWillBeProvided cannot both be set");

        // When
        SectionParameters.builder()
                .itemResourceId(itemId)
                .failedResourceId(failedId)
                .failedViewWillBeProvided()
                .build();
    }

    @Test
    public void givenConflictingEmptyParameters_whenBuild_thenThrowsException() {
        // Given
        final int itemId = 1;
        final int emptyId = 6;

        // Expect exception
        expectedException.expect(IllegalArgumentException.class);
        expectedException.expectMessage("emptyResourceId and emptyViewWillBeProvided cannot both be set");

        // When
        SectionParameters.builder()
                .itemResourceId(itemId)
                .emptyResourceId(emptyId)
                .emptyViewWillBeProvided()
                .build();
    }
}


text:
// Copyright (c) Corporation for National Research Initiatives
// Copyright (c) Jython Developers
package org.python.core;

import org.python.core.stringlib.FloatFormatter;
import org.python.core.stringlib.InternalFormat;
import org.python.core.stringlib.InternalFormat.Formatter;
import org.python.core.stringlib.InternalFormat.Spec;
import org.python.expose.ExposedGet;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
import org.python.expose.MethodType;

/**
 * A builtin python complex number
 */
@Untraversable
@ExposedType(name = "complex", doc = BuiltinDocs.complex_doc)
public class PyComplex extends PyObject {

    public static final PyType TYPE = PyType.fromClass(PyComplex.class);

    /** Format specification used by repr(). */
    static final Spec SPEC_REPR = InternalFormat.fromText(" >r"); // but also minFracDigits=0
    /** Format specification used by str() and none-format. (As CPython, but is that right?) */
    static final Spec SPEC_STR = InternalFormat.fromText(" >.12g");

    static PyComplex J = new PyComplex(0, 1.);

    public static final PyComplex Inf = new PyComplex(Double.POSITIVE_INFINITY,
            Double.POSITIVE_INFINITY);
    public static final PyComplex NaN = new PyComplex(Double.NaN, Double.NaN);

    @ExposedGet(doc = BuiltinDocs.complex_real_doc)
    public double real;

    @ExposedGet(doc = BuiltinDocs.complex_imag_doc)
    public double imag;

    public PyComplex(PyType subtype, double r, double i) {
        super(subtype);
        real = r;
        imag = i;
    }

    public PyComplex(double r, double i) {
        this(TYPE, r, i);
    }

    public PyComplex(double r) {
        this(r, 0.0);
    }

    @ExposedNew
    public static PyObject complex_new(PyNewWrapper new_, boolean init, PyType subtype,
            PyObject[] args, String[] keywords) {
        ArgParser ap = new ArgParser("complex", args, keywords, "real", "imag");
        PyObject real = ap.getPyObject(0, Py.Zero);
        PyObject imag = ap.getPyObject(1, null);

        // Special-case for single argument that is already complex
        if (real.getType() == TYPE && new_.for_type == subtype && imag == null) {
            return real;
        } else if (real instanceof PyString) {
            if (imag != null) {
                throw Py.TypeError("complex() can't take second arg if first is a string");
            }
            return real.__complex__();
        } else if (imag != null && imag instanceof PyString) {
            throw Py.TypeError("complex() second arg can't be a string");
        }

        try {
            real = real.__complex__();
        } catch (PyException pye) {
            if (!pye.match(Py.AttributeError)) {
                // __complex__ not supported
                throw pye;
            }
            // otherwise try other means
        }

        PyComplex complexReal;
        PyComplex complexImag;
        PyFloat toFloat = null;
        if (real instanceof PyComplex) {
            complexReal = (PyComplex)real;
        } else {
            try {
                toFloat = real.__float__();
            } catch (PyException pye) {
                if (pye.match(Py.AttributeError)) {
                    // __float__ not supported
                    throw Py.TypeError("complex() argument must be a string or a number");
                }
                throw pye;
            }
            complexReal = new PyComplex(toFloat.getValue());
        }

        if (imag == null) {
            complexImag = new PyComplex(0.0);
        } else if (imag instanceof PyComplex) {
            complexImag = (PyComplex)imag;
        } else {
            toFloat = null;
            try {
                toFloat = imag.__float__();
            } catch (PyException pye) {
                if (pye.match(Py.AttributeError)) {
                    // __float__ not supported
                    throw Py.TypeError("complex() argument must be a string or a number");
                }
                throw pye;
            }
            complexImag = new PyComplex(toFloat.getValue());
        }

        complexReal.real -= complexImag.imag;
        if (complexReal.imag == 0.0) {
            // necessary if complexImag is -0.0, given that adding 0.0 + -0.0 is 0.0
            complexReal.imag = complexImag.real;
        } else {
            complexReal.imag += complexImag.real;
        }
        if (new_.for_type != subtype) {
            complexReal = new PyComplexDerived(subtype, complexReal.real, complexReal.imag);
        }
        return complexReal;
    }

    public final PyFloat getReal() {
        return Py.newFloat(real);
    }

    public final PyFloat getImag() {
        return Py.newFloat(imag);
    }

    public static String toString(double value) {
        if (value == Math.floor(value) && value <= Long.MAX_VALUE && value >= Long.MIN_VALUE) {
            return Long.toString((long)value);
        } else {
            return Double.toString(value);
        }
    }

    @Override
    public String toString() {
        return __str__().toString();
    }

    @Override
    public PyString __str__() {
        return complex___str__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___str___doc)
    final PyString complex___str__() {
        return Py.newString(formatComplex(SPEC_STR));
    }

    @Override
    public PyString __repr__() {
        return complex___repr__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___repr___doc)
    final PyString complex___repr__() {
        return Py.newString(formatComplex(SPEC_REPR));
    }

    /**
     * Format this complex according to the specification passed in. Supports __str__
     * and __repr__, and none-format.
     *

     * In general, the output is surrounded in parentheses, like "(12.34+24.68j)".
     * However, if the real part is zero (but not negative zero), only the imaginary part is
     * printed, and without parentheses like "24.68j". The number format specification
     * passed in is used for the real and imaginary parts individually, with padding to width
     * afterwards (if the specification requires it).
     *
     * @param spec parsed format specification string
     * @return formatted value
     */
    private String formatComplex(Spec spec) {
        int size = 2 * FloatFormatter.size(spec) + 3;  // 2 floats + "(j)"
        FloatFormatter f = new FloatFormatter(new StringBuilder(size), spec);
        f.setBytes(true);
        // Even in r-format, complex strips *all* the trailing zeros.
        f.setMinFracDigits(0);
        if (Double.doubleToLongBits(real) == 0L) {
            // Real part is truly zero: show no real part.
            f.format(imag).append('j');
        } else {
            f.append('(').format(real).format(imag, "+").append("j)");
        }
        return f.pad().getResult();
    }

    @Override
    public int hashCode() {
        return complex___hash__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___hash___doc)
    final int complex___hash__() {
        if (imag == 0) {
            return new PyFloat(real).hashCode();
        } else {
            long v = Double.doubleToLongBits(real) ^ Double.doubleToLongBits(imag);
            return (int)v ^ (int)(v >> 32);
        }
    }

    @Override
    public boolean __nonzero__() {
        return complex___nonzero__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___nonzero___doc)
    final boolean complex___nonzero__() {
        return real != 0 || imag != 0;
    }

    @Override
    public int __cmp__(PyObject other) {
        if (!canCoerce(other)) {
            return -2;
        }
        PyComplex c = coerce(other);
        double oreal = c.real;
        double oimag = c.imag;
        if (real == oreal && imag == oimag) {
            return 0;
        }
        if (real != oreal) {
            return real < oreal ? -1 : 1;
        } else {
            return imag < oimag ? -1 : 1;
        }
    }

    @Override
    public PyObject __eq__(PyObject other) {
        return complex___eq__(other);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___eq___doc)
    final PyObject complex___eq__(PyObject other) {
        switch (eq_helper(other)) {
            case 0:
                return Py.False;
            case 1:
                return Py.True;
            default:
                return null;
        }
    }

    /**
     * Helper for {@link #complex___eq__(PyObject)} and {@link #complex___ne__(PyObject)}.
     *
     * @param other to compare for equality with this
     * @return 0 = false, 1 = true, 2 = don't know (ask the other object)
     */
    private int eq_helper(PyObject other) {
        // We only deal with primitive types here. All others delegate upwards (return 2).
        boolean equal;
        if (other instanceof PyComplex) {
            PyComplex c = ((PyComplex)other);
            equal = (this.real == c.real && this.imag == c.imag);
        } else if (other instanceof PyFloat) {
            PyFloat f = ((PyFloat)other);
            equal = (this.imag == 0.0 && this.real == f.getValue());
        } else if (other instanceof PyInteger || other instanceof PyLong) {
            if (this.imag == 0.0) {
                // The imaginary part is zero: other object primitive might equal the real part.
                double r = this.real;
                if (Double.isInfinite(r) || Double.isNaN(r)) {
                    // No integer primitive type can be infinite, and NaN never equals anything.
                    equal = false;
                } else {
                    // Delegate the logic to PyFloat
                    PyFloat f = new PyFloat(r);
                    equal = (f.float___cmp__(other) == 0);
                }
            } else {
                // No other primitive can have an imaginary part.
                equal = false;
            }
        } else {
            // other is not one of the types we know how to deal with.
            return 2;
        }
        // Only "known" cases end here: translate to return code
        return equal ? 1 : 0;
    }

    @Override
    public PyObject __ne__(PyObject other) {
        return complex___ne__(other);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___ne___doc)
    final PyObject complex___ne__(PyObject other) {
        switch (eq_helper(other)) {
            case 0:
                return Py.True;
            case 1:
                return Py.False;
            default:
                return null;
        }
    }

    private PyObject unsupported_comparison(PyObject other) {
        if (!canCoerce(other)) {
            return null;
        }
        throw Py.TypeError("cannot compare complex numbers using <, <=, >, >=");
    }

    @Override
    public PyObject __ge__(PyObject other) {
        return complex___ge__(other);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___ge___doc)
    final PyObject complex___ge__(PyObject other) {
        return unsupported_comparison(other);
    }

    @Override
    public PyObject __gt__(PyObject other) {
        return complex___gt__(other);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___gt___doc)
    final PyObject complex___gt__(PyObject other) {
        return unsupported_comparison(other);
    }

    @Override
    public PyObject __le__(PyObject other) {
        return complex___le__(other);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___le___doc)
    final PyObject complex___le__(PyObject other) {
        return unsupported_comparison(other);
    }

    @Override
    public PyObject __lt__(PyObject other) {
        return complex___lt__(other);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___lt___doc)
    final PyObject complex___lt__(PyObject other) {
        return unsupported_comparison(other);
    }

    @Override
    public Object __coerce_ex__(PyObject other) {
        return complex___coerce_ex__(other);
    }

    @ExposedMethod(doc = BuiltinDocs.complex___coerce___doc)
    final PyObject complex___coerce__(PyObject other) {
        return adaptToCoerceTuple(complex___coerce_ex__(other));
    }

    /**
     * Coercion logic for complex. Implemented as a final method to avoid invocation of virtual
     * methods from the exposed coerce.
     */
    final PyObject complex___coerce_ex__(PyObject other) {
        if (other instanceof PyComplex) {
            return other;
        } else if (other instanceof PyFloat) {
            return new PyComplex(((PyFloat)other).getValue(), 0);
        } else if (other instanceof PyInteger) {
            return new PyComplex(((PyInteger)other).getValue(), 0);
        } else if (other instanceof PyLong) {
            return new PyComplex(((PyLong)other).doubleValue(), 0);
        }
        return Py.None;
    }

    private final boolean canCoerce(PyObject other) {
        return other instanceof PyComplex || other instanceof PyFloat || other instanceof PyInteger
                || other instanceof PyLong;
    }

    private final PyComplex coerce(PyObject other) {
        if (other instanceof PyComplex) {
            return (PyComplex)other;
        } else if (other instanceof PyFloat) {
            return new PyComplex(((PyFloat)other).getValue(), 0);
        } else if (other instanceof PyInteger) {
            return new PyComplex(((PyInteger)other).getValue(), 0);
        } else if (other instanceof PyLong) {
            return new PyComplex(((PyLong)other).doubleValue(), 0);
        }
        throw Py.TypeError("xxx");
    }

    @Override
    public PyObject __add__(PyObject right) {
        return complex___add__(right);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___add___doc)
    final PyObject complex___add__(PyObject right) {
        if (!canCoerce(right)) {
            return null;
        }
        PyComplex c = coerce(right);
        return new PyComplex(real + c.real, imag + c.imag);
    }

    @Override
    public PyObject __radd__(PyObject left) {
        return complex___radd__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___radd___doc)
    final PyObject complex___radd__(PyObject left) {
        return __add__(left);
    }

    private final static PyObject _sub(PyComplex o1, PyComplex o2) {
        return new PyComplex(o1.real - o2.real, o1.imag - o2.imag);
    }

    @Override
    public PyObject __sub__(PyObject right) {
        return complex___sub__(right);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___sub___doc)
    final PyObject complex___sub__(PyObject right) {
        if (!canCoerce(right)) {
            return null;
        }
        return _sub(this, coerce(right));
    }

    @Override
    public PyObject __rsub__(PyObject left) {
        return complex___rsub__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rsub___doc)
    final PyObject complex___rsub__(PyObject left) {
        if (!canCoerce(left)) {
            return null;
        }
        return _sub(coerce(left), this);
    }

    private final static PyObject _mul(PyComplex o1, PyComplex o2) {
        if (Double.isNaN(o1.real) || Double.isNaN(o1.imag) || Double.isNaN(o2.real)
                || Double.isNaN(o2.imag)) {
            return NaN;
        }
        if (Double.isInfinite(o1.real) || Double.isInfinite(o1.imag) || Double.isInfinite(o2.real)
                || Double.isInfinite(o2.imag)) {
            return Inf;
        }

        return new PyComplex(o1.real * o2.real - o1.imag * o2.imag, o1.real * o2.imag + o1.imag
                * o2.real);
    }

    @Override
    public PyObject __mul__(PyObject right) {
        return complex___mul__(right);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___mul___doc)
    final PyObject complex___mul__(PyObject right) {
        if (!canCoerce(right)) {
            return null;
        }
        return _mul(this, coerce(right));
    }

    @Override
    public PyObject __rmul__(PyObject left) {
        return complex___rmul__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rmul___doc)
    final PyObject complex___rmul__(PyObject left) {
        if (!canCoerce(left)) {
            return null;
        }
        return _mul(coerce(left), this);
    }

    private final static PyObject _div(PyComplex a, PyComplex b) {
        double abs_breal = b.real < 0 ? -b.real : b.real;
        double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
        if (abs_breal >= abs_bimag) {
            // Divide tops and bottom by b.real
            if (abs_breal == 0.0) {
                throw Py.ZeroDivisionError("complex division");
            }
            double ratio = b.imag / b.real;
            double denom = b.real + b.imag * ratio;
            return new PyComplex((a.real + a.imag * ratio) / denom, //
                    (a.imag - a.real * ratio) / denom);
        } else {
            /* divide tops and bottom by b.imag */
            double ratio = b.real / b.imag;
            double denom = b.real * ratio + b.imag;
            return new PyComplex((a.real * ratio + a.imag) / denom, //
                    (a.imag * ratio - a.real) / denom);
        }
    }

    @Override
    public PyObject __div__(PyObject right) {
        return complex___div__(right);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___div___doc)
    final PyObject complex___div__(PyObject right) {
        if (!canCoerce(right)) {
            return null;
        } else if (Options.division_warning >= 2) {
            Py.warning(Py.DeprecationWarning, "classic complex division");
        }
        return _div(this, coerce(right));
    }

    @Override
    public PyObject __rdiv__(PyObject left) {
        return complex___rdiv__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rdiv___doc)
    final PyObject complex___rdiv__(PyObject left) {
        if (!canCoerce(left)) {
            return null;
        } else if (Options.division_warning >= 2) {
            Py.warning(Py.DeprecationWarning, "classic complex division");
        }
        return _div(coerce(left), this);
    }

    @Override
    public PyObject __floordiv__(PyObject right) {
        return complex___floordiv__(right);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___floordiv___doc)
    final PyObject complex___floordiv__(PyObject right) {
        if (!canCoerce(right)) {
            return null;
        }
        return _divmod(this, coerce(right)).__finditem__(0);
    }

    @Override
    public PyObject __rfloordiv__(PyObject left) {
        return complex___rfloordiv__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rfloordiv___doc)
    final PyObject complex___rfloordiv__(PyObject left) {
        if (!canCoerce(left)) {
            return null;
        }
        return _divmod(coerce(left), this).__finditem__(0);
    }

    // Special case __tojava__ for bug 1605, since we broke it with our support for faux floats.

    @Override
    public Object __tojava__(Class<?> c) {
        if (c.isInstance(this)) {
            return this;
        }
        return Py.NoConversion;
    }

    @Override
    public PyObject __truediv__(PyObject right) {
        return complex___truediv__(right);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___truediv___doc)
    final PyObject complex___truediv__(PyObject right) {
        if (!canCoerce(right)) {
            return null;
        }
        return _div(this, coerce(right));
    }

    @Override
    public PyObject __rtruediv__(PyObject left) {
        return complex___rtruediv__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rtruediv___doc)
    final PyObject complex___rtruediv__(PyObject left) {
        if (!canCoerce(left)) {
            return null;
        }
        return _div(coerce(left), this);
    }

    @Override
    public PyObject __mod__(PyObject right) {
        return complex___mod__(right);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___mod___doc)
    final PyObject complex___mod__(PyObject right) {
        if (!canCoerce(right)) {
            return null;
        }
        return _mod(this, coerce(right));
    }

    @Override
    public PyObject __rmod__(PyObject left) {
        return complex___rmod__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rmod___doc)
    final PyObject complex___rmod__(PyObject left) {
        if (!canCoerce(left)) {
            return null;
        }
        return _mod(coerce(left), this);
    }

    private static PyObject _mod(PyComplex value, PyComplex right) {
        Py.warning(Py.DeprecationWarning, "complex divmod(), // and % are deprecated");
        PyComplex z = (PyComplex)_div(value, right);

        z.real = Math.floor(z.real);
        z.imag = 0.0;

        return value.__sub__(z.__mul__(right));
    }

    @Override
    public PyObject __divmod__(PyObject right) {
        return complex___divmod__(right);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___divmod___doc)
    final PyObject complex___divmod__(PyObject right) {
        if (!canCoerce(right)) {
            return null;
        }
        return _divmod(this, coerce(right));
    }

    @Override
    public PyObject __rdivmod__(PyObject left) {
        return complex___rdivmod__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rdivmod___doc)
    final PyObject complex___rdivmod__(PyObject left) {
        if (!canCoerce(left)) {
            return null;
        }
        return _divmod(coerce(left), this);
    }

    private static PyObject _divmod(PyComplex value, PyComplex right) {
        Py.warning(Py.DeprecationWarning, "complex divmod(), // and % are deprecated");
        PyComplex z = (PyComplex)_div(value, right);

        z.real = Math.floor(z.real);
        z.imag = 0.0;

        return new PyTuple(z, value.__sub__(z.__mul__(right)));
    }

    private static PyObject ipow(PyComplex value, int iexp) {
        int pow = iexp;
        if (pow < 0) {
            pow = -pow;
        }

        double xr = value.real;
        double xi = value.imag;

        double zr = 1;
        double zi = 0;

        double tmp;

        while (pow > 0) {
            if ((pow & 0x1) != 0) {
                tmp = zr * xr - zi * xi;
                zi = zi * xr + zr * xi;
                zr = tmp;
            }
            pow >>= 1;
            if (pow == 0) {
                break;
            }
            tmp = xr * xr - xi * xi;
            xi = xr * xi * 2;
            xr = tmp;
        }

        PyComplex ret = new PyComplex(zr, zi);

        if (iexp < 0) {
            return new PyComplex(1, 0).__div__(ret);
        }
        return ret;
    }

    @Override
    public PyObject __pow__(PyObject right, PyObject modulo) {
        return complex___pow__(right, modulo);
    }

    @ExposedMethod(type = MethodType.BINARY, defaults = "null",
            doc = BuiltinDocs.complex___pow___doc)
    final PyObject complex___pow__(PyObject right, PyObject modulo) {
        if (modulo != null) {
            throw Py.ValueError("complex modulo");
        } else if (!canCoerce(right)) {
            return null;
        }
        return _pow(this, coerce(right));
    }

    @Override
    public PyObject __rpow__(PyObject left) {
        return complex___rpow__(left);
    }

    @ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.complex___rpow___doc)
    final PyObject complex___rpow__(PyObject left) {
        if (!canCoerce(left)) {
            return null;
        }
        return _pow(coerce(left), this);
    }

    public static PyObject _pow(PyComplex value, PyComplex right) {
        double xr = value.real;
        double xi = value.imag;
        double yr = right.real;
        double yi = right.imag;

        if (yr == 0 && yi == 0) {
            return new PyComplex(1, 0);
        }

        if (xr == 0 && xi == 0) {
            if (yi != 0 || yr < 0) {
                throw Py.ZeroDivisionError("0.0 to a negative or complex power");
            }
        }

        // Check for integral powers
        int iexp = (int)yr;
        if (yi == 0 && yr == iexp && iexp >= -128 && iexp <= 128) {
            return ipow(value, iexp);
        }

        double abs = Math.hypot(xr, xi);
        double len = Math.pow(abs, yr);

        double at = Math.atan2(xi, xr);
        double phase = at * yr;
        if (yi != 0) {
            len /= Math.exp(at * yi);
            phase += yi * Math.log(abs);
        }
        return new PyComplex(len * Math.cos(phase), len * Math.sin(phase));
    }

    @Override
    public PyObject __neg__() {
        return complex___neg__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___neg___doc)
    final PyObject complex___neg__() {
        return new PyComplex(-real, -imag);
    }

    @Override
    public PyObject __pos__() {
        return complex___pos__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___pos___doc)
    final PyObject complex___pos__() {
        return getType() == TYPE ? this : new PyComplex(real, imag);
    }

    @Override
    public PyObject __invert__() {
        throw Py.TypeError("bad operand type for unary ~");
    }

    @Override
    public PyObject __abs__() {
        return complex___abs__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___abs___doc)
    final PyObject complex___abs__() {
        double mag = Math.hypot(real, imag);
        if (Double.isInfinite(mag) && !(Double.isInfinite(real) || Double.isInfinite(imag))) {
            // In these circumstances Math.hypot quietly returns inf, but Python should raise.
            throw Py.OverflowError("absolute value too large");
        }
        return new PyFloat(mag);
    }

    @Override
    public PyObject __int__() {
        return complex___int__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___int___doc)
    final PyInteger complex___int__() {
        throw Py.TypeError("can't convert complex to int; use e.g. int(abs(z))");
    }

    @Override
    public PyObject __long__() {
        return complex___long__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___long___doc)
    final PyObject complex___long__() {
        throw Py.TypeError("can't convert complex to long; use e.g. long(abs(z))");
    }

    @Override
    public PyFloat __float__() {
        return complex___float__();
    }

    @ExposedMethod(doc = BuiltinDocs.complex___float___doc)
    final PyFloat complex___float__() {
        throw Py.TypeError("can't convert complex to float; use e.g. abs(z)");
    }

    @Override
    public PyComplex __complex__() {
        return new PyComplex(real, imag);
    }

    @Override
    public PyComplex conjugate() {
        return complex_conjugate();
    }

    @ExposedMethod(doc = BuiltinDocs.complex_conjugate_doc)
    final PyComplex complex_conjugate() {
        return new PyComplex(real, -imag);
    }

    @ExposedMethod(doc = BuiltinDocs.complex___getnewargs___doc)
    final PyTuple complex___getnewargs__() {
        return new PyTuple(new PyFloat(real), new PyFloat(imag));
    }

    @Override
    public PyTuple __getnewargs__() {
        return complex___getnewargs__();
    }

    @Override
    public PyObject __format__(PyObject formatSpec) {
        return complex___format__(formatSpec);
    }

    @ExposedMethod(doc = BuiltinDocs.complex___format___doc)
    final PyObject complex___format__(PyObject formatSpec) {

        // Parse the specification
        Spec spec = InternalFormat.fromText(formatSpec, "__format__");

        // fromText will have thrown if formatSpecStr is not a PyString (including PyUnicode)
        PyString formatSpecStr = (PyString)formatSpec;
        String result;

        // Validate the specification and detect the special case for none-format
        switch (checkSpecification(spec)) {

            case 0: // None-format
                // In none-format, we take the default type and precision from __str__.
                spec = spec.withDefaults(SPEC_STR);
                // And then we use the __str__ mechanism to get parentheses or real 0 elision.
                result = formatComplex(spec);
                break;

            case 1: // Floating-point formats
                // In any other format, defaults are those commonly used for numeric formats.
                spec = spec.withDefaults(Spec.NUMERIC);
                int size = 2 * FloatFormatter.size(spec) + 1; // 2 floats + "j"
                FloatFormatter f = new FloatFormatter(new StringBuilder(size), spec);
                f.setBytes(!(formatSpecStr instanceof PyUnicode));
                // Convert both parts as per specification
                f.format(real).format(imag, "+").append('j');
                result = f.pad().getResult();
                break;

            default: // The type code was not recognised
                throw Formatter.unknownFormat(spec.type, "complex");
        }

        // Wrap the result in the same type as the format string
        return formatSpecStr.createInstance(result);
    }

    /**
     * Validate a parsed specification, for PyComplex, returning 0 if it is a valid
     * none-format specification, 1 if it is a valid float specification, and some other value if it
     * not a valid type. If it has any other faults (e.g. alternate form was specified) the method
     * raises a descriptive exception.
     *
     * @param spec a parsed PEP-3101 format specification.
     * @return 0, 1, or other value for none-format, a float format, or incorrect type.
     * @throws PyException(ValueError) if the specification is faulty.
     */
    @SuppressWarnings("fallthrough")
    private static int checkSpecification(Spec spec) {

        // Slight differences between format types
        switch (spec.type) {

            case 'n':
                if (spec.grouping) {
                    throw Formatter.notAllowed("Grouping", "complex", spec.type);
                }
                // Fall through

            case Spec.NONE:
            case 'e':
            case 'f':
            case 'g':
            case 'E':
            case 'F':
            case 'G':
                // Check for disallowed parts of the specification
                if (spec.alternate) {
                    throw FloatFormatter.alternateFormNotAllowed("complex");
                } else if (spec.fill == '0') {
                    throw FloatFormatter.zeroPaddingNotAllowed("complex");
                } else if (spec.align == '=') {
                    throw FloatFormatter.alignmentNotAllowed('=', "complex");
                } else {
                    return (spec.type == Spec.NONE) ? 0 : 1;
                }

            default:
                // spec.type is invalid for complex
                return 2;
        }
    }

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


text:
package org.sakaiproject.assignment.impl.persistence;

import java.time.Instant;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.LockOptions;
import org.hibernate.NonUniqueResultException;
import org.hibernate.Session;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.persister.collection.CollectionPropertyNames;
import org.sakaiproject.assignment.api.AssignmentConstants;
import org.sakaiproject.assignment.api.AssignmentServiceConstants;
import org.sakaiproject.assignment.api.model.Assignment;
import org.sakaiproject.assignment.api.model.AssignmentSubmission;
import org.sakaiproject.assignment.api.model.AssignmentSubmissionSubmitter;
import org.sakaiproject.assignment.api.persistence.AssignmentRepository;
import org.sakaiproject.hibernate.HibernateCriterionUtils;
import org.sakaiproject.serialization.BasicSerializableRepository;
import org.springframework.transaction.annotation.Transactional;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by enietzel on 2/22/17.
 */
@Slf4j
@Transactional(readOnly = true)
public class AssignmentRepositoryImpl extends BasicSerializableRepository<Assignment, String> implements AssignmentRepository {

    @Override
    public Assignment findAssignment(String id) {
        return findOne(id);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Assignment> findAssignmentsBySite(String siteId) {
        return startCriteriaQuery()
                .add(Restrictions.eq("context", siteId))
                .add(Restrictions.eq("deleted", Boolean.FALSE))
                .list();
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Assignment> findDeletedAssignmentsBySite(String siteId) {
        return startCriteriaQuery()
                .add(Restrictions.eq("context", siteId))
                .add(Restrictions.eq("deleted", Boolean.TRUE))
                .list();
    }

    @Override
    public List<String> findAllAssignmentIds() {
        return startCriteriaQuery()
                .setProjection(Projections.property("id"))
                .list();
    }

    @Override
    @Transactional
    public void newAssignment(Assignment assignment) {
        if (!existsAssignment(assignment.getId())) {
            assignment.setDateCreated(Instant.now());
            sessionFactory.getCurrentSession().persist(assignment);
        }
    }

    @Override
    @Transactional
    public boolean existsAssignment(String assignmentId) {
        if (assignmentId != null && exists(assignmentId)) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public void deleteAssignment(String assignmentId) {
        Assignment assignment = findOne(assignmentId);
        if (assignment != null) {
            delete(assignment);
        }
    }

    @Override
    @Transactional
    public void deleteSubmission(String submissionId) {
        Session session = sessionFactory.getCurrentSession();
        AssignmentSubmission submission = (AssignmentSubmission) session.get(AssignmentSubmission.class, submissionId);
        if (submission != null) {
            log.info("Deleting submission {}", submission);
            Assignment assignment = submission.getAssignment();
            // must call refresh here to ensure the collections are initialized before changing, this is due to lazy loaded entities
            session.refresh(assignment);
            assignment.getSubmissions().remove(submission);
            session.update(assignment);
            session.flush();
        }
    }

    @Override
    @Transactional
    public void softDeleteAssignment(String assignmentId) {
        Assignment assignment = findOne(assignmentId);
        assignment.setDeleted(Boolean.TRUE);
        update(assignment);
    }

    @Override
    public AssignmentSubmission findSubmission(String submissionId) {
        return (AssignmentSubmission) sessionFactory.getCurrentSession().get(AssignmentSubmission.class, submissionId);
    }

    @Override
    @Transactional
    public void updateSubmission(AssignmentSubmission submission) {
        if (existsSubmission(submission.getId())) {
            submission.setDateModified(Instant.now());
            sessionFactory.getCurrentSession().merge(submission);
        }
    }

    @Override
    @Transactional
    public boolean existsSubmission(String submissionId) {
        if (submissionId != null && sessionFactory.getCurrentSession().get(AssignmentSubmission.class, submissionId) != null) {
            return true;
        }
        return false;
    }

    @Override
    @Transactional
    public AssignmentSubmission newSubmission(String assignmentId, Optional<String> groupId, Optional<Set<AssignmentSubmissionSubmitter>> submitters, Optional<Set<String>> feedbackAttachments, Optional<Set<String>> submittedAttachments, Optional<Map<String, String>> properties) {
        Assignment assignment = findAssignment(assignmentId);
        if (assignment != null) {
            Session session = sessionFactory.getCurrentSession();
            // Since this transaction is going to add a submission to the assignment we lock the assignment
            // the lock is freed once transaction is committed or rolled back
            session.buildLockRequest(LockOptions.UPGRADE).setLockMode(LockMode.PESSIMISTIC_WRITE).lock(assignment);

            AssignmentSubmission submission = new AssignmentSubmission();
            submission.setDateCreated(Instant.now());
            submitters.ifPresent(submission::setSubmitters);
            submitters.ifPresent(s -> s.forEach(submitter -> submitter.setSubmission(submission)));
            feedbackAttachments.ifPresent(submission::setFeedbackAttachments);
            submittedAttachments.ifPresent(submission::setAttachments);
            properties.ifPresent(submission::setProperties);
            if (assignment.getIsGroup()) { groupId.ifPresent(submission::setGroupId); }

            submission.setAssignment(assignment);
            assignment.getSubmissions().add(submission);

            session.persist(assignment);
            return submission;
        }
        return null;
    }

    @Override
    @Transactional
    @SuppressWarnings("unchecked")
    public AssignmentSubmission findSubmissionForUser(String assignmentId, String userId) {
        List<AssignmentSubmission> submissions = sessionFactory.getCurrentSession().createCriteria(AssignmentSubmission.class)
                .add(Restrictions.eq("assignment.id", assignmentId))
                .createAlias("submitters", "s")
                .add(Restrictions.eq("s.submitter", userId))
                .list();

        switch (submissions.size()) {
            case 0: return null;
            case 1: return submissions.get(0);
            default:
                log.info("Duplicate submissions detected for assignment {} and user {} attempting to clean", assignmentId, userId);
                // when more than 1 was found it is considered a duplicate submission

                // find non user submissions with no text or submitted date
                List<AssignmentSubmission> removable = submissions.stream()
                        .filter(s -> !s.getUserSubmission() && StringUtils.isBlank(s.getSubmittedText()) && s.getDateSubmitted() == null)
                        .collect(Collectors.toList());
                if  (submissions.size() - removable.size() > 1) {
                    log.debug("{} to many submissions, trying more agressively", submissions.size() - removable.size());
                    // still to many lets be a little more aggressive finding those that are not returned and no grade
                    submissions.removeAll(removable);
                    submissions.stream().filter(s -> !s.getReturned() && s.getGrade() == null).forEach(removable::add);
                }
                if ((submissions.size() - removable.size()) > 1) {
                    log.debug("{} to many submissions, take the first submission and remove the rest", submissions.size() - removable.size());
                    // if we get here it's likely there is no easy decision, so lets just take the first created submission
                    submissions.removeAll(removable);
                    submissions.sort(Comparator.comparing(AssignmentSubmission::getDateCreated));
                    removable.addAll(submissions.subList(1, submissions.size()));
                }
                if (submissions.size() > 1 && (submissions.size() - removable.size()) == 0) {
                    // if we have to many submissions for removal select the first
                    submissions.sort(Comparator.comparing(AssignmentSubmission::getDateCreated));
                    removable.remove(submissions.get(0));
                }
                submissions.removeAll(removable);
                removable.forEach(s -> deleteSubmission(s.getId()));
                return submissions.get(0);
        }
    }

    @Override
    @Transactional
    public List<AssignmentSubmission> findSubmissionForUsers(String assignmentId, List<String> userIds) {
        List<AssignmentSubmission> submissions = sessionFactory.getCurrentSession().createCriteria(AssignmentSubmission.class)
                .add(Restrictions.eq("assignment.id", assignmentId))
                .createAlias("submitters", "s")
                .add(HibernateCriterionUtils.CriterionInRestrictionSplitter("s.submitter", userIds))
                .list();
        return submissions;
    }

    @Override
    public AssignmentSubmission findSubmissionForGroup(String assignmentId, String groupId) {
        return (AssignmentSubmission) sessionFactory.getCurrentSession().createCriteria(AssignmentSubmission.class)
                .add(Restrictions.eq("assignment.id", assignmentId))
                .add(Restrictions.eq("groupId", groupId))
                .uniqueResult();
    }

    @Override
    public void initializeAssignment(Assignment assignment) {
        sessionFactory.getCurrentSession().refresh(assignment);
    }

    @Override
    public long countAssignmentSubmissions(String assignmentId, Boolean graded, Boolean hasSubmissionDate, Boolean userSubmission, List<String> userIds) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(AssignmentSubmission.class)
                .setProjection(Projections.countDistinct("id"))
                .add(Restrictions.eq("assignment.id", assignmentId))
                .add(Restrictions.eq("submitted", Boolean.TRUE))
                .createAlias("submitters", "s");

        if (graded != null) {
            criteria.add(Restrictions.eq("graded", graded));
        }
        if (hasSubmissionDate != null) {
            criteria.add(hasSubmissionDate ? Restrictions.isNotNull("dateSubmitted") : Restrictions.isNull("dateSubmitted"));
        }
        if (userSubmission != null) {
            criteria.add(Restrictions.eq("userSubmission", userSubmission));
        }
        if (userIds != null) {
            if (userIds.isEmpty()) {
                return 0; // if we have an empty list then we return always return 0
            } else {
                criteria.add(HibernateCriterionUtils.CriterionInRestrictionSplitter("s.submitter", userIds));
            }
        }
        return ((Number) criteria.uniqueResult()).longValue();
    }

    @Override
    public void resetAssignment(Assignment assignment) {
        if (assignment != null && assignment.getId() != null) {
            sessionFactory.getCache().evictEntity(Assignment.class, assignment.getId());
        }
    }

    @Override
    public String findAssignmentIdForGradebookLink(String context, String linkId) {
        return String.valueOf(startCriteriaQuery()
                .createAlias("properties", "p")
                .add(Restrictions.eq("context", context))
                .add(Restrictions.eq("p." + CollectionPropertyNames.COLLECTION_INDICES, AssignmentConstants.PROP_ASSIGNMENT_ASSOCIATE_GRADEBOOK_ASSIGNMENT))
                .add(Restrictions.eq("p." + CollectionPropertyNames.COLLECTION_ELEMENTS, linkId))
                .setProjection(Projections.property("id"))
                .uniqueResult());
    }
}


text:
package process_count

import (
	gm "github.com/gollector/gollector_metrics"
	"github.com/gollector/gollector/logger"
)

func GetMetric(params interface{}, log *logger.Logger) interface{} {
	result, err := gm.ProcessCount(params.(string))

	if err != nil {
		log.Log("crit", err.Error())
		return nil
	}

	return result
}


text:
class ModifyUserColumnConstraints < ActiveRecord::Migration
  def up
    # Remove the non-null constraint on email
    change_column :users, :email, :string, null: true
  end

  def down
    change_column :users, :email, :string, null: false
  end
end


text:
namespace ashbot {

bot::bot()
    :   context_(IRC_CHANNEL)
    ,   client_(context_)
{
    context_.set_irc_client(&client_);
    context_.register_commands();
}

void bot::run()
{
    client_.connect();
    client_.login(IRC_NICKNAME, IRC_TOKEN);
    client_.join(IRC_CHANNEL);
}

void bot::stop()
{
    context_.stop();
    client_.stop();
}
}


text:
class Bishop : public Piece
{
public:
    char toString() const;
private:
    bool check(unsigned int xPosition, unsigned int yPosition) const;
    void disable() const;
};

#endif // BISHOP_HPP


text:
//used for the media picker dialog
angular.module("umbraco").controller("Umbraco.Dialogs.TreePickerController",
	function ($scope, entityResource, eventsService, $log, searchService) {

		var dialogOptions = $scope.$parent.dialogOptions;
		$scope.dialogTreeEventHandler = $({});
		$scope.section = dialogOptions.section;
		$scope.treeAlias = dialogOptions.treeAlias;
		$scope.multiPicker = dialogOptions.multiPicker;
		$scope.hideHeader = dialogOptions.startNodeId ? true : false;
		$scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;

	    //create the custom query string param for this tree
		$scope.customTreeParams = dialogOptions.startNodeId ? "startNodeId=" + dialogOptions.startNodeId : "";
		$scope.customTreeParams += dialogOptions.customTreeParams ? "&" + dialogOptions.customTreeParams : "";

		//search defaults
		$scope.searcher = searchService.searchContent;
		$scope.entityType = "Document";
		$scope.results = [];

		//min / max values
		if(dialogOptions.minNumber){
			dialogOptions.minNumber = parseInt(dialogOptions.minNumber, 10);
		}
		if(dialogOptions.maxNumber){
			dialogOptions.maxNumber = parseInt(dialogOptions.maxNumber, 10);
		}

		//search
		if (dialogOptions.section === "member") {
			$scope.searcher = searchService.searchMembers;
			$scope.entityType = "Member";
		}
		else if (dialogOptions.section === "media") {
			$scope.searcher = searchService.searchMedia;
			$scope.entityType = "Media";
		}

		//Configures filtering
		if (dialogOptions.filter) {

			dialogOptions.filterExclude = false;
			dialogOptions.filterAdvanced = false;

			if(dialogOptions.filter[0] === "!"){
				dialogOptions.filterExclude = true;
				dialogOptions.filter = dialogOptions.filter.substring(1);
			}

			//used advanced filtering
			if(dialogOptions.filter[0] === "{"){
				dialogOptions.filterAdvanced = true;
			}

			$scope.dialogTreeEventHandler.bind("treeNodeExpanded", function (ev, args) {
				if (angular.isArray(args.children)) {
					performFiltering(args.children);
				}
			});
		}

		/** Method used for selecting a node */
		function select(text, id, entity) {
			//if we get the root, we just return a constructed entity, no need for server data
			if (id < 0) {
				if ($scope.multiPicker) {
					$scope.select(id);
				}
				else {
					var node = {
						alias: null,
						icon: "icon-folder",
						id: id,
						name: text
					};
					$scope.submit(node);
				}
			}else {
				$scope.showSearch = false;
				$scope.results = [];
				$scope.term = "";
				$scope.oldTerm = undefined;

				if ($scope.multiPicker) {
					$scope.select(id);
				}else {
					//if an entity has been passed in, use it
					if (entity) {
						$scope.submit(entity);
					}else {
						//otherwise we have to get it from the server
						entityResource.getById(id, $scope.entityType).then(function (ent) {
							$scope.submit(ent);
						});
					}
				}
			}
		}

		function performFiltering(nodes){
			if(dialogOptions.filterAdvanced){
				angular.forEach(_.where(nodes, angular.fromJson(dialogOptions.filter)), function(value, key){
					value.filtered = true;
					if(dialogOptions.filterCssClass){
						value.cssClasses.push(dialogOptions.filterCssClass);
					}
				});
			}else{
				var a = dialogOptions.filter.split(',');
				angular.forEach(nodes, function (value, key) {

					var found = a.indexOf(value.metaData.contentType) >= 0;

					if (!dialogOptions.filterExclude && !found || dialogOptions.filterExclude && found){
						value.filtered = true;

						if(dialogOptions.filterCssClass){
							value.cssClasses.push(dialogOptions.filterCssClass);
						}
					}
				});
			}
		}

	$scope.multiSubmit = function (result) {
		entityResource.getByIds(result, $scope.entityType).then(function (ents) {
			$scope.submit(ents);
		});
	};

	/** method to select a search result */
	$scope.selectResult = function (result) {
		//since result = an entity, we'll pass it in so we don't have to go back to the server
		select(result.name, result.id, result);
	};

	$scope.performSearch = function () {
		if ($scope.term) {
			if ($scope.oldTerm !== $scope.term) {
				$scope.results = [];

				$scope.searcher({ term: $scope.term }).then(function (data) {
					$scope.results = data;
				});

				$scope.showSearch = true;
				$scope.oldTerm = $scope.term;
			}
		}
		else {
			$scope.oldTerm = "";
			$scope.showSearch = false;
			$scope.results = [];
		}
	};

	//wires up selection
	$scope.dialogTreeEventHandler.bind("treeNodeSelect", function (ev, args) {
		args.event.preventDefault();
		args.event.stopPropagation();

		eventsService.emit("dialogs.treePickerController.select", args);

		if (args.node.filtered) {
		    return;
		}

	    //This is a tree node, so we don't have an entity to pass in, it will need to be looked up
	    //from the server in this method.
		select(args.node.name, args.node.id);

	    //ui...
		if ($scope.multiPicker) {
		    var c = $(args.event.target.parentElement);
		    if (!args.node.selected) {
		        args.node.selected = true;
		        var temp = "<i class='icon umb-tree-icon sprTree icon-check blue temporary'></i>";
		        var icon = c.find("i.umb-tree-icon");
		        if (icon.length > 0) {
		            icon.hide().after(temp);
		        }
		        else {
		            c.prepend(temp);
		        }
		    }
		    else {
		        args.node.selected = false;
		        c.find(".temporary").remove();
		        c.find("i.umb-tree-icon").show();
		    }
		}
	});
});


text:
#ifndef OPENIKEV2AUTHGENERATOR_H
#define OPENIKEV2AUTHGENERATOR_H

#include <libopenikev2/printable.h>
#include <libopenikev2/ikesa.h>

namespace openikev2 {

    /**
     This abstract class represents an AUTH generator, that performs the AUTH payload generation tasks
     @author Alejandro Perez Mendez, Pedro J. Fernandez Ruiz <alex@um.es, pedroj@um.es>
    */
    class AuthGenerator : public Printable {
            /****************************** METHODS ******************************/
        public:
            /**
             * Generates the Certificate Payloads to be included in the IKE_AUTH message
             * @param ike_sa IkeSa
             * @param payload_cert_req_r Received Certificate Request payloads
             * @return The Certificate Payload collection to be included in the IKE_AUTH message
             */
            virtual AutoVector<Payload_CERT> generateCertificatePayloads( const IkeSa& ike_sa, const vector<Payload_CERT_REQ*> payload_cert_req_r ) = 0;

            /**
             * Generate the AUTH payload to be included in the AUTH message
             * @param ike_sa IkeSa
             * @return The new AUTH payload
             */
            virtual auto_ptr<Payload_AUTH> generateAuthPayload( const IkeSa& ike_sa ) = 0;

            /**
            * Clones this AuthGenerator
            * @return A new cloned AuthGenerator
            */
            virtual auto_ptr<AuthGenerator> clone() const = 0;

            virtual string toStringTab( uint8_t tabs ) const = 0;

            virtual ~AuthGenerator();

    };

}

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

namespace Anony.Controls
{
    public class FlyoutHelper
    {
        protected Popup m_Popup;
        private Action CloseAction;
        public Popup Show(Popup popup, FrameworkElement button, double offset = 35d)
        {
            if (popup == null)
                throw new Exception("Popup is not defined");
            m_Popup = popup;
            if (button == null)
                throw new Exception("Button is not defined");
            if (double.IsNaN(offset))
                throw new Exception("Offset is not defined");
            var _Child = popup.Child as FrameworkElement;
            if (_Child == null)
                throw new Exception("Popup.Child is not defined");
            if (double.IsNaN(_Child.Height))
                throw new Exception("Popup.Child.Height is not defined");
            if (double.IsNaN(_Child.Width))
                throw new Exception("Popup.Child.Width is not defined");

            // get position of the button
            var _Page = Window.Current.Content as Page;
            var _Visual = button.TransformToVisual(_Page);
            var _Point = _Visual.TransformPoint(new Point(0, 0));
            var _Button = new
            {
                Top = _Point.Y,
                Left = _Point.X,
                Width = button.ActualWidth,
                Height = button.ActualHeight,
            };

            // determine location
            var _TargetTop = (_Button.Top) - _Child.Height - offset;
            var _TargetLeft = (_Button.Left + (_Button.Width / 2)) - (_Child.Width / 2);

            if ((_TargetLeft + _Child.Width) > Window.Current.Bounds.Width)
                _TargetLeft = Window.Current.Bounds.Width - _Child.Width - offset;
            if (_TargetLeft < 0)
                _TargetLeft = offset;

            // setup popup
            popup.VerticalOffset = _TargetTop;
            popup.HorizontalOffset = _TargetLeft;

            // add pretty animation(s)
            popup.ChildTransitions = new Windows.UI.Xaml.Media.Animation.TransitionCollection
            {
                new Windows.UI.Xaml.Media.Animation.EntranceThemeTransition
                {
                    FromHorizontalOffset = 0,
                    FromVerticalOffset = 20
                }
            };

            // setup
            m_Popup.IsLightDismissEnabled = true;
            m_Popup.IsOpen = true;

            // handle when it closes
            m_Popup.Closed -= popup_Closed;
            m_Popup.Closed += popup_Closed;

            // handle making it close
            Window.Current.Activated -= Current_Activated;
            Window.Current.Activated += Current_Activated;

            // return
            return m_Popup;
        }

        private FrameworkElement _parentElement;
        public void Show(FrameworkElement element, Popup popup)
        {
            m_Popup = popup;
            m_Popup.VerticalAlignment = VerticalAlignment.Stretch;
            m_Popup.HorizontalAlignment = HorizontalAlignment.Stretch;
            element.HorizontalAlignment = HorizontalAlignment.Stretch;
            element.VerticalAlignment = VerticalAlignment.Stretch;
            element.Width = Window.Current.Bounds.Width;
            element.Height = Window.Current.Bounds.Height;
            m_Popup.Child = element;

            //m_Popup.VerticalOffset = Window.Current.Bounds.Height;
            m_Popup.IsLightDismissEnabled = true;
            m_Popup.ChildTransitions = new Windows.UI.Xaml.Media.Animation.TransitionCollection
            {
                new Windows.UI.Xaml.Media.Animation.EntranceThemeTransition
                {
                    FromHorizontalOffset = 0,
                    FromVerticalOffset = 20
                }
            };
            m_Popup.IsLightDismissEnabled = true;
            m_Popup.IsOpen = true;

            // handle when it closes
            m_Popup.Closed -= popup_Closed;
            m_Popup.Closed += popup_Closed;

            // handle making it close
            Window.Current.Activated -= Current_Activated;
            Window.Current.Activated += Current_Activated;
        }

        public void Show(FrameworkElement element, Popup popup, Action action)
        {
            Show(element, popup);
            CloseAction = action;
        }
        public void ShowPopup(FrameworkElement element, Popup popup,double offset=0)
        {
            m_Popup = popup;
            m_Popup.Child = element;
            m_Popup.VerticalOffset = offset;
            m_Popup.IsLightDismissEnabled = true;
            m_Popup.ChildTransitions = new Windows.UI.Xaml.Media.Animation.TransitionCollection
            {
                new Windows.UI.Xaml.Media.Animation.EntranceThemeTransition
                {
                    FromHorizontalOffset = 0,
                    FromVerticalOffset = 20
                }
            };

            m_Popup.IsLightDismissEnabled = true;
            m_Popup.IsOpen = true;

            // handle when it closes
            m_Popup.Closed -= popup_Closed;
            m_Popup.Closed += popup_Closed;

            // handle making it close
            Window.Current.Activated -= Current_Activated;
            Window.Current.Activated += Current_Activated;
        }
        public void ShowInDown(FrameworkElement element)
        {
            element.Width = Window.Current.Bounds.Width;
            element.Height = 300;
            m_Popup.Child = element;
            m_Popup.IsLightDismissEnabled = true;
            m_Popup.ChildTransitions = new Windows.UI.Xaml.Media.Animation.TransitionCollection
            {
                new Windows.UI.Xaml.Media.Animation.EntranceThemeTransition
                {
                    FromHorizontalOffset = 0,
                    FromVerticalOffset = 20
                }
            };

            m_Popup.VerticalOffset = Window.Current.Bounds.Height - 340 - 130;

            m_Popup.IsLightDismissEnabled = true;
            m_Popup.IsOpen = true;

            m_Popup.Closed -= popup_Closed;
            m_Popup.Closed += popup_Closed;

            // handle making it close
            Window.Current.Activated -= Current_Activated;
            Window.Current.Activated += Current_Activated;
        }

        protected void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
        {
            if (m_Popup == null)
                return;
            if (e.WindowActivationState == Windows.UI.Core.CoreWindowActivationState.Deactivated)
                m_Popup.IsOpen = false;
        }

        protected async void popup_Closed(object sender, object e)
        {
            if (CloseAction != null)
                CloseAction();
            Window.Current.Activated -= Current_Activated;
            if (m_Popup == null)
                return;
            //PrepareCloseStory();
            //await Task.Delay(1500);
            try
            {
                if (_parentElement == null) return;
                var page = _parentElement.GetParentByType<Page>();
                if (page != null && page.BottomAppBar != null)
                {
                    page.BottomAppBar.Visibility = Visibility.Visible;
                }
            }
            catch
            {

            }
            finally
            {
                m_Popup.IsOpen = false;
                m_Popup = null;
            }
        }

        void StoryReverse_Completed(object sender, object e)
        {
            m_Popup.IsOpen = false;
        }
    }
}


text:
<!DOCTYPE html>
<html>
  <head>
    <title>object-fit, video</title>
    <style>
      video {
        width: 120px;
        height: 120px;
        border: 1px solid blue;
        background-color: gray;
        margin: 10px;
      }
    </style>
    <script src=media-file.js></script>
    <script>
        if (window.testRunner)
          testRunner.waitUntilDone();

        function init()
        {
            var videosPresented = allVideosPresentedPromise();
            setSrcByTagName("video", "content/test.ogv");

            videosPresented.then(() => testRunner.notifyDone());
        }
    </script>

  </head>
  <body onload="init();">
    <video style="object-fit: fill"></video>
    <video style="object-fit: contain"></video>
    <video style="object-fit: cover"></video>
    <video style="object-fit: none"></video>
    <video style="object-fit: scale-down"></video>
  </body>
</html>