text:
package sparklr.common;

import org.junit.Before;
import org.junit.Rule;
import org.junit.runner.RunWith;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.test.BeforeOAuth2Context;
import org.springframework.security.oauth2.client.test.OAuth2ContextSetup;
import org.springframework.security.oauth2.client.token.grant.implicit.ImplicitResourceDetails;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.client.token.grant.redirect.AbstractRedirectResourceDetails;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.InMemoryApprovalStore;
import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.sql.DataSource;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@IntegrationTest("server.port=0")
public abstract class AbstractIntegrationTests {

    @Value("${local.server.port}")
    private int port;

    private static String globalTokenPath;

    private static String globalAuthorizePath;

    @Rule
    public HttpTestUtils http = HttpTestUtils.standard();

    @Rule
    public OAuth2ContextSetup context = OAuth2ContextSetup.standard(http);

    @Autowired
    private ServerProperties server;

    @Autowired
    protected SecurityProperties security;

    @Autowired(required = false)
    private TokenStore tokenStore;

    @Autowired(required = false)
    private ApprovalStore approvalStore;

    @Autowired(required = false)
    private DataSource dataSource;

    @Before
    public void init() throws Exception {
        http.setPort(port);
        clear(tokenStore);
        clear(approvalStore);
    }

    @BeforeOAuth2Context
    public void fixPaths() {
        String prefix = server.getServletPrefix();
        http.setPort(port);
        http.setPrefix(prefix);
        BaseOAuth2ProtectedResourceDetails resource = (BaseOAuth2ProtectedResourceDetails) context.getResource();
        resource.setAccessTokenUri(http.getUrl(tokenPath()));
        if (resource instanceof AbstractRedirectResourceDetails) {
            ((AbstractRedirectResourceDetails) resource).setUserAuthorizationUri(http.getUrl(authorizePath()));
        }
        if (resource instanceof ImplicitResourceDetails) {
            resource.setAccessTokenUri(http.getUrl(authorizePath()));
        }
        if (resource instanceof ResourceOwnerPasswordResourceDetails) {
            ((ResourceOwnerPasswordResourceDetails) resource).setUsername(security.getUser().getName());
            ((ResourceOwnerPasswordResourceDetails) resource).setPassword(security.getUser().getPassword());
        }
    }

    private void clear(ApprovalStore approvalStore) throws Exception {
        if (approvalStore instanceof Advised) {
            Advised advised = (Advised) tokenStore;
            ApprovalStore target = (ApprovalStore) advised.getTargetSource().getTarget();
            clear(target);
            return;
        }
        if (approvalStore instanceof InMemoryApprovalStore) {
            ((InMemoryApprovalStore) approvalStore).clear();
        }
        if (approvalStore instanceof JdbcApprovalStore) {
            JdbcTemplate template = new JdbcTemplate(dataSource);
            template.execute("delete from oauth_approvals");
        }
    }

    private void clear(TokenStore tokenStore) throws Exception {
        if (tokenStore instanceof Advised) {
            Advised advised = (Advised) tokenStore;
            TokenStore target = (TokenStore) advised.getTargetSource().getTarget();
            clear(target);
            return;
        }
        if (tokenStore instanceof InMemoryTokenStore) {
            ((InMemoryTokenStore) tokenStore).clear();
        }
        if (tokenStore instanceof JdbcTokenStore) {
            JdbcTemplate template = new JdbcTemplate(dataSource);
            template.execute("delete from oauth_access_token");
            template.execute("delete from oauth_refresh_token");
            template.execute("delete from oauth_client_token");
            template.execute("delete from oauth_code");
        }
    }

    @Value("${oauth.paths.token:/oauth/token}")
    public void setTokenPath(String tokenPath) {
        globalTokenPath = tokenPath;
    }

    @Value("${oauth.paths.authorize:/oauth/authorize}")
    public void setAuthorizePath(String authorizePath) {
        globalAuthorizePath = authorizePath;
    }

    public static String tokenPath() {
        return globalTokenPath;
    }

    public static String authorizePath() {
        return globalAuthorizePath;
    }

}


text:
var win = Titanium.UI.currentWindow;

var l = Titanium.UI.createLabel({
	text:'Text area tests.',
	font:{fontSize:14},
	left:10,
	top:10,
	width:300,
	height:'auto'
});
win.add(l);

var ta1 = Titanium.UI.createTextArea({
	value:'I am a textarea',
	height:70,
	width:300,
	top:60,
	font:{fontSize:20,fontFamily:'Marker Felt', fontWeight:'bold'},
	color:'#888',
	textAlign:'left',
	appearance:Titanium.UI.KEYBOARD_APPEARANCE_ALERT,
	keyboardType:Titanium.UI.KEYBOARD_NUMBERS_PUNCTUATION,
	returnKeyType:Titanium.UI.RETURNKEY_EMERGENCY_CALL,
	borderWidth:2,
	borderColor:'#bbb',
	borderRadius:5,
	suppressReturn:false

});
win.add(ta1);

//
// Focus text area
//
var b1 = Titanium.UI.createButton({
	title:'Focus',
	height:40,
	width:200,
	top:140
});
win.add(b1);
b1.addEventListener('click', function()
{
	ta1.focus();
});

//
// Blur text area
//
var b2 = Titanium.UI.createButton({
	title:'Blur',
	height:40,
	width:200,
	top:190
});
win.add(b2);
b2.addEventListener('click', function()
{
	ta1.blur();
});

//
// Hide/Shw text area
//
var b3 = Titanium.UI.createButton({
	title:'Hide/Show',
	height:40,
	width:200,
	top:240
});
win.add(b3);
var visible=true;
b3.addEventListener('click', function()
{
	if (visible)
	{
		ta1.hide();
		visible=false;
	}
	else
	{
		ta1.show();
		visible=true;
	}
});

//
// Toggle Text area properties
//
var b4 = Titanium.UI.createButton({
	title:'Toggle Properties',
	top:290,
	height:40,
	width:200
});
win.add(b4);
var changed=false;
b4.addEventListener('click', function()
{
	if (!changed)
	{
		ta1.backgroundColor = '#336699';
		ta1.color = '#fff';
		ta1.textAlign = 'center';
		ta1.suppressReturn = true;
		ta1.autocapitalization = Titanium.UI.TEXT_AUTOCAPITALIZATION_ALL;
		changed=true;
	}
	else
	{
		ta1.backgroundColor = '#fff';
		ta1.color = '#888';
		ta1.textAlign = 'left';
		ta1.autocapitalization = Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE;
		changed=false;
		ta1.suppressReturn = false;
	}
});

//
// Text area events
//
ta1.addEventListener('change',function(e)
{
	l.text = 'change fired, value = ' + e.value + '\nfield value = ' + ta1.value;
});

ta1.addEventListener('blur',function(e)
{
	l.text = 'blur fired, value = ' + e.value;
});
ta1.addEventListener('focus',function(e)
{
	l.text = 'focus fired, value = ' + e.value;
});
ta1.addEventListener('return',function(e)
{
	l.text = 'return fired, value = ' + e.value;
});

redpajama_set_name: RedPajamaGithub


text:
package crop.parser.com.crop_final;

/**
 * Created by rohit on 4/11/15.
 */

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

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class NewProductActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;

    JSONParser jsonParser = new JSONParser();
    EditText longitude;
    EditText latitude;
    EditText inputpest;
    EditText infectedDate;
    EditText currentdate;
    EditText areaaffected;
    EditText info;

    // url to create new product
    private static String url_create_product = "http://10.0.2.2/android_connect/create_product.php";

    // JSON Node names
    private static final String TAG_SUCCESS = "success";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);

        // Edit Text
        longitude = (EditText) findViewById(R.id.longitude);
        latitude = (EditText) findViewById(R.id.latitude);
        inputpest = (EditText) findViewById(R.id.inputpest);
        infectedDate = (EditText) findViewById(R.id.infecteddate);
        currentdate = (EditText) findViewById(R.id.currentdate);
        areaaffected = (EditText) findViewById(R.id.areaaffected);
        info = (EditText) findViewById(R.id.info);

        // Create button
        Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

        // button click event
        btnCreateProduct.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // creating new product in background thread
                new CreateNewProduct().execute();

            }
        });
    }

    /**
     * Background Async Task to Create new product
     * */
    class CreateNewProduct extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewProductActivity.this);
            pDialog.setMessage("Creating Product..");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        /**
         * Creating product
         * */
        protected String doInBackground(String... args) {
            String longitude1 = longitude.getText().toString();
            String latitude1 = latitude.getText().toString();
            String inputpest1 = inputpest.getText().toString();
            String infectedDate1 = infectedDate.getText().toString();
            String currentdate1 = currentdate.getText().toString();
            String areaaffected1 = areaaffected.getText().toString();
            String info1 = info.getText().toString();
            Log.w("longitude1",longitude1);

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("longitude", longitude1));
            params.add(new BasicNameValuePair("latitude", latitude1));
            params.add(new BasicNameValuePair("inputpest", inputpest1));
            params.add(new BasicNameValuePair("infecteddate", infectedDate1));
            params.add(new BasicNameValuePair("currentdate", currentdate1));
            params.add(new BasicNameValuePair("areaaffected", areaaffected1));
            params.add(new BasicNameValuePair("info", info1));

            // getting JSON Object
            // Note that create product url accepts POST method
            JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                    "POST", params);

            // check log cat fro response
            Log.d("Create Response", json.toString());

            // check for success tag
            try {
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {
                    // successfully created product
                    Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
                    startActivity(i);

                    // closing this screen
                    finish();
                } else {
                    // failed to create product
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
        }

    }
}


text:
package io.appium.java_client.internal;

import static org.apache.commons.lang3.StringUtils.isBlank;

import com.google.common.collect.ImmutableMap;

import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.ios.IOSElement;
import io.appium.java_client.remote.AutomationName;
import io.appium.java_client.remote.MobilePlatform;
import io.appium.java_client.windows.WindowsElement;
import org.openqa.selenium.remote.RemoteWebElement;

import java.util.Map;
import java.util.Optional;

public enum ElementMap {
    ANDROID_UIAUTOMATOR2(AutomationName.ANDROID_UIAUTOMATOR2.toLowerCase(), AndroidElement.class),
    SELENDROID(AutomationName.SELENDROID.toLowerCase(), AndroidElement.class),
    IOS_XCUI_TEST(AutomationName.IOS_XCUI_TEST.toLowerCase(), IOSElement.class),
    ANDROID_UI_AUTOMATOR(MobilePlatform.ANDROID.toLowerCase(), AndroidElement.class),
    IOS_UI_AUTOMATION(MobilePlatform.IOS.toLowerCase(), IOSElement.class),
    WINDOWS(MobilePlatform.WINDOWS, WindowsElement.class);

    private static final Map<String, ElementMap> mobileElementMap;

    static {
        ImmutableMap.Builder<String, ElementMap> builder = ImmutableMap.builder();
        for (ElementMap e:values()) {
            builder.put(e.getPlatformOrAutomation(), e);
        }
        mobileElementMap = builder.build();
    }

    private final String platformOrAutomation;
    private final Class<? extends RemoteWebElement> elementClass;

    private ElementMap(String platformOrAutomation, Class<? extends MobileElement> elementClass) {
        this.platformOrAutomation = platformOrAutomation;
        this.elementClass = elementClass;
    }

    public String getPlatformOrAutomation() {
        return platformOrAutomation;
    }

    public Class<? extends RemoteWebElement> getElementClass() {
        return elementClass;
    }

    /**
     * Gets element class by {@code platform} and mobile {@code automation} type.
     *
     * @param platform is the mobile platform. See {@link MobilePlatform}.
     * @param automation is the mobile automation type. See {@link AutomationName}
     * @return subclass of {@link RemoteWebElement} that convenient to current session details.
     */
    public static Class<? extends RemoteWebElement> getElementClass(String platform, String automation) {
        if (isBlank(platform) && isBlank(automation)) {
            return RemoteWebElement.class;
        }
        ElementMap element = Optional.ofNullable(mobileElementMap.get(
                String.valueOf(platform).toLowerCase().trim()))
                .orElseGet(() -> mobileElementMap
                        .get(String.valueOf(automation).toLowerCase().trim()));
        if (element == null) {
            return RemoteWebElement.class;
        }
        return element.getElementClass();
    }
}


text:
package com.websoul.qatools.ui;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * Created by dimitris giannakos on 20/10/2017.
 */
@Service
public class AmazonSearchResultsPage {

    @FindBy(id="twotabsearchtextbox")
    WebElement searchBarInput;

    @FindBy(css="input.nav-input")
    WebElement searchSubmitButton;

    @FindBy(css="span[class='a-badge-label-inner a-text-ellipsis']")
    List<WebElement> listOfBadges;

    // Use annotations to locate elements.
    @FindBy(css = "img.s-access-image.cfMarker")
    WebElement searchItemSelect;

    @FindBy(xpath = "//li[@id='result_0']/div/div/div/div[2]/div/a/h2")
    WebElement searchResults;

    @FindBy(css = "[class='s-access-image cfMarker'")
    WebElement searchResultThirdItemSelect;

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<npc name="Mortimer" script="Mortimer.lua" walkinterval="2000" floorchange="0">
	<health now="100" max="100" />
	<look type="133" head="0" body="115" legs="102" feet="95" addons="0" />
	<parameters>
		<parameter key="module_shop" value="1" />
		<parameter key="shop_buyable" value="ectoplasm container,4863,750;botanists container,4869,500;orichalcum pearl,5022,80;crown backpack,10522,10000;" />
		<parameter key="shop_sellable" value="hydra egg,4850,500" />
	</parameters>
</npc>


text:
package io.permazen.core.type;

import com.google.common.base.Preconditions;

import io.permazen.util.ByteReader;
import io.permazen.util.ByteWriter;
import io.permazen.util.LongEncoder;
import io.permazen.util.ParseContext;

import java.time.Instant;
import java.util.regex.Pattern;

/**
 * Non-null {@link Instant} type. Null values are not supported by this class.
 *
 * <p>
 * Binary encoding is via two consecutive {@link LongEncoder}-encoded values, {@linkplain Instant#getEpochSecond epoch seconds}
 * followed by {@linkplain Instant#getNano nanoseconds}.
 */
public class InstantType extends NonNullFieldType<Instant> {

    private static final Pattern PATTERN = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?Z");

    private static final long serialVersionUID = -3907615112193058091L;

    public InstantType() {
        super(Instant.class, 0);
    }

// FieldType

    @Override
    public Instant read(ByteReader reader) {
        Preconditions.checkArgument(reader != null);
        return Instant.ofEpochSecond(LongEncoder.read(reader), (int)LongEncoder.read(reader));
    }

    @Override
    public void write(ByteWriter writer, Instant instant) {
        Preconditions.checkArgument(instant != null, "null instant");
        Preconditions.checkArgument(writer != null);
        LongEncoder.write(writer, instant.getEpochSecond());
        LongEncoder.write(writer, instant.getNano());
    }

    @Override
    public void skip(ByteReader reader) {
        Preconditions.checkArgument(reader != null);
        reader.skip(LongEncoder.decodeLength(reader.peek()));
        reader.skip(LongEncoder.decodeLength(reader.peek()));
    }

    @Override
    public Instant fromParseableString(ParseContext ctx) {
        return Instant.parse(ctx.matchPrefix(InstantType.PATTERN).group());
    }

    @Override
    public String toParseableString(Instant instant) {
        return instant.toString();
    }

    @Override
    public int compare(Instant instant1, Instant instant2) {
        return instant1.compareTo(instant2);
    }

    @Override
    public boolean hasPrefix0x00() {
        return false;
    }

    @Override
    public boolean hasPrefix0xff() {
        return false;
    }
}


text:
package quickfix.field;
import quickfix.IntField;

public class NoQuoteQualifiers extends IntField
{
  static final long serialVersionUID = 20050617;

  public static final int FIELD = 735;

  public NoQuoteQualifiers()
  {
    super(735);
  }

  public NoQuoteQualifiers(int data)
  {
     super(735, data);
  }

}


text:
const {test} = require('ava');
const {Database, Collection, Document} = require('../');

const db = new Database('localhost/mongorite_test_Collection_push');

const inspect = (obj, depth) => {
	console.log(require('util').inspect(obj, {colors: true, breakLength: 0, depth: depth}));
};

test('Pushin\'', assert => {
	let collection = new Collection();

	assert.is(collection.length, 0);
	collection.push({});
	assert.is(collection.length, 1);

	collection.push({});
	assert.is(collection.length, 2);

	collection.push({}, {});
	assert.is(collection.length, 4);

	collection.push([{}, {}]);
	assert.is(collection.length, 6);

	collection.push([{}, {}], {}, [{}]);
	assert.is(collection.length, 10);
});

test('prototype.push converts objects to documents', assert => {
	let collection = new Collection();
	collection.push({});
	assert.truthy(collection[0] instanceof Document);
});


text:
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
	android:duration="@integer/activity_transition_duration"
	android:fromAlpha="1.0"
	android:toAlpha="0.0"/>


text:
"""
40. Combination Sum II

Given a collection of candidate numbers (C) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
"""

class Solution(object):
    # http://www.cnblogs.com/zuoyuan/p/3777590.html
    # backtracking
    def dfs(self, candidates, target, start, valuelist):
        length = len(candidates)
        # remove duplicates
        if target == 0 and valuelist not in Solution.ret:
            return Solution.ret.append(valuelist)
        for i in range(start, length):
            if target < candidates[i]:
                return
            self.dfs(candidates,
                     target - candidates[i],
                     i + 1, # use i + 1 because each number only use once
                     valuelist + [candidates[i]])

    def combinationSum(self, candidates, target):
        """
        :type candidates: List[int]
        :type target: int
        :rtype: List[List[int]]
        """
        candidates.sort()
        Solution.ret = []
        self.dfs(candidates, target, 0, [])
        return Solution.ret

if __name__ == '__main__':
    print Solution().combinationSum([2, 3, 6, 7], 7)
    print Solution().combinationSum([10, 1, 2, 7, 6, 1, 5], 8)
    res = Solution().combinationSum(list(range(1,10)), 7)
    print list(filter(lambda x: len(x) == 3, res))


text:
package channel

import (
	"testing"

	"github.com/golang/protobuf/proto"
	"github.com/hyperledger/fabric/peer/common"
	cb "github.com/hyperledger/fabric/protos/common"
	pb "github.com/hyperledger/fabric/protos/peer"
	"github.com/stretchr/testify/assert"
)

func TestGetChannelInfo(t *testing.T) {
	InitMSP()
	resetFlags()

	mockBlockchainInfo := &cb.BlockchainInfo{
		Height:            1,
		CurrentBlockHash:  []byte("CurrentBlockHash"),
		PreviousBlockHash: []byte("PreviousBlockHash"),
	}
	mockPayload, err := proto.Marshal(mockBlockchainInfo)
	assert.NoError(t, err)

	mockResponse := &pb.ProposalResponse{
		Response: &pb.Response{
			Status:  200,
			Payload: mockPayload,
		},
		Endorsement: &pb.Endorsement{},
	}

	signer, err := common.GetDefaultSigner()
	assert.NoError(t, err)

	mockCF := &ChannelCmdFactory{
		EndorserClient:   common.GetMockEndorserClient(mockResponse, nil),
		BroadcastFactory: mockBroadcastClientFactory,
		Signer:           signer,
	}

	cmd := getinfoCmd(mockCF)
	AddFlags(cmd)

	args := []string{"-c", mockChannel}
	cmd.SetArgs(args)

	assert.NoError(t, cmd.Execute())
}

func TestGetChannelInfoMissingChannelID(t *testing.T) {
	InitMSP()
	resetFlags()

	signer, err := common.GetDefaultSigner()
	if err != nil {
		t.Fatalf("Get default signer error: %v", err)
	}

	mockCF := &ChannelCmdFactory{
		Signer: signer,
	}

	cmd := getinfoCmd(mockCF)

	AddFlags(cmd)

	cmd.SetArgs([]string{})

	assert.Error(t, cmd.Execute())
}


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

<percentiles>
  <percentile><lower>1</lower><content>Barbarian</content><upper>5</upper></percentile>
  <percentile><lower>6</lower><content>Bard</content><upper>10</upper></percentile>
  <percentile><lower>11</lower><content>Cleric</content><upper>30</upper></percentile>
  <percentile><lower>31</lower><content>Druid</content><upper>35</upper></percentile>
  <percentile><lower>36</lower><content>Fighter</content><upper>45</upper></percentile>
  <percentile><lower>46</lower><content>Monk</content><upper>50</upper></percentile>
  <percentile><lower>51</lower><content>Paladin</content><upper>55</upper></percentile>
  <percentile><lower>56</lower><content>Ranger</content><upper>65</upper></percentile>
  <percentile><lower>66</lower><content>Rogue</content><upper>75</upper></percentile>
  <percentile><lower>76</lower><content>Sorcerer</content><upper>80</upper></percentile>
  <percentile><lower>81</lower><content>Wizard</content><upper>100</upper></percentile>
</percentiles>


text:
<!--
  ~ Copyright (C) 2016-2019 Samuel Wall
  ~
  ~ 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.
  -->

<resources>
    <string name="app_name">Material Tap Target Prompt Sample</string>
    <string name="github">github.com/sjwall/MaterialTapTargetPrompt</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="action_settings">Settings</string>

    <string name="menu_prompt_title">Just how you want it</string>
    <string name="menu_prompt_description">Tap the menu icon to switch accounts, change settings & more</string>
    <string name="menu_prompt_content_description">This is an example of the accessibility content description, tap to exit. Tap the menu icon to switch accounts, change settings & more</string>

    <string name="overflow_prompt_title">More actions</string>
    <string name="overflow_prompt_description">Tap the 3 vertical dots to see more options</string>

    <string name="search_prompt_title">Search your emails</string>
    <string name="search_prompt_description">Tap the icon to quickly scan your emails</string>

    <string name="FabTarget_primaryText">Loaded from style</string>
    <string name="FabTarget_secondaryText">This was loaded from a style</string>

    <string name="example_navigation_title">Navigation</string>
    <string name="example_navigation_description">Displays prompt over the hamburger menu icon</string>

    <string name="example_overflow_title">Overflow</string>
    <string name="example_overflow_description">Displays prompt over the app bar more items menu item</string>

    <string name="example_search_title">App bar action icon</string>
    <string name="example_search_description">Displays prompt over the search icon in the app bar</string>

    <string name="example_fab_title">FAB</string>
    <string name="example_fab_description">Displays prompt over the FAB button</string>

    <string name="example_style_title">From style</string>
    <string name="example_style_description">Displays prompt over the app bar more items menu item with a style loaded from a resource</string>

    <string name="example_no_auto_dismiss_title">No auto dismiss</string>
    <string name="example_no_auto_dismiss_description">Displays prompt over the FAB button that can only be dismissed by pressing the FAB button</string>

    <string name="kotlin_activity_title">Kotlin</string>
    <string name="kotlin_activity_description">Examples written in Kotlin</string>

    <string name="example_dialog_title">Dialog</string>
    <string name="example_dialog_description">An example with a dialog</string>

    <string name="example_support_fragment_dialog_title">Support Fragment Dialog</string>
    <string name="example_support_fragment_dialog_description">An example with a support library fragment dialog</string>

    <string name="example_action_mode_title">Action Mode</string>
    <string name="example_action_mode_description">Shows an action mode with a prompt shown</string>

    <string name="action_mode_prompt_title">Action Mode</string>
    <string name="action_mode_prompt_description">Tap the back arrow to close the action mode</string>

    <string name="action_mode_tick_prompt_title">Tick</string>
    <string name="action_mode_tick_prompt_description">Replace this with your own action description</string>

    <string name="action_tick">Positive action</string>

    <string name="overflow_unavailable">Overflow unavailable</string>

    <string name="example_centre_title">Centre</string>
    <string name="example_centre_description">Displays activity with examples where the prompt is position away from the activity edges</string>
    <string name="example_centre_instructions">Tap on a button to show a prompt</string>

    <string name="fab_centre_title">Centre</string>
    <string name="fab_centre_description">Text and background are positioned differently</string>

    <string name="example_card_title">Cards</string>
    <string name="example_card_description">Displays activity with a prompt contained within a card</string>

    <string name="example_list_title">List</string>
    <string name="example_list_description">Displays activity with a prompt targeting a list item</string>

    <string name="title_activity_card">Card Example</string>

    <string name="example_card_fab_title">Card example</string>
    <string name="example_card_fab_description">Tap to see a card example</string>

    <string name="example_card_card_title">Card example</string>
    <string name="example_card_card_description">Clipped to card bounds</string>

    <string name="example_bottom_sheet_title">Bottom Sheet Dialog</string>
    <string name="example_bottom_sheet_description">Displays prompt over a bottom sheet dialog</string>

    <string name="example_rectangle_title" translatable="false">Rectangle Prompt</string>
    <string name="example_fullscreen_rectangle_title" translatable="false">Fullscreen Rectangle Prompt</string>
    <string name="example_rectangle_description" translatable="false">Displays a prompt with a rectangle background and focal</string>

    <string name="example_show_for_title">showFor</string>
    <string name="example_show_for_description">Displays prompt over the FAB button for 7 seconds</string>

    <string name="title_activity_list_example" translatable="false">List Example</string>
    <string name="example_sequence">Show an example of a sequence of prompts</string>
    <string name="example_sequence_title">Sequence</string>

    <string name="example_view_pager_title">View pager tab</string>
    <string name="example_view_pager_description">Show a prompt targeting a view pager tab</string>

    <string name="fab_dummy_content_desc">Dummy floating action button used for examples</string>
</resources>


text:
package placement

import (
	"encoding/hex"
	"fmt"
	"testing"

	"github.com/pingcap/failpoint"
	"github.com/pingcap/tidb/parser/model"
	"github.com/pingcap/tidb/tablecodec"
	"github.com/pingcap/tidb/util/codec"
	"github.com/stretchr/testify/require"
)

func TestEmpty(t *testing.T) {
	bundle := &Bundle{ID: GroupID(1)}
	require.True(t, bundle.IsEmpty())

	bundle = &Bundle{ID: GroupID(1), Index: 1}
	require.False(t, bundle.IsEmpty())

	bundle = &Bundle{ID: GroupID(1), Override: true}
	require.False(t, bundle.IsEmpty())

	bundle = &Bundle{ID: GroupID(1), Rules: []*Rule{{ID: "434"}}}
	require.False(t, bundle.IsEmpty())

	bundle = &Bundle{ID: GroupID(1), Index: 1, Override: true}
	require.False(t, bundle.IsEmpty())
}

func TestCloneBundle(t *testing.T) {
	bundle := &Bundle{ID: GroupID(1), Rules: []*Rule{{ID: "434"}}}

	newBundle := bundle.Clone()
	newBundle.ID = GroupID(2)
	newBundle.Rules[0] = &Rule{ID: "121"}

	require.Equal(t, &Bundle{ID: GroupID(1), Rules: []*Rule{{ID: "434"}}}, bundle)
	require.Equal(t, &Bundle{ID: GroupID(2), Rules: []*Rule{{ID: "121"}}}, newBundle)
}

func TestObjectID(t *testing.T) {
	type TestCase struct {
		name       string
		bundleID   string
		expectedID int64
		err        error
	}
	tests := []TestCase{
		{"non tidb bundle", "pd", 0, ErrInvalidBundleIDFormat},
		{"id of words", "TiDB_DDL_foo", 0, ErrInvalidBundleID},
		{"id of words and nums", "TiDB_DDL_3x", 0, ErrInvalidBundleID},
		{"id of floats", "TiDB_DDL_3.0", 0, ErrInvalidBundleID},
		{"id of negatives", "TiDB_DDL_-10", 0, ErrInvalidBundleID},
		{"id of positive integer", "TiDB_DDL_10", 10, nil},
	}
	for _, test := range tests {
		bundle := Bundle{ID: test.bundleID}
		id, err := bundle.ObjectID()
		if test.err == nil {
			require.NoError(t, err, test.name)
			require.Equal(t, test.expectedID, id, test.name)
		} else {
			require.ErrorIs(t, err, test.err, test.name)
		}
	}
}

func TestGetLeaderDCByBundle(t *testing.T) {
	testcases := []struct {
		name       string
		bundle     *Bundle
		expectedDC string
	}{
		{
			name: "only leader",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "12",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"bj"},
							},
						},
						Count: 1,
					},
				},
			},
			expectedDC: "bj",
		},
		{
			name: "no leader",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "12",
						Role: Voter,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"bj"},
							},
						},
						Count: 3,
					},
				},
			},
			expectedDC: "",
		},
		{
			name: "voter and leader",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "11",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"sh"},
							},
						},
						Count: 1,
					},
					{
						ID:   "12",
						Role: Voter,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"bj"},
							},
						},
						Count: 3,
					},
				},
			},
			expectedDC: "sh",
		},
		{
			name: "wrong label key",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "11",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "fake",
								Op:     In,
								Values: []string{"sh"},
							},
						},
						Count: 1,
					},
				},
			},
			expectedDC: "",
		},
		{
			name: "wrong operator",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "11",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     NotIn,
								Values: []string{"sh"},
							},
						},
						Count: 1,
					},
				},
			},
			expectedDC: "",
		},
		{
			name: "leader have multi values",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "11",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"sh", "bj"},
							},
						},
						Count: 1,
					},
				},
			},
			expectedDC: "",
		},
		{
			name: "irrelvant rules",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "15",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    EngineLabelKey,
								Op:     NotIn,
								Values: []string{EngineLabelTiFlash},
							},
						},
						Count: 1,
					},
					{
						ID:   "14",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "disk",
								Op:     NotIn,
								Values: []string{"ssd", "hdd"},
							},
						},
						Count: 1,
					},
					{
						ID:   "13",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"bj"},
							},
						},
						Count: 1,
					},
				},
			},
			expectedDC: "bj",
		},
		{
			name: "multi leaders 1",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "16",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"sh"},
							},
						},
						Count: 2,
					},
				},
			},
			expectedDC: "",
		},
		{
			name: "multi leaders 2",
			bundle: &Bundle{
				ID: GroupID(1),
				Rules: []*Rule{
					{
						ID:   "17",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"sh"},
							},
						},
						Count: 1,
					},
					{
						ID:   "18",
						Role: Leader,
						Constraints: Constraints{
							{
								Key:    "zone",
								Op:     In,
								Values: []string{"bj"},
							},
						},
						Count: 1,
					},
				},
			},
			expectedDC: "sh",
		},
	}
	for _, testcase := range testcases {
		result, ok := testcase.bundle.GetLeaderDC("zone")
		if len(testcase.expectedDC) > 0 {
			require.True(t, ok, testcase.name)
		} else {
			require.False(t, ok, testcase.name)
		}
		require.Equal(t, testcase.expectedDC, result, testcase.name)
	}
}

func TestString(t *testing.T) {
	bundle := &Bundle{
		ID: GroupID(1),
	}

	rules1, err := NewRules(Voter, 3, `["+zone=sh", "+zone=sh"]`)
	require.NoError(t, err)
	rules2, err := NewRules(Voter, 4, `["-zone=sh", "+zone=bj"]`)
	require.NoError(t, err)
	bundle.Rules = append(rules1, rules2...)

	require.Equal(t, "{\"group_id\":\"TiDB_DDL_1\",\"group_index\":0,\"group_override\":false,\"rules\":[{\"group_id\":\"\",\"id\":\"\",\"start_key\":\"\",\"end_key\":\"\",\"role\":\"voter\",\"count\":3,\"label_constraints\":[{\"key\":\"zone\",\"op\":\"in\",\"values\":[\"sh\"]}]},{\"group_id\":\"\",\"id\":\"\",\"start_key\":\"\",\"end_key\":\"\",\"role\":\"voter\",\"count\":4,\"label_constraints\":[{\"key\":\"zone\",\"op\":\"notIn\",\"values\":[\"sh\"]},{\"key\":\"zone\",\"op\":\"in\",\"values\":[\"bj\"]}]}]}", bundle.String())

	require.NoError(t, failpoint.Enable("github.com/pingcap/tidb/ddl/placement/MockMarshalFailure", `return(true)`))
	defer func() {
		require.NoError(t, failpoint.Disable("github.com/pingcap/tidb/ddl/placement/MockMarshalFailure"))
	}()
	require.Equal(t, "", bundle.String())
}

func TestNewBundle(t *testing.T) {
	require.Equal(t, &Bundle{ID: GroupID(3)}, NewBundle(3))
	require.Equal(t, &Bundle{ID: GroupID(-1)}, NewBundle(-1))
	_, err := NewBundleFromConstraintsOptions(nil)
	require.Error(t, err)
	_, err = NewBundleFromSugarOptions(nil)
	require.Error(t, err)
	_, err = NewBundleFromOptions(nil)
	require.Error(t, err)
}

func TestNewBundleFromOptions(t *testing.T) {
	type TestCase struct {
		name   string
		input  *model.PlacementSettings
		output []*Rule
		err    error
	}
	var tests []TestCase

	tests = append(tests, TestCase{
		name:  "empty 1",
		input: &model.PlacementSettings{},
		output: []*Rule{
			NewRule(Voter, 3, NewConstraintsDirect()),
		},
	})

	tests = append(tests, TestCase{
		name:  "empty 2",
		input: nil,
		err:   ErrInvalidPlacementOptions,
	})

	tests = append(tests, TestCase{
		name: "empty 3",
		input: &model.PlacementSettings{
			LearnerConstraints: "[+region=us]",
		},
		err: ErrInvalidPlacementOptions,
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: normal case 1",
		input: &model.PlacementSettings{
			PrimaryRegion: "us",
			Regions:       "us",
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Voter, 2, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
		},
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: normal case 2",
		input: &model.PlacementSettings{
			PrimaryRegion: "us",
			Regions:       "us",
			Schedule:      "majority_in_primary",
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Voter, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Voter, 1, NewConstraintsDirect()),
		},
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: few followers",
		input: &model.PlacementSettings{
			PrimaryRegion: "us",
			Regions:       "bj,sh,us",
			Followers:     1,
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Voter, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "bj", "sh"),
			)),
		},
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: omit regions 1",
		input: &model.PlacementSettings{
			Followers: 2,
			Schedule:  "even",
		},
		output: []*Rule{
			NewRule(Voter, 3, NewConstraintsDirect()),
		},
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: omit regions 2",
		input: &model.PlacementSettings{
			Followers: 2,
			Schedule:  "majority_in_primary",
		},
		output: []*Rule{
			NewRule(Voter, 3, NewConstraintsDirect()),
		},
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: wrong schedule prop",
		input: &model.PlacementSettings{
			PrimaryRegion: "us",
			Regions:       "us",
			Schedule:      "wrong",
		},
		err: ErrInvalidPlacementOptions,
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: invalid region name 1",
		input: &model.PlacementSettings{
			PrimaryRegion: ",=,",
			Regions:       ",=,",
		},
		err: ErrInvalidPlacementOptions,
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: invalid region name 2",
		input: &model.PlacementSettings{
			PrimaryRegion: "f",
			Regions:       ",=",
		},
		err: ErrInvalidPlacementOptions,
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: invalid region name 4",
		input: &model.PlacementSettings{
			PrimaryRegion: "",
			Regions:       "g",
		},
		err: ErrInvalidPlacementOptions,
	})

	tests = append(tests, TestCase{
		name: "sugar syntax: normal case 2",
		input: &model.PlacementSettings{
			PrimaryRegion: "us",
			Regions:       "sh,us",
			Followers:     5,
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Voter, 2, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Voter, 3, NewConstraintsDirect(
				NewConstraintDirect("region", In, "sh"),
			)),
		},
	})
	tests = append(tests, tests[len(tests)-1])
	tests[len(tests)-1].name = "sugar syntax: explicit schedule"
	tests[len(tests)-1].input.Schedule = "even"

	tests = append(tests, TestCase{
		name: "sugar syntax: majority schedule",
		input: &model.PlacementSettings{
			PrimaryRegion: "sh",
			Regions:       "bj,sh",
			Followers:     4,
			Schedule:      "majority_in_primary",
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "sh"),
			)),
			NewRule(Voter, 2, NewConstraintsDirect(
				NewConstraintDirect("region", In, "sh"),
			)),
			NewRule(Voter, 2, NewConstraintsDirect(
				NewConstraintDirect("region", In, "bj"),
			)),
		},
	})

	tests = append(tests, TestCase{
		name: "direct syntax: normal case 1",
		input: &model.PlacementSettings{
			Constraints: "[+region=us]",
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Voter, 2, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
		},
	})

	tests = append(tests, TestCase{
		name: "direct syntax: normal case 3",
		input: &model.PlacementSettings{
			Constraints: "[+region=us]",
			Followers:   2,
			Learners:    2,
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Voter, 2, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
			NewRule(Learner, 2, NewConstraintsDirect(
				NewConstraintDirect("region", In, "us"),
			)),
		},
	})

	tests = append(tests, TestCase{
		name: "direct syntax: lack count 1",
		input: &model.PlacementSettings{
			LeaderConstraints:   "[+region=as]",
			FollowerConstraints: "[-region=us]",
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect(NewConstraintDirect("region", In, "as"))),
			NewRule(Voter, 2, NewConstraintsDirect(NewConstraintDirect("region", NotIn, "us"))),
		},
	})

	tests = append(tests, TestCase{
		name: "direct syntax: lack count 2",
		input: &model.PlacementSettings{
			LeaderConstraints:  "[+region=as]",
			LearnerConstraints: "[-region=us]",
		},
		err: ErrInvalidPlacementOptions,
	})

	tests = append(tests, TestCase{
		name: "direct syntax: omit leader",
		input: &model.PlacementSettings{
			Followers:           2,
			FollowerConstraints: "[+region=bj]",
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect()),
			NewRule(Voter, 2, NewConstraintsDirect(NewConstraintDirect("region", In, "bj"))),
		},
	})

	tests = append(tests, TestCase{
		name: "direct syntax: conflicts 1",
		input: &model.PlacementSettings{
			Constraints:       "[+region=us]",
			LeaderConstraints: "[-region=us]",
			Followers:         2,
		},
		err: ErrConflictingConstraints,
	})

	tests = append(tests, TestCase{
		name: "direct syntax: conflicts 3",
		input: &model.PlacementSettings{
			Constraints:         "[+region=us]",
			FollowerConstraints: "[-region=us]",
			Followers:           2,
		},
		err: ErrConflictingConstraints,
	})

	tests = append(tests, TestCase{
		name: "direct syntax: conflicts 4",
		input: &model.PlacementSettings{
			Constraints:        "[+region=us]",
			LearnerConstraints: "[-region=us]",
			Followers:          2,
			Learners:           2,
		},
		err: ErrConflictingConstraints,
	})

	tests = append(tests, TestCase{
		name: "direct syntax: invalid format 1",
		input: &model.PlacementSettings{
			Constraints:       "[+region=us]",
			LeaderConstraints: "-region=us]",
			Followers:         2,
		},
		err: ErrInvalidConstraintsFormat,
	})

	tests = append(tests, TestCase{
		name: "direct syntax: invalid format 2",
		input: &model.PlacementSettings{
			Constraints:       "+region=us]",
			LeaderConstraints: "[-region=us]",
			Followers:         2,
		},
		err: ErrInvalidConstraintsFormat,
	})

	tests = append(tests, TestCase{
		name: "direct syntax: invalid format 4",
		input: &model.PlacementSettings{
			Constraints:         "[+region=us]",
			FollowerConstraints: "-region=us]",
			Followers:           2,
		},
		err: ErrInvalidConstraintsFormat,
	})

	tests = append(tests, TestCase{
		name: "direct syntax: invalid format 5",
		input: &model.PlacementSettings{
			Constraints:       "[+region=us]",
			LeaderConstraints: "-region=us]",
			Learners:          2,
			Followers:         2,
		},
		err: ErrInvalidConstraintsFormat,
	})

	tests = append(tests, TestCase{
		name: "direct syntax: learner dict constraints",
		input: &model.PlacementSettings{
			LearnerConstraints: `{"+region=us": 2}`,
		},
		output: []*Rule{
			NewRule(Leader, 1, NewConstraintsDirect()),
			NewRule(Voter, 2, NewConstraintsDirect()),
			NewRule(Learner, 2, NewConstraintsDirect(NewConstraintDirect("region", In, "us"))),
		},
	})

	tests = append(tests, TestCase{
		name: "direct syntax: learner dict constraints, with count",
		input: &model.PlacementSettings{
			LearnerConstraints: `{"+region=us": 2}`,
			Learners:           4,
		},
		err: ErrInvalidConstraintsRelicas,
	})

	for _, test := range tests {
		bundle, err := newBundleFromOptions(test.input)
		comment := fmt.Sprintf("[%s]\nerr1 %s\nerr2 %s", test.name, err, test.err)
		if test.err != nil {
			require.ErrorIs(t, err, test.err, comment)
		} else {
			require.NoError(t, err, comment)
			matchRules(test.output, bundle.Rules, comment, t)
		}
	}
}

func TestResetBundleWithSingleRule(t *testing.T) {
	bundle := &Bundle{
		ID: GroupID(1),
	}

	rules, err := NewRules(Voter, 3, `["+zone=sh", "+zone=sh"]`)
	require.NoError(t, err)
	bundle.Rules = rules

	bundle.Reset(RuleIndexTable, []int64{3})
	require.Equal(t, GroupID(3), bundle.ID)
	require.Equal(t, true, bundle.Override)
	require.Equal(t, RuleIndexTable, bundle.Index)
	require.Len(t, bundle.Rules, 1)
	require.Equal(t, bundle.ID, bundle.Rules[0].GroupID)

	startKey := hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(3)))
	require.Equal(t, startKey, bundle.Rules[0].StartKeyHex)

	endKey := hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(4)))
	require.Equal(t, endKey, bundle.Rules[0].EndKeyHex)
}

func TestResetBundleWithMultiRules(t *testing.T) {
	// build a bundle with three rules.
	bundle, err := NewBundleFromOptions(&model.PlacementSettings{
		LeaderConstraints:   `["+zone=bj"]`,
		Followers:           2,
		FollowerConstraints: `["+zone=hz"]`,
		Learners:            1,
		LearnerConstraints:  `["+zone=cd"]`,
		Constraints:         `["+disk=ssd"]`,
	})
	require.NoError(t, err)
	require.Equal(t, 3, len(bundle.Rules))

	// test if all the three rules are basic rules even the start key are not set.
	bundle.Reset(RuleIndexTable, []int64{1, 2, 3})
	require.Equal(t, GroupID(1), bundle.ID)
	require.Equal(t, RuleIndexTable, bundle.Index)
	require.Equal(t, true, bundle.Override)
	require.Equal(t, 3*3, len(bundle.Rules))
	// for id 1.
	startKey := hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(1)))
	endKey := hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(2)))
	require.Equal(t, startKey, bundle.Rules[0].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[0].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[1].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[1].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[2].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[2].EndKeyHex)
	// for id 2.
	startKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(2)))
	endKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(3)))
	require.Equal(t, startKey, bundle.Rules[3].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[3].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[4].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[4].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[5].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[5].EndKeyHex)
	// for id 3.
	startKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(3)))
	endKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(4)))
	require.Equal(t, startKey, bundle.Rules[6].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[6].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[7].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[7].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[8].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[8].EndKeyHex)

	// test if bundle has redundant rules.
	// for now, the bundle has 9 rules, each table id or partition id has the three with them.
	// once we reset this bundle for another ids, for example, adding partitions. we should
	// extend the basic rules(3 of them) to the new partition id.
	bundle.Reset(RuleIndexTable, []int64{1, 3, 4, 5})
	require.Equal(t, GroupID(1), bundle.ID)
	require.Equal(t, RuleIndexTable, bundle.Index)
	require.Equal(t, true, bundle.Override)
	require.Equal(t, 3*4, len(bundle.Rules))
	// for id 1.
	startKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(1)))
	endKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(2)))
	require.Equal(t, startKey, bundle.Rules[0].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[0].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[1].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[1].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[2].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[2].EndKeyHex)
	// for id 3.
	startKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(3)))
	endKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(4)))
	require.Equal(t, startKey, bundle.Rules[3].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[3].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[4].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[4].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[5].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[5].EndKeyHex)
	// for id 4.
	startKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(4)))
	endKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(5)))
	require.Equal(t, startKey, bundle.Rules[6].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[6].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[7].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[7].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[8].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[8].EndKeyHex)
	// for id 5.
	startKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(5)))
	endKey = hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(6)))
	require.Equal(t, startKey, bundle.Rules[9].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[9].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[10].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[10].EndKeyHex)
	require.Equal(t, startKey, bundle.Rules[11].StartKeyHex)
	require.Equal(t, endKey, bundle.Rules[11].EndKeyHex)
}

func TestTidy(t *testing.T) {
	bundle := &Bundle{
		ID: GroupID(1),
	}

	rules0, err := NewRules(Voter, 1, `["+zone=sh", "+zone=sh"]`)
	require.NoError(t, err)
	require.Len(t, rules0, 1)
	rules0[0].Count = 0 // test prune useless rules

	rules1, err := NewRules(Voter, 4, `["-zone=sh", "+zone=bj"]`)
	require.NoError(t, err)
	require.Len(t, rules1, 1)
	rules2, err := NewRules(Voter, 4, `["-zone=sh", "+zone=bj"]`)
	require.NoError(t, err)
	bundle.Rules = append(bundle.Rules, rules0...)
	bundle.Rules = append(bundle.Rules, rules1...)
	bundle.Rules = append(bundle.Rules, rules2...)

	err = bundle.Tidy()
	require.NoError(t, err)
	require.Len(t, bundle.Rules, 2)
	require.Equal(t, "1", bundle.Rules[0].ID)
	require.Len(t, bundle.Rules[0].Constraints, 3)
	require.Equal(t, Constraint{
		Op:     NotIn,
		Key:    EngineLabelKey,
		Values: []string{EngineLabelTiFlash},
	}, bundle.Rules[0].Constraints[2])
	require.Equal(t, "2", bundle.Rules[1].ID)

	// merge
	rules3, err := NewRules(Follower, 4, "")
	require.NoError(t, err)
	require.Len(t, rules3, 1)

	rules4, err := NewRules(Follower, 5, "")
	require.NoError(t, err)
	require.Len(t, rules4, 1)

	rules0[0].Role = Voter
	bundle.Rules = append(bundle.Rules, rules0...)
	bundle.Rules = append(bundle.Rules, rules3...)
	bundle.Rules = append(bundle.Rules, rules4...)

	chkfunc := func() {
		require.NoError(t, err)
		require.Len(t, bundle.Rules, 3)
		require.Equal(t, "0", bundle.Rules[0].ID)
		require.Equal(t, "1", bundle.Rules[1].ID)
		require.Equal(t, "follower", bundle.Rules[2].ID)
		require.Equal(t, 9, bundle.Rules[2].Count)
		require.Equal(t, Constraints{
			{
				Op:     NotIn,
				Key:    EngineLabelKey,
				Values: []string{EngineLabelTiFlash},
			},
		}, bundle.Rules[2].Constraints)
	}
	err = bundle.Tidy()
	chkfunc()

	// tidy again
	// it should be stable
	err = bundle.Tidy()
	chkfunc()

	// tidy again
	// it should be stable
	bundle2 := bundle.Clone()
	err = bundle2.Tidy()
	require.NoError(t, err)
	require.Equal(t, bundle, bundle2)

	bundle.Rules[2].Constraints = append(bundle.Rules[2].Constraints, Constraint{
		Op:     In,
		Key:    EngineLabelKey,
		Values: []string{EngineLabelTiFlash},
	})
	require.ErrorIs(t, bundle.Tidy(), ErrConflictingConstraints)
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.quota.generated;

import com.azure.core.util.Context;

/** Samples for Usages Get. */
public final class UsagesGetSamples {
    /*
     * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2021-03-15-preview/examples/getNetworkOneSkuUsages.json
     */
    /**
     * Sample code: Quotas_UsagesRequest_ForNetwork.
     *
     * @param manager Entry point to QuotaManager.
     */
    public static void quotasUsagesRequestForNetwork(com.azure.resourcemanager.quota.QuotaManager manager) {
        manager
            .usages()
            .getWithResponse(
                "MinPublicIpInterNetworkPrefixLength",
                "subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.Network/locations/eastus",
                Context.NONE);
    }

    /*
     * x-ms-original-file: specification/quota/resource-manager/Microsoft.Quota/preview/2021-03-15-preview/examples/getComputeOneSkuUsages.json
     */
    /**
     * Sample code: Quotas_UsagesRequest_ForCompute.
     *
     * @param manager Entry point to QuotaManager.
     */
    public static void quotasUsagesRequestForCompute(com.azure.resourcemanager.quota.QuotaManager manager) {
        manager
            .usages()
            .getWithResponse(
                "standardNDSFamily",
                "subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.Compute/locations/eastus",
                Context.NONE);
    }
}


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: bigip_iapp_service
short_description: Manages TCL iApp services on a BIG-IP.
description:
  - Manages TCL iApp services on a BIG-IP.
version_added: "2.4"
options:
  name:
    description:
      - The name of the iApp service that you want to deploy.
    required: True
  template:
    description:
      - The iApp template from which to instantiate a new service. This
        template must exist on your BIG-IP before you can successfully
        create a service. This parameter is required if the C(state)
        parameter is C(present).
  parameters:
    description:
      - A hash of all the required template variables for the iApp template.
        If your parameters are stored in a file (the more common scenario)
        it is recommended you use either the `file` or `template` lookups
        to supply the expected parameters.
  force:
    description:
      - Forces the updating of an iApp service even if the parameters to the
        service have not changed. This option is of particular importance if
        the iApp template that underlies the service has been updated in-place.
        This option is equivalent to re-configuring the iApp if that template
        has changed.
    default: False
  state:
    description:
      - When C(present), ensures that the iApp service is created and running.
        When C(absent), ensures that the iApp service has been removed.
    default: present
    choices:
      - present
      - absent
notes:
  - Requires the f5-sdk Python package on the host. This is as easy as pip
    install f5-sdk.
  - Requires the deepdiff Python package on the host. This is as easy as pip
    install f5-sdk.
requirements:
  - f5-sdk
  - deepdiff
extends_documentation_fragment: f5
author:
  - Tim Rupp (@caphrim007)
'''

EXAMPLES = '''
- name: Create HTTP iApp service from iApp template
  bigip_iapp_service:
      name: "foo-service"
      template: "f5.http"
      parameters: "{{ lookup('file', 'f5.http.parameters.json') }}"
      password: "secret"
      server: "lb.mydomain.com"
      state: "present"
      user: "admin"
  delegate_to: localhost

- name: Upgrade foo-service to v1.2.0rc4 of the f5.http template
  bigip_iapp_service:
      name: "foo-service"
      template: "f5.http.v1.2.0rc4"
      password: "secret"
      server: "lb.mydomain.com"
      state: "present"
      user: "admin"
  delegate_to: localhost

- name: Configure a service using parameters in YAML
  bigip_iapp_service:
      name: "tests"
      template: "web_frontends"
      password: "admin"
      server: "{{ inventory_hostname }}"
      server_port: "{{ bigip_port }}"
      validate_certs: "{{ validate_certs }}"
      state: "present"
      user: "admin"
      parameters:
          variables:
              - name: "var__vs_address"
                value: "1.1.1.1"
              - name: "pm__apache_servers_for_http"
                value: "2.2.2.1:80"
              - name: "pm__apache_servers_for_https"
                value: "2.2.2.2:80"
  delegate_to: localhost

- name: Re-configure a service whose underlying iApp was updated in place
  bigip_iapp_service:
      name: "tests"
      template: "web_frontends"
      password: "admin"
      force: yes
      server: "{{ inventory_hostname }}"
      server_port: "{{ bigip_port }}"
      validate_certs: "{{ validate_certs }}"
      state: "present"
      user: "admin"
      parameters:
          variables:
              - name: "var__vs_address"
                value: "1.1.1.1"
              - name: "pm__apache_servers_for_http"
                value: "2.2.2.1:80"
              - name: "pm__apache_servers_for_https"
                value: "2.2.2.2:80"
  delegate_to: localhost
'''

RETURN = '''
# only common fields returned
'''

from ansible.module_utils.f5_utils import (
    AnsibleF5Client,
    AnsibleF5Parameters,
    HAS_F5SDK,
    F5ModuleError,
    iteritems,
    iControlUnexpectedHTTPError
)
from deepdiff import DeepDiff

class Parameters(AnsibleF5Parameters):
    returnables = []
    api_attributes = [
        'tables', 'variables', 'template', 'lists', 'deviceGroup',
        'inheritedDevicegroup', 'inheritedTrafficGroup', 'trafficGroup'
    ]
    updatables = ['tables', 'variables', 'lists']

    def to_return(self):
        result = {}
        for returnable in self.returnables:
            result[returnable] = getattr(self, returnable)
        result = self._filter_params(result)
        return result

    def api_params(self):
        result = {}
        for api_attribute in self.api_attributes:
            if self.api_map is not None and api_attribute in self.api_map:
                result[api_attribute] = getattr(self, self.api_map[api_attribute])
            else:
                result[api_attribute] = getattr(self, api_attribute)
        result = self._filter_params(result)
        return result

    @property
    def tables(self):
        result = []
        if not self._values['tables']:
            return None
        tables = self._values['tables']
        for table in tables:
            tmp = dict()
            name = table.get('name', None)
            if name is None:
                raise F5ModuleError(
                    "One of the provided tables does not have a name"
                )
            tmp['name'] = str(name)
            columns = table.get('columnNames', None)
            if columns:
                tmp['columnNames'] = [str(x) for x in columns]
                # You cannot have rows without columns
                rows = table.get('rows', None)
                if rows:
                    tmp['rows'] = []
                    for row in rows:
                        tmp['rows'].append(dict(row=[str(x) for x in row['row']]))
            result.append(tmp)
        result = sorted(result, key=lambda k: k['name'])
        return result

    @tables.setter
    def tables(self, value):
        self._values['tables'] = value

    @property
    def variables(self):
        result = []
        if not self._values['variables']:
            return None
        variables = self._values['variables']
        for variable in variables:
            tmp = dict((str(k), str(v)) for k, v in iteritems(variable))
            if 'encrypted' not in tmp:
                # BIG-IP will inject an 'encrypted' key if you don't provide one.
                # If you don't provide one, then we give you the default 'no', by
                # default.
                tmp['encrypted'] = 'no'
            if 'value' not in tmp:
                tmp['value'] = ''

            # This seems to happen only on 12.0.0
            elif tmp['value'] == 'none':
                tmp['value'] = ''
            result.append(tmp)
        result = sorted(result, key=lambda k: k['name'])
        return result

    @variables.setter
    def variables(self, value):
        self._values['variables'] = value

    @property
    def lists(self):
        result = []
        if not self._values['lists']:
            return None
        lists = self._values['lists']
        for list in lists:
            tmp = dict((str(k), str(v)) for k, v in iteritems(list) if k != 'value')
            if 'encrypted' not in list:
                # BIG-IP will inject an 'encrypted' key if you don't provide one.
                # If you don't provide one, then we give you the default 'no', by
                # default.
                tmp['encrypted'] = 'no'
            if 'value' in list:
                if len(list['value']) > 0:
                    # BIG-IP removes empty values entries, so mimic this behavior
                    # for user-supplied values.
                    tmp['value'] = [str(x) for x in list['value']]
            result.append(tmp)
        result = sorted(result, key=lambda k: k['name'])
        return result

    @lists.setter
    def lists(self, value):
        self._values['lists'] = value

    @property
    def parameters(self):
        return dict(
            tables=self.tables,
            variables=self.variables,
            lists=self.lists
        )

    @parameters.setter
    def parameters(self, value):
        if value is None:
            return
        if 'tables' in value:
            self.tables = value['tables']
        if 'variables' in value:
            self.variables = value['variables']
        if 'lists' in value:
            self.lists = value['lists']
        if 'deviceGroup' in value:
            self.deviceGroup = value['deviceGroup']
        if 'inheritedDevicegroup' in value:
            self.inheritedDevicegroup = value['inheritedDevicegroup']
        if 'inheritedTrafficGroup' in value:
            self.inheritedTrafficGroup = value['inheritedTrafficGroup']
        if 'trafficGroup' in value:
            self.trafficGroup = value['trafficGroup']

    @property
    def template(self):
        if self._values['template'] is None:
            return None
        if self._values['template'].startswith("/" + self.partition):
            return self._values['template']
        elif self._values['template'].startswith("/"):
            return self._values['template']
        else:
            return '/{0}/{1}'.format(
                self.partition, self._values['template']
            )

    @template.setter
    def template(self, value):
        self._values['template'] = value

class ModuleManager(object):
    def __init__(self, client):
        self.client = client
        self.have = None
        self.want = Parameters(self.client.module.params)
        self.changes = Parameters()

    def _set_changed_options(self):
        changed = {}
        for key in Parameters.returnables:
            if getattr(self.want, key) is not None:
                changed[key] = getattr(self.want, key)
        if changed:
            self.changes = Parameters(changed)

    def _update_changed_options(self):
        changed = {}
        for key in Parameters.updatables:
            if getattr(self.want, key) is not None:
                attr1 = getattr(self.want, key)
                attr2 = getattr(self.have, key)
                if attr1 != attr2:
                    changed[key] = str(DeepDiff(attr1, attr2))
        if changed:
            self.changes = Parameters(changed)
            return True
        return False

    def exec_module(self):
        changed = False
        result = dict()
        state = self.want.state

        try:
            if state == "present":
                changed = self.present()
            elif state == "absent":
                changed = self.absent()
        except iControlUnexpectedHTTPError as e:
            raise F5ModuleError(str(e))

        changes = self.changes.to_return()
        result.update(**changes)
        result.update(dict(changed=changed))
        return result

    def exists(self):
        result = self.client.api.tm.sys.application.services.service.exists(
            name=self.want.name,
            partition=self.want.partition
        )
        return result

    def present(self):
        if self.exists():
            return self.update()
        else:
            return self.create()

    def create(self):
        self._set_changed_options()
        if self.client.check_mode:
            return True
        self.create_on_device()
        return True

    def update(self):
        self.have = self.read_current_from_device()
        if not self.should_update() and not self.want.force:
            return False
        if self.client.check_mode:
            return True
        self.update_on_device()
        return True

    def should_update(self):
        result = self._update_changed_options()
        if result:
            return True
        return False

    def update_on_device(self):
        params = self.want.api_params()
        params['execute-action'] = 'definition'
        resource = self.client.api.tm.sys.application.services.service.load(
            name=self.want.name,
            partition=self.want.partition
        )
        resource.update(**params)

    def read_current_from_device(self):
        result = self.client.api.tm.sys.application.services.service.load(
            name=self.want.name,
            partition=self.want.partition
        ).to_dict()
        result.pop('_meta_data', None)
        return Parameters(result)

    def create_on_device(self):
        params = self.want.api_params()
        self.client.api.tm.sys.application.services.service.create(
            name=self.want.name,
            partition=self.want.partition,
            **params
        )

    def absent(self):
        if self.exists():
            return self.remove()
        return False

    def remove(self):
        if self.client.check_mode:
            return True
        self.remove_from_device()
        if self.exists():
            raise F5ModuleError("Failed to delete the iApp service")
        return True

    def remove_from_device(self):
        resource = self.client.api.tm.sys.application.services.service.load(
            name=self.want.name,
            partition=self.want.partition
        )
        if resource:
            resource.delete()

class ArgumentSpec(object):
    def __init__(self):
        self.supports_check_mode = True
        self.argument_spec = dict(
            name=dict(required=True),
            template=dict(),
            parameters=dict(
                type='dict'
            ),
            state=dict(
                default='present',
                choices=['absent', 'present']
            ),
            force=dict(
                default=False,
                type='bool'
            )
        )
        self.f5_product_name = 'bigip'

def main():
    if not HAS_F5SDK:
        raise F5ModuleError("The python f5-sdk module is required")

    spec = ArgumentSpec()

    client = AnsibleF5Client(
        argument_spec=spec.argument_spec,
        supports_check_mode=spec.supports_check_mode,
        f5_product_name=spec.f5_product_name
    )

    try:
        mm = ModuleManager(client)
        results = mm.exec_module()
        client.module.exit_json(**results)
    except F5ModuleError as e:
        client.module.fail_json(msg=str(e))

if __name__ == '__main__':
    main()


text:
package org.openengsb.core.api.security;

import java.security.PrivateKey;

/**
 * service that provides the servers private key to other osgi-services (like filters)
 */
public interface PrivateKeySource {

    PrivateKey getPrivateKey();

}


text:
import {createBrowserHistory, History, Location, LocationState} from 'history'

@provideSingleton(RouterStore)
export default class RouterStore {
  history: History
  @observable location: Location

  constructor () {
    this.history = createBrowserHistory()
    this._updateLocation(this.history.location)
    this.history.listen(this._updateLocation)
    this.push = this.push.bind(this)
    this.replace = this.replace.bind(this)
    this.go = this.go.bind(this)
    this.goBack = this.goBack.bind(this)
    this.goForward = this.goForward.bind(this)
  }

  @action.bound
  _updateLocation (location: Location) {
    this.location = location
  }

  push (path: string | Location, state?: LocationState) {
    if (typeof path === 'string') this.history.push(path, state)
    else this.history.push(path)
  }

  replace (path: string | Location, state?: LocationState) {
    if (typeof path === 'string') this.history.replace(path, state)
    else this.history.replace(path)
  }

  go (n: number) {
    this.history.go(n)
  }

  goBack () {
    this.history.goBack()
  }

  goForward () {
    this.history.goForward()
  }
}


text:
package mixcoin

import (
	"bytes"
	"crypto/rand"
	"encoding/json"
	"log"
	"math/big"
	"os"
	"strings"

	"code.google.com/p/go.crypto/openpgp"
	"code.google.com/p/go.crypto/openpgp/armor"
)

func randInt(high int) int {
	bigRet, err := rand.Int(rand.Reader, big.NewInt(int64(high)))
	if err != nil {
		log.Panicf("error generating random int: %v", err)
	}

	return int(bigRet.Int64())
}

func serialize(chunkMsg *ChunkMessage) string {
	marshaledBytes, _ := json.Marshal(chunkMsg)
	return string(marshaledBytes)
}

func signText(entity *openpgp.Entity, text string) string {
	b := bytes.NewBuffer(nil)
	w, _ := armor.Encode(b, openpgp.SignatureType, nil)
	err := openpgp.DetachSignText(w, entity, strings.NewReader(text), nil)
	if err != nil {
		panic(err)
	}
	w.Close()
	return b.String()
}

func verifySignature(pubKey, signed, signatureArmor string) bool {
	keyRing, err := openpgp.ReadArmoredKeyRing(strings.NewReader(pubKey))
	if err != nil {
		panic(err)
	}

	signer, err := openpgp.CheckArmoredDetachedSignature(
		keyRing,
		strings.NewReader(signed),
		strings.NewReader(signatureArmor),
	)
	if err != nil {
		panic(err)
	}
	return signer != nil
}

func getPgpEntity() *openpgp.Entity {
	keyringFileBuffer, err := os.Open(cfg.PrivRingFile)
	if err != nil {
		panic(err)
	}

	defer keyringFileBuffer.Close()

	entityList, err := openpgp.ReadKeyRing(keyringFileBuffer)
	if err != nil {
		panic(err)
	}
	entity := entityList[0]
	passphrasebyte := []byte(cfg.Passphrase)
	entity.PrivateKey.Decrypt(passphrasebyte)
	for _, subkey := range entity.Subkeys {
		subkey.PrivateKey.Decrypt(passphrasebyte)
	}
	return entity
}

func signChunkMessage(chunkMsg *ChunkMessage) {
	log.Printf("signing chunk message")

	entity := getPgpEntity()
	serialized := serialize(chunkMsg)
	signature := signText(entity, serialized)
	chunkMsg.Warrant = signature
}

// NOTE: not sure if this works (if setting Warrant to '' removes
// it from the json)
func verifyWarrant(chunkMsg *ChunkMessage, pubKey string) bool {
	warrant := chunkMsg.Warrant
	msgCopy := *chunkMsg
	msgCopy.Warrant = ""
	serialized := serialize(&msgCopy)

	return verifySignature(pubKey, serialized, warrant)
}


text:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Q42.HueApi
{
  /// <summary>
  ///  Partial HueClient, contains requests to the /api/ url
  /// </summary>
  public partial class HueClient
  {
    /// <summary>
    /// Register your <paramref name="applicationName"/> and <paramref name="deviceName"/> at the Hue Bridge.
    /// </summary>
    /// <param name="applicationName">The name of your app.</param>
    /// <param name="deviceName">The name of the device.</param>
    /// <returns>Secret key for the app to communicate with the bridge.</returns>
    /// <exception cref="ArgumentNullException"><paramref name="applicationName"/> or <paramref name="deviceName"/> is <c>null</c>.</exception>
    /// <exception cref="ArgumentException"><paramref name="applicationName"/> or <paramref name="deviceName"/> aren't long enough, are empty or contains spaces.</exception>
    public async Task<string> RegisterAsync(string applicationName, string deviceName)
    {
      if (applicationName == null)
        throw new ArgumentNullException("applicationName");
      if (applicationName.Trim() == String.Empty)
        throw new ArgumentException("applicationName must not be empty", "applicationName");
      if (applicationName.Length > 20)
        throw new ArgumentException("applicationName max is 20 characters.", "applicationName");
      if(applicationName.Contains(" "))
        throw new ArgumentException("Cannot contain spaces.", "applicationName");

      if (deviceName == null)
        throw new ArgumentNullException("deviceName");
      if (deviceName.Length < 0 || deviceName.Trim() == String.Empty)
        throw new ArgumentException("deviceName must be at least 0 characters.", "deviceName");
      if (deviceName.Length > 19)
        throw new ArgumentException("deviceName max is 19 characters.", "deviceName");
      if (deviceName.Contains(" "))
        throw new ArgumentException("Cannot contain spaces.", "deviceName");

      string fullName = string.Format("{0}#{1}", applicationName, deviceName);

      JObject obj = new JObject();
      obj["devicetype"] = fullName;

      HttpClient client = HueClient.GetHttpClient();
      var response = await client.PostAsync(new Uri(string.Format("http://{0}/api", _ip)), new StringContent(obj.ToString())).ConfigureAwait(false);
      var stringResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

      JObject result;
      try
      {
        JArray jresponse = JArray.Parse(stringResponse);
        result = (JObject)jresponse.First;
      }
      catch
      {
        //Not an expected response. Return response as exception
        throw new Exception(stringResponse);
      }

      JToken error;
      if (result.TryGetValue("error", out error))
      {
        if (error["type"].Value<int>() == 101) // link button not pressed
          throw new Exception("Link button not pressed");
        else
          throw new Exception(error["description"].Value<string>());
      }

      var key = result["success"]["username"].Value<string>();
      Initialize(key);

      return key;
    }

    public async Task<bool> CheckConnection()
    {
      HttpClient client = HueClient.GetHttpClient();

      try
      {
        //Check if there is a hue bridge on the specified IP by checking the content of description.xml
        var result = await client.GetAsync(string.Format("http://{0}/description.xml", _ip)).ConfigureAwait(false);
        if (result.IsSuccessStatusCode)
        {
          string res = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
          if (!string.IsNullOrWhiteSpace(res))
          {
            if (!res.ToLower().Contains("philips hue bridge"))
              return false;
          }
        }
        else
        {
          return false;
        }
      }
      catch(Exception e)
      {
        return false;
      }

      try
      {
        //Check if app is registered
        var test = await this.GetBridgeAsync().ConfigureAwait(false);
      }
      catch
      {
        return false;
      }

      return true;
    }
  }
}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Duracellko.PlanningPoker.Domain.Test
{
    [TestClass]
    public class EstimationParticipantStatusTest
    {
        [TestMethod]
        public void Constructor_MemberNameSpecified_MemberNameIsSet()
        {
            // Arrange
            var name = "Member";

            // Act
            var result = new EstimationParticipantStatus(name, false);

            // Verify
            Assert.AreEqual<string>(name, result.MemberName);
        }

        [TestMethod]
        public void Constructor_MemberNameNotSpecified_ArgumentNullException()
        {
            // Arrange
            string? name = null;

            // Act
            Assert.ThrowsException<ArgumentNullException>(() => new EstimationParticipantStatus(name!, false));
        }

        [TestMethod]
        public void Constructor_EstimatedSpecified_EstimatedIsSet()
        {
            // Arrange
            var estimated = true;

            // Act
            var result = new EstimationParticipantStatus("Member", estimated);

            // Verify
            Assert.IsTrue(estimated);
        }
    }
}


text:
class MusicPlayer : private sf::NonCopyable
{
public:
    MusicPlayer();
    void play(const std::string& filename);
    void stop();
    void setPaused(bool paused);
    void setVolume(float volume);
    float getVolume() const;
    sf::SoundSource::Status getStatus();
private:
    sf::Music mMusic;
    float mVolume;
};

#endif


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('products', '0031_buyers_to_customers'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='purchase',
            options={'verbose_name': 'Purchase', 'verbose_name_plural': 'Purchases'},
        ),
    ]


text: module.exports = require("npm:browserify-aes@1.0.6/browser");


text:
var vumigo = require('vumigo_v02');
var fixtures = require('./fixtures');
var AppTester = vumigo.AppTester;
var assert = require('assert');
var optoutstore = require('./optoutstore');
var DummyOptoutResource = optoutstore.DummyOptoutResource;
var _ = require('lodash');

describe("UoP TB app", function() {
    describe("for sms use", function() {
        var app;
        var tester;

        beforeEach(function() {
            app = new go.app.GoUOPBMOH();

            tester = new AppTester(app);

            tester
                .setup.char_limit(160)
                .setup.config.app({
                    name: 'smsapp',
                    testing_today: '2015-04-03 06:07:08.999',
                    metric_store: 'uopboh_test',  // _env at the end
                    services: {
                        hub: {
                            api_token: 'test_token',
                            url: "http://127.0.0.1:8000/"
                        }
                    }

                })
                .setup(function(api) {
                    api.resources.add(new DummyOptoutResource());
                    api.resources.attach(api);
                })
                .setup(function(api) {
                    api.metrics.stores = {'uopboh_test': {}};
                })
                .setup(function(api) {
                    fixtures().forEach(api.http.fixtures.add);
                })
        });

        describe("when the unknown user sends a 'STOP' message", function() {
            it("should optout and stop", function() {
                return tester
                    .setup.user.addr('064001')
                    .inputs('STOP')
                    // check navigation
                    .check.interaction({
                        state: 'state_stop_completed',
                        reply:
                            'Removed! You will no longer recieve messages from us.'
                    })
                    .run();
            });
        });

    });
});


text:
using System;
using System.Globalization;
using System.IO;
using Newtonsoft.Json;

namespace LeaSearch.Infrastructure.Storage
{
    /// <summary>
    /// Serialize object using json format.
    /// </summary>
    public class JsonStrorage<T>
    {
        protected readonly JsonSerializerSettings _serializerSettings;
        protected T _data;
        public const string FileSuffix = ".json";

        /// <summary>
        /// all info will write to this path
        /// </summary>
        public string FilePath { get; set; }

        public JsonStrorage()
        {
            // use property initialization instead of DefaultValueAttribute
            // easier and flexible for default value of object
            _serializerSettings = new JsonSerializerSettings
            {
                ObjectCreationHandling = ObjectCreationHandling.Replace,
                NullValueHandling = NullValueHandling.Ignore
            };
        }

        public T Load()
        {
            if (File.Exists(FilePath))
            {
                var searlized = File.ReadAllText(FilePath);
                if (!string.IsNullOrWhiteSpace(searlized))
                {
                    Deserialize(searlized);
                }
                else
                {
                    LoadDefault();
                }
            }
            else
            {
                LoadDefault();
            }
            return _data;
        }

        private void Deserialize(string searlized)
        {
            try
            {
                _data = JsonConvert.DeserializeObject<T>(searlized, _serializerSettings);
            }
            catch (JsonException e)
            {
                LoadDefault();
                Logger.Logger.Exception($"|JsonStrorage.Deserialize|Deserialize error for json <{FilePath}>", e);
            }

            if (_data == null)
            {
                LoadDefault();
            }
        }

        protected virtual void LoadDefault()
        {
            if (File.Exists(FilePath))
            {
                BackupOriginFile();
            }

            _data = JsonConvert.DeserializeObject<T>("{}", _serializerSettings);
            Save();
        }

        protected void BackupOriginFile()
        {
            var timestamp = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fffffff", CultureInfo.CurrentUICulture);
            var directory = Path.GetDirectoryName(FilePath);
            var originName = Path.GetFileNameWithoutExtension(FilePath);
            var backupName = $"{originName}-{timestamp}{FileSuffix}";
            var backupPath = Path.Combine(directory, backupName);
            File.Copy(FilePath, backupPath, true);
            // todo give user notification for the backup process
        }

        public void Save()
        {
            string serialized = JsonConvert.SerializeObject(_data, Formatting.Indented);
            File.WriteAllText(FilePath, serialized);
        }
    }
}


text:
using log4net;
using SysInfoInventryWinReg.Generic;
using System;
using System.IO;

namespace SysInfoInventryWinReg.Model
{
    /// <summary>
    /// The class is used as a filter  during the processing of xml config file data using
    /// </summary>
    public class ConfiguratorBaseConfig
    {
        /// <summary>
        /// Get the log instance for this class to create log.
        /// </summary>
        private static ILog logger = LogManager.GetLogger(typeof(ConfiguratorBaseConfig));

        /// <summary>
        /// Get or set if to use configurator or skip during the processing
        /// </summary>
        public bool UseConfigurator { get; set; }

        /// <summary>
        /// As cutomised set and get is not possible with auto properties
        /// </summary>
        protected string configPath;
        /// <summary>
        /// Get or set the relative path of the xml file to read
        /// </summary>
        public string ConfigPath
        {
            get { return configPath; }
            set { configPath = NormalizePath(value); }
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="useConfig">If to use the filter config or skip.</param>
        /// <param name="relPath">The relative path of config file. Relative to the current environment path or the application path.</param>
        public ConfiguratorBaseConfig(bool useConfig, string relPath)
        {
            UseConfigurator = useConfig;
            ConfigPath = NormalizePath(relPath);
        }

        /// <summary>
        /// Check and rationalize the path string to full path.
        /// If the path is relative then prepend the application path if not provided
        /// with root path.
        /// </summary>
        /// <param name="relPath"></param>
        /// <returns></returns>
        private string NormalizePath(string relPath)
        {
            if (System.IO.Path.IsPathRooted(relPath) == false)
                return Path.Combine(ConstantsConfig.ApplicationPath, relPath);

            return relPath;
        }

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="useConfig">If to use the filter config or skip.</param>
        public ConfiguratorBaseConfig(bool useConfig) : this(useConfig, string.Empty) { }

        /// <summary>
        /// Default constructor
        /// </summary>
        /// <param name="relPath">The relative path of config file. Relative to the current environment path or the application path.</param>
        public ConfiguratorBaseConfig(string relPath) : this(true, relPath) { }

        /// <summary>
        /// Default constructor
        /// </summary>
        public ConfiguratorBaseConfig() : this(true, string.Empty) { }

        /// <summary>
        /// Manipulated property to check if the config file is to be read as a normal file or as partial
        /// </summary>
        public virtual bool IsConfigReadAsNormalFile
        {
            get
            {
                if (string.IsNullOrEmpty(this.ConfigPath) == true)
                {
                    logger.Fatal("No config file provided to read");
                    throw new ArgumentNullException("RelativePath");
                }

                System.IO.FileInfo fiInfo = new System.IO.FileInfo(this.ConfigPath);
                return ((fiInfo.Length / 1024.0) <= ConstantsConfig.LimitXmlFileReadKB);
            }
        }

        /// <summary>
        /// Manipulated property to check if the config file is to be read as a partial
        /// </summary>
        public virtual bool IsConfigReadAsPartialFile
        {
            get
            {
                return false;
            }
        }
    }
}


text:
#include "qminimalwindowsurface.h"
#include <QtCore/qdebug.h>
#include <QtGui/private/qapplication_p.h>

QT_BEGIN_NAMESPACE

QMinimalWindowSurface::QMinimalWindowSurface(QWidget *window)
    : QWindowSurface(window)
{
    //qDebug() << "QMinimalWindowSurface::QMinimalWindowSurface:" << (long)this;
}

QMinimalWindowSurface::~QMinimalWindowSurface()
{
}

QPaintDevice *QMinimalWindowSurface::paintDevice()
{
    //qDebug() << "QMinimalWindowSurface::paintDevice";
    return &mImage;
}

void QMinimalWindowSurface::flush(QWidget *widget, const QRegion &region, const QPoint &offset)
{
    Q_UNUSED(widget);
    Q_UNUSED(region);
    Q_UNUSED(offset);

    static int c = 0;
    QString filename = QString("output%1.png").arg(c++, 4, 10, QLatin1Char('0'));
    qDebug() << "QMinimalWindowSurface::flush() saving contents to" << filename.toLocal8Bit().constData();
    mImage.save(filename);
}

void QMinimalWindowSurface::resize(const QSize &size)
{
    //qDebug() << "QMinimalWindowSurface::setGeometry:" << (long)this << rect;
    QWindowSurface::resize(size);
    QImage::Format format = QApplicationPrivate::platformIntegration()->screens().first()->format();
    if (mImage.size() != size)
        mImage = QImage(size, format);
}

QT_END_NAMESPACE


text:
<?php

/**
 * This file is part of the BEAR.JwtAuthModule package.
 *
 * @license http://opensource.org/licenses/MIT MIT
 */
namespace BEAR\JwtAuth\Extractor;

use Aura\Web\Request;
use BEAR\JwtAuth\Annotation\Cookie;

class CookieTokenExtractor implements TokenExtractorInterface
{
    /**
     * @var string
     */
    private $cookie;

    /**
     * @var Request
     */
    private $request;

    /**
     * @Cookie("cookie")
     */
    public function __construct(string $cookie, Request $request)
    {
        $this->cookie = $cookie;
        $this->request = $request;
    }

    public function extract() : string
    {
        return $this->request->cookies->get($this->cookie) ?? '';
    }
}


text:
import sys
from sqlalchemy import create_engine
import pandas as pd

def import_csv(dbname, f):
        chunks = 20000
        j=0
        index_start = 1
        engine = create_engine('postgresql://lauren:llc@localhost:5432/police')
        for df in pd.read_csv(f, chunksize = chunks, iterator=True, encoding='utf-8'):
                df.index += index_start
                j+=1
                print("completed {} rows".format(j*chunks))
                df.to_sql(dbname, engine, if_exists='append')
                index_start = df.index[-1] + 1

if __name__=="__main__":
        dbname = sys.argv[1]
        f = sys.argv[2]
        import_csv(dbname, f)


text:
<md-menu>
  <md-button class="downArrow historyButton" aria-label="Open menu with custom trigger" ng-click="$mdMenu.open()"  ng-disabled="vizHistory.length == 0">
  </md-button>
  <md-menu-content width="2" ng-click="$mdMenu.close()">
    <md-menu-item ng-repeat="viz in vizHistory">
      <md-button ng-click="getSelectedViz(viz)">
        {{viz.historyTitle}}
      </md-button>
    </md-menu-item>
  </md-menu-content>
</md-menu>


text:
package org.Webgatherer.CoreEngine.Core.ThreadCommunication;

import java.util.Map;
import java.util.Queue;

/**
 * @author Rick Dane
 */
public interface ThreadCommunication {

    public void setThreadIdentifier(String identifier);

    public void setShouldBeRunning(boolean status);

    public boolean isOutputDataHolderEmpty();

    public void setPageQueue(Queue pageQueue);

    /**
     * the thread can check this to gracefully "shutdown" itself if set to false
     *
     * @return
     */
    public Boolean shouldBeRunning();

    public void addToOutputDataHolder(String[] string);

    public void addToSendbackDataHolder(String[] string);

    public boolean isSendbackDataHolderEmpty();

    public String[] getFromSendbackDataHolder();

    public boolean isPageQueueEmpty();

    public String[] getFromPageQueue();

    public String[] getFromOutputDataHolder();

    /**
     * Sets an object into the local hashmap for storing custom objects, these objects are ONLY meant for use
     * within workflows as they are inherently error prone due to lack of generics
     *
     * @param key
     * @param obj
     */
    public void setCustomDataMapElement(String key, Object obj);

    public Object getCustomDataMapElement(String key);

    public Map<String, Object> getCustomDataMap();

    public void setCustomDataMap(Map map);

    public void addToPageQueue(String[] page);

    public boolean isWebGathererThreadFinished();

    public void setIsWebGathererThreadFinished(boolean value);
}


text:
package proguard.classfile.visitor;

import proguard.classfile.*;

/**
 * This class visits ProgramMember objects referring to methods, identified by
 * a name and descriptor pair.
 *
 * @author Eric Lafortune
 */
public class NamedMethodVisitor implements ClassVisitor
{
    private final String        name;
    private final String        descriptor;
    private final MemberVisitor memberVisitor;

    public NamedMethodVisitor(String        name,
                              String        descriptor,
                              MemberVisitor memberVisitor)
    {
        this.name          = name;
        this.descriptor    = descriptor;
        this.memberVisitor = memberVisitor;
    }

    // Implementations for ClassVisitor.

    public void visitProgramClass(ProgramClass programClass)
    {
        programClass.methodAccept(name, descriptor, memberVisitor);
    }

    public void visitLibraryClass(LibraryClass libraryClass)
    {
        libraryClass.methodAccept(name, descriptor, memberVisitor);
    }
}


text:
def fmt_pci_address(pci_device):
    # type: (dict) -> str
    domain = pci_device['domain'] if 'domain' in pci_device else 0
    return "%s:%s:%s.%s" % (format(domain, '04x'),
                            format(pci_device['bus'], '02x'),
                            format(pci_device['slot'], '02x'),
                            format(pci_device['function'], 'x'))


text:
(function() {
	'use strict';

	angular
		.module('catalogue.favorites')
		.controller('FavoritesController', FavoritesController);

	FavoritesController.$inject = ['businessInfo', '$state', 'favoritesService', 'favoritesSenderService'];

	/* @ngInject */
	function FavoritesController(businessInfo, $state, favoritesService, favoritesSenderService) {
		var vm = angular.extend(this, {
			items: [],
			deleteItem: deleteItem,
			sendFavorites: sendFavorites,
			showProductDetails: showProductDetails
		});

		(function activate() {
			loadItems();
		})();

		// ********************************************************************

		function loadItems() {
			vm.items = favoritesService.getAll();
		}

		function deleteItem(item) {
			favoritesService.deleteItem(item.guid);
			loadItems();
		}

		function sendFavorites() {
			favoritesSenderService.sendFavorites(businessInfo.email, vm.items);
		}

		function showProductDetails(product) {
			$state.go('app.product', {
				productId: product.guid,
				categoryId: product.categoryId
			});
		}
	}
})();