text:
<?php
namespace Aws\Token;

use Aws;
use Aws\Api\DateTimeResult;
use Aws\CacheInterface;
use Aws\Exception\TokenException;
use GuzzleHttp\Promise;

/**
 * Token providers are functions that accept no arguments and return a
 * promise that is fulfilled with an {@see \Aws\Token\TokenInterface}
 * or rejected with an {@see \Aws\Exception\TokenException}.
 *
 * <code>
 * use Aws\Token\TokenProvider;
 * $provider = TokenProvider::defaultProvider();
 * // Returns a TokenInterface or throws.
 * $token = $provider()->wait();
 * </code>
 *
 * Token providers can be composed to create a token using conditional
 * logic that can create different tokens in different environments. You
 * can compose multiple providers into a single provider using
 * {@see Aws\Token\TokenProvider::chain}. This function accepts
 * providers as variadic arguments and returns a new function that will invoke
 * each provider until a token is successfully returned.
 */
class TokenProvider
{
    use ParsesIniTrait;
    const ENV_PROFILE = 'AWS_PROFILE';

    /**
     * Create a default token provider tha checks for cached a SSO token from
     * the CLI
     *
     * This provider is automatically wrapped in a memoize function that caches
     * previously provided tokens.
     *
     * @param array $config Optional array of token provider options.
     *
     * @return callable
     */
    public static function defaultProvider(array $config = [])
    {

        $cacheable = [
            'sso',
        ];

        $defaultChain = [];

        if (
            !isset($config['use_aws_shared_config_files'])
            || $config['use_aws_shared_config_files'] !== false
        ) {
            $profileName = getenv(self::ENV_PROFILE) ?: 'default';
            $defaultChain['sso'] = self::sso(
                $profileName,
                self::getHomeDir() . '/.aws/config',
                $config
            );
        }

        if (isset($config['token'])
            && $config['token'] instanceof CacheInterface
        ) {
            foreach ($cacheable as $provider) {
                if (isset($defaultChain[$provider])) {
                    $defaultChain[$provider] = self::cache(
                        $defaultChain[$provider],
                        $config['token'],
                        'aws_cached_' . $provider . '_token'
                    );
                }
            }
        }

        return self::memoize(
            call_user_func_array(
                [TokenProvider::class, 'chain'],
                array_values($defaultChain)
            )
        );
    }

    /**
     * Create a token provider function from a static token.
     *
     * @param TokenInterface $token
     *
     * @return callable
     */
    public static function fromToken(TokenInterface $token)
    {
        $promise = Promise\Create::promiseFor($token);

        return function () use ($promise) {
            return $promise;
        };
    }

    /**
     * Creates an aggregate token provider that invokes the provided
     * variadic providers one after the other until a provider returns
     * a token.
     *
     * @return callable
     */
    public static function chain()
    {
        $links = func_get_args();
        //Common use case for when aws_shared_config_files is false
        if (empty($links)) {
            return function () {
                return Promise\Create::promiseFor(false);
            };
        }

        return function () use ($links) {
            /** @var callable $parent */
            $parent = array_shift($links);
            $promise = $parent();
            while ($next = array_shift($links)) {
                $promise = $promise->otherwise($next);
            }
            return $promise;
        };
    }

    /**
     * Wraps a token provider and caches a previously provided token.
     * Ensures that cached tokens are refreshed when they expire.
     *
     * @param callable $provider Token provider function to wrap.
     * @return callable
     */
    public static function memoize(callable $provider)
    {
        return function () use ($provider) {
            static $result;
            static $isConstant;

            // Constant tokens will be returned constantly.
            if ($isConstant) {
                return $result;
            }

            // Create the initial promise that will be used as the cached value
            // until it expires.
            if (null === $result) {
                $result = $provider();
            }

            // Return a token that could expire and refresh when needed.
            return $result
                ->then(function (TokenInterface $token) use ($provider, &$isConstant, &$result) {
                    // Determine if the token is constant.
                    if (!$token->getExpiration()) {
                        $isConstant = true;
                        return $token;
                    }

                    if (!$token->isExpired()) {
                        return $token;
                    }
                    return $result = $provider();
                })
                ->otherwise(function($reason) use (&$result) {
                    // Cleanup rejected promise.
                    $result = null;
                    return Promise\Create::promiseFor(null);
                });
        };
    }

    /**
     * Wraps a token provider and saves provided token in an
     * instance of Aws\CacheInterface. Forwards calls when no token found
     * in cache and updates cache with the results.
     *
     * @param callable $provider Token provider function to wrap
     * @param CacheInterface $cache Cache to store the token
     * @param string|null $cacheKey (optional) Cache key to use
     *
     * @return callable
     */
    public static function cache(
        callable $provider,
        CacheInterface $cache,
        $cacheKey = null
    ) {
        $cacheKey = $cacheKey ?: 'aws_cached_token';

        return function () use ($provider, $cache, $cacheKey) {
            $found = $cache->get($cacheKey);
            if (is_array($found) && isset($found['token'])) {
                if (isset($found['token']) && $found['token'] instanceof TokenInterface) {
                    $foundToken = $found['token'];
                    if (!$foundToken->isExpired()) {
                        return Promise\Create::promiseFor($foundToken);
                    }
                    if (isset($found['refreshMethod']) && is_callable($found['refreshMethod'])) {
                        return Promise\Create::promiseFor($found['refreshMethod']());
                    }
                }
            }

            return $provider()
                ->then(function (TokenInterface $token) use (
                    $cache,
                    $cacheKey
                ) {
                    $cache->set(
                        $cacheKey,
                        $token,
                        null === $token->getExpiration() ?
                            0 : $token->getExpiration() - time()
                    );

                    return $token;
                });
        };
    }

    /**
     * Gets profiles from the ~/.aws/config ini file
     */
    private static function loadDefaultProfiles() {
        $profiles = [];
        $configFile = self::getHomeDir() . '/.aws/config';

        if (file_exists($configFile)) {
            $configProfileData = \Aws\parse_ini_file($configFile, true, INI_SCANNER_RAW);
            foreach ($configProfileData as $name => $profile) {
                // standardize config profile names
                $name = str_replace('profile ', '', $name);
                if (!isset($profiles[$name])) {
                    $profiles[$name] = $profile;
                }
            }
        }

        return $profiles;
    }

    private static function reject($msg)
    {
        return new Promise\RejectedPromise(new TokenException($msg));
    }

    /**
     * Token provider that creates a token from cached sso credentials
     *
     * @param string $ssoProfileName the name of the ini profile name
     * @param string $filename the location of the ini file
     * @param array $config configuration options
     *
     * @return SsoToken
     * @see Aws\Token\SsoToken for $config details.
     */
    public static function sso($profileName, $filename, $config = [])
    {
        return new SsoTokenProvider($profileName, $filename, $config);
    }
}


text:
.class public Ljava/net/SocketUtils;
.super Ljava/lang/Object;
.source "SocketUtils.java"

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 33
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method public static setCreated(Ljava/net/Socket;)V
    .locals 1
    .param p0, "s"    # Ljava/net/Socket;

    .prologue
    .line 30
    const/4 v0, 0x1

    iput-boolean v0, p0, Ljava/net/Socket;->isCreated:Z

    .line 31
    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
MapViewer = function(){
	_this = this;
	_this.ViewModel = null;
	_this.FindLatestTimer = null;
	_this.IsBuilding = false;
	_this.Hash = null;
	_this.HashCompare = null;
	_this.MapSelector = "#CombatViewModel";

	_this.FindLatest = function() {
		HashCompare = localStorage.getItem("MAPVIEW-Hash");
		if(HashCompare !== null && _this.Hash != HashCompare){
			//console.log("Update Found", hash);
			_this.BuildMap(HashCompare);
		}
	};

	_this.BuildMap = function(hash) {
		if(!_this.IsBuilding){
			//console.log("Building");
			_this.IsBuilding = true;
			try {
				var combatObj = JSON.parse(localStorage.getItem("MAPVIEW-ViewModel"));
				if(combatObj) {
					_this.ViewModel.Load(combatObj);
					WORKSPACE.GridMap.setZoom(combatObj.GridZoom || 1);
					WORKSPACE.GridMap.panTo(combatObj.GridCenter || [0,0]);

					if(!combatObj.ShowDarkness) {
						var canvas = $("#grid-light")[0],
							ctx = canvas.getContext('2d');
						ctx.clearRect(0, 0, canvas.width, canvas.height);
					}

					if(!combatObj.ShowFog) {
						var canvas = $("#grid-fog")[0],
							ctx = canvas.getContext('2d');
						ctx.clearRect(0, 0, canvas.width, canvas.height);
					} else {
						WORKSPACE.Helpers.DrawFog();
					}
				}
			} catch(e) {
				console.log(e);
			}
			_this.Hash = hash;
			_this.IsBuilding = false;
		}
	};

	_this.Init = function() {
		WORKSPACE.ViewModels.CombatViewModel = _this.ViewModel = new CombatViewModel();
		ko.applyBindings(_this.ViewModel, $(_this.MapSelector)[0]);
		_this.FindLatestTimer = setInterval(_this.FindLatest, 25);
	};
};

$(function() {
	var MAP = new MapViewer();
	WORKSPACE.Shim();
	WORKSPACE.IsLoaded = true;
	MAP.Init();
});


text:
package tz.gzu.oip.admin.controller.sp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tz.gzu.oip.admin.dto.sp.ShopGroupBuyDto;
import tz.gzu.oip.dm.po.Shopgroupbuy;
import tz.gzu.oip.dm.service.sp.ShopgroupbuyService;

import java.sql.Timestamp;
import java.util.List;

@RestController
@RequestMapping("groupBuying")
public class GroupBuyingController {

    @Autowired
    private ShopgroupbuyService shopgroupbuyService;

    @GetMapping("/{cPage}/{pSize}")
    public ShopGroupBuyDto getAllGroupBuy(@PathVariable int cPage,@PathVariable int pSize){
        List<Shopgroupbuy> shopGroupBuy = shopgroupbuyService.findAllGroupBuy(cPage,pSize);
        int count = shopgroupbuyService.count();
        return new ShopGroupBuyDto(shopGroupBuy,count);
    }

    @PutMapping
    public void addGroupBuy(@RequestBody Shopgroupbuy shopgroupbuy){
        System.out.println(shopgroupbuy.getGpprice());
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        if(ts.before(shopgroupbuy.getStarttime())){
            shopgroupbuy.setIs_start(0);
        }else if(ts.after(shopgroupbuy.getStarttime()) && ts.before(shopgroupbuy.getEndtime())){
            shopgroupbuy.setIs_start(1);
        }else if(ts.after(shopgroupbuy.getEndtime())){
            shopgroupbuy.setIs_start(2);
        }
        this.shopgroupbuyService.insert(shopgroupbuy);
    }

    @PostMapping
    public void modifyShopGroupBuy(@RequestBody Shopgroupbuy shopgroupbuy){
        System.out.println(shopgroupbuy.getGpprice());
        this.shopgroupbuyService.update(shopgroupbuy);
    }

    @DeleteMapping("/{gpid}")
    public void deleteShopGroupBuy(@PathVariable Integer gpid){ this.shopgroupbuyService.delete(gpid); }
}


text:
namespace chrono {
namespace vehicle {
namespace fmtv {

const double FMTV_BrakeSimple::m_maxtorque = 7500;

FMTV_BrakeSimple::FMTV_BrakeSimple(const std::string& name) : ChBrakeSimple(name) {}

}  // namespace fmtv
}  // end namespace vehicle
}  // end namespace chrono


text:
require 'spec_helper'

describe Task do
  let(:task) { Task.new }

  it { should respond_to(:description) }

  describe "#description is not" do
    before { task.description = nil }
    it { should_not be_valid }
  end
end


text:
package com.google.firebase.udacity.friendlychat;

import android.net.Uri;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.firebase.ui.auth.AuthUI;

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

/**
 * Created by Eduard on 14/04/2017.
 */

public class ChatFragment extends Fragment implements IView {

    public static final String TAG = "ChatFragment";

    private static final int RC_SIGN_IN = 1;
    private static final int RC_PHOTO_PICKER = 2;

    private ListView mMessageListView;
    private ProgressBar mProgressBar;
    private ImageButton mPhotoPickerButton;
    private EditText mMessageEditText;
    private Button mSendButton;
    private MessageAdapter mMessageAdapter;

    private IPresenter mPresenter;

    public ChatFragment() { }

    public static ChatFragment newInstance() {
        return new ChatFragment();
    }

    @Override
    public void setPresenter(@NonNull IPresenter presenter) {
        this.mPresenter = presenter;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        List<FriendlyMessage> friendlyMessages = new ArrayList<>();
        Context context = getActivity().getApplicationContext();
        mMessageAdapter = new MessageAdapter(context, R.layout.item_message, friendlyMessages);
    }

    @Override
    public void onPause() {
        super.onPause();
        mPresenter.pause();
        mMessageAdapter.clear();
    }

    @Override
    public void onResume() {
        super.onResume();
        mPresenter.start();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.chat_frag, container, false);

        // Initialize references to views
        mProgressBar = (ProgressBar) root.findViewById(R.id.progressBar);
        mMessageListView = (ListView) root.findViewById(R.id.messageListView);
        mPhotoPickerButton = (ImageButton) root.findViewById(R.id.photoPickerButton);
        mMessageEditText = (EditText) root.findViewById(R.id.messageEditText);
        mSendButton = (Button) root.findViewById(R.id.sendButton);

        mMessageListView.setAdapter(mMessageAdapter);

        // Initialize progress bar
        mProgressBar.setVisibility(ProgressBar.INVISIBLE);

        // ImagePickerButton shows an image picker to upload a image for a message
        mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/jpeg");
                intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
                startActivityForResult(
                        Intent.createChooser(intent, "Complete action using"),
                        RC_PHOTO_PICKER);
            }
        });

        // Enable Send button when there's text to send
        mMessageEditText.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.toString().trim().length() > 0) {
                    mSendButton.setEnabled(true);
                } else {
                    mSendButton.setEnabled(false);
                }
            }

            public void afterTextChanged(Editable editable) { }
        });
        mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(IRepository.DEFAULT_MSG_LENGTH_LIMIT)});

        // Send button sends a message and clears the EditText
        mSendButton.setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View view) {
                String textMsg = mMessageEditText.getText().toString();
                mPresenter.addNewMessage(textMsg);
                // Clear input box
                mMessageEditText.setText("");
            }
        });

        setHasOptionsMenu(true);

        return root;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            if (resultCode == MainActivity.RESULT_OK) {
                Toast.makeText(getActivity(), "Signed in", Toast.LENGTH_SHORT).show();
            } else if (resultCode == MainActivity.RESULT_CANCELED) {
                Toast.makeText(getActivity(), "Signed in cancel", Toast.LENGTH_SHORT).show();
                getActivity().finish();
            }
        }
        else if (requestCode == RC_PHOTO_PICKER && resultCode == MainActivity.RESULT_OK) {
            Uri selectImageUrl = data.getData();
            mPresenter.addNewMessage(selectImageUrl);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.main_menu, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.sign_out_menu:
                // sign out for firebase authentication
                AuthUI.getInstance().signOut(getActivity());
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    // IView methods
    @Override
    public void clearAllMessage() {
        mMessageAdapter.clear();
    }

    @Override
    public void newMessage(FriendlyMessage msg) {
        mMessageAdapter.add(msg);
    }

    @Override
    public void notifyUser(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void requestAuthentication() {
        startActivityForResult(
                AuthUI.getInstance()
                        .createSignInIntentBuilder()
                        .setIsSmartLockEnabled(false)
                        .setProviders(
                                AuthUI.EMAIL_PROVIDER,
                                AuthUI.GOOGLE_PROVIDER)
                        .build(),
                RC_SIGN_IN);
    }

    @Override
    public void updateMsgLength(int length) {
        mMessageEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(length)});
    }
}


text:
package org.elasticsearch.action.admin.cluster.snapshots.get;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.snapshots.Snapshot;
import org.elasticsearch.snapshots.SnapshotFeatureInfo;
import org.elasticsearch.snapshots.SnapshotFeatureInfoTests;
import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.snapshots.SnapshotInfo;
import org.elasticsearch.snapshots.SnapshotInfoTestUtils;
import org.elasticsearch.snapshots.SnapshotShardFailure;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xcontent.ToXContent;
import org.elasticsearch.xcontent.XContentParser;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Predicate;
import java.util.regex.Pattern;

import static org.elasticsearch.snapshots.SnapshotInfo.INDEX_DETAILS_XCONTENT_PARAM;
import static org.elasticsearch.test.AbstractXContentTestCase.xContentTester;
import static org.hamcrest.CoreMatchers.containsString;

public class GetSnapshotsResponseTests extends ESTestCase {
    // We can not subclass AbstractSerializingTestCase because it
    // can only be used for instances with equals and hashCode
    // GetSnapshotResponse does not override equals and hashCode.
    // It does not override equals and hashCode, because it
    // contains ElasticsearchException, which does not override equals and hashCode.

    private GetSnapshotsResponse doParseInstance(XContentParser parser) throws IOException {
        return GetSnapshotsResponse.fromXContent(parser);
    }

    private GetSnapshotsResponse copyInstance(GetSnapshotsResponse instance) throws IOException {
        return copyInstance(
            instance,
            new NamedWriteableRegistry(Collections.emptyList()),
            (out, value) -> value.writeTo(out),
            GetSnapshotsResponse::new,
            Version.CURRENT
        );

    }

    private void assertEqualInstances(GetSnapshotsResponse expectedInstance, GetSnapshotsResponse newInstance) {
        assertEquals(expectedInstance.getSnapshots(), newInstance.getSnapshots());
        assertEquals(expectedInstance.next(), newInstance.next());
        assertEquals(expectedInstance.getFailures().keySet(), newInstance.getFailures().keySet());
        for (Map.Entry<String, ElasticsearchException> expectedEntry : expectedInstance.getFailures().entrySet()) {
            ElasticsearchException expectedException = expectedEntry.getValue();
            ElasticsearchException newException = newInstance.getFailures().get(expectedEntry.getKey());
            assertThat(newException.getMessage(), containsString(expectedException.getMessage()));
        }
    }

    private List<SnapshotInfo> createSnapshotInfos(String repoName) {
        ArrayList<SnapshotInfo> snapshots = new ArrayList<>();
        final int targetSize = between(5, 10);
        for (int i = 0; i < targetSize; ++i) {
            SnapshotId snapshotId = new SnapshotId("snapshot " + i, UUIDs.base64UUID());
            String reason = randomBoolean() ? null : "reason";
            ShardId shardId = new ShardId("index", UUIDs.base64UUID(), 2);
            List<SnapshotShardFailure> shardFailures = Collections.singletonList(new SnapshotShardFailure("node-id", shardId, "reason"));
            List<SnapshotFeatureInfo> featureInfos = randomList(5, SnapshotFeatureInfoTests::randomSnapshotFeatureInfo);
            snapshots.add(
                new SnapshotInfo(
                    new Snapshot(repoName, snapshotId),
                    Arrays.asList("index1", "index2"),
                    Collections.singletonList("ds"),
                    featureInfos,
                    reason,
                    System.currentTimeMillis(),
                    randomIntBetween(2, 3),
                    shardFailures,
                    randomBoolean(),
                    SnapshotInfoTestUtils.randomUserMetadata(),
                    System.currentTimeMillis(),
                    SnapshotInfoTestUtils.randomIndexSnapshotDetails()
                )
            );
        }
        return snapshots;
    }

    private GetSnapshotsResponse createTestInstance() {
        Set<String> repositories = new HashSet<>();
        Map<String, ElasticsearchException> failures = new HashMap<>();
        List<SnapshotInfo> responses = new ArrayList<>();

        for (int i = 0; i < randomIntBetween(0, 5); i++) {
            String repository = randomValueOtherThanMany(repositories::contains, () -> randomAlphaOfLength(10));
            repositories.add(repository);
            responses.addAll(createSnapshotInfos(repository));
        }

        for (int i = 0; i < randomIntBetween(0, 5); i++) {
            String repository = randomValueOtherThanMany(repositories::contains, () -> randomAlphaOfLength(10));
            repositories.add(repository);
            failures.put(repository, new ElasticsearchException(randomAlphaOfLength(10)));
        }

        return new GetSnapshotsResponse(
            responses,
            failures,
            randomBoolean()
                ? Base64.getUrlEncoder()
                    .encodeToString(
                        (randomAlphaOfLengthBetween(1, 5) + "," + randomAlphaOfLengthBetween(1, 5) + "," + randomAlphaOfLengthBetween(1, 5))
                            .getBytes(StandardCharsets.UTF_8)
                    )
                : null,
            randomIntBetween(responses.size(), responses.size() + 100),
            randomIntBetween(0, 100)
        );
    }

    public void testSerialization() throws IOException {
        GetSnapshotsResponse testInstance = createTestInstance();
        GetSnapshotsResponse deserializedInstance = copyInstance(testInstance);
        assertEqualInstances(testInstance, deserializedInstance);
    }

    public void testFromXContent() throws IOException {
        // Explicitly include the index details, excluded by default, since this is required for a faithful round-trip
        final ToXContent.MapParams params = new ToXContent.MapParams(Map.of(INDEX_DETAILS_XCONTENT_PARAM, "true"));

        // Don't inject random fields into the custom snapshot metadata, because the metadata map is equality-checked after doing a
        // round-trip through xContent serialization/deserialization. Even though the rest of the object ignores unknown fields,
        // `metadata` doesn't ignore unknown fields (it just includes them in the parsed object, because the keys are arbitrary),
        // so any new fields added to the metadata before it gets deserialized that weren't in the serialized version will
        // cause the equality check to fail.
        //
        // Also don't inject random junk into the index details section, since this is keyed by index name but the values
        // are required to be a valid IndexSnapshotDetails
        //
        // The actual fields are nested in an array, so this regex matches fields with names of the form
        // `snapshots.3.metadata`
        final Predicate<String> predicate = Pattern.compile("snapshots\\.\\d+\\.metadata.*")
            .asMatchPredicate()
            .or(Pattern.compile("snapshots\\.\\d+\\.index_details").asMatchPredicate())
            .or(Pattern.compile("failures\\.*").asMatchPredicate());
        xContentTester(this::createParser, this::createTestInstance, params, this::doParseInstance).numberOfTestRuns(1)
            .supportsUnknownFields(true)
            .shuffleFieldsExceptions(Strings.EMPTY_ARRAY)
            .randomFieldsExcludeFilter(predicate)
            .assertEqualsConsumer(this::assertEqualInstances)
            // We set it to false, because GetSnapshotsResponse contains
            // ElasticsearchException, whose xContent creation/parsing are not stable.
            .assertToXContentEquivalence(false)
            .test();
    }

}


text:
package sk.atris.netxms.confrepo.service.supplier;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import sk.atris.netxms.confrepo.enums.NetxmsConfigSections;
import sk.atris.netxms.confrepo.model.entities.configItem.*;
import sk.atris.netxms.confrepo.model.netxmsConfig.NetxmsConfigRepository;

import java.util.List;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class AvailableItemsSupplier {
    @Getter
    private static final AvailableItemsSupplier instance = new AvailableItemsSupplier();

    private final JsonNodeFactory jsonFactory = JsonNodeFactory.instance;

    public String getAllAvailableItemsJson(NetxmsConfigRepository netxmsConfig) {
        ObjectNode allItemsJson = jsonFactory.objectNode();

        log.debug("Starting to prepare all available items JSON.");

        for (DciSummaryTable item : netxmsConfig.getRepository(DciSummaryTable.class).getShallowCopy()) {
            ArrayNode thisItemsRevisions = getItemRevisionsForJson(item);

            ObjectNode thisItemJson = jsonFactory.objectNode();
            thisItemJson.put("title", item.getTitle());
            thisItemJson.set("instances", thisItemsRevisions);

            allItemsJson.with(NetxmsConfigSections.DCI_SUMMARY_TABLES.toString()).set(item.getGuid(), thisItemJson);
        }

        for (EppRule item : netxmsConfig.getRepository(EppRule.class).getShallowCopy()) {
            ArrayNode thisItemsRevisions = getItemRevisionsForJson(item);

            ObjectNode thisItemJson = jsonFactory.objectNode();
            thisItemJson.put("comments", item.getComment());
            thisItemJson.set("instances", thisItemsRevisions);

            allItemsJson.with(NetxmsConfigSections.RULES.toString()).set(item.getGuid(), thisItemJson);
        }

        for (Event item : netxmsConfig.getRepository(Event.class).getShallowCopy()) {
            ArrayNode thisItemsRevisions = getItemRevisionsForJson(item);

            ObjectNode thisItemJson = jsonFactory.objectNode();
            thisItemJson.put("name", item.getName());
            thisItemJson.set("instances", thisItemsRevisions);

            allItemsJson.with(NetxmsConfigSections.EVENTS.toString()).set(item.getGuid(), thisItemJson);
        }

        for (ObjectTool item : netxmsConfig.getRepository(ObjectTool.class).getShallowCopy()) {
            ArrayNode thisItemsRevisions = getItemRevisionsForJson(item);

            ObjectNode thisItemJson = jsonFactory.objectNode();
            thisItemJson.put("name", item.getName());
            thisItemJson.set("instances", thisItemsRevisions);

            allItemsJson.with(NetxmsConfigSections.OBJECT_TOOLS.toString()).set(item.getGuid(), thisItemJson);
        }

        for (Script item : netxmsConfig.getRepository(Script.class).getShallowCopy()) {
            ArrayNode thisItemsRevisions = getItemRevisionsForJson(item);

            ObjectNode thisItemJson = jsonFactory.objectNode();
            thisItemJson.put("name", item.getName());
            thisItemJson.set("instances", thisItemsRevisions);

            allItemsJson.with(NetxmsConfigSections.SCRIPTS.toString()).set(item.getGuid(), thisItemJson);
        }

        for (Template item : netxmsConfig.getRepository(Template.class).getShallowCopy()) {
            ArrayNode thisItemsRevisions = getItemRevisionsForJson(item);

            ObjectNode thisItemJson = jsonFactory.objectNode();
            thisItemJson.put("name", item.getName());
            thisItemJson.set("instances", thisItemsRevisions);

            allItemsJson.with(NetxmsConfigSections.TEMPLATES.toString()).set(item.getGuid(), thisItemJson);
        }

        for (Trap item : netxmsConfig.getRepository(Trap.class).getShallowCopy()) {
            ArrayNode thisItemsRevisions = getItemRevisionsForJson(item);

            ObjectNode thisItemJson = jsonFactory.objectNode();
            thisItemJson.put("description", item.getDescription());
            thisItemJson.set("instances", thisItemsRevisions);

            allItemsJson.with(NetxmsConfigSections.TRAPS.toString()).set(item.getGuid(), thisItemJson);
        }

        log.debug("Finished preparing all available items JSON.");
        return allItemsJson.toString();
    }

    private <T extends ConfigItem> ArrayNode getItemRevisionsForJson(T item) {
        List<ItemRevision> revisions = item.getRevisionsShallowCopy();
        ArrayNode revisionsJson = jsonFactory.arrayNode();

        // loop over revisions from back to front to return them from newest to oldest
        for (int i = item.getRevisionCount() - 1; i >= 0; i--) {
            ItemRevision r = revisions.get(i);

            ObjectNode revision = jsonFactory.objectNode();

            revision.put("version", r.getVersion());
            revision.put("timestamp", r.getTimestamp());
            revision.put("comment", r.getMessage());

            revisionsJson.add(revision);
        }

        return revisionsJson;
    }
}


text:
set -o errexit
set -o nounset
set -o pipefail

KUBE_ROOT=$(dirname "${BASH_SOURCE}")/..
source "${KUBE_ROOT}/hack/lib/init.sh"
source "${KUBE_ROOT}/hack/lib/test.sh"

function cleanup()
{
    [[ -n ${APISERVER_PID-} ]] && kill ${APISERVER_PID} 1>&2 2>/dev/null
    [[ -n ${CTLRMGR_PID-} ]] && kill ${CTLRMGR_PID} 1>&2 2>/dev/null
    [[ -n ${KUBELET_PID-} ]] && kill ${KUBELET_PID} 1>&2 2>/dev/null

    kube::etcd::cleanup
    rm -rf "${KUBE_TEMP}"

    kube::log::status "Clean up complete"
}

trap cleanup EXIT SIGINT

kube::util::ensure-temp-dir
kube::etcd::start

ETCD_HOST=${ETCD_HOST:-127.0.0.1}
ETCD_PORT=${ETCD_PORT:-4001}
API_PORT=${API_PORT:-8080}
API_HOST=${API_HOST:-127.0.0.1}
KUBELET_PORT=${KUBELET_PORT:-10250}
KUBELET_HEALTHZ_PORT=${KUBELET_HEALTHZ_PORT:-10248}
CTLRMGR_PORT=${CTLRMGR_PORT:-10252}

# Check kubectl
kube::log::status "Running kubectl with no options"
"${KUBE_OUTPUT_HOSTBIN}/kubectl"

kube::log::status "Starting kubelet in masterless mode"
"${KUBE_OUTPUT_HOSTBIN}/kubelet" \
  --really_crash_for_testing=true \
  --root_dir=/tmp/kubelet.$$ \
  --cert_dir="${TMPDIR:-/tmp/}" \
  --docker_endpoint="fake://" \
  --hostname_override="127.0.0.1" \
  --address="127.0.0.1" \
  --port="$KUBELET_PORT" \
  --healthz_port="${KUBELET_HEALTHZ_PORT}" 1>&2 &
KUBELET_PID=$!
kube::util::wait_for_url "http://127.0.0.1:${KUBELET_HEALTHZ_PORT}/healthz" "kubelet: " 0.2 25
kill ${KUBELET_PID} 1>&2 2>/dev/null

kube::log::status "Starting kubelet in masterful mode"
"${KUBE_OUTPUT_HOSTBIN}/kubelet" \
  --really_crash_for_testing=true \
  --root_dir=/tmp/kubelet.$$ \
  --cert_dir="${TMPDIR:-/tmp/}" \
  --docker_endpoint="fake://" \
  --hostname_override="127.0.0.1" \
  --address="127.0.0.1" \
  --api_servers="${API_HOST}:${API_PORT}" \
  --port="$KUBELET_PORT" \
  --healthz_port="${KUBELET_HEALTHZ_PORT}" 1>&2 &
KUBELET_PID=$!

kube::util::wait_for_url "http://127.0.0.1:${KUBELET_HEALTHZ_PORT}/healthz" "kubelet: " 0.2 25

# Start kube-apiserver
kube::log::status "Starting kube-apiserver"
"${KUBE_OUTPUT_HOSTBIN}/kube-apiserver" \
  --address="127.0.0.1" \
  --public_address_override="127.0.0.1" \
  --port="${API_PORT}" \
  --etcd_servers="http://${ETCD_HOST}:${ETCD_PORT}" \
  --public_address_override="127.0.0.1" \
  --kubelet_port=${KUBELET_PORT} \
  --runtime_config=api/v1beta3 \
  --cert_dir="${TMPDIR:-/tmp/}" \
  --portal_net="10.0.0.0/24" 1>&2 &
APISERVER_PID=$!

kube::util::wait_for_url "http://127.0.0.1:${API_PORT}/healthz" "apiserver: "

# Start controller manager
kube::log::status "Starting CONTROLLER-MANAGER"
"${KUBE_OUTPUT_HOSTBIN}/kube-controller-manager" \
  --machines="127.0.0.1" \
  --master="127.0.0.1:${API_PORT}" 1>&2 &
CTLRMGR_PID=$!

kube::util::wait_for_url "http://127.0.0.1:${CTLRMGR_PORT}/healthz" "controller-manager: "
kube::util::wait_for_url "http://127.0.0.1:${API_PORT}/api/v1beta3/nodes/127.0.0.1" "apiserver(nodes): " 0.2 25

# Expose kubectl directly for readability
PATH="${KUBE_OUTPUT_HOSTBIN}":$PATH

kube_api_versions=(
  ""
  v1beta1
  v1beta2
  v1beta3
)
for version in "${kube_api_versions[@]}"; do
  if [[ -z "${version}" ]]; then
    kube_flags=(
      -s "http://127.0.0.1:${API_PORT}"
      --match-server-version
    )
    [ "$(kubectl get minions -t '{{ .apiVersion }}' "${kube_flags[@]}")" == "v1beta3" ]
  else
    kube_flags=(
      -s "http://127.0.0.1:${API_PORT}"
      --match-server-version
      --api-version="${version}"
    )
    [ "$(kubectl get minions -t '{{ .apiVersion }}' "${kube_flags[@]}")" == "${version}" ]
  fi
  id_field=".metadata.name"
  labels_field=".metadata.labels"
  service_selector_field=".spec.selector"
  rc_replicas_field=".spec.replicas"
  rc_status_replicas_field=".status.replicas"
  rc_container_image_field=".spec.template.spec.containers"
  port_field="(index .spec.ports 0).port"
  if [ "${version}" = "v1beta1" ] || [ "${version}" = "v1beta2" ]; then
    id_field=".id"
    labels_field=".labels"
    service_selector_field=".selector"
    rc_replicas_field=".desiredState.replicas"
    rc_status_replicas_field=".currentState.replicas"
    rc_container_image_field=".desiredState.podTemplate.desiredState.manifest.containers"
    port_field=".port"
  fi

  # Passing no arguments to create is an error
  ! kubectl create

  ###########################
  # POD creation / deletion #
  ###########################

  kube::log::status "Testing kubectl(${version}:pods)"

  ### Create POD valid-pod from JSON
  # Pre-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create "${kube_flags[@]}" -f examples/limitrange/valid-pod.json
  # Post-condition: valid-pod POD is running
  kubectl get "${kube_flags[@]}" pods -o json
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  kube::test::get_object_assert 'pod valid-pod' "{{$id_field}}" 'valid-pod'
  kube::test::get_object_assert 'pod/valid-pod' "{{$id_field}}" 'valid-pod'
  kube::test::get_object_assert 'pods/valid-pod' "{{$id_field}}" 'valid-pod'
  # Describe command should print detailed information
  kube::test::describe_object_assert pods 'valid-pod' "Name:" "Image(s):" "Host:" "Labels:" "Status:" "Replication Controllers"

  ### Dump current valid-pod POD
  output_pod=$(kubectl get pod valid-pod -o yaml --output-version=v1beta3 "${kube_flags[@]}")

  ### Delete POD valid-pod by id
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  # Command
  kubectl delete pod valid-pod "${kube_flags[@]}"
  # Post-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''

  ### Create POD valid-pod from dumped YAML
  # Pre-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  echo "${output_pod}" | kubectl create -f - "${kube_flags[@]}"
  # Post-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'

  ### Delete POD valid-pod from JSON
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  # Command
  kubectl delete -f examples/limitrange/valid-pod.json "${kube_flags[@]}"
  # Post-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''

  ### Create POD redis-master from JSON
  # Pre-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/limitrange/valid-pod.json "${kube_flags[@]}"
  # Post-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'

  ### Delete POD valid-pod with label
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert "pods -l'name in (valid-pod)'" '{{range.items}}{{$id_field}}:{{end}}' 'valid-pod:'
  # Command
  kubectl delete pods -l'name in (valid-pod)' "${kube_flags[@]}"
  # Post-condition: no POD is running
  kube::test::get_object_assert "pods -l'name in (valid-pod)'" '{{range.items}}{{$id_field}}:{{end}}' ''

  ### Create POD valid-pod from JSON
  # Pre-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/limitrange/valid-pod.json "${kube_flags[@]}"
  # Post-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'

  ### Delete PODs with no parameter mustn't kill everything
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  # Command
  ! kubectl delete pods "${kube_flags[@]}"
  # Post-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'

  ### Delete PODs with --all and a label selector is not permitted
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  # Command
  ! kubectl delete --all pods -l'name in (valid-pod)' "${kube_flags[@]}"
  # Post-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'

  ### Delete all PODs
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  # Command
  kubectl delete --all pods "${kube_flags[@]}" # --all remove all the pods
  # Post-condition: no POD is running
  kube::test::get_object_assert "pods -l'name in (valid-pod)'" '{{range.items}}{{$id_field}}:{{end}}' ''

  ### Create two PODs
  # Pre-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/limitrange/valid-pod.json "${kube_flags[@]}"
  kubectl create -f examples/redis/redis-proxy.yaml "${kube_flags[@]}"
  # Post-condition: valid-pod and redis-proxy PODs are running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'redis-proxy:valid-pod:'

  ### Delete multiple PODs at once
  # Pre-condition: valid-pod and redis-proxy PODs are running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'redis-proxy:valid-pod:'
  # Command
  kubectl delete pods valid-pod redis-proxy "${kube_flags[@]}" # delete multiple pods at once
  # Post-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''

  ### Create two PODs
  # Pre-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/limitrange/valid-pod.json "${kube_flags[@]}"
  kubectl create -f examples/redis/redis-proxy.yaml "${kube_flags[@]}"
  # Post-condition: valid-pod and redis-proxy PODs are running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'redis-proxy:valid-pod:'

  ### Stop multiple PODs at once
  # Pre-condition: valid-pod and redis-proxy PODs are running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'redis-proxy:valid-pod:'
  # Command
  kubectl stop pods valid-pod redis-proxy "${kube_flags[@]}" # stop multiple pods at once
  # Post-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''

  ### Create valid-pod POD
  # Pre-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/limitrange/valid-pod.json "${kube_flags[@]}"
  # Post-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'

  ### Label the valid-pod POD
  # Pre-condition: valid-pod is not labelled
  kube::test::get_object_assert 'pod valid-pod' "{{range$labels_field}}{{.}}:{{end}}" 'valid-pod:'
  # Command
  kubectl label pods valid-pod new-name=new-valid-pod "${kube_flags[@]}"
  # Post-conditon: valid-pod is labelled
  kube::test::get_object_assert 'pod valid-pod' "{{range$labels_field}}{{.}}:{{end}}" 'valid-pod:new-valid-pod:'

  ### Delete POD by label
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  # Command
  kubectl delete pods -lnew-name=new-valid-pod "${kube_flags[@]}"
  # Post-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''

  ### Create valid-pod POD
  # Pre-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/limitrange/valid-pod.json "${kube_flags[@]}"
  # Post-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'

  ### Overwriting an existing label is not permitted
  # Pre-condition: name is valid-pod
  kube::test::get_object_assert 'pod valid-pod' "{{${labels_field}.name}}" 'valid-pod'
  # Command
  ! kubectl label pods valid-pod name=valid-pod-super-sayan "${kube_flags[@]}"
  # Post-condition: name is still valid-pod
  kube::test::get_object_assert 'pod valid-pod' "{{${labels_field}.name}}" 'valid-pod'

  ### --overwrite must be used to overwrite existing label, can be applied to all resources
  # Pre-condition: name is valid-pod
  kube::test::get_object_assert 'pod valid-pod' "{{${labels_field}.name}}" 'valid-pod'
  # Command
  kubectl label --overwrite pods --all name=valid-pod-super-sayan "${kube_flags[@]}"
  # Post-condition: name is valid-pod-super-sayan
  kube::test::get_object_assert 'pod valid-pod' "{{${labels_field}.name}}" 'valid-pod-super-sayan'

  ### Delete POD by label
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  # Command
  kubectl delete pods -l'name in (valid-pod-super-sayan)' "${kube_flags[@]}"
  # Post-condition: no POD is running
  kube::test::get_object_assert pods "{{range.items}}{{$id_field}}:{{end}}" ''

  ##############
  # Namespaces #
  ##############

  ### Create POD valid-pod in specific namespace
  # Pre-condition: no POD is running
  kube::test::get_object_assert 'pods --namespace=other' "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create "${kube_flags[@]}" --namespace=other -f examples/limitrange/valid-pod.json
  # Post-condition: valid-pod POD is running
  kube::test::get_object_assert 'pods --namespace=other' "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'

  ### Delete POD valid-pod in specific namespace
  # Pre-condition: valid-pod POD is running
  kube::test::get_object_assert 'pods --namespace=other' "{{range.items}}{{$id_field}}:{{end}}" 'valid-pod:'
  # Command
  kubectl delete "${kube_flags[@]}" pod --namespace=other valid-pod
  # Post-condition: no POD is running
  kube::test::get_object_assert 'pods --namespace=other' "{{range.items}}{{$id_field}}:{{end}}" ''

  #################
  # Pod templates #
  #################

  # Note: pod templates exist only in v1beta3 and above, so output will always be in that form

  ### Create PODTEMPLATE
  # Pre-condition: no PODTEMPLATE
  kube::test::get_object_assert podtemplates "{{range.items}}{{.metadata.name}}:{{end}}" ''
  # Command
  kubectl create -f examples/walkthrough/podtemplate.json "${kube_flags[@]}"
  # Post-condition: nginx PODTEMPLATE is available
  kube::test::get_object_assert podtemplates "{{range.items}}{{.metadata.name}}:{{end}}" 'nginx:'

  ### Printing pod templates works
  kubectl get podtemplates "${kube_flags[@]}"
  ### Display of an object which doesn't existing in v1beta1 and v1beta2 works
  [[ "$(kubectl get podtemplates -o yaml "${kube_flags[@]}" | grep nginx)" ]]

  ### Delete nginx pod template by name
  # Pre-condition: nginx pod template is available
  kube::test::get_object_assert podtemplates "{{range.items}}{{.metadata.name}}:{{end}}" 'nginx:'
  # Command
  kubectl delete podtemplate nginx "${kube_flags[@]}"
  # Post-condition: No templates exist
  kube::test::get_object_assert podtemplate "{{range.items}}{{.metadata.name}}:{{end}}" ''

  ############
  # Services #
  ############

  kube::log::status "Testing kubectl(${version}:services)"

  ### Create redis-master service from JSON
  # Pre-condition: Only the default kubernetes services are running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:'
  # Command
  kubectl create -f examples/guestbook/redis-master-service.json "${kube_flags[@]}"
  # Post-condition: redis-master service is running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:redis-master:'
  # Describe command should print detailed information
  kube::test::describe_object_assert services 'redis-master' "Name:" "Labels:" "Selector:" "IP:" "Port:" "Endpoints:" "Session Affinity:"

  ### Dump current redis-master service
  output_service=$(kubectl get service redis-master -o json --output-version=v1beta3 "${kube_flags[@]}")

  ### Delete redis-master-service by id
  # Pre-condition: redis-master service is running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:redis-master:'
  # Command
  kubectl delete service redis-master "${kube_flags[@]}"
  # Post-condition: Only the default kubernetes services are running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:'

  ### Create redis-master-service from dumped JSON
  # Pre-condition: Only the default kubernetes services are running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:'
  # Command
  echo "${output_service}" | kubectl create -f - "${kube_flags[@]}"
  # Post-condition: redis-master service is running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:redis-master:'

  ### Create redis-master-${version}-test service
  # Pre-condition: redis-master-service service is running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:redis-master:'
  # Command
  kubectl create -f - "${kube_flags[@]}" << __EOF__
{
  "kind": "Service",
  "apiVersion": "v1beta3",
  "metadata": {
    "name": "service-${version}-test"
  },
  "spec": {
    "ports": [
      {
        "protocol": "TCP",
        "port": 80,
        "targetPort": 80
      }
    ]
  }
}
__EOF__
  # Post-condition:redis-master-service service is running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:redis-master:service-.*-test:'

  # Command
  kubectl update service "${kube_flags[@]}" service-${version}-test --patch="{\"spec\":{\"selector\":{\"my\":\"test-label\"}},\"apiVersion\":\"v1beta3\"}" --api-version=v1beta3
  # Post-condition: selector has "test-label" label.
  kube::test::get_object_assert "service service-${version}-test" "{{range$service_selector_field}}{{.}}{{end}}" "test-label"

  ### Identity
  kubectl get service "${kube_flags[@]}" service-${version}-test -o json | kubectl update "${kube_flags[@]}" -f -

  ### Delete services by id
  # Pre-condition: redis-master-service service is running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:redis-master:service-.*-test:'
  # Command
  kubectl delete service redis-master "${kube_flags[@]}"
  kubectl delete service "service-${version}-test" "${kube_flags[@]}"
  # Post-condition: Only the default kubernetes services are running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:'

  ### Create two services
  # Pre-condition: Only the default kubernetes services are running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:'
  # Command
  kubectl create -f examples/guestbook/redis-master-service.json "${kube_flags[@]}"
  kubectl create -f examples/guestbook/redis-slave-service.json "${kube_flags[@]}"
  # Post-condition: redis-master and redis-slave services are running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:redis-master:redis-slave:'

  ### Delete multiple services at once
  # Pre-condition: redis-master and redis-slave services are running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:redis-master:redis-slave:'
  # Command
  kubectl delete services redis-master redis-slave "${kube_flags[@]}" # delete multiple services at once
  # Post-condition: Only the default kubernetes services are running
  kube::test::get_object_assert services "{{range.items}}{{$id_field}}:{{end}}" 'kubernetes:kubernetes-ro:'

  ###########################
  # Replication controllers #
  ###########################

  kube::log::status "Testing kubectl(${version}:replicationcontrollers)"

  ### Create replication controller frontend from JSON
  # Pre-condition: no replication controller is running
  kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/guestbook/frontend-controller.json "${kube_flags[@]}"
  # Post-condition: frontend replication controller is running
  kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:'
  # Describe command should print detailed information
  kube::test::describe_object_assert rc 'frontend' "Name:" "Image(s):" "Labels:" "Selector:" "Replicas:" "Pods Status:"

  ### Resize replication controller frontend with current-replicas and replicas
  # Pre-condition: 3 replicas
  kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '3'
  # Command
  kubectl resize --current-replicas=3 --replicas=2 replicationcontrollers frontend "${kube_flags[@]}"
  # Post-condition: 2 replicas
  kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'

  ### Resize replication controller frontend with (wrong) current-replicas and replicas
  # Pre-condition: 2 replicas
  kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'
  # Command
  ! kubectl resize --current-replicas=3 --replicas=2 replicationcontrollers frontend "${kube_flags[@]}"
  # Post-condition: nothing changed
  kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'

  ### Resize replication controller frontend with replicas only
  # Pre-condition: 2 replicas
  kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '2'
  # Command
  kubectl resize  --replicas=3 replicationcontrollers frontend "${kube_flags[@]}"
  # Post-condition: 3 replicas
  kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '3'

  ### Expose replication controller as service
  # Pre-condition: 3 replicas
  kube::test::get_object_assert 'rc frontend' "{{$rc_replicas_field}}" '3'
  # Command
  kubectl expose rc frontend --port=80 "${kube_flags[@]}"
  # Post-condition: service exists
  kube::test::get_object_assert 'service frontend' "{{$port_field}}" '80'
  # Command
  kubectl expose service frontend --port=443 --name=frontend-2 "${kube_flags[@]}"
  # Post-condition: service exists
  kube::test::get_object_assert 'service frontend-2' "{{$port_field}}" '443'
  # Command
  kubectl create -f examples/limitrange/valid-pod.json "${kube_flags[@]}"
  kubectl expose pod valid-pod --port=444 --name=frontend-3 "${kube_flags[@]}"
  # Post-condition: service exists
  kube::test::get_object_assert 'service frontend-3' "{{$port_field}}" '444'
  # Cleanup services
  kubectl delete pod valid-pod "${kube_flags[@]}"
  kubectl delete service frontend{,-2,-3} "${kube_flags[@]}"

  ### Perform a rolling update with --image
  # Command
  kubectl rolling-update frontend --image=kubernetes/pause --update-period=10ns --poll-interval=10ms "${kube_flags[@]}"
  # Post-condition: current image IS kubernetes/pause
  kube::test::get_object_assert 'rc frontend' '{{range \$c:=$rc_container_image_field}} {{\$c.image}} {{end}}' ' +kubernetes/pause +'

  ### Delete replication controller with id
  # Pre-condition: frontend replication controller is running
  kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:'
  # Command
  kubectl stop rc frontend "${kube_flags[@]}"
  # Post-condition: no replication controller is running
  kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''

  ### Create two replication controllers
  # Pre-condition: no replication controller is running
  kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/guestbook/frontend-controller.json "${kube_flags[@]}"
  kubectl create -f examples/guestbook/redis-slave-controller.json "${kube_flags[@]}"
  # Post-condition: frontend and redis-slave
  kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:redis-slave:'

  ### Delete multiple controllers at once
  # Pre-condition: frontend and redis-slave
  kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" 'frontend:redis-slave:'
  # Command
  kubectl stop rc frontend redis-slave "${kube_flags[@]}" # delete multiple controllers at once
  # Post-condition: no replication controller is running
  kube::test::get_object_assert rc "{{range.items}}{{$id_field}}:{{end}}" ''

  ######################
  # Persistent Volumes #
  ######################

  ### Create and delete persistent volume examples
  # Pre-condition: no persistent volumes currently exist
  kube::test::get_object_assert pv "{{range.items}}{{.$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/persistent-volumes/volumes/local-01.yaml "${kube_flags[@]}"
  kube::test::get_object_assert pv "{{range.items}}{{.$id_field}}:{{end}}" 'pv0001:'
  kubectl delete pv pv0001 "${kube_flags[@]}"
  kubectl create -f examples/persistent-volumes/volumes/local-02.yaml "${kube_flags[@]}"
  kube::test::get_object_assert pv "{{range.items}}{{.$id_field}}:{{end}}" 'pv0002:'
  kubectl delete pv pv0002 "${kube_flags[@]}"
  kubectl create -f examples/persistent-volumes/volumes/gce.yaml "${kube_flags[@]}"
  kube::test::get_object_assert pv "{{range.items}}{{.$id_field}}:{{end}}" 'pv0003:'
  kubectl delete pv pv0003 "${kube_flags[@]}"
  # Post-condition: no PVs
  kube::test::get_object_assert pv "{{range.items}}{{.$id_field}}:{{end}}" ''

  ############################
  # Persistent Volume Claims #
  ############################

  ### Create and delete persistent volume claim examples
  # Pre-condition: no persistent volume claims currently exist
  kube::test::get_object_assert pvc "{{range.items}}{{.$id_field}}:{{end}}" ''
  # Command
  kubectl create -f examples/persistent-volumes/claims/claim-01.yaml "${kube_flags[@]}"
  kube::test::get_object_assert pvc "{{range.items}}{{.$id_field}}:{{end}}" 'myclaim-1:'
  kubectl delete pvc myclaim-1 "${kube_flags[@]}"

  kubectl create -f examples/persistent-volumes/claims/claim-02.yaml "${kube_flags[@]}"
  kube::test::get_object_assert pvc "{{range.items}}{{.$id_field}}:{{end}}" 'myclaim-2:'
  kubectl delete pvc myclaim-2 "${kube_flags[@]}"

  kubectl create -f examples/persistent-volumes/claims/claim-03.json "${kube_flags[@]}"
  kube::test::get_object_assert pvc "{{range.items}}{{.$id_field}}:{{end}}" 'myclaim-3:'
  kubectl delete pvc myclaim-3 "${kube_flags[@]}"
  # Post-condition: no PVCs
  kube::test::get_object_assert pvc "{{range.items}}{{.$id_field}}:{{end}}" ''

  #########
  # Nodes #
  #########

  kube::log::status "Testing kubectl(${version}:nodes)"

  kube::test::get_object_assert nodes "{{range.items}}{{$id_field}}:{{end}}" '127.0.0.1:'

  kube::test::describe_object_assert nodes "127.0.0.1" "Name:" "Labels:" "CreationTimestamp:" "Conditions:" "Addresses:" "Capacity:" "Pods:"

  ###########
  # Minions #
  ###########

  if [[ "${version}" = "v1beta1" ]] || [[ "${version}" = "v1beta2" ]]; then
    kube::log::status "Testing kubectl(${version}:minions)"

    kube::test::get_object_assert minions "{{range.items}}{{$id_field}}:{{end}}" '127.0.0.1:'

    # TODO: I should be a MinionList instead of List
    kube::test::get_object_assert minions '{{.kind}}' 'List'

    kube::test::describe_object_assert minions "127.0.0.1" "Name:" "Conditions:" "Addresses:" "Capacity:" "Pods:"
  fi

  #####################
  # Retrieve multiple #
  #####################

  kube::log::status "Testing kubectl(${version}:multiget)"
  kube::test::get_object_assert 'nodes/127.0.0.1 service/kubernetes' "{{range.items}}{{$id_field}}:{{end}}" '127.0.0.1:kubernetes:'

  #####################
  # Resource aliasing #
  #####################

  kube::log::status "Testing resource aliasing"
  kubectl create -f examples/cassandra/cassandra.yaml "${kube_flags[@]}"
  kubectl create -f examples/cassandra/cassandra-controller.yaml "${kube_flags[@]}"
  kubectl create -f examples/cassandra/cassandra-service.yaml "${kube_flags[@]}"
  kube::test::get_object_assert "all -l'name=cassandra'" "{{range.items}}{{$id_field}}:{{end}}" 'cassandra:cassandra:cassandra:'
  kubectl delete all -l name=cassandra "${kube_flags[@]}"

  ###########
  # Swagger #
  ###########

  if [[ -n "${version}" ]]; then
    # Verify schema
    file="${KUBE_TEMP}/schema-${version}.json"
    curl -s "http://127.0.0.1:${API_PORT}/swaggerapi/api/${version}" > "${file}"
    [[ "$(grep "list of returned" "${file}")" ]]
    [[ "$(grep "list of pods" "${file}")" ]]
    [[ "$(grep "watch for changes to the described resources" "${file}")" ]]
  fi

  kube::test::clear_all
done

kube::log::status "TEST PASSED"


text:
<?php
/**
 * The7 3.5.0 patch.
 *
 * @package the7
 * @since 3.5.0
 */

if ( ! class_exists( 'The7_DB_Patch_030500', false ) ) {

	class The7_DB_Patch_030500 extends The7_DB_Patch {

		protected function do_apply() {

			// Rename microwidgets '-mobile-layout' option.
			$microwidgets = array(
				'header-elements-contact-address',
				'header-elements-contact-phone',
				'header-elements-contact-email',
				'header-elements-contact-skype',
				'header-elements-contact-clock',
				'header-elements-login',
				'header-elements-text',
				'header-elements-text-2',
				'header-elements-text-3',
				'header-elements-menu',
				'header-elements-woocommerce_cart',
				'header-elements-soc_icons',
				'header-elements-search',
			);

			foreach ( $microwidgets as $base_key ) {
				$this->rename_option( "{$base_key}-mobile-layout", "{$base_key}-second-header-switch" );
			}
		}

	}

}


text:
* Detects which CSS selectors your app is using and creates a file without the unused CSS.

Able to also detect **dynamically-loaded CSS selectors** in your javascript.

PurifyCSS has been designed from the beginning with **single-page apps** in mind.

*This is in addition to working with multi-page apps. PurifyCSS is voodoo magic.*

# Potential reduction
* [Bootstrap](https://github.com/twbs/bootstrap) file: ~140k characters.
* Average Bootstrap usage: ~40% (at most)
* Minified Bootstrap: ~117k characters.
* Purified + Minified Bootstrap: **~27k characters**

# Install
```
npm install purify-css
```

#Able to detect
* Anytime your class name is intact in your code.

##### Example for the class ```button-active```
``` html
  <!-- html -->
  <!-- class directly on element -->
  <div class="button-active">click</div>
```

``` javascript
  // javascript
  // this example is jquery, but anytime your class name
  // is together in your javascript, it will work
  $(button).addClass('button-active');
```

* Dynamically created classes

##### Example for the class ```button-active```
``` javascript
  // can detect even if class is split
  var half = 'button-';
  $(button).addClass(half + 'active');

  // can detect even if class is joined
  var dynamicClass = ['button', 'active'].join('-');
  $(button).addClass(dynamicClass);
```

* **All** javascript frameworks

##### Example for the class ```angular-button```
``` javascript
  <!-- angular template -->
  <div ng-class="'angular' + '-button'"></div>
```

##### Example for the class ```commentBox```
```javascript
  // react component
  var CommentBox = React.createClass({
    render: function() {
      return (
        <div className="commentBox">
          Hello, world! I am a CommentBox.
        </div>
      );
    }
  });
  React.render(
    <CommentBox />,
    document.getElementById('content')
  );
```

### PurifyCSS detects all JS frameworks. It is voodoo magic.

# API
```javascript
var purify = require('purify-css');

purify(content, css, options, callback);
```

## ```content```
##### Type: ```Array``` or ```String```

**```Array```** of filepaths to the files you want to search through for used classes (HTML, Javascripts, Templates, anything that relates to CSS classes)

**```String```** of content you want us to look for used classes.

## ```css```
##### Type: ```Array``` or ```String```

**```Array```** of filepaths to the CSS files you want us to filter.

**```String```** of CSS you want us to filter.

##```options (optional)```
##### Type: ```Object```

##### Properties of options object:

* **```minify:```** Set to ```true``` to minify. Default: ```false```.

* **```output:```** Filepath to write purified CSS to. Returns raw string if ```false```. Default: ```false```.

* **```info:```** Logs info on how much CSS was removed if ```true```. Default: ```false```.

* **```rejected:```** Logs the CSS rules that were removed if ```true```. Default: ```false```.

##```callback (optional)```
##### Type: ```Function```

##### Example
``` javascript
purify(content, css, options, function(output){
  console.log(output, ' is the result of purify');
});
```

##### Example without options
``` javascript
purify(content, css, function(output){
  console.log('callback without options');
});
```

## Command Line Tool

```
$ npm install -g purify-css
```

```
$ purifycss
usage: purifycss <css> <content> [option ...]

options:
 --min                Minify CSS
 --out [filepath]     Filepath to write purified CSS to
 --info               Logs info on how much CSS was removed
 --rejected           Logs the CSS rules that were removed

 -h, --help           Prints help (this message) and exits
```

# At build time
[Grunt](https://github.com/purifycss/grunt-purify-css)

[Gulp](https://github.com/purifycss/gulp-purifycss)


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

namespace Light.Data
{
    internal class LightContainsDataFieldInfo : LightDataFieldInfo, ISupportNotDefine, IDataFieldInfoConvert
    {
        private bool _isNot;

        private readonly object _collection;

        private readonly DataFieldInfo _baseFieldInfo;

        public LightContainsDataFieldInfo(DataFieldInfo info, object collection)
            : base(info.TableMapping)
        {
            if (collection == null)
                throw new ArgumentNullException(nameof(collection));
            _collection = collection;
            _baseFieldInfo = info;
        }

        public void SetNot()
        {
            _isNot = !_isNot;
        }

        internal override string CreateSqlString(CommandFactory factory, bool isFullName, CreateSqlState state)
        {
            var sql = state.GetDataSql(this, isFullName);
            if (sql != null) {
                return sql;
            }

            object obj = _baseFieldInfo.CreateSqlString(factory, isFullName, state);
            var values = (IEnumerable)LambdaExpressionExtend.ConvertLambdaObject(_collection);
            var list = new List<string>();
            foreach (var item in values) {
                list.Add(state.AddDataParameter(factory, _baseFieldInfo.ToParameter(item.AdjustValue())));
            }

            if (list.Count > 0)
            {
                sql = factory.CreateCollectionParamsQuerySql(obj,
                    _isNot ? QueryCollectionPredicate.NotIn : QueryCollectionPredicate.In, list);
            }
            else
            {
                var value = _isNot;
                sql = factory.CreateBooleanConstantSql(value);
            }
            state.SetDataSql(this, isFullName, sql);
            return sql;
        }

        public QueryExpression ConvertToExpression()
        {
            return new LightContainsQueryExpression(this);
        }
    }
}


text:
package limitranger

import (
	"fmt"
	"io"
	"sort"
	"strings"
	"time"

	lru "github.com/hashicorp/golang-lru"

	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"
	"k8s.io/apiserver/pkg/admission"
	api "k8s.io/kubernetes/pkg/apis/core"
	"k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
	informers "k8s.io/kubernetes/pkg/client/informers/informers_generated/internalversion"
	corelisters "k8s.io/kubernetes/pkg/client/listers/core/internalversion"
	kubeapiserveradmission "k8s.io/kubernetes/pkg/kubeapiserver/admission"
)

const (
	limitRangerAnnotation = "kubernetes.io/limit-ranger"
)

// Register registers a plugin
func Register(plugins *admission.Plugins) {
	plugins.Register("LimitRanger", func(config io.Reader) (admission.Interface, error) {
		return NewLimitRanger(&DefaultLimitRangerActions{})
	})
}

// LimitRanger enforces usage limits on a per resource basis in the namespace
type LimitRanger struct {
	*admission.Handler
	client  internalclientset.Interface
	actions LimitRangerActions
	lister  corelisters.LimitRangeLister

	// liveLookups holds the last few live lookups we've done to help ammortize cost on repeated lookup failures.
	// This let's us handle the case of latent caches, by looking up actual results for a namespace on cache miss/no results.
	// We track the lookup result here so that for repeated requests, we don't look it up very often.
	liveLookupCache *lru.Cache
	liveTTL         time.Duration
}

var _ admission.MutationInterface = &LimitRanger{}
var _ admission.ValidationInterface = &LimitRanger{}
var _ kubeapiserveradmission.WantsInternalKubeInformerFactory = &LimitRanger{}

type liveLookupEntry struct {
	expiry time.Time
	items  []*api.LimitRange
}

func (l *LimitRanger) SetInternalKubeInformerFactory(f informers.SharedInformerFactory) {
	limitRangeInformer := f.Core().InternalVersion().LimitRanges()
	l.SetReadyFunc(limitRangeInformer.Informer().HasSynced)
	l.lister = limitRangeInformer.Lister()
}

func (l *LimitRanger) ValidateInitialization() error {
	if l.lister == nil {
		return fmt.Errorf("missing limitRange lister")
	}
	if l.client == nil {
		return fmt.Errorf("missing client")
	}
	return nil
}

// Admit admits resources into cluster that do not violate any defined LimitRange in the namespace
func (l *LimitRanger) Admit(a admission.Attributes) (err error) {
	return l.runLimitFunc(a, l.actions.MutateLimit)
}

// Validate admits resources into cluster that do not violate any defined LimitRange in the namespace
func (l *LimitRanger) Validate(a admission.Attributes) (err error) {
	return l.runLimitFunc(a, l.actions.ValidateLimit)
}

func (l *LimitRanger) runLimitFunc(a admission.Attributes, limitFn func(limitRange *api.LimitRange, kind string, obj runtime.Object) error) (err error) {
	if !l.actions.SupportsAttributes(a) {
		return nil
	}

	obj := a.GetObject()
	name := "Unknown"
	if obj != nil {
		name, _ = meta.NewAccessor().Name(obj)
		if len(name) == 0 {
			name, _ = meta.NewAccessor().GenerateName(obj)
		}
	}

	// ignore all objects marked for deletion
	oldObj := a.GetOldObject()
	if oldObj != nil {
		oldAccessor, err := meta.Accessor(oldObj)
		if err != nil {
			return admission.NewForbidden(a, err)
		}
		if oldAccessor.GetDeletionTimestamp() != nil {
			return nil
		}
	}

	items, err := l.GetLimitRanges(a)
	if err != nil {
		return err
	}

	// ensure it meets each prescribed min/max
	for i := range items {
		limitRange := items[i]

		if !l.actions.SupportsLimit(limitRange) {
			continue
		}

		err = limitFn(limitRange, a.GetResource().Resource, a.GetObject())
		if err != nil {
			return admission.NewForbidden(a, err)
		}
	}
	return nil
}

func (l *LimitRanger) GetLimitRanges(a admission.Attributes) ([]*api.LimitRange, error) {
	items, err := l.lister.LimitRanges(a.GetNamespace()).List(labels.Everything())
	if err != nil {
		return nil, admission.NewForbidden(a, fmt.Errorf("unable to %s %v at this time because there was an error enforcing limit ranges", a.GetOperation(), a.GetResource()))
	}

	// if there are no items held in our indexer, check our live-lookup LRU, if that misses, do the live lookup to prime it.
	if len(items) == 0 {
		lruItemObj, ok := l.liveLookupCache.Get(a.GetNamespace())
		if !ok || lruItemObj.(liveLookupEntry).expiry.Before(time.Now()) {
			// TODO: If there are multiple operations at the same time and cache has just expired,
			// this may cause multiple List operations being issued at the same time.
			// If there is already in-flight List() for a given namespace, we should wait until
			// it is finished and cache is updated instead of doing the same, also to avoid
			// throttling - see #22422 for details.
			liveList, err := l.client.Core().LimitRanges(a.GetNamespace()).List(metav1.ListOptions{})
			if err != nil {
				return nil, admission.NewForbidden(a, err)
			}
			newEntry := liveLookupEntry{expiry: time.Now().Add(l.liveTTL)}
			for i := range liveList.Items {
				newEntry.items = append(newEntry.items, &liveList.Items[i])
			}
			l.liveLookupCache.Add(a.GetNamespace(), newEntry)
			lruItemObj = newEntry
		}
		lruEntry := lruItemObj.(liveLookupEntry)

		for i := range lruEntry.items {
			items = append(items, lruEntry.items[i])
		}

	}

	return items, nil
}

// NewLimitRanger returns an object that enforces limits based on the supplied limit function
func NewLimitRanger(actions LimitRangerActions) (*LimitRanger, error) {
	liveLookupCache, err := lru.New(10000)
	if err != nil {
		return nil, err
	}

	if actions == nil {
		actions = &DefaultLimitRangerActions{}
	}

	return &LimitRanger{
		Handler:         admission.NewHandler(admission.Create, admission.Update),
		actions:         actions,
		liveLookupCache: liveLookupCache,
		liveTTL:         time.Duration(30 * time.Second),
	}, nil
}

var _ = kubeapiserveradmission.WantsInternalKubeInformerFactory(&LimitRanger{})
var _ = kubeapiserveradmission.WantsInternalKubeClientSet(&LimitRanger{})

func (a *LimitRanger) SetInternalKubeClientSet(client internalclientset.Interface) {
	a.client = client
}

// defaultContainerResourceRequirements returns the default requirements for a container
// the requirement.Limits are taken from the LimitRange defaults (if specified)
// the requirement.Requests are taken from the LimitRange default request (if specified)
func defaultContainerResourceRequirements(limitRange *api.LimitRange) api.ResourceRequirements {
	requirements := api.ResourceRequirements{}
	requirements.Requests = api.ResourceList{}
	requirements.Limits = api.ResourceList{}

	for i := range limitRange.Spec.Limits {
		limit := limitRange.Spec.Limits[i]
		if limit.Type == api.LimitTypeContainer {
			for k, v := range limit.DefaultRequest {
				value := v.Copy()
				requirements.Requests[k] = *value
			}
			for k, v := range limit.Default {
				value := v.Copy()
				requirements.Limits[k] = *value
			}
		}
	}
	return requirements
}

// mergeContainerResources handles defaulting all of the resources on a container.
func mergeContainerResources(container *api.Container, defaultRequirements *api.ResourceRequirements, annotationPrefix string, annotations []string) []string {
	setRequests := []string{}
	setLimits := []string{}
	if container.Resources.Limits == nil {
		container.Resources.Limits = api.ResourceList{}
	}
	if container.Resources.Requests == nil {
		container.Resources.Requests = api.ResourceList{}
	}
	for k, v := range defaultRequirements.Limits {
		_, found := container.Resources.Limits[k]
		if !found {
			container.Resources.Limits[k] = *v.Copy()
			setLimits = append(setLimits, string(k))
		}
	}
	for k, v := range defaultRequirements.Requests {
		_, found := container.Resources.Requests[k]
		if !found {
			container.Resources.Requests[k] = *v.Copy()
			setRequests = append(setRequests, string(k))
		}
	}
	if len(setRequests) > 0 {
		sort.Strings(setRequests)
		a := strings.Join(setRequests, ", ") + fmt.Sprintf(" request for %s %s", annotationPrefix, container.Name)
		annotations = append(annotations, a)
	}
	if len(setLimits) > 0 {
		sort.Strings(setLimits)
		a := strings.Join(setLimits, ", ") + fmt.Sprintf(" limit for %s %s", annotationPrefix, container.Name)
		annotations = append(annotations, a)
	}
	return annotations
}

// mergePodResourceRequirements merges enumerated requirements with default requirements
// it annotates the pod with information about what requirements were modified
func mergePodResourceRequirements(pod *api.Pod, defaultRequirements *api.ResourceRequirements) {
	annotations := []string{}

	for i := range pod.Spec.Containers {
		annotations = mergeContainerResources(&pod.Spec.Containers[i], defaultRequirements, "container", annotations)
	}

	for i := range pod.Spec.InitContainers {
		annotations = mergeContainerResources(&pod.Spec.InitContainers[i], defaultRequirements, "init container", annotations)
	}

	if len(annotations) > 0 {
		if pod.ObjectMeta.Annotations == nil {
			pod.ObjectMeta.Annotations = make(map[string]string)
		}
		val := "LimitRanger plugin set: " + strings.Join(annotations, "; ")
		pod.ObjectMeta.Annotations[limitRangerAnnotation] = val
	}
}

// requestLimitEnforcedValues returns the specified values at a common precision to support comparability
func requestLimitEnforcedValues(requestQuantity, limitQuantity, enforcedQuantity resource.Quantity) (request, limit, enforced int64) {
	request = requestQuantity.Value()
	limit = limitQuantity.Value()
	enforced = enforcedQuantity.Value()
	// do a more precise comparison if possible (if the value won't overflow)
	if request <= resource.MaxMilliValue && limit <= resource.MaxMilliValue && enforced <= resource.MaxMilliValue {
		request = requestQuantity.MilliValue()
		limit = limitQuantity.MilliValue()
		enforced = enforcedQuantity.MilliValue()
	}
	return
}

// minConstraint enforces the min constraint over the specified resource
func minConstraint(limitType api.LimitType, resourceName api.ResourceName, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error {
	req, reqExists := request[resourceName]
	lim, limExists := limit[resourceName]
	observedReqValue, observedLimValue, enforcedValue := requestLimitEnforcedValues(req, lim, enforced)

	if !reqExists {
		return fmt.Errorf("minimum %s usage per %s is %s.  No request is specified.", resourceName, limitType, enforced.String())
	}
	if observedReqValue < enforcedValue {
		return fmt.Errorf("minimum %s usage per %s is %s, but request is %s.", resourceName, limitType, enforced.String(), req.String())
	}
	if limExists && (observedLimValue < enforcedValue) {
		return fmt.Errorf("minimum %s usage per %s is %s, but limit is %s.", resourceName, limitType, enforced.String(), lim.String())
	}
	return nil
}

// maxRequestConstraint enforces the max constraint over the specified resource
// use when specify LimitType resource doesn't recognize limit values
func maxRequestConstraint(limitType api.LimitType, resourceName api.ResourceName, enforced resource.Quantity, request api.ResourceList) error {
	req, reqExists := request[resourceName]
	observedReqValue, _, enforcedValue := requestLimitEnforcedValues(req, resource.Quantity{}, enforced)

	if !reqExists {
		return fmt.Errorf("maximum %s usage per %s is %s.  No request is specified.", resourceName, limitType, enforced.String())
	}
	if observedReqValue > enforcedValue {
		return fmt.Errorf("maximum %s usage per %s is %s, but request is %s.", resourceName, limitType, enforced.String(), req.String())
	}
	return nil
}

// maxConstraint enforces the max constraint over the specified resource
func maxConstraint(limitType api.LimitType, resourceName api.ResourceName, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error {
	req, reqExists := request[resourceName]
	lim, limExists := limit[resourceName]
	observedReqValue, observedLimValue, enforcedValue := requestLimitEnforcedValues(req, lim, enforced)

	if !limExists {
		return fmt.Errorf("maximum %s usage per %s is %s.  No limit is specified.", resourceName, limitType, enforced.String())
	}
	if observedLimValue > enforcedValue {
		return fmt.Errorf("maximum %s usage per %s is %s, but limit is %s.", resourceName, limitType, enforced.String(), lim.String())
	}
	if reqExists && (observedReqValue > enforcedValue) {
		return fmt.Errorf("maximum %s usage per %s is %s, but request is %s.", resourceName, limitType, enforced.String(), req.String())
	}
	return nil
}

// limitRequestRatioConstraint enforces the limit to request ratio over the specified resource
func limitRequestRatioConstraint(limitType api.LimitType, resourceName api.ResourceName, enforced resource.Quantity, request api.ResourceList, limit api.ResourceList) error {
	req, reqExists := request[resourceName]
	lim, limExists := limit[resourceName]
	observedReqValue, observedLimValue, _ := requestLimitEnforcedValues(req, lim, enforced)

	if !reqExists || (observedReqValue == int64(0)) {
		return fmt.Errorf("%s max limit to request ratio per %s is %s, but no request is specified or request is 0.", resourceName, limitType, enforced.String())
	}
	if !limExists || (observedLimValue == int64(0)) {
		return fmt.Errorf("%s max limit to request ratio per %s is %s, but no limit is specified or limit is 0.", resourceName, limitType, enforced.String())
	}

	observedRatio := float64(observedLimValue) / float64(observedReqValue)
	displayObservedRatio := observedRatio
	maxLimitRequestRatio := float64(enforced.Value())
	if enforced.Value() <= resource.MaxMilliValue {
		observedRatio = observedRatio * 1000
		maxLimitRequestRatio = float64(enforced.MilliValue())
	}

	if observedRatio > maxLimitRequestRatio {
		return fmt.Errorf("%s max limit to request ratio per %s is %s, but provided ratio is %f.", resourceName, limitType, enforced.String(), displayObservedRatio)
	}

	return nil
}

// sum takes the total of each named resource across all inputs
// if a key is not in each input, then the output resource list will omit the key
func sum(inputs []api.ResourceList) api.ResourceList {
	result := api.ResourceList{}
	keys := []api.ResourceName{}
	for i := range inputs {
		for k := range inputs[i] {
			keys = append(keys, k)
		}
	}
	for _, key := range keys {
		total, isSet := int64(0), true

		for i := range inputs {
			input := inputs[i]
			v, exists := input[key]
			if exists {
				if key == api.ResourceCPU {
					total = total + v.MilliValue()
				} else {
					total = total + v.Value()
				}
			} else {
				isSet = false
			}
		}

		if isSet {
			if key == api.ResourceCPU {
				result[key] = *(resource.NewMilliQuantity(total, resource.DecimalSI))
			} else {
				result[key] = *(resource.NewQuantity(total, resource.DecimalSI))
			}

		}
	}
	return result
}

// DefaultLimitRangerActions is the default implementation of LimitRangerActions.
type DefaultLimitRangerActions struct{}

// ensure DefaultLimitRangerActions implements the LimitRangerActions interface.
var _ LimitRangerActions = &DefaultLimitRangerActions{}

// Limit enforces resource requirements of incoming resources against enumerated constraints
// on the LimitRange.  It may modify the incoming object to apply default resource requirements
// if not specified, and enumerated on the LimitRange
func (d *DefaultLimitRangerActions) MutateLimit(limitRange *api.LimitRange, resourceName string, obj runtime.Object) error {
	switch resourceName {
	case "pods":
		return PodMutateLimitFunc(limitRange, obj.(*api.Pod))
	}
	return nil
}

// Limit enforces resource requirements of incoming resources against enumerated constraints
// on the LimitRange.  It may modify the incoming object to apply default resource requirements
// if not specified, and enumerated on the LimitRange
func (d *DefaultLimitRangerActions) ValidateLimit(limitRange *api.LimitRange, resourceName string, obj runtime.Object) error {
	switch resourceName {
	case "pods":
		return PodValidateLimitFunc(limitRange, obj.(*api.Pod))
	case "persistentvolumeclaims":
		return PersistentVolumeClaimValidateLimitFunc(limitRange, obj.(*api.PersistentVolumeClaim))
	}
	return nil
}

// SupportsAttributes ignores all calls that do not deal with pod resources or storage requests (PVCs).
// Also ignores any call that has a subresource defined.
func (d *DefaultLimitRangerActions) SupportsAttributes(a admission.Attributes) bool {
	if a.GetSubresource() != "" {
		return false
	}

	return a.GetKind().GroupKind() == api.Kind("Pod") || a.GetKind().GroupKind() == api.Kind("PersistentVolumeClaim")
}

// SupportsLimit always returns true.
func (d *DefaultLimitRangerActions) SupportsLimit(limitRange *api.LimitRange) bool {
	return true
}

// PersistentVolumeClaimValidateLimitFunc enforces storage limits for PVCs.
// Users request storage via pvc.Spec.Resources.Requests.  Min/Max is enforced by an admin with LimitRange.
// Claims will not be modified with default values because storage is a required part of pvc.Spec.
// All storage enforced values *only* apply to pvc.Spec.Resources.Requests.
func PersistentVolumeClaimValidateLimitFunc(limitRange *api.LimitRange, pvc *api.PersistentVolumeClaim) error {
	var errs []error
	for i := range limitRange.Spec.Limits {
		limit := limitRange.Spec.Limits[i]
		limitType := limit.Type
		if limitType == api.LimitTypePersistentVolumeClaim {
			for k, v := range limit.Min {
				// normal usage of minConstraint. pvc.Spec.Resources.Limits is not recognized as user input
				if err := minConstraint(limitType, k, v, pvc.Spec.Resources.Requests, api.ResourceList{}); err != nil {
					errs = append(errs, err)
				}
			}
			for k, v := range limit.Max {
				// We want to enforce the max of the LimitRange against what
				// the user requested.
				if err := maxRequestConstraint(limitType, k, v, pvc.Spec.Resources.Requests); err != nil {
					errs = append(errs, err)
				}
			}
		}
	}
	return utilerrors.NewAggregate(errs)
}

// PodMutateLimitFunc sets resource requirements enumerated by the pod against
// the specified LimitRange.  The pod may be modified to apply default resource
// requirements if not specified, and enumerated on the LimitRange
func PodMutateLimitFunc(limitRange *api.LimitRange, pod *api.Pod) error {
	defaultResources := defaultContainerResourceRequirements(limitRange)
	mergePodResourceRequirements(pod, &defaultResources)
	return nil
}

// PodValidateLimitFunc enforces resource requirements enumerated by the pod against
// the specified LimitRange.
func PodValidateLimitFunc(limitRange *api.LimitRange, pod *api.Pod) error {
	var errs []error

	for i := range limitRange.Spec.Limits {
		limit := limitRange.Spec.Limits[i]
		limitType := limit.Type
		// enforce container limits
		if limitType == api.LimitTypeContainer {
			for j := range pod.Spec.Containers {
				container := &pod.Spec.Containers[j]
				for k, v := range limit.Min {
					if err := minConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil {
						errs = append(errs, err)
					}
				}
				for k, v := range limit.Max {
					if err := maxConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil {
						errs = append(errs, err)
					}
				}
				for k, v := range limit.MaxLimitRequestRatio {
					if err := limitRequestRatioConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil {
						errs = append(errs, err)
					}
				}
			}
			for j := range pod.Spec.InitContainers {
				container := &pod.Spec.InitContainers[j]
				for k, v := range limit.Min {
					if err := minConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil {
						errs = append(errs, err)
					}
				}
				for k, v := range limit.Max {
					if err := maxConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil {
						errs = append(errs, err)
					}
				}
				for k, v := range limit.MaxLimitRequestRatio {
					if err := limitRequestRatioConstraint(limitType, k, v, container.Resources.Requests, container.Resources.Limits); err != nil {
						errs = append(errs, err)
					}
				}
			}
		}

		// enforce pod limits on init containers
		if limitType == api.LimitTypePod {
			containerRequests, containerLimits := []api.ResourceList{}, []api.ResourceList{}
			for j := range pod.Spec.Containers {
				container := &pod.Spec.Containers[j]
				containerRequests = append(containerRequests, container.Resources.Requests)
				containerLimits = append(containerLimits, container.Resources.Limits)
			}
			podRequests := sum(containerRequests)
			podLimits := sum(containerLimits)
			for j := range pod.Spec.InitContainers {
				container := &pod.Spec.InitContainers[j]
				// take max(sum_containers, any_init_container)
				for k, v := range container.Resources.Requests {
					if v2, ok := podRequests[k]; ok {
						if v.Cmp(v2) > 0 {
							podRequests[k] = v
						}
					} else {
						podRequests[k] = v
					}
				}
				for k, v := range container.Resources.Limits {
					if v2, ok := podLimits[k]; ok {
						if v.Cmp(v2) > 0 {
							podLimits[k] = v
						}
					} else {
						podLimits[k] = v
					}
				}
			}
			for k, v := range limit.Min {
				if err := minConstraint(limitType, k, v, podRequests, podLimits); err != nil {
					errs = append(errs, err)
				}
			}
			for k, v := range limit.Max {
				if err := maxConstraint(limitType, k, v, podRequests, podLimits); err != nil {
					errs = append(errs, err)
				}
			}
			for k, v := range limit.MaxLimitRequestRatio {
				if err := limitRequestRatioConstraint(limitType, k, v, podRequests, podLimits); err != nil {
					errs = append(errs, err)
				}
			}
		}
	}
	return utilerrors.NewAggregate(errs)
}