text:
package goagrep

import (
	"bufio"
	"fmt"
	"log"
	"math"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/boltdb/bolt"
	"github.com/cheggaaa/pb"
)

// VERBOSE is a flag to turn on/off status information during parsing
var VERBOSE bool

func init() {
	VERBOSE = false
}

func getPartials(s string, tupleLength int) []string {
	partials := make([]string, 100)
	num := 0
	s = strings.TrimSpace(strings.Replace(strings.ToLower(s), " ", "", -1))
	slen := len(s)
	if slen <= tupleLength {
		if slen <= 3 {
			partials[num] = "zzz"
			num = num + 1
		} else {
			for i := 0; i <= slen-3; i++ {
				partials[num] = s[i : i+3]
				num = num + 1
			}
		}
	} else {
		for i := 0; i <= slen-tupleLength; i++ {
			partials[num] = s[i : i+tupleLength]
			num = num + 1
			if num >= 100 {
				break
			}
		}
	}
	return partials[0:num]
}

func scanWords(wordpath string, tupleLength int, makeLookup bool) (words map[string]int, tuples map[string]string, wordsLookup map[int]string, tuplesLookup map[string][]int) {
	totalLines := lineCount(wordpath)

	inFile, _ := os.Open(wordpath)
	defer inFile.Close()
	scanner := bufio.NewScanner(inFile)
	scanner.Split(bufio.ScanLines)

	// initialize
	words = make(map[string]int)
	tuples = make(map[string]string)
	wordsLookup = make(map[int]string)
	tuplesLookup = make(map[string][]int)

	numTuples := 0
	numWords := 0
	lineNum := 0
	var bar *pb.ProgressBar
	if VERBOSE {
		fmt.Println("Parsing subsets...")
		bar = pb.StartNew(totalLines)
	}
	for scanner.Scan() {
		if VERBOSE {
			bar.Increment()
		}
		lineNum++
		s := strings.TrimSpace(scanner.Text())

		_, ok := words[s]
		if ok == false {
			if makeLookup {
				wordsLookup[numWords] = s
			} else {
				words[s] = numWords
			}

			partials := getPartials(s, tupleLength)
			for i := 0; i < len(partials); i++ {
				_, ok := tuples[partials[i]]
				if makeLookup {
					_, ok = tuplesLookup[partials[i]]
				}
				if ok == false {
					if makeLookup {
						tuplesLookup[partials[i]] = append([]int{}, numWords)
					} else {
						tuples[partials[i]] = strconv.Itoa(numWords)
					}
					numTuples++
				} else {
					if makeLookup {
						tuplesLookup[partials[i]] = append(tuplesLookup[partials[i]], numWords)
					} else {
						tuples[partials[i]] += " " + strconv.Itoa(numWords)
					}
				}
			}

			numWords++
		}

	}
	if VERBOSE {
		bar.FinishPrint("Finished parsing subsets")
	}
	return
}

func dumpToBoltDB(path string, words map[string]int, tuples map[string]string, tupleLength int) {
	var bar *pb.ProgressBar
	var start time.Time
	wordBuckets := int(len(words) / 600)
	if wordBuckets < 10 {
		wordBuckets = 10
	}
	if VERBOSE {
		fmt.Printf("Creating %v word buckets\n", wordBuckets)
	}

	if _, err := os.Stat(path); err == nil {
		os.Remove(path)
		if VERBOSE {
			fmt.Println("Removed old " + path)
		}
	}

	// Open a new bolt database
	db, err := bolt.Open(path, 0600, &bolt.Options{NoGrowSync: false})
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	if VERBOSE {
		fmt.Println("Creating subset buckets...")
		bar = pb.StartNew(len(tuples))
		start = time.Now()
	}
	err = db.Batch(func(tx *bolt.Tx) error {
		for k := range tuples {
			if VERBOSE {
				bar.Increment()
			}
			firstLetter := string(k[0])
			secondLetter := string(k[1])
			if strings.Contains(alphabet, firstLetter) && strings.Contains(alphabet, secondLetter) {
				_, err := tx.CreateBucketIfNotExists([]byte("tuples-" + firstLetter + secondLetter))
				if err != nil {
					return fmt.Errorf("create bucket: %s", err)
				}
			}
		}
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
	if VERBOSE {
		elapsed := time.Since(start)
		bar.FinishPrint("Creating subset buckets took " + elapsed.String())
	}

	db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucket([]byte("tuples"))
		if err != nil {
			return fmt.Errorf("create bucket: %s", err)
		}
		return nil
	})

	if VERBOSE {
		fmt.Println("Creating words buckets...")
	}
	db.Batch(func(tx *bolt.Tx) error {
		for i := 0; i < wordBuckets; i++ {
			_, err := tx.CreateBucket([]byte("words-" + strconv.Itoa(i)))
			if err != nil {
				return fmt.Errorf("create bucket: %s", err)
			}
		}
		return nil
	})

	db.Update(func(tx *bolt.Tx) error {
		_, err := tx.CreateBucket([]byte("vars"))
		if err != nil {
			return fmt.Errorf("create bucket: %s", err)
		}
		return nil
	})

	// fmt.Printf("INSERT INTO words (id,word) values (%v,'%v');\n", v, k)
	if VERBOSE {
		fmt.Println("Loading words into db...")
		start = time.Now()
		bar = pb.StartNew(len(words))
	}
	err = db.Batch(func(tx *bolt.Tx) error {
		for k, v := range words {
			if VERBOSE {
				bar.Increment()
			}
			if len(k) > 0 {
				b := tx.Bucket([]byte("words-" + strconv.Itoa(int(math.Mod(float64(v), float64(wordBuckets))))))
				b.Put([]byte(strconv.Itoa(v)), []byte(k))
			}
		}
		return nil
	})
	if err != nil {
		log.Fatal(err)
	}
	if VERBOSE {
		elapsed := time.Since(start)
		bar.FinishPrint("Words took " + elapsed.String())
	}

	if VERBOSE {
		fmt.Println("Loading subsets into db...")
		start = time.Now()
		bar = pb.StartNew(len(tuples))
	}
	err = db.Update(func(tx *bolt.Tx) error {
		for k, v := range tuples {
			if VERBOSE {
				bar.Increment()
			}
			firstLetter := string(k[0])
			secondLetter := string(k[1])
			if strings.Contains(alphabet, firstLetter) && strings.Contains(alphabet, secondLetter) {
				b := tx.Bucket([]byte("tuples-" + firstLetter + secondLetter))
				b.Put([]byte(k), []byte(v))
			} else {
				b := tx.Bucket([]byte("tuples"))
				b.Put([]byte(k), []byte(v))
			}
		}
		return nil
	})
	if err != nil {
		log.Fatal(err) // BUG(schollz): Windows file resize error: https://github.com/schollz/goagrep/issues/6
	}
	if VERBOSE {
		elapsed := time.Since(start)
		bar.FinishPrint("Subsets took " + elapsed.String())
	}

	db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("vars"))
		err := b.Put([]byte("tupleLength"), []byte(strconv.Itoa(tupleLength)))
		return err
	})

	db.Update(func(tx *bolt.Tx) error {
		b := tx.Bucket([]byte("vars"))
		err := b.Put([]byte("wordBuckets"), []byte(strconv.Itoa(wordBuckets)))
		return err
	})
}

// GenerateDB generates the database with precomputed strings for later searching.
// It is required to you generate a database before you use the GetMatch() function.
//
// stringListPath is the filename of the list of strings you want to use
//
// databasePath is the filename of the database that is outputed
//
// tupleLength is the length of the subsets you want to use
func GenerateDB(stringListPath string, databasePath string, tupleLength int, verbosity bool) {
	VERBOSE = verbosity
	words, tuples, _, _ := scanWords(stringListPath, tupleLength, false)
	dumpToBoltDB(databasePath, words, tuples, tupleLength)
}

func GenerateDBInMemory(stringListPath string, tupleLength int, verbosity bool) (words map[int]string, tuples map[string][]int) {
	VERBOSE = verbosity
	_, _, words, tuples = scanWords(stringListPath, tupleLength, true)
	return
}


text:
_By [adamlubek](https://github.com/adamlubek)_

This recipe demonstrates RxJs implementation of Flappy Bird like game.

[![Ultimate RxJS](https://drive.google.com/uc?export=view&id=1qq2-q-eVe-F_-d0eSvTyqaGRjpfLDdJz 'Ultimate RxJS')](https://ultimatecourses.com/courses/rxjs?ref=4)

### Example Code

( [StackBlitz](https://stackblitz.com/edit/rxjs-flappy-bird?file=index.ts) )

![Flappy Bird](https://drive.google.com/uc?export=view&id=1NcV8nce0NfvqghyBr0gxLoPm_Y4zjzXI)

#### index.ts

```js
// RxJS v6+
import { interval, merge, combineLatest, fromEvent } from 'rxjs';
import { tap, scan, takeWhile } from 'rxjs/operators';
import { paint } from './html-renderer';

const gamePipe = (x, y) => ({ x, y, checked: false });
const gameSize = 10;
const createPipes = y =>
  (random =>
    Array.from(Array(gameSize).keys())
      .map(e => gamePipe(e, y))
      .filter(e => e.x < random || e.x > random + 2))(
    Math.floor(Math.random() * Math.floor(gameSize))
  );

const gamePipes$ = interval(500).pipe(
  scan < any,
  any >
    (acc =>
      (acc.length < 2 ? [...acc, createPipes(gameSize)] : acc)
        .filter(c => c.some(e => e.y > 0))
        .map(cols => cols.map(e => gamePipe(e.x, e.y - 1))),
    [createPipes(gameSize / 2), createPipes(gameSize)])
);

const fly = xPos => (xPos > 0 ? (xPos -= 1) : xPos);
const fall = xPos => (xPos < gameSize - 1 ? (xPos += 1) : gameSize - 1);
const bird$ = merge(interval(300), fromEvent(document, 'keydown')).pipe(
  scan < any,
  any >
    ((xPos, curr) => (curr instanceof KeyboardEvent ? fly(xPos) : fall(xPos)),
    gameSize - 1)
);

const updateGame = (bird, pipes) =>
  (game => (
    pipes.forEach(col => col.forEach(v => (game[v.x][v.y] = 2))),
    (game[bird][0] = 1),
    game
  ))(
    Array(gameSize)
      .fill(0)
      .map(e => Array(gameSize).fill(0))
  );

const valueOnCollisionFor = pipes => ({
  when: predicate =>
    !pipes[0][0].checked && predicate ? ((pipes[0][0].checked = true), 1) : 0
});

combineLatest(bird$, gamePipes$)
  .pipe(
    scan < any,
    any >
      ((state, [bird, pipes]) => ({
        bird: bird,
        pipes: pipes,
        lives:
          state.lives -
          valueOnCollisionFor(pipes).when(
            pipes.some(c => c.some(c => c.y === 0 && c.x === bird))
          ),
        score:
          state.score + valueOnCollisionFor(pipes).when(pipes[0][0].y === 0)
      }),
      { lives: 3, score: 0, bird: 0, pipes: [] }),
    tap(state =>
      paint(updateGame(state.bird, state.pipes), state.lives, state.score)
    ),
    takeWhile(state => state.lives > 0)
  )
  .subscribe();
```

#### html-renderer.ts

```js
const createElem = col => {
  const elem = document.createElement('div');
  elem.classList.add('board');
  elem.style.display = 'inline-block';
  elem.style.marginLeft = '10px';
  elem.style.height = '6px';
  elem.style.width = '6px';
  elem.style['background-color'] =
    col === 0
      ? 'white'
      : col === 1
      ? 'cornflowerblue'
      : col === 2
      ? 'gray'
      : 'silver';
  elem.style['border-radius'] = '90%';
  return elem;
};

export const paint = (game: number[][], lives, score) => {
  document.body.innerHTML = `Lives: ${lives}, Score: ${score}`;

  game.forEach(row => {
    const rowContainer = document.createElement('div');
    row.forEach(col => rowContainer.appendChild(createElem(col)));
    document.body.appendChild(rowContainer);
  });
};
```

### Operators Used

- [combineLatest](../operators/combination/combinelatest.md)
- [fromEvent](../operators/creation/fromevent.md)
- [interval](../operators/creation/interval.md)
- [merge](../operators/combination/merge.md)
- [scan](../operators/transformation/scan.md)
- [takeWhile](../operators/filtering/takewhile.md)
- [tap](../operators/utility/do.md)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>lib2to3.fixes.fix_future — ArcherBashPYDocs 1.0.0. documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic|Roboto+Slab:400,700|Inconsolata:400,700&subset=latin,cyrillic' rel='stylesheet' type='text/css'>

    <link rel="stylesheet" href="../../../_static/css/theme.css" type="text/css" />

    <link rel="top" title="ArcherBashPYDocs 1.0.0. documentation" href="../../../index.html"/>
        <link rel="up" title="Module code" href="../../index.html"/>

           ArcherBashPYDocs

  <form id="rtd-search-form" class="wy-form" action="../../../search.html" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

        ArcherBashPYDocs

Docs »

Module code »

lib2to3.fixes.fix_future

Source code for lib2to3.fixes.fix_future

"""Remove __future__ imports

from __future__ import foo is replaced with an empty line.
"""
# Author: Christian Heimes

# Local imports
from .. import fixer_base
from ..fixer_util import BlankLine

[docs]class FixFuture(fixer_base.BaseFix):
    BM_compatible = True

    PATTERN = """import_from< 'from' module_name="__future__" 'import' any >"""

    # This should be run last -- some things check for the import
    run_order = 10

[docs]    def transform(self, node, results):
        new = BlankLine()
        new.prefix = node.prefix
        return new

        © Copyright 2015, Weldon Henson.

  Built with Sphinx using a theme provided by Read the Docs.


text:
@interface NSString (HtmlProcessing)

- (NSString *)prepareHTML;

- (NSString *)prepareHTMLAndRemoveTags:(NSArray *)removeTags;

@end


text:
(function ($) {
    "use strict";
    /*global jQuery, document, window*/
    $(document).ready(function () {
        SimpleCaptchaField.validate();
    });

}(jQuery));

var SimpleCaptchaField = function () {

    return {
        validate: function () {

            $("form." + SIMPLECAPTCHAFORM + " input[type='submit']").on('click', function (e) {
                e.preventDefault();

                var Captcha = $("input.SimpleCaptchaField").val();
                var url = "simple-validation/validate/" + Captcha;

                $form = $(this).closest('form');
                $.ajax({
                    url: url,
                    type: 'get',
                    success: function (results) {
                        $form.attr('data-recaptcha',results);
                        if (results === 'valid') {
                            $form.submit();
                            return true;
                        } else {
                            $('.input-captcha').append("
Correct captcha is required
");
                            return false;
                        }
                    },
                    error: function () {
                        alert('Sorry there has been an error');
                    }
                });

            });

        }
    }
}();


text:
package com.eas.client.form.published.widgets.model;

import java.text.ParseException;

import com.bearsoft.gwt.ui.widgets.FormattedObjectBox;
import com.bearsoft.gwt.ui.widgets.ObjectFormat;
import com.eas.client.Utils;
import com.eas.client.converters.DateValueConverter;
import com.eas.client.converters.DoubleValueConverter;
import com.eas.client.converters.StringValueConverter;
import com.eas.client.form.ControlsUtils;
import com.eas.client.form.events.ActionEvent;
import com.eas.client.form.events.ActionHandler;
import com.eas.client.form.events.HasActionHandlers;
import com.eas.client.form.published.HasEmptyText;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;

public class ModelFormattedField extends ModelDecoratorBox<Object> implements HasEmptyText, HasActionHandlers {

	protected String emptyText;

	public ModelFormattedField() {
		super(new FormattedObjectBox());
	}

	protected int actionHandlers;
	protected HandlerRegistration valueChangeReg;

	@Override
	public HandlerRegistration addActionHandler(ActionHandler handler) {
		final HandlerRegistration superReg = super.addHandler(handler, ActionEvent.getType());
		if (actionHandlers == 0) {
			valueChangeReg = addValueChangeHandler(new ValueChangeHandler<Object>() {

				@Override
				public void onValueChange(ValueChangeEvent<Object> event) {
					if (!settingValue)
						ActionEvent.fire(ModelFormattedField.this, ModelFormattedField.this);
				}

			});
		}
		actionHandlers++;
		return new HandlerRegistration() {
			@Override
			public void removeHandler() {
				superReg.removeHandler();
				actionHandlers--;
				if (actionHandlers == 0) {
					assert valueChangeReg != null : "Erroneous use of addActionHandler/removeHandler detected in ModelFormattedField";
					valueChangeReg.removeHandler();
					valueChangeReg = null;
				}
			}
		};
	}

	public String getFormat() {
		return ((FormattedObjectBox) decorated).getFormat();
	}

	public void setFormat(String aValue) throws ParseException {
		((FormattedObjectBox) decorated).setFormat(aValue);
	}

	public int getValueType() {
		return ((FormattedObjectBox) decorated).getValueType();
	}

	public void setValueType(int aValue) throws ParseException {
		((FormattedObjectBox) decorated).setValueType(aValue);
	}

	public String getText() {
		return ((FormattedObjectBox) decorated).getText();
	}

	public void setText(String aValue) {
		settingValue = true;
		try {
			((FormattedObjectBox) decorated).setText(aValue);
		} finally {
			settingValue = false;
		}
	}

	@Override
	public Object convert(Object aValue) {
		switch (getValueType()) {
		case ObjectFormat.CURRENCY:
		case ObjectFormat.NUMBER:
		case ObjectFormat.PERCENT:
			DoubleValueConverter dc = new DoubleValueConverter();
			return dc.convert(aValue);
		case ObjectFormat.DATE:
		case ObjectFormat.TIME:
			DateValueConverter dtc = new DateValueConverter();
			return dtc.convert(aValue);
		case ObjectFormat.MASK:
		case ObjectFormat.REGEXP:
		case ObjectFormat.TEXT:
			StringValueConverter sc = new StringValueConverter();
			return sc.convert(aValue);
		default:
			return aValue;
		}
	}

	public JavaScriptObject getOnParse() {
		return ((FormattedObjectBox)decorated).getOnParse();
	}

	public void setOnParse(JavaScriptObject aValue) {
		((FormattedObjectBox)decorated).setOnParse(aValue);
	}

	public JavaScriptObject getOnFormat() {
		return ((FormattedObjectBox)decorated).getOnFormat();
	}

	public void setOnFormat(JavaScriptObject aValue) {
		((FormattedObjectBox)decorated).setOnFormat(aValue);
	}

	@Override
	public String getEmptyText() {
		return emptyText;
	}

	@Override
	public void setEmptyText(String aValue) {
		emptyText = aValue;
		ControlsUtils.applyEmptyText(getElement(), emptyText);
	}

	@Override
	public void setPublished(JavaScriptObject aValue) {
		super.setPublished(aValue);
		if (published != null) {
			publish(this, published);
		}
	}

	private native static void publish(ModelFormattedField aWidget, JavaScriptObject aPublished)/*-{
		Object.defineProperty(aPublished, "emptyText", {
			get : function() {
				return aWidget.@com.eas.client.form.published.HasEmptyText::getEmptyText()();
			},
			set : function(aValue) {
				aWidget.@com.eas.client.form.published.HasEmptyText::setEmptyText(Ljava/lang/String;)(aValue != null ? '' + aValue : null);
			}
		});
		Object.defineProperty(aPublished, "value", {
			get : function() {
				return $wnd.P.boxAsJs(aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::getJsValue()());
			},
			set : function(aValue) {
				aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::setJsValue(Ljava/lang/Object;)($wnd.P.boxAsJava(aValue));
			}
		});
		Object.defineProperty(aPublished, "valueType", {
			get : function() {
				return $wnd.P.boxAsJs(aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::getValueType()());
			},
			set : function(aValue) {
				aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::setValueType(I)(aValue != null ? aValue : null);
			}
		});
		Object.defineProperty(aPublished, "text", {
			get : function() {
				return aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::getText()();
			},
			set : function(aValue) {
				aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::setText(Ljava/lang/String;)($wnd.P.boxAsJava(aValue));
			}
		});
		Object.defineProperty(aPublished, "format", {
			get : function() {
				return aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::getFormat()();
			},
			set : function(aValue) {
				aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::setFormat(Ljava/lang/String;)(aValue != null ? '' + aValue : null);
			}
		});
		Object.defineProperty(aPublished, "onFormat", {
			get : function() {
				return aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::getOnFormat()();
			},
			set : function(aValue) {
				aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::setOnFormat(Lcom/google/gwt/core/client/JavaScriptObject;)(aValue);
			}
		});
		Object.defineProperty(aPublished, "onParse", {
			get : function() {
				return aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::getOnParse()();
			},
			set : function(aValue) {
				aWidget.@com.eas.client.form.published.widgets.model.ModelFormattedField::setOnParse(Lcom/google/gwt/core/client/JavaScriptObject;)(aValue);
			}
		});
	}-*/;

	public Object getJsValue() {
		return Utils.toJs(getValue());
	}

	public void setJsValue(Object value) throws Exception {
		setValue(convert(Utils.toJava(value)), true);
	}

	@Override
	protected void clearValue() {
		super.clearValue();
		ActionEvent.fire(this, this);
	}

	@Override
    protected void setReadonly(boolean aValue) {
		((FormattedObjectBox)decorated).getElement().setPropertyBoolean("readOnly", aValue);
    }

	@Override
    protected boolean isReadonly() {
		return ((FormattedObjectBox)decorated).getElement().getPropertyBoolean("readOnly");
    }
}


text:
package com.evolveum.midpoint.web.component.assignment;

import java.util.ArrayList;
import java.util.List;

import javax.xml.namespace.QName;

import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper;
import com.evolveum.midpoint.web.component.objectdetails.AssignmentHolderTypeAssignmentsTabPanel;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator;
import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn;
import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;

import com.evolveum.midpoint.gui.api.component.BasePanel;
import com.evolveum.midpoint.gui.api.model.LoadableModel;
import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.web.component.AjaxButton;
import com.evolveum.midpoint.web.component.data.column.IconColumn;
import com.evolveum.midpoint.web.component.util.VisibleBehaviour;

/**
 * Created by honchar
 */
public class SwitchAssignmentTypePanel extends BasePanel<PrismContainerWrapper<AssignmentType>> {
    private static final long serialVersionUID = 1L;

    private static final String ID_ASSIGNMENT_TYPE_BUTTONS = "assignmentTypeButtons";
    private static final String ID_ALL_ASSIGNMENTS = "allAssignments";
    private static final String ID_ROLE_TYPE_ASSIGNMENTS = "roleTypeAssignments";
    private static final String ID_ORG_TYPE_ASSIGNMENTS = "orgTypeAssignments";
    private static final String ID_SERVICE_TYPE_ASSIGNMENTS = "serviceTypeAssignments";
    private static final String ID_RESOURCE_TYPE_ASSIGNMENTS = "resourceTypeAssignments";
    private static final String ID_POLICY_RULE_TYPE_ASSIGNMENTS = "policyRuleTypeAssignments";
    private static final String ID_ENTITLEMENT_ASSIGNMENTS = "entitlementAssignments";
    private static final String ID_FOCUS_MAPPING_ASSIGNMENTS = "focusMappingAssignments";
    private static final String ID_CONSENT_ASSIGNMENTS = "consentAssignments";
    private static final String ID_ASSIGNMENTS = "assignmentsPanel";
    private static final String ID_DATA_PROTECTION_ASSIGNMENTS = "dataProtectionAssignments";

    private String activeButtonId = ID_ALL_ASSIGNMENTS;

    public SwitchAssignmentTypePanel(String id, IModel<PrismContainerWrapper<AssignmentType>> assignmentContainerWrapperModel) {
        super(id, assignmentContainerWrapperModel);
    }

    @Override
    protected void onInitialize(){
        super.onInitialize();
        add(new VisibleBehaviour(() -> getModelObject() != null));
        initButtonsPanel();
        initAssignmentsPanel();

        setOutputMarkupId(true);
    }

    private void initButtonsPanel(){
        WebMarkupContainer buttonsContainer = new WebMarkupContainer(ID_ASSIGNMENT_TYPE_BUTTONS);
        buttonsContainer.setOutputMarkupId(true);
        buttonsContainer.add(new VisibleBehaviour(() -> getButtonsContainerVisibilityModel().getObject()));
        add(buttonsContainer);

        AjaxButton allAssignmentsButton = new AjaxButton(ID_ALL_ASSIGNMENTS, createStringResource("AssignmentPanel.allLabel")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                AssignmentPanel assignmentPanel =
                        new AssignmentPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()) {
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected boolean isNewObjectButtonVisible(PrismObject focusObject){
                                return !isReadonly() && super.isNewObjectButtonVisible(focusObject);
                            }
                        };
                assignmentPanel.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, assignmentPanel, ID_ALL_ASSIGNMENTS);
            }
        };
        allAssignmentsButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_ALL_ASSIGNMENTS)));
        allAssignmentsButton.setOutputMarkupId(true);
        allAssignmentsButton.setOutputMarkupPlaceholderTag(true);
        buttonsContainer.add(allAssignmentsButton);

        AjaxButton roleTypeAssignmentsButton = new AjaxButton(ID_ROLE_TYPE_ASSIGNMENTS, createStringResource("ObjectType.RoleType")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                AbstractRoleAssignmentPanel assignmentPanel =
                        new AbstractRoleAssignmentPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()) {
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected QName getAssignmentType() {
                                return RoleType.COMPLEX_TYPE;
                            }

                            @Override
                            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected boolean isNewObjectButtonVisible(PrismObject focusObject){
                                return !isReadonly() && super.isNewObjectButtonVisible(focusObject);
                            }
                        };
                assignmentPanel.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, assignmentPanel, ID_ROLE_TYPE_ASSIGNMENTS);
            }
        };
        roleTypeAssignmentsButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_ROLE_TYPE_ASSIGNMENTS)));
        roleTypeAssignmentsButton.setOutputMarkupId(true);
        buttonsContainer.add(roleTypeAssignmentsButton);

        AjaxButton orgTypeAssignmentsButton = new AjaxButton(ID_ORG_TYPE_ASSIGNMENTS, createStringResource("ObjectType.OrgType")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                AbstractRoleAssignmentPanel assignmentPanel =
                        new AbstractRoleAssignmentPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()) {
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected QName getAssignmentType() {
                                return OrgType.COMPLEX_TYPE;
                            }

                            @Override
                            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected boolean isNewObjectButtonVisible(PrismObject focusObject){
                                return !isReadonly() && super.isNewObjectButtonVisible(focusObject);
                            }
                        };
                assignmentPanel.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, assignmentPanel, ID_ORG_TYPE_ASSIGNMENTS);
            }
        };
        orgTypeAssignmentsButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_ORG_TYPE_ASSIGNMENTS)));
        orgTypeAssignmentsButton.setOutputMarkupId(true);
        buttonsContainer.add(orgTypeAssignmentsButton);

        AjaxButton serviceTypeAssignmentsButton = new AjaxButton(ID_SERVICE_TYPE_ASSIGNMENTS, createStringResource("ObjectType.ServiceType")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                AbstractRoleAssignmentPanel assignmentPanel =
                        new AbstractRoleAssignmentPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()) {
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected QName getAssignmentType() {
                                return ServiceType.COMPLEX_TYPE;
                            }

                            @Override
                            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected boolean isNewObjectButtonVisible(PrismObject focusObject){
                                return !isReadonly() && super.isNewObjectButtonVisible(focusObject);
                            }
                        };
                assignmentPanel.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, assignmentPanel, ID_SERVICE_TYPE_ASSIGNMENTS);

            }
        };
        serviceTypeAssignmentsButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_SERVICE_TYPE_ASSIGNMENTS)));
        serviceTypeAssignmentsButton.setOutputMarkupId(true);
        buttonsContainer.add(serviceTypeAssignmentsButton);

        AjaxButton resourceTypeAssignmentsButton = new AjaxButton(ID_RESOURCE_TYPE_ASSIGNMENTS, createStringResource("ObjectType.ResourceType")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                ConstructionAssignmentPanel constructionsPanel =
                        new ConstructionAssignmentPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()){
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected boolean isNewObjectButtonVisible(PrismObject focusObject){
                                return !isReadonly() && super.isNewObjectButtonVisible(focusObject);
                            }
                        };
                constructionsPanel.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, constructionsPanel, ID_RESOURCE_TYPE_ASSIGNMENTS);
            }
        };
        resourceTypeAssignmentsButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_RESOURCE_TYPE_ASSIGNMENTS)));
        resourceTypeAssignmentsButton.setOutputMarkupId(true);
        buttonsContainer.add(resourceTypeAssignmentsButton);

        AjaxButton policyRuleTypeAssignmentsButton = new AjaxButton(ID_POLICY_RULE_TYPE_ASSIGNMENTS, createStringResource("AssignmentType.policyRule")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                PolicyRulesPanel policyRulesPanel =
                        new PolicyRulesPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()){
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected boolean isNewObjectButtonVisible(PrismObject focusObject){
                                return !isReadonly() && super.isNewObjectButtonVisible(focusObject);
                            }
                        } ;
                policyRulesPanel.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, policyRulesPanel, ID_POLICY_RULE_TYPE_ASSIGNMENTS);

            }
        };
        policyRuleTypeAssignmentsButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_POLICY_RULE_TYPE_ASSIGNMENTS)));
        policyRuleTypeAssignmentsButton.setOutputMarkupId(true);

        policyRuleTypeAssignmentsButton.add(new VisibleBehaviour(()  -> isAssignmentPanelVisible()));

        buttonsContainer.add(policyRuleTypeAssignmentsButton);

        AjaxButton dataProtectionButton = new AjaxButton(ID_DATA_PROTECTION_ASSIGNMENTS, createStringResource("pageAdminFocus.dataProtection")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                GenericAbstractRoleAssignmentPanel dataProtectionPanel =
                        new GenericAbstractRoleAssignmentPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()) {
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected boolean isNewObjectButtonVisible(PrismObject focusObject){
                                return !isReadonly() && super.isNewObjectButtonVisible(focusObject);
                            }
                        };
                dataProtectionPanel.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, dataProtectionPanel, ID_DATA_PROTECTION_ASSIGNMENTS);

            }
        };
        dataProtectionButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_DATA_PROTECTION_ASSIGNMENTS)));
        dataProtectionButton.setOutputMarkupId(true);
        dataProtectionButton.add(new VisibleBehaviour(()  ->
                WebModelServiceUtils.isEnableExperimentalFeature(SwitchAssignmentTypePanel.this.getPageBase())));
        buttonsContainer.add(dataProtectionButton);

        AjaxButton entitlementAssignmentsButton = new AjaxButton(ID_ENTITLEMENT_ASSIGNMENTS, createStringResource("AbstractRoleMainPanel.inducedEntitlements")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                InducedEntitlementsPanel entitlementAssignments =
                        new InducedEntitlementsPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()) {
                            private static final long serialVersionUID = 1L;

                            @Override
                            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }

                            @Override
                            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
                                target.add(SwitchAssignmentTypePanel.this);
                            }
                        };
                entitlementAssignments.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, entitlementAssignments, ID_ENTITLEMENT_ASSIGNMENTS);

            }
        };
        entitlementAssignmentsButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_ENTITLEMENT_ASSIGNMENTS)));
        entitlementAssignmentsButton.setOutputMarkupId(true);

        entitlementAssignmentsButton.add(new VisibleBehaviour(()  -> isAssignmentPanelVisible() && isInducement()));
        buttonsContainer.add(entitlementAssignmentsButton);

        AjaxButton focusMappingAssignmentsButton = new AjaxButton(ID_FOCUS_MAPPING_ASSIGNMENTS, createStringResource("AssignmentType.focusMappings")) {
            private static final long serialVersionUID = 1L;

            @Override
            public void onClick(AjaxRequestTarget target) {
                AssignmentPanel assignmentPanel =
                        new AssignmentPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()) {
                            private static final long serialVersionUID = 1L;

                            //TODO may be we will need FocusMappingsAssignmentsPanel later
                            @Override
                            protected List<IColumn<PrismContainerValueWrapper<AssignmentType>, String>> initBasicColumns() {
                                List<IColumn<PrismContainerValueWrapper<AssignmentType>, String>> columns = new ArrayList<>();

                                columns.add(new IconColumn<PrismContainerValueWrapper<AssignmentType>>(Model.of("")) {

                                    private static final long serialVersionUID = 1L;

                                    @Override
                                    protected DisplayType getIconDisplayType(IModel<PrismContainerValueWrapper<AssignmentType>> rowModel) {
                                        return WebComponentUtil.createDisplayType(WebComponentUtil.createDefaultBlackIcon(
                                                AssignmentsUtil.getTargetType(rowModel.getObject().getRealValue())));
                                    }

                                });

                                columns.add(new AbstractColumn<PrismContainerValueWrapper<AssignmentType>, String>(createStringResource("PolicyRulesPanel.nameColumn")){
                                    private static final long serialVersionUID = 1L;

                                    @Override
                                    public void populateItem(Item<ICellPopulator<PrismContainerValueWrapper<AssignmentType>>> cellItem,
                                                                          String componentId, final IModel<PrismContainerValueWrapper<AssignmentType>> rowModel) {
                                        String name = AssignmentsUtil.getName(rowModel.getObject(), getParentPage());
                                        if (StringUtils.isBlank(name)) {
                                            name = createStringResource("AssignmentPanel.noName").getString();
                                        }
                                        cellItem.add(new Label(componentId, Model.of(name)));
                                    }
                                });
                                return columns;
                            }

                            @Override
                            protected ObjectQuery createObjectQuery(){
                                ObjectQuery query = super.createObjectQuery();
                                ObjectQuery focusMappingsQuery = SwitchAssignmentTypePanel.this.getPageBase().getPrismContext()
                                        .queryFor(AssignmentType.class)
                                        .exists(AssignmentType.F_FOCUS_MAPPINGS)
                                        .build();
                                query.addFilter(focusMappingsQuery.getFilter());
                                return query;
                            }

                            @Override
                            protected boolean isNewObjectButtonVisible(PrismObject focusObject){
                                return false;
                            }

                            @Override
                            protected QName getAssignmentType() {
                                return AssignmentType.F_FOCUS_MAPPINGS;
                            }

                        };
                assignmentPanel.setOutputMarkupId(true);
                switchAssignmentTypePerformed(target, assignmentPanel, ID_FOCUS_MAPPING_ASSIGNMENTS);
            }
        };
        focusMappingAssignmentsButton.add(AttributeAppender.append("class", getButtonStyleModel(ID_FOCUS_MAPPING_ASSIGNMENTS)));
        focusMappingAssignmentsButton.setOutputMarkupId(true);

        focusMappingAssignmentsButton.add(new VisibleBehaviour(()  -> isAssignmentPanelVisible()));
        buttonsContainer.add(focusMappingAssignmentsButton);

        //GDPR feature.. temporary disabled MID-4281
//        AjaxButton consentsButton = new AjaxButton(ID_CONSENT_ASSIGNMENTS, createStringResource("FocusType.consents")) {
//                            private static final long serialVersionUID = 1L;
//
//            @Override
//            public void onClick(AjaxRequestTarget target) {
//                GdprAssignmentPanel gdprAssignmentPanel =
//                        new GdprAssignmentPanel(ID_ASSIGNMENTS, SwitchAssignmentTypePanel.this.getModel()){
// private static final long serialVersionUID = 1L;
//
//        @Override
//        protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
//            target.add(SwitchAssignmentTypePanel.this);
//        }
//
//        @Override
//        protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target) {
//            target.add(SwitchAssignmentTypePanel.this);
//        }
// };
//                gdprAssignmentPanel.setOutputMarkupId(true);
//                SwitchAssignmentTypePanel.this.addOrReplace(gdprAssignmentPanel);
//                target.add(SwitchAssignmentTypePanel.this);
//            }
//        };
//        consentsButton.setOutputMarkupId(true);
//        buttonsContainer.add(consentsButton);
    }

    private boolean isAssignmentPanelVisible() {
        if (getModelObject() == null){
            return false;
        }
        PrismObjectWrapper<?> objectWrapper = getModelObject().findObjectWrapper();
        if (objectWrapper == null ) {
            return true;
        }
        return objectWrapper.getObject().asObjectable() instanceof AbstractRoleType;
    }

    private LoadableModel<Boolean> getButtonsContainerVisibilityModel(){
        return new LoadableModel<Boolean>() {
            @Override
            protected Boolean load() {
                return getAssignmentsPanel().getMultivalueContainerListPanel().isListPanelVisible();
            }
        };
    }

    private void switchAssignmentTypePerformed(AjaxRequestTarget target, AssignmentPanel assignmentsPanel, String buttonId){
        activeButtonId = buttonId;
        addOrReplace(assignmentsPanel);
        target.add(SwitchAssignmentTypePanel.this);
    }

    private LoadableModel<String> getButtonStyleModel(String buttonId){
        return new LoadableModel<String>() {
            @Override
            protected String load() {
                if (activeButtonId.equals(buttonId)){
                    return "btn btn-primary";
                } else {
                    return "btn btn-default";
                }
            }
        };
    }

    private void initAssignmentsPanel(){
        AssignmentPanel assignmentsPanel = new AssignmentPanel(ID_ASSIGNMENTS, getModel()){
            private static final long serialVersionUID = 1L;

            @Override
            protected void assignmentDetailsPerformed(AjaxRequestTarget target) {
                target.add(SwitchAssignmentTypePanel.this);
            }

            @Override
            protected void cancelAssignmentDetailsPerformed(AjaxRequestTarget target){
                target.add(SwitchAssignmentTypePanel.this);
            }
        };
        assignmentsPanel.setOutputMarkupId(true);
        add(assignmentsPanel);
    }

    public AssignmentPanel getAssignmentsPanel(){
        return (AssignmentPanel) get(ID_ASSIGNMENTS);
    }

    protected boolean isInducement(){
        return false;
    }

    protected boolean isReadonly(){
        return false;
    }
}


text:
package org.spongepowered.api.util.reflect;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.base.Optional;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Nullable;

/**
 * Finds properties by enumerating accessors and then later finding the
 * closest matching mutator.
 */
public class AccessorFirstStrategy implements PropertySearchStrategy {

    private static final Pattern ACCESSOR = Pattern.compile("^get([A-Z].*)");
    private static final Pattern ACCESSOR_BOOL = Pattern.compile("^is([A-Z].*)");
    private static final Pattern ACCESSOR_KEEPS = Pattern.compile("^(keeps[A-Z].*)");
    private static final Pattern MUTATOR = Pattern.compile("^set([A-Z].*)");

    /**
     * Find the corresponding mutator for an accessor method from a collection
     * of candidates.
     *
     * @param accessor The accessor
     * @param candidates The collection of candidates
     * @return A mutator, if found
     */
    @Nullable
    private static Method findMutator(Method accessor, Collection<Method> candidates) {
        Class<?> expectedType = accessor.getReturnType();

        for (Method method : candidates) {
            // TODO: Handle supertypes
            if (method.getParameterTypes()[0] == expectedType || expectedType == Optional.class) {
                return method;
            }
        }

        return null;
    }

    /**
     * Detect whether the given method is an accessor and if so, return the
     * property name.
     *
     * @param method The method
     * @return The property name, if the method is an accessor
     */
    @Nullable
    private static String getAccessorName(Method method) {
        Matcher m;

        if (Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0) {
            m = ACCESSOR.matcher(method.getName());
            if (m.matches() && !method.getReturnType().equals(void.class)) {
                return getPropertyName(m.group(1));
            }

            m = ACCESSOR_BOOL.matcher(method.getName());
            if (m.matches() && method.getReturnType().equals(boolean.class)) {
                return getPropertyName(m.group(1));
            }

            m = ACCESSOR_KEEPS.matcher(method.getName());
            if (m.matches() && method.getReturnType().equals(boolean.class)) {
                return getPropertyName(m.group(1));
            }
        }
        return null;
    }

    /**
     * Detect whether the given method is an mutator and if so, return the
     * property name.
     *
     * @param method The method
     * @return The property name, if the method is an mutator
     */
    @Nullable
    private static String getMutatorName(Method method) {
        Matcher m;

        if (Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 1 && method.getReturnType() == void.class) {
            m = MUTATOR.matcher(method.getName());
            if (m.matches()) {
                return getPropertyName(m.group(1));
            }
        }

        return null;
    }

    /**
     * Clean up the property name.
     *
     * @param name The name
     * @return The cleaned up name
     */
    private static String getPropertyName(String name) {
        return Character.toLowerCase(name.charAt(0)) + name.substring(1);
    }

    @Override
    public ImmutableSet<? extends Property> findProperties(final Class<?> type) {
        checkNotNull(type, "type");

        final Multimap<String, Method> accessors = HashMultimap.create();
        final Multimap<String, Method> mutators = HashMultimap.create();
        final Queue<Class<?>> queue = new NonNullUniqueQueue<Class<?>>();
        final Map<String, Method> accessorHierarchyBottoms = new HashMap<String, Method>();

        queue.add(type); // Start off with our target type

        Class<?> scannedType;
        while ((scannedType = queue.poll()) != null) {
            for (Method method : scannedType.getMethods()) {
                String name;

                Method leastSpecificMethod;
                if ((name = getAccessorName(method)) != null && ((leastSpecificMethod = accessorHierarchyBottoms.get(name)) == null
                                                                 || leastSpecificMethod.getReturnType() != method.getReturnType())) {
                    accessors.put(name, method);
                    if (accessorHierarchyBottoms.get(name) == null
                        || method.getReturnType().isAssignableFrom(accessorHierarchyBottoms.get(name).getReturnType())) {
                        accessorHierarchyBottoms.put(name, method);
                    }
                } else if ((name = getMutatorName(method)) != null) {
                    mutators.put(name, method);
                }
            }

            for (Class<?> implInterfaces : scannedType.getInterfaces()) {
                queue.offer(implInterfaces);
            }
            queue.offer(scannedType.getSuperclass());
        }

        final ImmutableSet.Builder<Property> result = ImmutableSet.builder();

        for (Map.Entry<String, Method> entry : accessors.entries()) {
            Method accessor = entry.getValue();
            @Nullable Method mutator = findMutator(entry.getValue(), mutators.get(entry.getKey()));
            result.add(new Property(entry.getKey(), accessor.getReturnType(), accessorHierarchyBottoms.get(entry.getKey()), accessor, mutator));
        }

        return result.build();
    }

}


text:
package com.haskforce.utils;

import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.util.Function;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

public class FileUtil {
    public static void updateFileText(final Project project, final PsiFile file, final Function<String, String> function) {
        final Application app = ApplicationManager.getApplication();
        app.saveAll();
        app.invokeLater(new Runnable() {
            @Override
            public void run() {
                final Document document = PsiDocumentManager.getInstance(project).getDocument(file);
                if (document == null) {
                    return;
                }
                CommandProcessor.getInstance().executeCommand(project, new Runnable() {
                    @Override
                    public void run() {
                        app.runWriteAction(new Runnable() {
                            @Override
                            public void run() {
                                document.setText(function.fun(document.getText()));
                            }
                        });
                    }
                }, "Update text for " + file.getName(), "", document);
            }
        });
    }

    /**
     * Returns an array of directory names as the relative path to `file` from the source root.
     * For example, given file "project/src/foo/bar/baz.hs" the result would be `{"foo", "bar"}`.
     */
    public static @Nullable List<String> getPathFromSourceRoot(Project project, VirtualFile file) {
        VirtualFile root = getSourceRoot(project, file);
        final String rootPath;
        if (root == null || (rootPath = root.getCanonicalPath()) == null) {
            return null;
        }
        ArrayList<String> result = new ArrayList<String>(0);
        VirtualFile directory = file;
        while (directory != null) {
            if (rootPath.equals(directory.getCanonicalPath())) {
                return result;
            }
            result.add(0, directory.getName());
            directory = directory.getParent();
        }
        return null;
    }

    public static @Nullable VirtualFile getSourceRoot(Project project, VirtualFile file) {
        if (project == null || file == null) {
            return null;
        }
        VirtualFile[] roots = ProjectRootManager.getInstance(project).getContentSourceRoots();
        for (VirtualFile root : roots) {
            final String rootPath = root.getCanonicalPath();
            if (rootPath == null) {
                continue;
            }
            VirtualFile directory = file;
            while (directory != null) {
                if (rootPath.equals(directory.getCanonicalPath())) {
                    return directory;
                }
                directory = directory.getParent();
            }
        }
        return null;
    }

    public static PsiDirectory findOrCreateSubdirectory(@NotNull PsiDirectory dir, @NotNull String name) {
        PsiDirectory result = dir.findSubdirectory(name);
        return result == null ? dir.createSubdirectory(name) : result;
    }
}


text:
/**
 * A simple test case that determines if elements, specified by a selector,
 * exist or not.
 *
 * The test fails for elements that are found and a case is created for each
 * one. The test passes is the selector finds no matching elements.
 */
'use strict';

quail.documentReadingDirection = function (quail, test, Case, options) {

  var selector = ['[lang="he"]', '[lang="ar"]'].join(', ');

  this.get('$scope').each(function () {
    var candidates = $(this).find(selector);
    if (!candidates.length) {
      test.add(quail.lib.Case({
        element: undefined,
        status: 'inapplicable'
      }));
    } else {
      candidates.each(function () {
        if (this.hasAttribute('dir') && (this.getAttribute('dir') || '') === 'rtl') {
          test.add(quail.lib.Case({
            element: this,
            status: 'passed'
          }));
        } else {
          test.add(quail.lib.Case({
            element: this,
            status: 'failed'
          }));
        }
      });
    }
  });
};


text:
test_number=02
description="expression using indexes"

infile="$test_dir/imps_clks.log"
outfile="$test_dir/test_$test_number.actual"
expected="$test_dir/test_$test_number.expected"

$bin -p -d 'þ' -e 'sprintf "%.3f", [2] / [3] * 100' \
     -b 'N/A' $infile > "$outfile"

if [ $? -ne 0 ] ||
   [ "`diff -q $outfile $expected`" ]; then
  test_status $test_number 1 "$description" FAIL
else
  test_status $test_number 1 "$description" PASS
  rm "$outfile"
fi


text:
using Domain.Interfaces;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Repository
{
    public class Repository<T> : IRepository<T> where T : class
    {
        protected readonly DbContext Context;

        public Repository(DbContext context)
        {
            Context = context;
        }

        public void Excluir(int id)
        {
            var entity = this.ObterPorId(id);
            Context.Set<T>().Remove(entity);
        }

        public void Excluir(T Entity)
        {
            Context.Set<T>().Remove(Entity);
        }

        public void Inserir(T Entity)
        {
            Context.Set<T>().Add(Entity);
        }

        public T ObterPorId(int? id)
        {
            return Context.Set<T>().Find(id);
        }

        public IEnumerable<T> ObterTodos()
        {
            return Context.Set<T>().ToList();
        }

        public IEnumerable<T> ObterTodos(Func<T, bool> predicate)
        {
            return Context.Set<T>().Where(predicate).ToList();
        }
    }
}


text:
package org.togglz.spring.boot.autoconfigure;

import org.togglz.core.repository.property.PropertySource;

import java.util.*;

/**
 * {@link PropertySource} implementation for use with {@link Properties}.
 *
 * @author Marcel Overdijk
 */
public class PropertiesPropertySource implements PropertySource {

    private Properties values = new Properties();

    public PropertiesPropertySource(Properties properties) {
        this.values = properties;
    }

    @Override
    public void reloadIfUpdated() {
        // do nothing
    }

    @Override
    public Set<String> getKeysStartingWith(String prefix) {
        Set<String> result = new HashSet<String>();
        Enumeration<?> keys = values.propertyNames();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement().toString();
            if (key.startsWith(prefix)) {
                result.add(key);
            }
        }
        return result;
    }

    @Override
    public String getValue(String key, String defaultValue) {
        return values.getProperty(key, defaultValue);
    }

    @Override
    public Editor getEditor() {
        return new PropertiesEditor(values);
    }

    private void setValues(Properties values) {
        this.values = values;
    }

    private class PropertiesEditor implements Editor {

        private Properties newValues;

        private PropertiesEditor(Properties values) {
            newValues = new Properties();
            newValues.putAll(values);
        }

        @Override
        public void setValue(String key, String value) {
            if (value != null) {
                newValues.setProperty(key, value);
            } else {
                newValues.remove(key);
            }
        }

        @Override
        public void removeKeysStartingWith(String prefix) {
            Iterator<Map.Entry<Object, Object>> iterator = newValues.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<Object, Object> entry = iterator.next();
                if (entry.getKey().toString().startsWith(prefix)) {
                    iterator.remove();
                }
            }
        }

        @Override
        public void commit() {
            setValues(newValues);
        }
    }
}


text:
CREATE TABLE tender_product (
  id          INTEGER          -- ID тендера
, product_id  INTEGER          -- ID позиции
, amount      NUMERIC NOT NULL -- количество
, start_price NUMERIC NOT NULL -- начальная цена
, bid_step    NUMERIC NOT NULL -- шаг цены
, CONSTRAINT  tender_product_pkey PRIMARY KEY (id, product_id)
);

-- ----------------------------------------------------------------------------
-- bid - ставки участников тендера
CREATE TABLE bid (
  id         INTEGER                     -- ID ставки
, tender_id  INTEGER                     -- ID тендера
, product_id INTEGER                     -- ID позиции
, amount     NUMERIC NOT NULL            -- количество
, price      NUMERIC NOT NULL            -- цена
, is_winner  BOOL NOT NULL DEFAULT FALSE -- ставка победила
, win_amount NUMERIC                     -- объем победы, если отличается от объема ставки
, CONSTRAINT bid_pkey PRIMARY KEY (id, product_id)
, CONSTRAINT bif_fkey_tender_product FOREIGN KEY (tender_id, product_id) REFERENCES tender_product
);


text:
package ga

import (
	"bytes"
	"fmt"
	"net/http"
	"net/url"
	"regexp"
)

var trackingIDMatcher = regexp.MustCompile(`^UA-\d+-\d+$`)

func NewClient(trackingID string) (*Client, error) {
	if !trackingIDMatcher.MatchString(trackingID) {
		return nil, fmt.Errorf("Invalid Tracking ID: %s", trackingID)
	}
	return &Client{
		UseTLS:             true,
		protocolVersion:    "1",
		protocolVersionSet: true,
		trackingID:         trackingID,
		clientID:           "go-ga",
		clientIDSet:        true,
	}, nil
}

type hitType interface {
	addFields(url.Values) error
}

func (c *Client) Send(h hitType) error {

	cpy := c.Copy()

	v := url.Values{}

	cpy.setType(h)

	err := cpy.addFields(v)
	if err != nil {
		return err
	}

	err = h.addFields(v)
	if err != nil {
		return err
	}

	url := ""
	if cpy.UseTLS {
		url = "http://www.google-analytics.com/collect"
	} else {
		url = "https://ssl.google-analytics.com/collect"
	}

	str := v.Encode()
	buf := bytes.NewBufferString(str)

	resp, err := http.Post(url, "application/x-www-form-urlencoded", buf)
	if err != nil {
		return err
	}

	if resp.StatusCode/100 != 2 {
		return fmt.Errorf("Rejected by Google with code %d", resp.StatusCode)
	}

	// fmt.Printf("POST %s => %d\n", str, resp.StatusCode)

	return nil
}


text:
    Id
    Name
    Description
    Actions

  {% for security_group in security_groups %}

    {{ security_group.id }}
    {{ security_group.name }}
    {{ security_group.description }}

Edit Rules

        {% if security_group.name != 'default' %}

{% include "user/security_group_delete_form.html" with form=delete_form %}

        {% endif %}

  {% endfor %}


text:
describe("Animation", function() {

  var widget, nativeBridge;

  function animationId() {
    return nativeBridge.calls({op: "create", type: "tabris.Animation"}).pop().id;
  }

  function createOp() {
    return nativeBridge.calls({op: "create", type: "tabris.Animation"}).pop().properties;
  }

  beforeEach(function() {
    nativeBridge = new NativeBridgeSpy();
    tabris._reset();
    tabris._init(nativeBridge);
    tabris.registerWidget("TestType", {_properties: {foo: "any"}});
    widget = tabris.create("TestType");
  });

  afterEach(function() {
    delete tabris.TestType;
  });

  describe("widget.animate", function() {

    it("creates native animation with target", function() {
      widget.animate({}, {});
      expect(createOp().target).toBe(widget.cid);
    });

    it("disposes Animation object on widget dispose", function() {
      widget.animate({}, {});
      var animation = tabris(animationId());

      widget.dispose();

      expect(animation.isDisposed()).toBe(true);
    });

    it("does not keep references to Animation object after completion", function() {
      widget.animate({}, {});
      var animation = tabris(animationId());
      tabris._notify(animation.cid, "Completion", {});
      spyOn(animation, "dispose");

      widget.dispose();

      expect(animation.dispose).not.toHaveBeenCalled();
    });

    it("sets animated properties on animation", function() {
      widget.animate({opacity: 0.4, transform: {rotation: 0.5}}, {});
      var expected = {
        opacity: 0.4,
        transform: {rotation: 0.5, scaleX: 1, scaleY: 1, translationX: 0, translationY: 0}
      };
      expect(createOp().properties).toEqual(expected);
    });

    it("caches animated properties in widget", function() {
      widget.animate({opacity: 0.4, transform: {rotation: 0.5}}, {});
      expect(widget.get("opacity")).toBe(0.4);
      expect(widget.get("transform")).toEqual({
        rotation: 0.5,
        scaleX: 1,
        scaleY: 1,
        translationX: 0,
        translationY: 0
      });
    });

    it("caches only valid properties in widget", function() {
      widget.set("foo", 1);
      widget.animate({opacity: 0.4, transform: {foo: 0.5}, foo: 2}, {});
      expect(widget.get("foo")).toBe(1);
      expect(widget.get("opacity")).toBe(0.4);
      expect(widget.get("transform")).toEqual({
        rotation: 0,
        scaleX: 1,
        scaleY: 1,
        translationX: 0,
        translationY: 0
      });
    });

    it("sets valid options only", function() {
      widget.animate({}, {
        delay: 10, duration: 100, repeat: 1, reverse: true, easing: "ease-out", foo: "bar"
      });
      expect(createOp()).toEqual({
        delay: 10,
        duration: 100,
        repeat: 1,
        reverse: true,
        easing: "ease-out",
        target: widget.cid,
        properties: {}
      });
    });

    it("warns against invalid options", function() {
      spyOn(console, "warn");

      widget.animate({}, {foo: "bar"});

      expect(console.warn).toHaveBeenCalledWith("TestType: Ignored invalid animation option \"foo\"");
    });

    it("warns against invalid properties", function() {
      spyOn(console, "warn");

      widget.animate({background: "#00ff00", opacity: 0}, {});

      expect(console.warn).toHaveBeenCalledWith("TestType: Ignored invalid animation property \"background\"");
      expect(createOp().properties).toEqual({opacity: 0});
    });

    it("warns against invalid property values", function() {
      spyOn(console, "warn");

      widget.animate({opacity: 0, transform: {foo: "bar"}}, {});

      expect(console.warn).toHaveBeenCalledWith("TestType: Ignored invalid animation property value for \"transform\"");
      expect(createOp().properties).toEqual({opacity: 0});
    });

    it("issues listen call for Start", function() {
      widget.animate({}, {});
      expect(nativeBridge.calls({
        op: "listen",
        id: animationId(),
        event: "Start",
        listen: true
      }).length).toBe(1);
    });

    it("issues listen call for Completion", function() {
      widget.animate({}, {});
      expect(nativeBridge.calls({
        op: "listen",
        id: animationId(),
        event: "Completion",
        listen: true
      }).length).toBe(1);
    });

    it("starts animation", function() {
      widget.animate({}, {});
      expect(nativeBridge.calls({op: "call", id: animationId(), method: "start"}).length).toBe(1);
    });

    it("disposes animation on completion", function() {
      widget.animate({}, {});
      expect(nativeBridge.calls({op: "destroy", id: animationId()}).length).toBe(0);

      tabris._notify(animationId(), "Completion", {});
      expect(nativeBridge.calls({op: "destroy", id: animationId()}).length).toBe(1);
    });

    it("returns nothing", function() {
      expect(widget.animate({}, {})).not.toBeDefined();
    });

  });

  describe("events", function() {

    beforeEach(function() {
      widget.animate({}, {duration: 123, name: "bar"});
    });

    it("animationstart", function() {
      var listener = jasmine.createSpy();
      widget.on("animationstart", listener);

      tabris._notify(animationId(), "Start", {});

      expect(listener).toHaveBeenCalled();
      expect(listener.calls.argsFor(0)[0]).toBe(widget);
      expect(listener.calls.argsFor(0)[1]).toEqual({duration: 123, name: "bar"});
    });

    it("animationend", function() {
      var listener = jasmine.createSpy();
      widget.on("animationend", listener);

      tabris._notify(animationId(), "Completion", {});

      expect(listener).toHaveBeenCalled();
      expect(listener.calls.argsFor(0)[0]).toBe(widget);
      expect(listener.calls.argsFor(0)[1]).toEqual({duration: 123, name: "bar"});
    });

  });

});


text:
<?php
return array (
  'Manage users' => 'Správa uživatelů',
  'Add new user' => 'Přidat nového uživatele',
  'Admin' => 'Administrátor',
  'All' => 'Vše',
  'Delete user account' => 'Smazat uživatelský účet',
  'Edit user account' => 'Upravit uživatelský účet',
  'Email' => 'E-mailová adresa',
  'In this overview you can find every registered user and manage him.' => 'V tomto přehledu naleznete a můžete spravovat libovolného uživatele.',
  'No' => 'Ne',
  'Overview' => 'Přehled',
  'Search for email' => 'Hledat e-mailovou adresu',
  'Search for username' => 'Hledat uživatelské jméno',
  'Username' => 'Uživatelské jméno',
  'View user profile' => 'Zobrazit profil uživatele',
  'Yes' => 'Ano',
);


text:
BSLS_IDENT("$Id: $")

//@PURPOSE: Provide a semaphore class optimizing 'post'.
//
//@CLASSES:
//  bslmt::FastPostSemaphore: semaphore class optimizing 'post'
//
//@SEE_ALSO: bslmt_semaphore
//
//@DESCRIPTION: This component defines a semaphore, 'bslmt::FastPostSemaphore',
// with the 'post' operation being optimized at the potential expense of other
// operations.  In particular, 'bslmt::FastPostSemaphore' is an efficient
// synchronization primitive that enables sharing of a counted number of
// resources.  'bslmt::FastPostSemaphore' supports the methods 'timedWait',
// 'enable', and 'disable' in addition to the standard semaphore methods.
//
// Commonly, during periods of time when the protected resource is scarce (the
// semaphore count is frequently zero) and threads are frequently blocked on
// wait methods, pessimizing the performance of the threads that block will
// have little effect on overall performance.  In this case, optimizing 'post'
// *may* be a performance improvement.  Note that when the resource is
// plentiful, there are no blocked threads and we expect the differences
// between semaphore implementations to be trivial.
//
///Supported Clock-Types
///---------------------
// The component 'bsls::SystemClockType' supplies the enumeration indicating
// the system clock on which timeouts supplied to other methods should be
// based.  If the clock type indicated at construction is
// 'bsls::SystemClockType::e_REALTIME', the timeout should be expressed as an
// absolute offset since 00:00:00 UTC, January 1, 1970 (which matches the epoch
// used in 'bsls::SystemTime::now(bsls::SystemClockType::e_REALTIME)'.  If the
// clock type indicated at construction is
// 'bsls::SystemClockType::e_MONOTONIC', the timeout should be expressed as an
// absolute offset since the epoch of this clock (which matches the epoch used
// in 'bsls::SystemTime::now(bsls::SystemClockType::e_MONOTONIC)'.
//
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: A Simple Queue
///- - - - - - - - - - - - -
// This example illustrates a very simple fixed-size queue where potential
// clients can push integers to a queue, and later retrieve the integer values
// from the queue in FIFO order.  Also, 'waitUntilEmpty' is implimented to
// depict the common usage of 'getDisabledState'.
//
// First, we define the 'IntQueue' class:
//..
//  class IntQueue {
//      // FIFO queue of integer values.
//
//      // DATA
//      bsl::vector<int>         d_data;            // queue values
//
//      bslmt::FastPostSemaphore d_pushSem;         // resource availability
//                                                  // for push
//
//      bslmt::FastPostSemaphore d_popSem;          // resource availability
//                                                  // for pop
//
//      bsls::AtomicUint         d_pushIdx;         // index to push to
//
//      bsls::AtomicUint         d_popIdx;          // index to pop from
//
//      mutable bslmt::Mutex     d_emptyMutex;      // blocking point for
//                                                  // 'waitUntilEmpty'
//
//      mutable bslmt::Condition d_emptyCondition;  // condition variable for
//                                                  // 'waitUntilEmpty'
//
//      // NOT IMPLEMENTED
//      IntQueue(const IntQueue&);
//      IntQueue& operator=(const IntQueue&);
//
//    public:
//      // PUBLIC CONSTANTS
//      enum ReturnValue {
//          e_SUCCESS  = bslmt::FastPostSemaphore::e_SUCCESS,   // indicates
//                                                              // success
//
//          e_DISABLED = bslmt::FastPostSemaphore::e_DISABLED,  // indicates
//                                                              // queue is
//                                                              // disabled
//
//          e_FAILED = bslmt::FastPostSemaphore::e_FAILED       // indicates
//                                                              // failure
//      };
//
//      // CREATORS
//      explicit
//      IntQueue(bsl::size_t capacity, bslma::Allocator *basicAllocator = 0);
//          // Create an 'IntQueue' object with the specified 'capacity'.
//          // Optionally specify a 'basicAllocator' used to supply memory.  If
//          // 'basicAllocator' is 0, the currently installed default allocator
//          // is used.
//
//      //! ~IntQueue() = default;
//          // Destroy this object.
//
//      // MANIPULATORS
//      void disablePopFront();
//          // Disable dequeueing from this queue.  All subsequent invocations
//          // of 'popFront' and 'waitUntilEmpty' will fail immediately.  All
//          // blocked invocations of 'popFront' and 'waitUntilEmpty' will fail
//          // immediately.  If the queue is already dequeue disabled, this
//          // method has no effect.
//
//      void enablePopFront();
//          // Enable dequeuing.  If the queue is not dequeue disabled, this
//          // method has no effect.
//
//      int popFront(int *value);
//          // Remove the element from the front of this queue and load that
//          // element into the specified 'value'.  If the queue is empty,
//          // block until it is not empty.  Return 0 on success, and a nonzero
//          // value if the queue is disabled.
//
//      int pushBack(int value);
//          // Append the specified 'value' to the back of this queue, blocking
//          // until either space is available - if necessary - or the queue is
//          // disabled.  Return 0 on success, and a nonzero value if the queue
//          // is disabled.
//
//      // ACCESSORS
//      int waitUntilEmpty() const;
//          // Block until all the elements in this queue are removed.  Return
//          // 0 on success, and a non-zero value if the queue is not empty and
//          // 'isPopFrontDisabled()'.  A blocked thread waiting for the queue
//          // to empty will return a non-zero value if 'disablePopFront' is
//          // invoked.
//  };
//..
// Next, implement the queue:
//..
//  // CREATORS
//  IntQueue::IntQueue(bsl::size_t capacity, bslma::Allocator *basicAllocator)
//  : d_data(capacity, basicAllocator)
//  , d_pushSem(static_cast<int>(capacity))
//  , d_popSem(0)
//  , d_pushIdx(0)
//  , d_popIdx(0)
//  , d_emptyMutex()
//  , d_emptyCondition()
//  {
//  }
//
//  // MANIPULATORS
//  void IntQueue::disablePopFront()
//  {
//      d_popSem.disable();
//  }
//
//  void IntQueue::enablePopFront()
//  {
//      d_popSem.enable();
//  }
//
//  int IntQueue::popFront(int *value)
//  {
//      // wait for available element
//
//      int rv = d_popSem.wait();
//      if (0 != rv) {
//          return rv;                                                // RETURN
//      }
//
//      *value = d_data[d_popIdx++ % d_data.size()];
//
//      d_pushSem.post();  // signal additional empty element
//
//      if (0 == d_popSem.getValue()) {
//          {
//              bslmt::LockGuard<bslmt::Mutex> guard(&d_emptyMutex);
//          }
//          d_emptyCondition.broadcast();
//      }
//
//      return 0;
//  }
//
//  int IntQueue::pushBack(int value)
//  {
//      // wait for an empty element
//
//      int rv = d_pushSem.wait();
//      if (0 != rv) {
//          return rv;                                                // RETURN
//      }
//
//      d_data[d_pushIdx++ % d_data.size()] = value;
//
//      d_popSem.post();  // signal additional available element
//
//      return 0;
//  }
//
//  // ACCESSORS
//  int IntQueue::waitUntilEmpty() const
//  {
//      bslmt::LockGuard<bslmt::Mutex> guard(&d_emptyMutex);
//
//      int state = d_popSem.getDisabledState();
//
//      while (d_popSem.getValue()) {
//          if (state != d_popSem.getDisabledState()) {
//              return e_DISABLED;                                    // RETURN
//          }
//          d_emptyCondition.wait(&d_emptyMutex);
//      }
//
//      return e_SUCCESS;
//  }
//..
// Then, declare an instance of 'IntQueue':
//..
//  IntQueue queue(10);
//..
// Next, populate some values:
//..
//  assert(0 == queue.pushBack(5));
//  assert(0 == queue.pushBack(7));
//  assert(0 == queue.pushBack(3));
//..
// Now, pop and verify the values:
//..
//  int value;
//
//  assert(0 == queue.popFront(&value));
//  assert(5 == value);
//
//  assert(0 == queue.popFront(&value));
//  assert(7 == value);
//
//  assert(0 == queue.popFront(&value));
//  assert(3 == value);
//..
// Finally, use 'waitUntilEmpty' to verify the queue is empty:
//..
//  assert(IntQueue::e_SUCCESS == queue.waitUntilEmpty());
//..

#include <bslscm_version.h>

#include <bslmt_condition.h>
#include <bslmt_fastpostsemaphoreimpl.h>
#include <bslmt_lockguard.h>
#include <bslmt_mutex.h>
#include <bslmt_threadutil.h>

#include <bsls_atomicoperations.h>
#include <bsls_systemclocktype.h>
#include <bsls_timeinterval.h>
#include <bsls_types.h>

namespace BloombergLP {
namespace bslmt {

                         // =======================
                         // class FastPostSemaphore
                         // =======================

class FastPostSemaphore {
    // This class implements a semaphore type, optimized for 'post', for thread
    // synchronization.

    // PRIVATE TYPES
    typedef FastPostSemaphoreImpl<bsls::AtomicOperations,
                                  bslmt::Mutex,
                                  bslmt::Condition,
                                  bslmt::ThreadUtil> Impl;

    // DATA
    Impl d_impl;

    // NOT IMPLEMENTED
    FastPostSemaphore(const FastPostSemaphore&);
    FastPostSemaphore& operator=(const FastPostSemaphore&);

  public:
    // PUBLIC CONSTANTS
    enum ReturnValue {
        e_SUCCESS     = Impl::e_SUCCESS,      // indicates success

        e_DISABLED    = Impl::e_DISABLED,     // indicates semaphore is
                                              // disabled

        e_TIMED_OUT   = Impl::e_TIMED_OUT,    // indicates operation timed out

        e_WOULD_BLOCK = Impl::e_WOULD_BLOCK,  // indicates operation would
                                              // block ('tryWait')

        e_FAILED      = Impl::e_FAILED        // indicates failure reported
                                              // from 'd_condition'
    };

    // CREATORS
    explicit
    FastPostSemaphore(
    bsls::SystemClockType::Enum clockType = bsls::SystemClockType::e_REALTIME);
        // Create a 'FastPostSemaphore' object initially having a count of 0.
        // Optionally specify a 'clockType' indicating the type of the system
        // clock against which the 'bsls::TimeInterval' timeouts passed to the
        // 'timedWait' method are to be interpreted.  If 'clockType' is not
        // specified then the realtime system clock is used.

    explicit
    FastPostSemaphore(
    int                         count,
    bsls::SystemClockType::Enum clockType = bsls::SystemClockType::e_REALTIME);
        // Create a 'FastPostSemaphore' object initially having the specified
        // 'count'.  Optionally specify a 'clockType' indicating the type of
        // the system clock against which the 'bsls::TimeInterval' timeouts
        // passed to the 'timedWait' method are to be interpreted.  If
        // 'clockType' is not specified then the realtime system clock is used.

    //! ~FastPostSemaphore() = default;
        // Destroy this object.

    // MANIPULATORS
    void enable();
        // Enable waiting on this semaphore.  If the semaphore is not disabled,
        // this call has no effect.

    void disable();
        // Disable waiting on this semaphore.  All subsequent invocations of
        // 'wait', 'tryWait', and 'timedWait' will fail immediately.  All
        // blocked invocations of 'wait' and 'timedWait' will fail immediately.
        // If the semaphore is already disabled, this method will have no
        // effect.

    void post();
        // Atomically increment the count of this semaphore.

    void post(int value);
        // Atomically increase the count of this semaphore by the specified
        // 'value'.  The behavior is undefined unless 'value > 0'.

    int take(int maximumToTake);
        // If the count of this semaphore is positive, reduce the count by the
        // lesser of the count and the specified 'maximumToTake' and return the
        // magnitude of the change to the count.  Otherwise, do nothing and
        // return 0.

    int takeAll();
        // If the count of this semaphore is positive, reduce the count to 0
        // and return the original value of the count.  Otherwise, do nothing
        // and return 0.

    int timedWait(const bsls::TimeInterval& timeout);
        // If this semaphore is initially disabled, or becomes disabled while
        // blocking, return 'e_DISABLED' with no effect on the count.
        // Otherwise, block until the count of this semaphore is a positive
        // value or the specified 'timeout' expires.  If the count of this
        // semaphore is a positive value, return 0 and atomically decrement the
        // count.  If the 'timeout' expires, return 'e_TIMEDOUT' with no effect
        // on the count.  Return 'e_FAILED' if an error occurs.  The 'timeout'
        // is an absolute time represented as an interval from some epoch,
        // which is determined by the clock indicated at construction (see
        // {Supported Clock-Types} in the component documentation).

    int tryWait();
        // If this semaphore is initially disabled, return 'e_DISABLED' with no
        // effect on the count.  Otherwise, if the count of this semaphore is a
        // positive value, return 0 and atomically decrement the count.  If
        // this semaphore is not disabled and the count of this semaphore is
        // not a positive value, return 'e_WOULD_BLOCK' with no effect on the
        // count.

    int wait();
        // If this semaphore is initially disabled, or becomes disabled while
        // blocking, return 'e_DISABLED' with no effect on the count.
        // Otherwise, block until the count of this semaphore is a positive
        // value, return 0 and atomically decrement the count.  Return
        // 'e_FAILED' if an error occurs.

    // ACCESSORS
    int getDisabledState() const;
        // Return an odd value if this semaphore is wait disabled, and an even
        // value otherwise.  The returned value can be used to detect a rapid
        // short sequence of 'disable' and 'enable' invocations by comparing
        // the value returned by 'getDisabledState' before and after the
        // sequence.  For example, for any initial state of a semaphore
        // instance 'obj':
        //..
        //  int state = obj.getDisabledState();
        //  obj.disable();
        //  obj.enable();
        //  ASSERT(state != obj.getDisabledState());
        //..
        // This functionality is useful in higher-level components to determine
        // if this semaphore was disabled during an operation.

    int getValue() const;
        // Return the current value ('count > 0 ? count : 0') of this
        // semaphore.

    bool isDisabled() const;
        // Return 'true' if this semaphore is wait disabled, and 'false'
        // otherwise.  Note that the semaphore is created in the "wait enabled"
        // state.
};

// ============================================================================
//                             INLINE DEFINITIONS
// ============================================================================

                         // -----------------------
                         // class FastPostSemaphore
                         // -----------------------

// CREATORS
inline
FastPostSemaphore::FastPostSemaphore(bsls::SystemClockType::Enum clockType)
: d_impl(clockType)
{
}

inline
FastPostSemaphore::FastPostSemaphore(int                         count,
                                     bsls::SystemClockType::Enum clockType)
: d_impl(count, clockType)
{
}

// MANIPULATORS
inline
void FastPostSemaphore::disable()
{
    d_impl.disable();
}

inline
void FastPostSemaphore::enable()
{
    d_impl.enable();
}

inline
void FastPostSemaphore::post()
{
    d_impl.post();
}

inline
void FastPostSemaphore::post(int value)
{
    d_impl.post(value);
}

inline
int FastPostSemaphore::take(int maximumToTake)
{
    return d_impl.take(maximumToTake);
}

inline
int FastPostSemaphore::takeAll()
{
    return d_impl.takeAll();
}

inline
int FastPostSemaphore::timedWait(const bsls::TimeInterval& timeout)
{
    return d_impl.timedWait(timeout);
}

inline
int FastPostSemaphore::tryWait()
{
    return d_impl.tryWait();
}

inline
int FastPostSemaphore::wait()
{
    return d_impl.wait();
}

// ACCESSORS
inline
int FastPostSemaphore::getDisabledState() const
{
    return d_impl.getDisabledState();
}

inline
int FastPostSemaphore::getValue() const
{
    return d_impl.getValue();
}

inline
bool FastPostSemaphore::isDisabled() const
{
    return d_impl.isDisabled();
}

}  // close package namespace
}  // close enterprise namespace

#endif

// ----------------------------------------------------------------------------
// Copyright 2019 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
layout: post
title: "minute-media-video-instream-multiple-ad-providers-stg"
excerpt: "minute-media-video-instream-multiple-ad-providers-stg"
categories: articles
tags: [sample-post, video]
comments: true
share: true
---


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="butler">

        <roleset framnet="" id="butler.01" name="act as a butler for someone" vncls="29.8">
            <roles>
                <role descr="Butler" f="" n="0">
                    <vnrole vncls="29.8" vntheta="agent"/>
                </role>
                <role descr="Lucky person, org, event, with butler's services" f="" n="1">
                    <vnrole vncls="29.8" vntheta="theme"/>
                </role>
                <note/>
            </roles>
            <example name="Short and to the point: all args" src="web usage" type="">
                <text>He butlered for a gentleman.</text>
                <note/>
                <arg f="" n="0">He</arg>
                <rel f="">butlered</rel>
                <arg f="" n="1">for a gentleman</arg>
            </example>
            <note>Hand-corrected by Claire</note>
        </roleset>
        <note>Automatically created based on framefiles: model (29.8)</note>
    </predicate>
    <note/>
</frameset>


text:
<?php

namespace Cake\Utility\Crypto;

use LogicException;

/**
 * OpenSSL implementation of crypto features for Cake\Utility\Security
 *
 * OpenSSL should be favored over mcrypt as it is actively maintained and
 * more widely available.
 *
 * This class is not intended to be used directly and should only
 * be used in the context of Cake\Utility\Security.
 *
 * @internal
 */
class OpenSsl
{

    /**
     * Not implemented
     *
     * @param string $text Encrypted string to decrypt, normal string to encrypt
     * @param string $key Key to use as the encryption key for encrypted data.
     * @param string $operation Operation to perform, encrypt or decrypt
     * @throws \LogicException Rijndael compatibility does not exist with Openssl.
     * @return void
     */
    public static function rijndael($text, $key, $operation)
    {
        throw new LogicException('rijndael is not compatible with OpenSSL. Use mcrypt instead.');
    }

    /**
     * Encrypt a value using AES-256.
     *
     * *Caveat* You cannot properly encrypt/decrypt data with trailing null bytes.
     * Any trailing null bytes will be removed on decryption due to how PHP pads messages
     * with nulls prior to encryption.
     *
     * @param string $plain The value to encrypt.
     * @param string $key The 256 bit/32 byte key to use as a cipher key.
     * @param string|null $hmacSalt The salt to use for the HMAC process. Leave null to use Security.salt.
     * @return string Encrypted data.
     * @throws \InvalidArgumentException On invalid data or key.
     */
    public static function encrypt($plain, $key, $hmacSalt = null)
    {
        $method = 'AES-256-CBC';
        $ivSize = openssl_cipher_iv_length($method);

        $iv = openssl_random_pseudo_bytes($ivSize);

        return $iv . openssl_encrypt($plain, $method, $key, OPENSSL_RAW_DATA, $iv);
    }

    /**
     * Decrypt a value using AES-256.
     *
     * @param string $cipher The ciphertext to decrypt.
     * @param string $key The 256 bit/32 byte key to use as a cipher key.
     * @return string Decrypted data. Any trailing null bytes will be removed.
     * @throws \InvalidArgumentException On invalid data or key.
     */
    public static function decrypt($cipher, $key)
    {
        $method = 'AES-256-CBC';
        $ivSize = openssl_cipher_iv_length($method);

        $iv = mb_substr($cipher, 0, $ivSize, '8bit');

        $cipher = mb_substr($cipher, $ivSize, null, '8bit');

        return openssl_decrypt($cipher, $method, $key, OPENSSL_RAW_DATA, $iv);
    }
}


text:
FROM alpine:3.6

# add our user and group first to make sure their IDs get assigned consistently, regardless of whatever dependencies get added
RUN addgroup -S redis && adduser -S -G redis redis

# grab su-exec for easy step-down from root
RUN apk add --no-cache 'su-exec>=0.2'

ENV REDIS_VERSION 4.0.1
ENV REDIS_DOWNLOAD_URL http://download.redis.io/releases/redis-4.0.1.tar.gz
ENV REDIS_DOWNLOAD_SHA 2049cd6ae9167f258705081a6ef23bb80b7eff9ff3d0d7481e89510f27457591

# for redis-sentinel see: http://redis.io/topics/sentinel
RUN set -ex; \
\
apk add --no-cache --virtual .build-deps \
coreutils \
gcc \
linux-headers \
make \
musl-dev \
; \
\
wget -O redis.tar.gz "$REDIS_DOWNLOAD_URL"; \
echo "$REDIS_DOWNLOAD_SHA *redis.tar.gz" | sha256sum -c -; \
mkdir -p /usr/src/redis; \
tar -xzf redis.tar.gz -C /usr/src/redis --strip-components=1; \
rm redis.tar.gz; \
\
# disable Redis protected mode [1] as it is unnecessary in context of Docker
# (ports are not automatically exposed when running inside Docker, but rather explicitly by specifying -p / -P)
# [1]: https://github.com/antirez/redis/commit/edd4d555df57dc84265fdfb4ef59a4678832f6da
grep -q '^#define CONFIG_DEFAULT_PROTECTED_MODE 1$' /usr/src/redis/src/server.h; \
sed -ri 's!^(#define CONFIG_DEFAULT_PROTECTED_MODE) 1$!\1 0!' /usr/src/redis/src/server.h; \
grep -q '^#define CONFIG_DEFAULT_PROTECTED_MODE 0$' /usr/src/redis/src/server.h; \
# for future reference, we modify this directly in the source instead of just supplying a default configuration flag because apparently "if you specify any argument to redis-server, [it assumes] you are going to specify everything"
# see also https://github.com/docker-library/redis/issues/4#issuecomment-50780840
# (more exactly, this makes sure the default behavior of "save on SIGTERM" stays functional by default)
\
make -C /usr/src/redis -j "$(nproc)"; \
make -C /usr/src/redis install; \
\
rm -r /usr/src/redis; \
\
apk del .build-deps

RUN mkdir /data && chown redis:redis /data
VOLUME /data
WORKDIR /data

COPY docker-entrypoint.sh /usr/local/bin/
ENTRYPOINT ["docker-entrypoint.sh"]

EXPOSE 6379
CMD ["redis-server"]