text:
// ============================================================================
//   Copyright 2006-2012 Daniel W. Dyer
//
//   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.
// ============================================================================
package org.uncommons.maths.combinatorics;

import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.testng.annotations.Test;

/**
 * Unit test for the {@link PermutationGenerator} class.
 * @author Daniel Dyer
 */
public class PermutationGeneratorTest
{
    private final String[] elements = {"1", "2", "3"};

    /**
     * This is the main test case and ensures that the permutation generator
     * produces the correct output.
     */
    @Test
    public void testPermutations()
    {
        PermutationGenerator<String> generator = new PermutationGenerator<String>(elements);
        assert generator.getTotalPermutations() == 6 : "Possible permutations should be 6.";
        assert generator.getRemainingPermutations() == 6 : "Remaining permutations should be 6.";

        String[] permutation1 = generator.nextPermutationAsArray();
        assert permutation1.length == 3 : "Permutation length should be 3.";
        assert generator.getRemainingPermutations() == 5 : "Remaining permutations should be 5.";
        assert !permutation1[0].equals(permutation1[1]) : "Permutation elements should be different.";
        assert !permutation1[0].equals(permutation1[2]) : "Permutation elements should be different.";
        assert !permutation1[1].equals(permutation1[2]) : "Permutation elements should be different.";

        List<String> permutation2 = generator.nextPermutationAsList();
        assert permutation2.size() == 3 : "Permutation length should be 3.";
        assert generator.getRemainingPermutations() == 4: "Remaining permutations should be 4.";
        // Make sure this combination is different from the previous one.
        assert !permutation2.get(0).equals(permutation2.get(1)) : "Permutation elements should be different.";
        assert !permutation2.get(0).equals(permutation2.get(2)) : "Permutation elements should be different.";
        assert !permutation2.get(1).equals(permutation2.get(2)) : "Permutation elements should be different.";

        String perm1String = permutation1[0] + permutation1[1] + permutation1[2];
        String perm2String = permutation2.get(0) + permutation2.get(1) + permutation2.get(2);
        assert !(perm1String).equals(perm2String) : "Permutation should be different from previous one.";
    }

    /**
     * Make sure that the permutation generator correctly calculates how many
     * permutations are remaining.
     */
    @Test
    public void testPermutationCount()
    {
        PermutationGenerator<String> generator = new PermutationGenerator<String>(elements);
        assert generator.getTotalPermutations() == 6 : "Possible permutations should be 6.";
        assert generator.hasMore() : "Generator should have more permutations available.";
        assert generator.getRemainingPermutations() == 6 : "Remaining permutations should be 6.";
        // Generate all of the permutations.
        List<String> temp = new LinkedList<String>();
        for (int i = 6; i > 0; i--)
        {
            generator.nextPermutationAsList(temp);
        }
        assert generator.getTotalPermutations() == 6 : "Total permutations should be unchanged.";
        assert generator.getRemainingPermutations() == 0 : "Remaining permutations should be zero.";
        assert !generator.hasMore() : "Should be no more permutations.";
    }

    /**
     * Ensures that the permutation generator works correctly with the "for-each" style
     * loop.
     */
    @Test
    public void testIterable()
    {
        PermutationGenerator<String> generator = new PermutationGenerator<String>(elements);
        Set<String> distinctPermutations = new HashSet<String>();
        for (List<String> permutation : generator)
        {
            assert permutation.size() == 3 : "Wrong permutation length: " + permutation.size();
            // Flatten to a single string for easier comparison.
            distinctPermutations.add(permutation.get(0) + permutation.get(1) + permutation.get(2));
        }
        assert distinctPermutations.size() == 6 : "Wrong number of permutations: " + distinctPermutations.size();
    }

    /**
     * Ensures that the iterator is read-only.
     */
    @Test(expectedExceptions = UnsupportedOperationException.class)
    public void testIteratorRemove()
    {
        PermutationGenerator<String> generator = new PermutationGenerator<String>(elements);
        Iterator<List<String>> iterator = generator.iterator();
        iterator.next();
        iterator.remove(); // Should throw UnsupportedOperationException.
    }

    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testTooManyElements()
    {
        // 21 elements is too many to be able to process using 64-bit values.
        new PermutationGenerator<Integer>(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
                                                        11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21});
        // Should throw an IllegalArgumentException.
    }

    /**
     * When generating a permutation into an existing array, that
     * array must be big enough to hold the permutation.
     */
    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testDestinationArrayTooShort()
    {
        PermutationGenerator<String> generator = new PermutationGenerator<String>(elements);
        generator.nextPermutationAsArray(new String[2]); // Should throw an exception.
    }

    /**
     * When generating a permutation into an existing array, that array should
     * not be bigger than required.  Otherwise subtle bugs may occur in programs
     * that use the permutation generator when the end of the array contains nulls
     * or zeros.
     */
    @Test(expectedExceptions = IllegalArgumentException.class)
    public void testDestinationArrayTooLong()
    {
        PermutationGenerator<String> generator = new PermutationGenerator<String>(elements);
        generator.nextPermutationAsArray(new String[4]); // Should throw an exception.
    }

    /**
     * Zero-length permutations for an emtpy set of elements is not an error.
     * It should not return any permutations other than a single empty one.
     */
    @Test
    public void testZeroLength()
    {
        PermutationGenerator<String> generator = new PermutationGenerator<String>(Collections.<String>emptyList());
        assert generator.getTotalPermutations() == 1 : "Should be only one permutation.";
        List<String> permutation = generator.nextPermutationAsList();
        assert permutation.isEmpty() : "Permutation should be zero-length.";
        assert !generator.hasMore() : "Should be no more permutations.";
    }

    @Test(dependsOnMethods = "testZeroLength",
          expectedExceptions = IllegalStateException.class)
    public void testExhaustion()
    {
        PermutationGenerator<String> generator = new PermutationGenerator<String>(Collections.<String>emptyList());
        generator.nextPermutationAsList(); // First one should succeed.
        generator.nextPermutationAsList(); // Second one should throw an exception.
    }
}


text:
package utilsfakes

import (
	"context"
	"sync"

	"github.com/cloudfoundry/buildpacks-ci/cve-notification-app/utils"
	"go.mongodb.org/mongo-driver/mongo"
)

type FakeMongoUtilsInterface struct {
	CVEExistsStub        func(string, context.Context, *mongo.Collection) (bool, error)
	cVEExistsMutex       sync.RWMutex
	cVEExistsArgsForCall []struct {
		arg1 string
		arg2 context.Context
		arg3 *mongo.Collection
	}
	cVEExistsReturns struct {
		result1 bool
		result2 error
	}
	cVEExistsReturnsOnCall map[int]struct {
		result1 bool
		result2 error
	}
	CreateCVEStub        func(*utils.CVE, context.Context, *mongo.Collection) error
	createCVEMutex       sync.RWMutex
	createCVEArgsForCall []struct {
		arg1 *utils.CVE
		arg2 context.Context
		arg3 *mongo.Collection
	}
	createCVEReturns struct {
		result1 error
	}
	createCVEReturnsOnCall map[int]struct {
		result1 error
	}
	DisconnectMongoClientStub        func(*mongo.Client, context.Context) error
	disconnectMongoClientMutex       sync.RWMutex
	disconnectMongoClientArgsForCall []struct {
		arg1 *mongo.Client
		arg2 context.Context
	}
	disconnectMongoClientReturns struct {
		result1 error
	}
	disconnectMongoClientReturnsOnCall map[int]struct {
		result1 error
	}
	FindCVEStub        func(string, context.Context, *mongo.Collection) (utils.CVE, error)
	findCVEMutex       sync.RWMutex
	findCVEArgsForCall []struct {
		arg1 string
		arg2 context.Context
		arg3 *mongo.Collection
	}
	findCVEReturns struct {
		result1 utils.CVE
		result2 error
	}
	findCVEReturnsOnCall map[int]struct {
		result1 utils.CVE
		result2 error
	}
	GetAllCVEsStub        func(context.Context, *mongo.Collection) ([]utils.CVE, error)
	getAllCVEsMutex       sync.RWMutex
	getAllCVEsArgsForCall []struct {
		arg1 context.Context
		arg2 *mongo.Collection
	}
	getAllCVEsReturns struct {
		result1 []utils.CVE
		result2 error
	}
	getAllCVEsReturnsOnCall map[int]struct {
		result1 []utils.CVE
		result2 error
	}
	GetMongoClientStub        func() (*mongo.Client, context.Context, error)
	getMongoClientMutex       sync.RWMutex
	getMongoClientArgsForCall []struct {
	}
	getMongoClientReturns struct {
		result1 *mongo.Client
		result2 context.Context
		result3 error
	}
	getMongoClientReturnsOnCall map[int]struct {
		result1 *mongo.Client
		result2 context.Context
		result3 error
	}
	GetMongoCollectionStub        func(mongo.Client, string, string) *mongo.Collection
	getMongoCollectionMutex       sync.RWMutex
	getMongoCollectionArgsForCall []struct {
		arg1 mongo.Client
		arg2 string
		arg3 string
	}
	getMongoCollectionReturns struct {
		result1 *mongo.Collection
	}
	getMongoCollectionReturnsOnCall map[int]struct {
		result1 *mongo.Collection
	}
	GetUniqueDependenciesStub        func(context.Context, *mongo.Collection) ([]utils.CVE, error)
	getUniqueDependenciesMutex       sync.RWMutex
	getUniqueDependenciesArgsForCall []struct {
		arg1 context.Context
		arg2 *mongo.Collection
	}
	getUniqueDependenciesReturns struct {
		result1 []utils.CVE
		result2 error
	}
	getUniqueDependenciesReturnsOnCall map[int]struct {
		result1 []utils.CVE
		result2 error
	}
	RemoveAllCVEsStub        func(string, context.Context, *mongo.Collection) error
	removeAllCVEsMutex       sync.RWMutex
	removeAllCVEsArgsForCall []struct {
		arg1 string
		arg2 context.Context
		arg3 *mongo.Collection
	}
	removeAllCVEsReturns struct {
		result1 error
	}
	removeAllCVEsReturnsOnCall map[int]struct {
		result1 error
	}
	invocations      map[string][][]interface{}
	invocationsMutex sync.RWMutex
}

func (fake *FakeMongoUtilsInterface) CVEExists(arg1 string, arg2 context.Context, arg3 *mongo.Collection) (bool, error) {
	fake.cVEExistsMutex.Lock()
	ret, specificReturn := fake.cVEExistsReturnsOnCall[len(fake.cVEExistsArgsForCall)]
	fake.cVEExistsArgsForCall = append(fake.cVEExistsArgsForCall, struct {
		arg1 string
		arg2 context.Context
		arg3 *mongo.Collection
	}{arg1, arg2, arg3})
	stub := fake.CVEExistsStub
	fakeReturns := fake.cVEExistsReturns
	fake.recordInvocation("CVEExists", []interface{}{arg1, arg2, arg3})
	fake.cVEExistsMutex.Unlock()
	if stub != nil {
		return stub(arg1, arg2, arg3)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeMongoUtilsInterface) CVEExistsCallCount() int {
	fake.cVEExistsMutex.RLock()
	defer fake.cVEExistsMutex.RUnlock()
	return len(fake.cVEExistsArgsForCall)
}

func (fake *FakeMongoUtilsInterface) CVEExistsCalls(stub func(string, context.Context, *mongo.Collection) (bool, error)) {
	fake.cVEExistsMutex.Lock()
	defer fake.cVEExistsMutex.Unlock()
	fake.CVEExistsStub = stub
}

func (fake *FakeMongoUtilsInterface) CVEExistsArgsForCall(i int) (string, context.Context, *mongo.Collection) {
	fake.cVEExistsMutex.RLock()
	defer fake.cVEExistsMutex.RUnlock()
	argsForCall := fake.cVEExistsArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}

func (fake *FakeMongoUtilsInterface) CVEExistsReturns(result1 bool, result2 error) {
	fake.cVEExistsMutex.Lock()
	defer fake.cVEExistsMutex.Unlock()
	fake.CVEExistsStub = nil
	fake.cVEExistsReturns = struct {
		result1 bool
		result2 error
	}{result1, result2}
}

func (fake *FakeMongoUtilsInterface) CVEExistsReturnsOnCall(i int, result1 bool, result2 error) {
	fake.cVEExistsMutex.Lock()
	defer fake.cVEExistsMutex.Unlock()
	fake.CVEExistsStub = nil
	if fake.cVEExistsReturnsOnCall == nil {
		fake.cVEExistsReturnsOnCall = make(map[int]struct {
			result1 bool
			result2 error
		})
	}
	fake.cVEExistsReturnsOnCall[i] = struct {
		result1 bool
		result2 error
	}{result1, result2}
}

func (fake *FakeMongoUtilsInterface) CreateCVE(arg1 *utils.CVE, arg2 context.Context, arg3 *mongo.Collection) error {
	fake.createCVEMutex.Lock()
	ret, specificReturn := fake.createCVEReturnsOnCall[len(fake.createCVEArgsForCall)]
	fake.createCVEArgsForCall = append(fake.createCVEArgsForCall, struct {
		arg1 *utils.CVE
		arg2 context.Context
		arg3 *mongo.Collection
	}{arg1, arg2, arg3})
	stub := fake.CreateCVEStub
	fakeReturns := fake.createCVEReturns
	fake.recordInvocation("CreateCVE", []interface{}{arg1, arg2, arg3})
	fake.createCVEMutex.Unlock()
	if stub != nil {
		return stub(arg1, arg2, arg3)
	}
	if specificReturn {
		return ret.result1
	}
	return fakeReturns.result1
}

func (fake *FakeMongoUtilsInterface) CreateCVECallCount() int {
	fake.createCVEMutex.RLock()
	defer fake.createCVEMutex.RUnlock()
	return len(fake.createCVEArgsForCall)
}

func (fake *FakeMongoUtilsInterface) CreateCVECalls(stub func(*utils.CVE, context.Context, *mongo.Collection) error) {
	fake.createCVEMutex.Lock()
	defer fake.createCVEMutex.Unlock()
	fake.CreateCVEStub = stub
}

func (fake *FakeMongoUtilsInterface) CreateCVEArgsForCall(i int) (*utils.CVE, context.Context, *mongo.Collection) {
	fake.createCVEMutex.RLock()
	defer fake.createCVEMutex.RUnlock()
	argsForCall := fake.createCVEArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}

func (fake *FakeMongoUtilsInterface) CreateCVEReturns(result1 error) {
	fake.createCVEMutex.Lock()
	defer fake.createCVEMutex.Unlock()
	fake.CreateCVEStub = nil
	fake.createCVEReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeMongoUtilsInterface) CreateCVEReturnsOnCall(i int, result1 error) {
	fake.createCVEMutex.Lock()
	defer fake.createCVEMutex.Unlock()
	fake.CreateCVEStub = nil
	if fake.createCVEReturnsOnCall == nil {
		fake.createCVEReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.createCVEReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeMongoUtilsInterface) DisconnectMongoClient(arg1 *mongo.Client, arg2 context.Context) error {
	fake.disconnectMongoClientMutex.Lock()
	ret, specificReturn := fake.disconnectMongoClientReturnsOnCall[len(fake.disconnectMongoClientArgsForCall)]
	fake.disconnectMongoClientArgsForCall = append(fake.disconnectMongoClientArgsForCall, struct {
		arg1 *mongo.Client
		arg2 context.Context
	}{arg1, arg2})
	stub := fake.DisconnectMongoClientStub
	fakeReturns := fake.disconnectMongoClientReturns
	fake.recordInvocation("DisconnectMongoClient", []interface{}{arg1, arg2})
	fake.disconnectMongoClientMutex.Unlock()
	if stub != nil {
		return stub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1
	}
	return fakeReturns.result1
}

func (fake *FakeMongoUtilsInterface) DisconnectMongoClientCallCount() int {
	fake.disconnectMongoClientMutex.RLock()
	defer fake.disconnectMongoClientMutex.RUnlock()
	return len(fake.disconnectMongoClientArgsForCall)
}

func (fake *FakeMongoUtilsInterface) DisconnectMongoClientCalls(stub func(*mongo.Client, context.Context) error) {
	fake.disconnectMongoClientMutex.Lock()
	defer fake.disconnectMongoClientMutex.Unlock()
	fake.DisconnectMongoClientStub = stub
}

func (fake *FakeMongoUtilsInterface) DisconnectMongoClientArgsForCall(i int) (*mongo.Client, context.Context) {
	fake.disconnectMongoClientMutex.RLock()
	defer fake.disconnectMongoClientMutex.RUnlock()
	argsForCall := fake.disconnectMongoClientArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeMongoUtilsInterface) DisconnectMongoClientReturns(result1 error) {
	fake.disconnectMongoClientMutex.Lock()
	defer fake.disconnectMongoClientMutex.Unlock()
	fake.DisconnectMongoClientStub = nil
	fake.disconnectMongoClientReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeMongoUtilsInterface) DisconnectMongoClientReturnsOnCall(i int, result1 error) {
	fake.disconnectMongoClientMutex.Lock()
	defer fake.disconnectMongoClientMutex.Unlock()
	fake.DisconnectMongoClientStub = nil
	if fake.disconnectMongoClientReturnsOnCall == nil {
		fake.disconnectMongoClientReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.disconnectMongoClientReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeMongoUtilsInterface) FindCVE(arg1 string, arg2 context.Context, arg3 *mongo.Collection) (utils.CVE, error) {
	fake.findCVEMutex.Lock()
	ret, specificReturn := fake.findCVEReturnsOnCall[len(fake.findCVEArgsForCall)]
	fake.findCVEArgsForCall = append(fake.findCVEArgsForCall, struct {
		arg1 string
		arg2 context.Context
		arg3 *mongo.Collection
	}{arg1, arg2, arg3})
	stub := fake.FindCVEStub
	fakeReturns := fake.findCVEReturns
	fake.recordInvocation("FindCVE", []interface{}{arg1, arg2, arg3})
	fake.findCVEMutex.Unlock()
	if stub != nil {
		return stub(arg1, arg2, arg3)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeMongoUtilsInterface) FindCVECallCount() int {
	fake.findCVEMutex.RLock()
	defer fake.findCVEMutex.RUnlock()
	return len(fake.findCVEArgsForCall)
}

func (fake *FakeMongoUtilsInterface) FindCVECalls(stub func(string, context.Context, *mongo.Collection) (utils.CVE, error)) {
	fake.findCVEMutex.Lock()
	defer fake.findCVEMutex.Unlock()
	fake.FindCVEStub = stub
}

func (fake *FakeMongoUtilsInterface) FindCVEArgsForCall(i int) (string, context.Context, *mongo.Collection) {
	fake.findCVEMutex.RLock()
	defer fake.findCVEMutex.RUnlock()
	argsForCall := fake.findCVEArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}

func (fake *FakeMongoUtilsInterface) FindCVEReturns(result1 utils.CVE, result2 error) {
	fake.findCVEMutex.Lock()
	defer fake.findCVEMutex.Unlock()
	fake.FindCVEStub = nil
	fake.findCVEReturns = struct {
		result1 utils.CVE
		result2 error
	}{result1, result2}
}

func (fake *FakeMongoUtilsInterface) FindCVEReturnsOnCall(i int, result1 utils.CVE, result2 error) {
	fake.findCVEMutex.Lock()
	defer fake.findCVEMutex.Unlock()
	fake.FindCVEStub = nil
	if fake.findCVEReturnsOnCall == nil {
		fake.findCVEReturnsOnCall = make(map[int]struct {
			result1 utils.CVE
			result2 error
		})
	}
	fake.findCVEReturnsOnCall[i] = struct {
		result1 utils.CVE
		result2 error
	}{result1, result2}
}

func (fake *FakeMongoUtilsInterface) GetAllCVEs(arg1 context.Context, arg2 *mongo.Collection) ([]utils.CVE, error) {
	fake.getAllCVEsMutex.Lock()
	ret, specificReturn := fake.getAllCVEsReturnsOnCall[len(fake.getAllCVEsArgsForCall)]
	fake.getAllCVEsArgsForCall = append(fake.getAllCVEsArgsForCall, struct {
		arg1 context.Context
		arg2 *mongo.Collection
	}{arg1, arg2})
	stub := fake.GetAllCVEsStub
	fakeReturns := fake.getAllCVEsReturns
	fake.recordInvocation("GetAllCVEs", []interface{}{arg1, arg2})
	fake.getAllCVEsMutex.Unlock()
	if stub != nil {
		return stub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeMongoUtilsInterface) GetAllCVEsCallCount() int {
	fake.getAllCVEsMutex.RLock()
	defer fake.getAllCVEsMutex.RUnlock()
	return len(fake.getAllCVEsArgsForCall)
}

func (fake *FakeMongoUtilsInterface) GetAllCVEsCalls(stub func(context.Context, *mongo.Collection) ([]utils.CVE, error)) {
	fake.getAllCVEsMutex.Lock()
	defer fake.getAllCVEsMutex.Unlock()
	fake.GetAllCVEsStub = stub
}

func (fake *FakeMongoUtilsInterface) GetAllCVEsArgsForCall(i int) (context.Context, *mongo.Collection) {
	fake.getAllCVEsMutex.RLock()
	defer fake.getAllCVEsMutex.RUnlock()
	argsForCall := fake.getAllCVEsArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeMongoUtilsInterface) GetAllCVEsReturns(result1 []utils.CVE, result2 error) {
	fake.getAllCVEsMutex.Lock()
	defer fake.getAllCVEsMutex.Unlock()
	fake.GetAllCVEsStub = nil
	fake.getAllCVEsReturns = struct {
		result1 []utils.CVE
		result2 error
	}{result1, result2}
}

func (fake *FakeMongoUtilsInterface) GetAllCVEsReturnsOnCall(i int, result1 []utils.CVE, result2 error) {
	fake.getAllCVEsMutex.Lock()
	defer fake.getAllCVEsMutex.Unlock()
	fake.GetAllCVEsStub = nil
	if fake.getAllCVEsReturnsOnCall == nil {
		fake.getAllCVEsReturnsOnCall = make(map[int]struct {
			result1 []utils.CVE
			result2 error
		})
	}
	fake.getAllCVEsReturnsOnCall[i] = struct {
		result1 []utils.CVE
		result2 error
	}{result1, result2}
}

func (fake *FakeMongoUtilsInterface) GetMongoClient() (*mongo.Client, context.Context, error) {
	fake.getMongoClientMutex.Lock()
	ret, specificReturn := fake.getMongoClientReturnsOnCall[len(fake.getMongoClientArgsForCall)]
	fake.getMongoClientArgsForCall = append(fake.getMongoClientArgsForCall, struct {
	}{})
	stub := fake.GetMongoClientStub
	fakeReturns := fake.getMongoClientReturns
	fake.recordInvocation("GetMongoClient", []interface{}{})
	fake.getMongoClientMutex.Unlock()
	if stub != nil {
		return stub()
	}
	if specificReturn {
		return ret.result1, ret.result2, ret.result3
	}
	return fakeReturns.result1, fakeReturns.result2, fakeReturns.result3
}

func (fake *FakeMongoUtilsInterface) GetMongoClientCallCount() int {
	fake.getMongoClientMutex.RLock()
	defer fake.getMongoClientMutex.RUnlock()
	return len(fake.getMongoClientArgsForCall)
}

func (fake *FakeMongoUtilsInterface) GetMongoClientCalls(stub func() (*mongo.Client, context.Context, error)) {
	fake.getMongoClientMutex.Lock()
	defer fake.getMongoClientMutex.Unlock()
	fake.GetMongoClientStub = stub
}

func (fake *FakeMongoUtilsInterface) GetMongoClientReturns(result1 *mongo.Client, result2 context.Context, result3 error) {
	fake.getMongoClientMutex.Lock()
	defer fake.getMongoClientMutex.Unlock()
	fake.GetMongoClientStub = nil
	fake.getMongoClientReturns = struct {
		result1 *mongo.Client
		result2 context.Context
		result3 error
	}{result1, result2, result3}
}

func (fake *FakeMongoUtilsInterface) GetMongoClientReturnsOnCall(i int, result1 *mongo.Client, result2 context.Context, result3 error) {
	fake.getMongoClientMutex.Lock()
	defer fake.getMongoClientMutex.Unlock()
	fake.GetMongoClientStub = nil
	if fake.getMongoClientReturnsOnCall == nil {
		fake.getMongoClientReturnsOnCall = make(map[int]struct {
			result1 *mongo.Client
			result2 context.Context
			result3 error
		})
	}
	fake.getMongoClientReturnsOnCall[i] = struct {
		result1 *mongo.Client
		result2 context.Context
		result3 error
	}{result1, result2, result3}
}

func (fake *FakeMongoUtilsInterface) GetMongoCollection(arg1 mongo.Client, arg2 string, arg3 string) *mongo.Collection {
	fake.getMongoCollectionMutex.Lock()
	ret, specificReturn := fake.getMongoCollectionReturnsOnCall[len(fake.getMongoCollectionArgsForCall)]
	fake.getMongoCollectionArgsForCall = append(fake.getMongoCollectionArgsForCall, struct {
		arg1 mongo.Client
		arg2 string
		arg3 string
	}{arg1, arg2, arg3})
	stub := fake.GetMongoCollectionStub
	fakeReturns := fake.getMongoCollectionReturns
	fake.recordInvocation("GetMongoCollection", []interface{}{arg1, arg2, arg3})
	fake.getMongoCollectionMutex.Unlock()
	if stub != nil {
		return stub(arg1, arg2, arg3)
	}
	if specificReturn {
		return ret.result1
	}
	return fakeReturns.result1
}

func (fake *FakeMongoUtilsInterface) GetMongoCollectionCallCount() int {
	fake.getMongoCollectionMutex.RLock()
	defer fake.getMongoCollectionMutex.RUnlock()
	return len(fake.getMongoCollectionArgsForCall)
}

func (fake *FakeMongoUtilsInterface) GetMongoCollectionCalls(stub func(mongo.Client, string, string) *mongo.Collection) {
	fake.getMongoCollectionMutex.Lock()
	defer fake.getMongoCollectionMutex.Unlock()
	fake.GetMongoCollectionStub = stub
}

func (fake *FakeMongoUtilsInterface) GetMongoCollectionArgsForCall(i int) (mongo.Client, string, string) {
	fake.getMongoCollectionMutex.RLock()
	defer fake.getMongoCollectionMutex.RUnlock()
	argsForCall := fake.getMongoCollectionArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}

func (fake *FakeMongoUtilsInterface) GetMongoCollectionReturns(result1 *mongo.Collection) {
	fake.getMongoCollectionMutex.Lock()
	defer fake.getMongoCollectionMutex.Unlock()
	fake.GetMongoCollectionStub = nil
	fake.getMongoCollectionReturns = struct {
		result1 *mongo.Collection
	}{result1}
}

func (fake *FakeMongoUtilsInterface) GetMongoCollectionReturnsOnCall(i int, result1 *mongo.Collection) {
	fake.getMongoCollectionMutex.Lock()
	defer fake.getMongoCollectionMutex.Unlock()
	fake.GetMongoCollectionStub = nil
	if fake.getMongoCollectionReturnsOnCall == nil {
		fake.getMongoCollectionReturnsOnCall = make(map[int]struct {
			result1 *mongo.Collection
		})
	}
	fake.getMongoCollectionReturnsOnCall[i] = struct {
		result1 *mongo.Collection
	}{result1}
}

func (fake *FakeMongoUtilsInterface) GetUniqueDependencies(arg1 context.Context, arg2 *mongo.Collection) ([]utils.CVE, error) {
	fake.getUniqueDependenciesMutex.Lock()
	ret, specificReturn := fake.getUniqueDependenciesReturnsOnCall[len(fake.getUniqueDependenciesArgsForCall)]
	fake.getUniqueDependenciesArgsForCall = append(fake.getUniqueDependenciesArgsForCall, struct {
		arg1 context.Context
		arg2 *mongo.Collection
	}{arg1, arg2})
	stub := fake.GetUniqueDependenciesStub
	fakeReturns := fake.getUniqueDependenciesReturns
	fake.recordInvocation("GetUniqueDependencies", []interface{}{arg1, arg2})
	fake.getUniqueDependenciesMutex.Unlock()
	if stub != nil {
		return stub(arg1, arg2)
	}
	if specificReturn {
		return ret.result1, ret.result2
	}
	return fakeReturns.result1, fakeReturns.result2
}

func (fake *FakeMongoUtilsInterface) GetUniqueDependenciesCallCount() int {
	fake.getUniqueDependenciesMutex.RLock()
	defer fake.getUniqueDependenciesMutex.RUnlock()
	return len(fake.getUniqueDependenciesArgsForCall)
}

func (fake *FakeMongoUtilsInterface) GetUniqueDependenciesCalls(stub func(context.Context, *mongo.Collection) ([]utils.CVE, error)) {
	fake.getUniqueDependenciesMutex.Lock()
	defer fake.getUniqueDependenciesMutex.Unlock()
	fake.GetUniqueDependenciesStub = stub
}

func (fake *FakeMongoUtilsInterface) GetUniqueDependenciesArgsForCall(i int) (context.Context, *mongo.Collection) {
	fake.getUniqueDependenciesMutex.RLock()
	defer fake.getUniqueDependenciesMutex.RUnlock()
	argsForCall := fake.getUniqueDependenciesArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2
}

func (fake *FakeMongoUtilsInterface) GetUniqueDependenciesReturns(result1 []utils.CVE, result2 error) {
	fake.getUniqueDependenciesMutex.Lock()
	defer fake.getUniqueDependenciesMutex.Unlock()
	fake.GetUniqueDependenciesStub = nil
	fake.getUniqueDependenciesReturns = struct {
		result1 []utils.CVE
		result2 error
	}{result1, result2}
}

func (fake *FakeMongoUtilsInterface) GetUniqueDependenciesReturnsOnCall(i int, result1 []utils.CVE, result2 error) {
	fake.getUniqueDependenciesMutex.Lock()
	defer fake.getUniqueDependenciesMutex.Unlock()
	fake.GetUniqueDependenciesStub = nil
	if fake.getUniqueDependenciesReturnsOnCall == nil {
		fake.getUniqueDependenciesReturnsOnCall = make(map[int]struct {
			result1 []utils.CVE
			result2 error
		})
	}
	fake.getUniqueDependenciesReturnsOnCall[i] = struct {
		result1 []utils.CVE
		result2 error
	}{result1, result2}
}

func (fake *FakeMongoUtilsInterface) RemoveAllCVEs(arg1 string, arg2 context.Context, arg3 *mongo.Collection) error {
	fake.removeAllCVEsMutex.Lock()
	ret, specificReturn := fake.removeAllCVEsReturnsOnCall[len(fake.removeAllCVEsArgsForCall)]
	fake.removeAllCVEsArgsForCall = append(fake.removeAllCVEsArgsForCall, struct {
		arg1 string
		arg2 context.Context
		arg3 *mongo.Collection
	}{arg1, arg2, arg3})
	stub := fake.RemoveAllCVEsStub
	fakeReturns := fake.removeAllCVEsReturns
	fake.recordInvocation("RemoveAllCVEs", []interface{}{arg1, arg2, arg3})
	fake.removeAllCVEsMutex.Unlock()
	if stub != nil {
		return stub(arg1, arg2, arg3)
	}
	if specificReturn {
		return ret.result1
	}
	return fakeReturns.result1
}

func (fake *FakeMongoUtilsInterface) RemoveAllCVEsCallCount() int {
	fake.removeAllCVEsMutex.RLock()
	defer fake.removeAllCVEsMutex.RUnlock()
	return len(fake.removeAllCVEsArgsForCall)
}

func (fake *FakeMongoUtilsInterface) RemoveAllCVEsCalls(stub func(string, context.Context, *mongo.Collection) error) {
	fake.removeAllCVEsMutex.Lock()
	defer fake.removeAllCVEsMutex.Unlock()
	fake.RemoveAllCVEsStub = stub
}

func (fake *FakeMongoUtilsInterface) RemoveAllCVEsArgsForCall(i int) (string, context.Context, *mongo.Collection) {
	fake.removeAllCVEsMutex.RLock()
	defer fake.removeAllCVEsMutex.RUnlock()
	argsForCall := fake.removeAllCVEsArgsForCall[i]
	return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3
}

func (fake *FakeMongoUtilsInterface) RemoveAllCVEsReturns(result1 error) {
	fake.removeAllCVEsMutex.Lock()
	defer fake.removeAllCVEsMutex.Unlock()
	fake.RemoveAllCVEsStub = nil
	fake.removeAllCVEsReturns = struct {
		result1 error
	}{result1}
}

func (fake *FakeMongoUtilsInterface) RemoveAllCVEsReturnsOnCall(i int, result1 error) {
	fake.removeAllCVEsMutex.Lock()
	defer fake.removeAllCVEsMutex.Unlock()
	fake.RemoveAllCVEsStub = nil
	if fake.removeAllCVEsReturnsOnCall == nil {
		fake.removeAllCVEsReturnsOnCall = make(map[int]struct {
			result1 error
		})
	}
	fake.removeAllCVEsReturnsOnCall[i] = struct {
		result1 error
	}{result1}
}

func (fake *FakeMongoUtilsInterface) Invocations() map[string][][]interface{} {
	fake.invocationsMutex.RLock()
	defer fake.invocationsMutex.RUnlock()
	fake.cVEExistsMutex.RLock()
	defer fake.cVEExistsMutex.RUnlock()
	fake.createCVEMutex.RLock()
	defer fake.createCVEMutex.RUnlock()
	fake.disconnectMongoClientMutex.RLock()
	defer fake.disconnectMongoClientMutex.RUnlock()
	fake.findCVEMutex.RLock()
	defer fake.findCVEMutex.RUnlock()
	fake.getAllCVEsMutex.RLock()
	defer fake.getAllCVEsMutex.RUnlock()
	fake.getMongoClientMutex.RLock()
	defer fake.getMongoClientMutex.RUnlock()
	fake.getMongoCollectionMutex.RLock()
	defer fake.getMongoCollectionMutex.RUnlock()
	fake.getUniqueDependenciesMutex.RLock()
	defer fake.getUniqueDependenciesMutex.RUnlock()
	fake.removeAllCVEsMutex.RLock()
	defer fake.removeAllCVEsMutex.RUnlock()
	copiedInvocations := map[string][][]interface{}{}
	for key, value := range fake.invocations {
		copiedInvocations[key] = value
	}
	return copiedInvocations
}

func (fake *FakeMongoUtilsInterface) recordInvocation(key string, args []interface{}) {
	fake.invocationsMutex.Lock()
	defer fake.invocationsMutex.Unlock()
	if fake.invocations == nil {
		fake.invocations = map[string][][]interface{}{}
	}
	if fake.invocations[key] == nil {
		fake.invocations[key] = [][]interface{}{}
	}
	fake.invocations[key] = append(fake.invocations[key], args)
}

var _ utils.MongoUtilsInterface = new(FakeMongoUtilsInterface)

redpajama_set_name: RedPajamaGithub


text:
angular.module("uib/template/datepicker/datepicker.html", []).run(["$templateCache", function ($templateCache) {
  $templateCache.put("uib/template/datepicker/datepicker.html",
    "
\n" +
    "

\n" +
    "

\n" +
    "

\n" +
    "
\n" +
    "");
}]);


text:
<!DOCTYPE html>

	<meta charset="utf-8" />
	<title>{% if meta.title %}{{ meta.title }} | {% endif %}{{ site_title }}</title>
{% if meta.description %}
	<meta name="description" content="{{ meta.description }}">
{% endif %}{% if meta.robots %}
	<meta name="robots" content="{{ meta.robots }}">
{% endif %}
	<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,700" type="text/css" />
	<link rel="stylesheet" href="{{ theme_url }}/normalize.min.css" type="text/css" />
    <link rel="stylesheet" href="{{ theme_url }}/main.css" type="text/css" />

{{ site_title }}

				{% for page in pages %}
                    {% if not page.date %}
                        {% if page.title != "Home" %}

{{ page.title }}

                        {% endif %}
                    {% endif %}
				{% endfor %}

            {{ content }}

        Powered by Pico.
        ©2013 Michael Bickley


text:
<?php namespace IIMS\Forms;

class Supplier extends FormValidator {
    protected $rules = [
        'company_name' => 'required|unique:suppliers',
        'phone'        => 'unique:suppliers',
        'mobile'       => 'unique:suppliers',
        'email'        => 'email|unique:suppliers',
        'website'      => 'url|unique:suppliers',
        'address'      => 'required'
    ];
}


text:
///////////////////////////////////////////////////////////////////////////////
// FILE:          LeicaDMRHub.cpp
// PROJECT:       Micro-Manager
// SUBSYSTEM:     DeviceAdapters
//-----------------------------------------------------------------------------
// DESCRIPTION:   LeicaDMR hub module. Required for operation of all
//                LeicaDMR devices
//
// AUTHOR:        Nico Stuurman, nico@cmp.ucsf.edu 07/02/2009
//
// COPYRIGHT:     University of California, San Francisco, 2006
//                100xImaging, Inc. 2009
//                All rights reserved
//
// LICENSE:       This library is free software; you can redistribute it and/or
//                modify it under the terms of the GNU Lesser General Public
//                License as published by the Free Software Foundation.
//
//                You should have received a copy of the GNU Lesser General Public
//                License along with the source distribution; if not, write to
//                the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
//                Boston, MA  02111-1307  USA
//
//                This file is distributed in the hope that it will be useful,
//                but WITHOUT ANY WARRANTY; without even the implied warranty
//                of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
//
//                IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//                CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//                INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES.

#define _CRT_SECURE_NO_DEPRECATE

#include "assert.h"
#include <memory.h>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include "LeicaDMRHub.h"
#include "LeicaDMR.h"

#ifdef WIN32
#include <windows.h>
#endif

using namespace std;

LeicaDMRHub::LeicaDMRHub () :
   rLFA_(0),
   port_(""),
   initialized_(false)
{
   ClearRcvBuf();
}

LeicaDMRHub::~LeicaDMRHub()
{
   initialized_ = false;
}

int LeicaDMRHub::Initialize(MM::Device& device, MM::Core& core)
{
   if (initialized_)
      return DEVICE_OK;

   int ret = GetVersion (device, core, version_);
   if (ret != DEVICE_OK) {
      // some serial ports do not open correctly right away, so try once more:
      ret = GetVersion(device, core, version_);
      if (ret != DEVICE_OK)
         return ret;
   }

   ret = GetMicroscope(device, core, microscope_);
   if (ret != DEVICE_OK)
      return ret;

   std::ostringstream os;
   os << "Microscope type: " << microscope_;
   core.LogMessage(&device, os.str().c_str(), false);
   os.str("");
   os << "Firmware version: " << version_;
   core.LogMessage(&device, os.str().c_str(), false);

   for (int i=0; i<maxNrDevices_; i++)
      present_[i] = false;

   if (microscope_ == "DMIRBE" || microscope_ == "DMRXA" || microscope_ == "DMRA") {
      GetPresence(device, core, zDrive_);
      GetPresence(device, core, objNosepiece_);
   }
   if (microscope_ == "DMRXA" || microscope_ == "DMRA") {
      GetPresence(device, core, fDia_);
      GetPresence(device, core, rLFA4_);
      GetPresence(device, core, rLFA8_);
      GetPresence(device, core, lamp_);
      if (present_[rLFA4_])
         rLFA_ = rLFA4_;
      else if (present_[rLFA8_])
         rLFA_ = rLFA8_;
   }
   if (microscope_ == "DMIRBE") {
      GetPresence(device, core, iCPrismTurret_);
   }

   initialized_ = true;

   return DEVICE_OK;
}

///////////////////////////////////////////////////////////////////////////////
// Device commands
///////////////////////////////////////////////////////////////////////////////

int LeicaDMRHub::GetVersion(MM::Device& device, MM::Core& core, std::string& version)
{
   return GetCommand(device, core, gMic_, 25, version);
}

int LeicaDMRHub::GetMicroscope(MM::Device& device, MM::Core& core, std::string& microscope)
{
   int ret = GetCommand(device, core, gMic_, 26, microscope);
   if (ret != DEVICE_OK) {
      // the dmrxe does not have this command and will time out
      microscope = "DMRXE";
   } else
      microscope = microscope.erase(microscope.find_last_not_of(" ") + 1);
   return DEVICE_OK;
}

// Halogen Lamp

int LeicaDMRHub::GetLampIntensity(MM::Device& device, MM::Core& core, int& intensity)
{
   return GetCommand(device, core, lamp_, 10, intensity);
}

int LeicaDMRHub::SetLampIntensity(MM::Device& device, MM::Core& core, int intensity)
{
   return SetCommand(device, core, lamp_, 02, intensity);
}

// Reflected Light Turret

int LeicaDMRHub::SetRLModulePosition(MM::Device& device, MM::Core& core, int pos)
{
   if (! (rLFA_ == rLFA4_ || rLFA_ == rLFA8_))
      return ERR_INVALID_REFLECTOR_TURRET;

   return SetCommand(device, core, rLFA_, 2, pos);
}

/**
 * Request the current position from the RL Module
 * Sometimes, it does not answer correctly (i.e., 12010 yields 12010)
 * Keep on trying for up to 500 mseconds, 50 msec intervals
 */
int LeicaDMRHub::GetRLModulePosition(MM::Device& device, MM::Core& core, int& pos)
{
   if (! (rLFA_ == rLFA4_ || rLFA_ == rLFA8_))
      return ERR_INVALID_REFLECTOR_TURRET;

   pos = 0;
   MM::MMTime start = core.GetCurrentMMTime();
   int ret;
   while (pos == 0 && (core.GetCurrentMMTime() - start < 500000) ) {
      ret = GetCommand(device, core, rLFA_, 10, pos);
      if (ret != DEVICE_OK)
         return ret;
      CDeviceUtils::SleepMs(50);
   }
   if (pos == 0)
      return ERR_INVALID_POSITION;

   return DEVICE_OK;
}

int LeicaDMRHub::GetRLModuleNumberOfPositions(MM::Device& /*device*/, MM::Core& /*core*/, int& nrPos)
{
   if (rLFA_ == rLFA4_)
      nrPos = 4;
   else if (rLFA_ == rLFA8_)
      nrPos = 8;
   return DEVICE_OK;
}

// Reflected Light Shutter

int LeicaDMRHub::SetRLShutter(MM::Device& device, MM::Core& core, bool open)
{
   if (! (rLFA_ == rLFA4_ || rLFA_ == rLFA8_))
      return ERR_INVALID_REFLECTOR_TURRET;

   int pos = 0;
   if (open)
      pos = 1 ;
   return SetCommand(device, core, rLFA_, 12, pos);
}

int LeicaDMRHub::GetRLShutter(MM::Device& device, MM::Core& core, bool& open)
{
   if (! (rLFA_ == rLFA4_ || rLFA_ == rLFA8_))
      return ERR_INVALID_REFLECTOR_TURRET;

   int pos = 0;
   int ret = GetCommand(device, core, rLFA_, 13, pos);
   if (ret != DEVICE_OK)
	   return ret;

   open = false;
   if (pos == 1)
      open = true;

   return DEVICE_OK;
}

// Z Drive
int LeicaDMRHub::SetZAbs(MM::Device& device, MM::Core& core, long position)
{
   return SetCommand(device, core, zDrive_, 2, (int) position);
}

int LeicaDMRHub::SetZRel(MM::Device& device, MM::Core& core, long position)
{
   return SetCommand(device, core, zDrive_, 3, (int) position);
}

int LeicaDMRHub::MoveZConst(MM::Device& device, MM::Core& core, int speed)
{
   return SetCommand(device, core, zDrive_, 4, speed);
}

int LeicaDMRHub::StopZ(MM::Device& device, MM::Core& core)
{
   return SetCommand(device, core, zDrive_, 6);
}

int LeicaDMRHub::GetZAbs(MM::Device& device, MM::Core& core, long& position)
{
   int pos;
   int ret =  GetCommand(device, core, zDrive_, 10, pos);
   if (ret != DEVICE_OK)
      return ret;
   position = (long) pos;

   return DEVICE_OK;
}

int LeicaDMRHub::GetZUpperThreshold(MM::Device& device, MM::Core& core, long& position)
{
   int pos;
   int ret =  GetCommand(device, core, zDrive_, 14, pos);
   if (ret != DEVICE_OK)
      return ret;
   position = (long) pos;

   return DEVICE_OK;
}

int LeicaDMRHub::SetObjNosepiecePosition(MM::Device& device, MM::Core& core, int pos)
{
   return SetCommand(device, core, objNosepiece_, 2, pos);
}

int LeicaDMRHub::GetObjNosepiecePosition(MM::Device& device, MM::Core& core, int& pos)
{
   return GetCommand(device, core, objNosepiece_, 10, pos);
}

int LeicaDMRHub::SetObjNosepieceImmMode(MM::Device& device, MM::Core& core, int mode)
{
   return SetCommand(device, core, objNosepiece_, 16, mode);
}

int LeicaDMRHub::GetObjNosepieceImmMode(MM::Device& device, MM::Core& core, int& mode)
{
   return GetCommand(device, core, objNosepiece_, 17, mode);
}

int LeicaDMRHub::SetObjNosepieceRotationMode(MM::Device& device, MM::Core& core, int mode)
{
   return SetCommand(device, core, objNosepiece_, 12, mode);
}

int LeicaDMRHub::GetObjNosepieceRotationMode(MM::Device& device, MM::Core& core, int& mode)
{
   return GetCommand(device, core, objNosepiece_, 13, mode);
}

int LeicaDMRHub::GetObjNosepieceNumberOfPositions(MM::Device& device, MM::Core& core, int& nrPos)
{
   std::string status;
   int ret = GetCommand(device, core, objNosepiece_, 11, status);
   if (ret != DEVICE_OK)
      return ret;

   std::stringstream ss;
   ss << status[2];
   ss >> nrPos;

   return DEVICE_OK;
}

int LeicaDMRHub::SetApertureDiaphragmPosition(MM::Device& device, MM::Core& core, int pos)
{
   return SetCommand(device, core, aDia_, 2, pos);
}

int LeicaDMRHub::GetApertureDiaphragmPosition(MM::Device& device, MM::Core& core, int& pos)
{
   return GetCommand(device, core, aDia_, 10, pos);
}

int LeicaDMRHub::BreakApertureDiaphragm(MM::Device& device, MM::Core& core)
{
   return SetCommand(device, core, aDia_, 6);
}

int LeicaDMRHub::SetFieldDiaphragmPosition(MM::Device& device, MM::Core& core, int pos)
{
   return SetCommand(device, core, fDia_, 2, pos);
}

int LeicaDMRHub::GetFieldDiaphragmPosition(MM::Device& device, MM::Core& core, int& pos)
{
   return GetCommand(device, core, fDia_, 10, pos);
}

int LeicaDMRHub::SetCondensorPosition(MM::Device& device, MM::Core& core, int pos)
{
   return SetCommand(device, core, fDia_, 12, pos);
}

int LeicaDMRHub::GetCondensorPosition(MM::Device& device, MM::Core& core, int& pos)
{
   return GetCommand(device, core, fDia_, 13, pos);
}

int LeicaDMRHub::BreakFieldDiaphragm(MM::Device& device, MM::Core& core)
{
   return SetCommand(device, core, fDia_, 6);
}

///////////////////////////////////////////////////////////////////////////////
// HUB generic methods
///////////////////////////////////////////////////////////////////////////////

int LeicaDMRHub::GetPresence(MM::Device& device, MM::Core& core, int deviceId)
{
   if (deviceId > maxNrDevices_)
      return ERR_INDEX_OUT_OF_BOUNDS;

   int present;
   GetCommand(device, core, deviceId, 1, present);
   if (present == 1)
      present_[deviceId] = true;

   return DEVICE_OK;
}

/**
 * Clears the serial receive buffer.
 */
void LeicaDMRHub::ClearAllRcvBuf(MM::Device& device, MM::Core& core)
{
   // Read whatever has been received so far:
   unsigned long read = RCV_BUF_LENGTH;
   while (read == (unsigned long) RCV_BUF_LENGTH)
   {
      core.ReadFromSerial(&device, port_.c_str(), (unsigned char*)rcvBuf_, RCV_BUF_LENGTH,  read);
   }
   // Delete it all:
   memset(rcvBuf_, 0, RCV_BUF_LENGTH);
}

void LeicaDMRHub::ClearRcvBuf()
{
   memset(rcvBuf_, 0, RCV_BUF_LENGTH);
}

/**
 * Sends serial command to the MMCore virtual serial port.
 * returns data from the microscope as a string
 */
int LeicaDMRHub::GetCommand(MM::Device& device, MM::Core& core,  int deviceId, int command, std::string& answer)
{
   if (port_ == "")
      return ERR_PORT_NOT_SET;

   ClearAllRcvBuf(device, core);

   // send command
   std::ostringstream os;
   os << std::setw(2) << std::setfill('0') << deviceId;
   os << std::setw(3) << std::setfill('0') << command;
   int ret = core.SetSerialCommand(&device, port_.c_str(), os.str().c_str(), "\r");
   if (ret != DEVICE_OK)
      return ret;

   char rcvBuf[RCV_BUF_LENGTH];
   ret = core.GetSerialAnswer(&device, port_.c_str(), RCV_BUF_LENGTH, rcvBuf, "\r");
   if (ret != DEVICE_OK)
      return ret;

   std::stringstream s1, s2, s3;
   int commandCheck, deviceIdCheck;
   s1 << rcvBuf[0] << rcvBuf[1];
   s1 >> deviceIdCheck;
   s2 << rcvBuf[2] << rcvBuf[3] << rcvBuf[4];
   s2 >> commandCheck;
   if ( (deviceId != deviceIdCheck) || (command != commandCheck))
      return ERR_UNEXPECTED_ANSWER;

   if (strlen(rcvBuf) > 5)
      s3 << rcvBuf + 5;

   answer = s3.str();

   return DEVICE_OK;

}

/**
 * Sends serial command to the MMCore virtual serial port.
 * returns data from the microscope as an integer
 */
int LeicaDMRHub::GetCommand(MM::Device& device, MM::Core& core,  int deviceId, int command, int& answer)
{
   std::string reply;
   int ret = GetCommand(device, core, deviceId, command, reply);
   if (ret != DEVICE_OK)
      return ret;

   std::stringstream ss;
   ss << reply;
   ss >> answer;

   return DEVICE_OK;
}

/**
 * Sends serial command to the MMCore virtual serial port appended with data.
 */
int LeicaDMRHub::SetCommand(MM::Device& device, MM::Core& core,  int deviceId, int command, int data)
{
   if (port_ == "")
      return ERR_PORT_NOT_SET;

   ClearAllRcvBuf(device, core);

   // send command
   std::ostringstream os;
   os << std::setw(2) << std::setfill('0') << deviceId;
   os << std::setw(3) << std::setfill('0') << command << data;
   int ret = core.SetSerialCommand(&device, port_.c_str(), os.str().c_str(), "\r");
   if (ret != DEVICE_OK)
      return ret;

   char rcvBuf[RCV_BUF_LENGTH];
   ret = core.GetSerialAnswer(&device, port_.c_str(), RCV_BUF_LENGTH, rcvBuf, "\r");
   if (ret != DEVICE_OK)
      return ret;

   std::stringstream s1, s2, s3;
   int commandCheck, deviceIdCheck;
   s1 << rcvBuf[0] << rcvBuf[1];
   s1 >> deviceIdCheck;
   s2 << rcvBuf[2] << rcvBuf[3] << rcvBuf[4];
   s2 >> commandCheck;
   if ( (deviceId != deviceIdCheck) || (command != commandCheck))
      return ERR_UNEXPECTED_ANSWER;

   // TODO: error checking in the answer

   return DEVICE_OK;
}

/**
 * Sends serial command to the MMCore virtual serial port.
 */
int LeicaDMRHub::SetCommand(MM::Device& device, MM::Core& core,  int deviceId, int command)
{
   if (port_ == "")
      return ERR_PORT_NOT_SET;

   ClearAllRcvBuf(device, core);

   // send command
   std::ostringstream os;
   os << std::setw(2) << std::setfill('0') << deviceId;
   os << std::setw(3) << std::setfill('0') << command;
   int ret = core.SetSerialCommand(&device, port_.c_str(), os.str().c_str(), "\r");
   if (ret != DEVICE_OK)
      return ret;

   char rcvBuf[RCV_BUF_LENGTH];
   ret = core.GetSerialAnswer(&device, port_.c_str(), RCV_BUF_LENGTH, rcvBuf, "\r");
   if (ret != DEVICE_OK)
      return ret;

   std::stringstream s1, s2, s3;
   int commandCheck, deviceIdCheck;
   s1 << rcvBuf[0] << rcvBuf[1];
   s1 >> deviceIdCheck;
   s2 << rcvBuf[2] << rcvBuf[3] << rcvBuf[4];
   s2 >> commandCheck;
   if ( (deviceId != deviceIdCheck) || (command != commandCheck))
      return ERR_UNEXPECTED_ANSWER;

   // TODO: error checking in the answer

   return DEVICE_OK;
}


text:
{% load thumbnail %}

    {% thumbnail banner.get_image size as im %}

    {% empty %}

    {% endthumbnail %}


text:
using System;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Runtime.Serialization.Formatters.Binary;

using View_Spot_of_City.Helper;

namespace View_Spot_of_City.Form
{
    /// <summary>
    /// LicenseDlg.xaml 的交互逻辑
    /// </summary>
    public partial class LicenseDlg : Window, INotifyPropertyChanged
    {
        string path = AppDomain.CurrentDomain.BaseDirectory + "License.dat";
        private bool _IsCorrect;
        public LicenseDlg()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        public bool IsCorrect
        {
            get
            {
                return _IsCorrect;
            }
            set
            {
                _IsCorrect = value;
                if (this.PropertyChanged != null)
                {
                    this.PropertyChanged(this, new PropertyChangedEventArgs("IsCorrect"));
                    if (_IsCorrect)
                    {
                        image = "pack://Application:,,,/Icon/Correct.png";
                        toolTip = "Correct";
                    }
                    else
                    {
                        image = "pack://Application:,,,/Icon/Error.png";
                        toolTip = "Error";
                    }
                }
            }
        }

        private string _image;
        public string image
        {
            get
            {
                return _image;
            }
            set
            {
                if (_image != value)
                {
                    _image = value;
                    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("image"));
                }
            }
        }

        private string _toolTip;
        public string toolTip
        {
            get
            {
                return _toolTip;
            }
            set
            {
                if (_toolTip != value)
                {
                    _toolTip = value;
                    this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("toolTip"));
                }
            }
        }

        private Visibility _visibility;
        public Visibility visibility
        {
            get
            {
                return _visibility;
            }
            set
            {
                if (_visibility != value)
                {
                    if (_visibility != value)
                    {
                        _visibility = value;
                        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("visibility"));
                    }
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            Stream s = File.Open(path, FileMode.Create);//创建a.bat文件 如果之前错在a.bat文件则覆盖,无则创建
            BinaryFormatter b = new BinaryFormatter();//创建一个序列化的对象
            string Date = DateTime.Now.AddYears(1).ToString("yyyy-MM-dd hh:mm:ss");//使用期限1年
            b.Serialize(s, Date);//将数据序列化后给s
            s.Close();
            this.DialogResult = true;
            this.Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void txtFieldName_TextChanged(object sender, TextChangedEventArgs e)
        {
            DateTime Now = DateTime.Now;
            DateTime Last = Now.AddMinutes(-1);
            string resultNow = MD5_Encryption.MD5Encode(Now.ToShortDateString() + " " + Now.ToShortTimeString());
            string resultLast = MD5_Encryption.MD5Encode(Last.ToShortDateString() + " " + Last.ToShortTimeString());
            string resultDevelop = MD5_Encryption.MD5Encode("rsgisgeeks");
            if (this.txtFieldName.Text == resultNow || this.txtFieldName.Text == resultLast || this.txtFieldName.Text == resultDevelop)
            {
                IsCorrect = true;
                LogManager.LogManager.Info("注册软件");
            }
            else
            {
                IsCorrect = false;
            }
        }
    }
}


text:
var chai = require('chai');
var sinonChai = require('sinon-chai')
var expect = chai.expect
chai.use(sinonChai)
var sinon = require('sinon');
var path = require('path');
var fse = require('fs-extra');

var config = require('../../../src/cli').config
config.set({root: path.join(process.cwd(), 'test','fixtures')})

var abeExtend = require('../../../src/cli').abeExtend
var cmsData = require('../../../src/cli').cmsData
var Manager = require('../../../src/cli').Manager
var coreUtils = require('../../../src/cli').coreUtils
var cmsOperations = require('../../../src/cli').cmsOperations
var cmsTemplates = require('../../../src/cli').cmsTemplates
var Manager = require('../../../src/cli').Manager;
var Page = require('../../../src/cli').Page;

describe('cmsOperations', function() {
  before( function(done) {
    Manager.instance.init()
      .then(function () {
        Manager.instance._whereKeys = ['title', 'priority', 'abe_meta', 'articles']
        Manager.instance.updateList()

        this.fixture = {
          htmlArticle: fse.readFileSync(path.join(process.cwd(), 'test', 'fixtures', 'templates', 'article.html'), 'utf8'),
          jsonArticle: fse.readJsonSync(path.join(process.cwd(), 'test', 'fixtures', 'files', 'article-2.json')),
          jsonHomepage: fse.readJsonSync(path.join(process.cwd(), 'test', 'fixtures', 'data', 'homepage-1.json'))
        }
        done()

      }.bind(this))
  });

  /**
   * cmsOperations.remove.remove
   *
   */
  it('cmsOperations.remove.removeFile()', function() {
    // stub
    var s = sinon.sandbox.create();
    s.stub(fse, 'removeSync', function () { return null; }.bind(this));
    s.stub(coreUtils.file, 'exist', function () { return null; }.bind(this));

    var res = cmsOperations.remove.removeFile('test.html')
    chai.expect(res).to.be.equal(undefined);

    fse.removeSync.restore()
    coreUtils.file.exist.restore()
  });

  /**
   * cmsOperations.remove.remove
   *
   */
  it('cmsOperations.remove.remove()', function() {
    // stub
    var s = sinon.sandbox.create();
    s.stub(abeExtend.hooks.instance, 'trigger', function (str, obj) { return str, obj; }.bind(this));
    s.stub(cmsOperations.remove, 'removeFile', function () { return null; }.bind(this));
    s.stub(cmsData.revision, 'getVersions', function () { return []; }.bind(this));
    s.stub(Manager.instance, 'removePostFromList', function () { return null; }.bind(this));

    var res = cmsOperations.remove.remove('test.html')
    chai.expect(res).to.be.equal(undefined);

    abeExtend.hooks.instance.trigger.restore()
    cmsOperations.remove.removeFile.restore()
    cmsData.revision.getVersions.restore()
    Manager.instance.removePostFromList.restore()
  });
});


text:
package registry

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"path"
	"strings"
	"sync"

	"github.com/google/go-containerregistry/internal/verify"
	v1 "github.com/google/go-containerregistry/pkg/v1"
)

// Returns whether this url should be handled by the blob handler
// This is complicated because blob is indicated by the trailing path, not the leading path.
// https://github.com/opencontainers/distribution-spec/blob/master/spec.md#pulling-a-layer
// https://github.com/opencontainers/distribution-spec/blob/master/spec.md#pushing-a-layer
func isBlob(req *http.Request) bool {
	elem := strings.Split(req.URL.Path, "/")
	elem = elem[1:]
	if elem[len(elem)-1] == "" {
		elem = elem[:len(elem)-1]
	}
	if len(elem) < 3 {
		return false
	}
	return elem[len(elem)-2] == "blobs" || (elem[len(elem)-3] == "blobs" &&
		elem[len(elem)-2] == "uploads")
}

// blobHandler represents a minimal blob storage backend, capable of serving
// blob contents.
type blobHandler interface {
	// Get gets the blob contents, or errNotFound if the blob wasn't found.
	Get(ctx context.Context, repo string, h v1.Hash) (io.ReadCloser, error)
}

// blobStatHandler is an extension interface representing a blob storage
// backend that can serve metadata about blobs.
type blobStatHandler interface {
	// Stat returns the size of the blob, or errNotFound if the blob wasn't
	// found, or redirectError if the blob can be found elsewhere.
	Stat(ctx context.Context, repo string, h v1.Hash) (int64, error)
}

// blobPutHandler is an extension interface representing a blob storage backend
// that can write blob contents.
type blobPutHandler interface {
	// Put puts the blob contents.
	//
	// The contents will be verified against the expected size and digest
	// as the contents are read, and an error will be returned if these
	// don't match. Implementations should return that error, or a wrapper
	// around that error, to return the correct error when these don't match.
	Put(ctx context.Context, repo string, h v1.Hash, rc io.ReadCloser) error
}

// blobDeleteHandler is an extension interface representing a blob storage
// backend that can delete blob contents.
type blobDeleteHandler interface {
	// Delete the blob contents.
	Delete(ctx context.Context, repo string, h v1.Hash) error
}

// redirectError represents a signal that the blob handler doesn't have the blob
// contents, but that those contents are at another location which registry
// clients should redirect to.
type redirectError struct {
	// Location is the location to find the contents.
	Location string

	// Code is the HTTP redirect status code to return to clients.
	Code int
}

func (e redirectError) Error() string { return fmt.Sprintf("redirecting (%d): %s", e.Code, e.Location) }

// errNotFound represents an error locating the blob.
var errNotFound = errors.New("not found")

type memHandler struct {
	m    map[string][]byte
	lock sync.Mutex
}

func (m *memHandler) Stat(_ context.Context, _ string, h v1.Hash) (int64, error) {
	m.lock.Lock()
	defer m.lock.Unlock()

	b, found := m.m[h.String()]
	if !found {
		return 0, errNotFound
	}
	return int64(len(b)), nil
}
func (m *memHandler) Get(_ context.Context, _ string, h v1.Hash) (io.ReadCloser, error) {
	m.lock.Lock()
	defer m.lock.Unlock()

	b, found := m.m[h.String()]
	if !found {
		return nil, errNotFound
	}
	return ioutil.NopCloser(bytes.NewReader(b)), nil
}
func (m *memHandler) Put(_ context.Context, _ string, h v1.Hash, rc io.ReadCloser) error {
	m.lock.Lock()
	defer m.lock.Unlock()

	defer rc.Close()
	all, err := ioutil.ReadAll(rc)
	if err != nil {
		return err
	}
	m.m[h.String()] = all
	return nil
}
func (m *memHandler) Delete(_ context.Context, _ string, h v1.Hash) error {
	m.lock.Lock()
	defer m.lock.Unlock()

	if _, found := m.m[h.String()]; !found {
		return errNotFound
	}

	delete(m.m, h.String())
	return nil
}

// blobs
type blobs struct {
	blobHandler blobHandler

	// Each upload gets a unique id that writes occur to until finalized.
	uploads map[string][]byte
	lock    sync.Mutex
}

func (b *blobs) handle(resp http.ResponseWriter, req *http.Request) *regError {
	elem := strings.Split(req.URL.Path, "/")
	elem = elem[1:]
	if elem[len(elem)-1] == "" {
		elem = elem[:len(elem)-1]
	}
	// Must have a path of form /v2/{name}/blobs/{upload,sha256:}
	if len(elem) < 4 {
		return &regError{
			Status:  http.StatusBadRequest,
			Code:    "NAME_INVALID",
			Message: "blobs must be attached to a repo",
		}
	}
	target := elem[len(elem)-1]
	service := elem[len(elem)-2]
	digest := req.URL.Query().Get("digest")
	contentRange := req.Header.Get("Content-Range")

	repo := req.URL.Host + path.Join(elem[1:len(elem)-2]...)

	switch req.Method {
	case http.MethodHead:
		h, err := v1.NewHash(target)
		if err != nil {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "NAME_INVALID",
				Message: "invalid digest",
			}
		}

		var size int64
		if bsh, ok := b.blobHandler.(blobStatHandler); ok {
			size, err = bsh.Stat(req.Context(), repo, h)
			if errors.Is(err, errNotFound) {
				return regErrBlobUnknown
			} else if err != nil {
				var rerr redirectError
				if errors.As(err, &rerr) {
					http.Redirect(resp, req, rerr.Location, rerr.Code)
					return nil
				}
				return regErrInternal(err)
			}
		} else {
			rc, err := b.blobHandler.Get(req.Context(), repo, h)
			if errors.Is(err, errNotFound) {
				return regErrBlobUnknown
			} else if err != nil {
				var rerr redirectError
				if errors.As(err, &rerr) {
					http.Redirect(resp, req, rerr.Location, rerr.Code)
					return nil
				}
				return regErrInternal(err)
			}
			defer rc.Close()
			size, err = io.Copy(ioutil.Discard, rc)
			if err != nil {
				return regErrInternal(err)
			}
		}

		resp.Header().Set("Content-Length", fmt.Sprint(size))
		resp.Header().Set("Docker-Content-Digest", h.String())
		resp.WriteHeader(http.StatusOK)
		return nil

	case http.MethodGet:
		h, err := v1.NewHash(target)
		if err != nil {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "NAME_INVALID",
				Message: "invalid digest",
			}
		}

		var size int64
		var r io.Reader
		if bsh, ok := b.blobHandler.(blobStatHandler); ok {
			size, err = bsh.Stat(req.Context(), repo, h)
			if errors.Is(err, errNotFound) {
				return regErrBlobUnknown
			} else if err != nil {
				var rerr redirectError
				if errors.As(err, &rerr) {
					http.Redirect(resp, req, rerr.Location, rerr.Code)
					return nil
				}
				return regErrInternal(err)
			}

			rc, err := b.blobHandler.Get(req.Context(), repo, h)
			if errors.Is(err, errNotFound) {
				return regErrBlobUnknown
			} else if err != nil {
				var rerr redirectError
				if errors.As(err, &rerr) {
					http.Redirect(resp, req, rerr.Location, rerr.Code)
					return nil
				}

				return regErrInternal(err)
			}
			defer rc.Close()
			r = rc
		} else {
			tmp, err := b.blobHandler.Get(req.Context(), repo, h)
			if errors.Is(err, errNotFound) {
				return regErrBlobUnknown
			} else if err != nil {
				var rerr redirectError
				if errors.As(err, &rerr) {
					http.Redirect(resp, req, rerr.Location, rerr.Code)
					return nil
				}

				return regErrInternal(err)
			}
			defer tmp.Close()
			var buf bytes.Buffer
			io.Copy(&buf, tmp)
			size = int64(buf.Len())
			r = &buf
		}

		resp.Header().Set("Content-Length", fmt.Sprint(size))
		resp.Header().Set("Docker-Content-Digest", h.String())
		resp.WriteHeader(http.StatusOK)
		io.Copy(resp, r)
		return nil

	case http.MethodPost:
		bph, ok := b.blobHandler.(blobPutHandler)
		if !ok {
			return regErrUnsupported
		}

		// It is weird that this is "target" instead of "service", but
		// that's how the index math works out above.
		if target != "uploads" {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "METHOD_UNKNOWN",
				Message: fmt.Sprintf("POST to /blobs must be followed by /uploads, got %s", target),
			}
		}

		if digest != "" {
			h, err := v1.NewHash(digest)
			if err != nil {
				return regErrDigestInvalid
			}

			vrc, err := verify.ReadCloser(req.Body, req.ContentLength, h)
			if err != nil {
				return regErrInternal(err)
			}
			defer vrc.Close()

			if err = bph.Put(req.Context(), repo, h, vrc); err != nil {
				if errors.As(err, &verify.Error{}) {
					log.Printf("Digest mismatch: %v", err)
					return regErrDigestMismatch
				}
				return regErrInternal(err)
			}
			resp.Header().Set("Docker-Content-Digest", h.String())
			resp.WriteHeader(http.StatusCreated)
			return nil
		}

		id := fmt.Sprint(rand.Int63())
		resp.Header().Set("Location", "/"+path.Join("v2", path.Join(elem[1:len(elem)-2]...), "blobs/uploads", id))
		resp.Header().Set("Range", "0-0")
		resp.WriteHeader(http.StatusAccepted)
		return nil

	case http.MethodPatch:
		if service != "uploads" {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "METHOD_UNKNOWN",
				Message: fmt.Sprintf("PATCH to /blobs must be followed by /uploads, got %s", service),
			}
		}

		if contentRange != "" {
			start, end := 0, 0
			if _, err := fmt.Sscanf(contentRange, "%d-%d", &start, &end); err != nil {
				return &regError{
					Status:  http.StatusRequestedRangeNotSatisfiable,
					Code:    "BLOB_UPLOAD_UNKNOWN",
					Message: "We don't understand your Content-Range",
				}
			}
			b.lock.Lock()
			defer b.lock.Unlock()
			if start != len(b.uploads[target]) {
				return &regError{
					Status:  http.StatusRequestedRangeNotSatisfiable,
					Code:    "BLOB_UPLOAD_UNKNOWN",
					Message: "Your content range doesn't match what we have",
				}
			}
			l := bytes.NewBuffer(b.uploads[target])
			io.Copy(l, req.Body)
			b.uploads[target] = l.Bytes()
			resp.Header().Set("Location", "/"+path.Join("v2", path.Join(elem[1:len(elem)-3]...), "blobs/uploads", target))
			resp.Header().Set("Range", fmt.Sprintf("0-%d", len(l.Bytes())-1))
			resp.WriteHeader(http.StatusNoContent)
			return nil
		}

		b.lock.Lock()
		defer b.lock.Unlock()
		if _, ok := b.uploads[target]; ok {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "BLOB_UPLOAD_INVALID",
				Message: "Stream uploads after first write are not allowed",
			}
		}

		l := &bytes.Buffer{}
		io.Copy(l, req.Body)

		b.uploads[target] = l.Bytes()
		resp.Header().Set("Location", "/"+path.Join("v2", path.Join(elem[1:len(elem)-3]...), "blobs/uploads", target))
		resp.Header().Set("Range", fmt.Sprintf("0-%d", len(l.Bytes())-1))
		resp.WriteHeader(http.StatusNoContent)
		return nil

	case http.MethodPut:
		bph, ok := b.blobHandler.(blobPutHandler)
		if !ok {
			return regErrUnsupported
		}

		if service != "uploads" {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "METHOD_UNKNOWN",
				Message: fmt.Sprintf("PUT to /blobs must be followed by /uploads, got %s", service),
			}
		}

		if digest == "" {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "DIGEST_INVALID",
				Message: "digest not specified",
			}
		}

		b.lock.Lock()
		defer b.lock.Unlock()

		h, err := v1.NewHash(digest)
		if err != nil {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "NAME_INVALID",
				Message: "invalid digest",
			}
		}

		defer req.Body.Close()
		in := ioutil.NopCloser(io.MultiReader(bytes.NewBuffer(b.uploads[target]), req.Body))

		size := int64(verify.SizeUnknown)
		if req.ContentLength > 0 {
			size = int64(len(b.uploads[target])) + req.ContentLength
		}

		vrc, err := verify.ReadCloser(in, size, h)
		if err != nil {
			return regErrInternal(err)
		}
		defer vrc.Close()

		if err := bph.Put(req.Context(), repo, h, vrc); err != nil {
			if errors.As(err, &verify.Error{}) {
				log.Printf("Digest mismatch: %v", err)
				return regErrDigestMismatch
			}
			return regErrInternal(err)
		}

		delete(b.uploads, target)
		resp.Header().Set("Docker-Content-Digest", h.String())
		resp.WriteHeader(http.StatusCreated)
		return nil

	case http.MethodDelete:
		bdh, ok := b.blobHandler.(blobDeleteHandler)
		if !ok {
			return regErrUnsupported
		}

		h, err := v1.NewHash(target)
		if err != nil {
			return &regError{
				Status:  http.StatusBadRequest,
				Code:    "NAME_INVALID",
				Message: "invalid digest",
			}
		}
		if err := bdh.Delete(req.Context(), repo, h); err != nil {
			return regErrInternal(err)
		}
		resp.WriteHeader(http.StatusAccepted)
		return nil

	default:
		return &regError{
			Status:  http.StatusBadRequest,
			Code:    "METHOD_UNKNOWN",
			Message: "We don't understand your method + url",
		}
	}
}