text:
using Backend.Fx.BuildingBlocks;

namespace Backend.Fx.SimpleInjectorDependencyInjection.Tests.DummyImpl.ASimpleDomain
{
    public interface ITestApplicationService : IApplicationService
    { }

    public class AnApplicationService : ITestApplicationService
    { }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Utilities for working with nozzles.
"""

from __future__ import absolute_import, division

import numpy as np

from skaero.gasdynamics import isentropic, shocks

class Nozzle(object):
    """Class representing a nozzle.

    """

    def __init__(self, x, A):
        self.x = x
        self.A = A

    def plot(self, ax, where=None, interpolate=False, **kwargs):
        """Plots the nozzle geometry.

        Parameters
        ----------
        ax : matplotlib.axes.Axes
            Axes where the nozzle geometry should be plotted.

        """
        radius = np.sqrt(self.A / np.pi)
        ax.set_xlim(self.x[0], self.x[-1])
        ax.fill_between(self.x, radius, -radius, where, interpolate, **kwargs)

    def solve_flow(self, fl, p_0, T_0, p_B):
        """Solves the flow through the nozzle.

        For the time being, it assumes isentropic flow and uses a quasi one
        dimensional model.

        Parameters
        ----------
        fl : IsentropicFlow
            Isentropic flow through the nozzle.
        p_0 : float
            Stagnation pressure at the reservoir.
        T_0 : float
            Stagnation temperature at the reservoir.
        p_B : float
            Back pressure at the exit section.

        Returns
        -------
        M : array
            Mach distribution along the nozzle.
        p : array
            Pressure distribution along the nozzle.

        Raises
        ------
        ValueError
            If the back pressure is higher than the reservoir pressure.

        Notes
        -----
        First of all, the function computes the isentropic conditions to
        discriminate if we have fully subsonic flow, chocked flow with shock
        inside nozzle or chocked fully supersonic flow.

        """
        p_ratio = p_B / p_0
        if p_ratio > 1.0:
            raise ValueError("Back pressure must be lower than reservoir pressure")

        # Exit and minimum area
        A_e = self.A[-1]
        A_min = np.min(self.A)
        i_min = np.argmin(self.A)

        # 1. Compute isentropic conditions at the exit
        # Points 1 (subsonic) and 2 (supersonic)
        M_e_1, M_e_2 = isentropic.mach_from_area_ratio(fl, A_e / A_min)

        pe_p0_1 = fl.p_p0(M_e_1)
        pe_p0_2 = fl.p_p0(M_e_2)

        # 2. Normal shock at the exit of the nozzle
        ns_e = shocks.NormalShock(M_e_2)
        pe_p0_3 = pe_p0_2 * ns_e.p2_p1

        # 3. Discriminate case
        M = np.empty_like(self.x)
        p = np.empty_like(self.x)

        if pe_p0_1 <= p_ratio <= 1.0:
            print("Fully subsonic flow")
            # 1. Compute M_e (inverse fl.p_p0(M))
            # 2. Compute area ratio from M_e (fl.A_Ac(M_e))
            # 3. The area ratio in each point is A_Ac = A * Ae_Ac / Ae
            #    so I can compute the Mach number distribution
        elif pe_p0_3 <= p_ratio < pe_p0_1:
            print("Shock inside the nozzle")
            # First I have to compute shock location and properties
        elif p_ratio < pe_p0_3:
            print("Fully isentropic subsonic-supersonic flow")
            # I already have Ac = A_min, so I can directly compute the Mach
            # number distribution
            Ac = A_min
            for i in range(i_min + 1):
                M[i] = isentropic.mach_from_area_ratio(fl, self.A[i] / Ac)[0]
            for i in range(i_min, len(M)):
                M[i] = isentropic.mach_from_area_ratio(fl, self.A[i] / Ac)[1]
            # Stagnation pressure does not change, as the flow is fully
            # isentropic
            p = p_0 * fl.p_p0(M)

        return M, p


text:
@interface ListProjectsTests : XCTestCase
@property (nonatomic, strong) ListProjectsInteractor *pi;
@end

@implementation ListProjectsTests

- (void)setUp {
    [super setUp];
    // This method is called before the invocation of each test method in the class.
    [MagicalRecord setupCoreDataStackWithInMemoryStore];
    self.pi = [[ListProjectsInteractor alloc] init];
}

- (void)tearDown {
    // This method is called after the invocation of each test method in the class.
    [MagicalRecord cleanUp];
    [super tearDown];
}

- (void)testFirstTimeRequestingProjectsOneIsCreatedForTheTemplates {

    NSUInteger initialCount = [Project MR_countOfEntities];
    NSFetchRequest *request = [self.pi requestAllDefault];
    NSError *error = nil;
    NSUInteger afterCount = [self.pi.defaultMOC countForFetchRequest:request error:&error];

    XCTAssertTrue(initialCount != NSNotFound);
    XCTAssertTrue(afterCount != NSNotFound);
    XCTAssertEqual(initialCount, 0);
    XCTAssertEqual(afterCount, 1);
}

#pragma mark - Testing private methods
- (void)testCreatingTheTemplatesProjectHasTrueForTheBoolean {

    BOOL hasMethod = [self.pi respondsToSelector:@selector(_createTemplatesProjectInContext:)];
    XCTAssertTrue(hasMethod);

    if (hasMethod) {
        Project *templatesProj = [self.pi performSelector:@selector(_createTemplatesProjectInContext:) withObject:self.pi.defaultMOC];

        XCTAssertEqual([templatesProj.templatesContainer boolValue], YES);
    }
}

@end


text:
import Mmenu from '../../core/oncanvas/mmenu.oncanvas';
import OPTIONS from './_options';
import * as DOM from '../../_modules/dom';
import { extend } from '../../_modules/helpers';

export default function (this: Mmenu) {
    this.opts.iconPanels = this.opts.iconPanels || {};

    //	Extend options.
    const options = extend(this.opts.iconPanels, OPTIONS);

    let keepFirst = false;

    if (options.visible == 'first') {
        keepFirst = true;
        options.visible = 1;
    }

    options.visible = Math.min(3, Math.max(1, options.visible));
    options.visible++;

    //	Add the iconpanels
    if (options.add) {
        this.bind('initMenu:after', () => {
            this.node.menu.classList.add('mm-menu--iconpanel');
        });

        this.bind('initPanel:after', panel => {
            panel.tabIndex = -1;
        });

        //  Keyboard navigation
        this.bind('initPanels:after', () => {
            document.addEventListener('keyup', evnt => {

                //  When tabbing inside the menu
                if (evnt.key === 'Tab' &&
                    document.activeElement?.closest('.mm-menu') === this.node.menu
                ) {
                    /** panel where focus is in. */
                    const panel = document.activeElement.closest('.mm-panel') as HTMLElement;

                    //  Tabbing in a parent-panel.
                    if (!document.activeElement.matches('.mm-panel__blocker') &&
                        panel?.matches('.mm-panel--parent')
                    ) {
                        //  backward tabbing: focus blocker.
                        if (evnt.shiftKey) {
                            DOM.children(panel, '.mm-panel__blocker')[0].focus();

                            //  forward tabbing: focus opened panel.
                        } else {
                            DOM.children(this.node.pnls, '.mm-panel--opened')[0].focus();
                        }

                    }
                }
            });
        });

        //  Show only the main panel.
        if (keepFirst) {
            this.bind('initMenu:after', () => {
                DOM.children(this.node.pnls, '.mm-panel')[0]?.classList.add('mm-panel--iconpanel-first');
            });

        //  Show parent panel(s).
        } else {
            /** The classnames that can be set to a panel */
            const classnames = [
                'mm-panel--iconpanel-0',
                'mm-panel--iconpanel-1',
                'mm-panel--iconpanel-2',
                'mm-panel--iconpanel-3'
            ];

            this.bind('openPanel:after', (panel: HTMLElement) => {

                //  Do nothing when opening a vertical submenu
                if (panel.parentElement.matches('.mm-listitem--vertical')) {
                    return;
                }

                let panels = DOM.children(this.node.pnls, '.mm-panel');

                //	Filter out panels that are not opened.
                panels = panels.filter((panel) =>
                    panel.matches('.mm-panel--parent')
                );

                //	Add the current panel to the list.
                panels.push(panel);

                //	Slice the opened panels to the max visible amount.
                panels = panels.slice(-options.visible);

                //	Add the "iconpanel" classnames.
                panels.forEach((panel, p) => {
                    panel.classList.remove(...classnames);
                    panel.classList.add('mm-panel--iconpanel-' + p);
                });
            });
        }

        this.bind('initPanel:after', (panel: HTMLElement) => {
            if (
                options.blockPanel &&
                !panel.parentElement.matches('.mm-listitem--vertical') &&
                !DOM.children(panel, '.mm-panel__blocker')[0]
            ) {
                const blocker = DOM.create('a.mm-panel__blocker') as HTMLAnchorElement;
                blocker.href = `#${panel.closest('.mm-panel').id}`;
                blocker.title = this.i18n(this.conf.screenReader.closeSubmenu);

                panel.prepend(blocker);
            }
        });
    }
}


text:
package kr.co.inger.hotwind.hello.tests.helpers;

import java.util.List;
import java.util.Map;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.ObjectUtils;

import com.google.common.base.Objects;

/**
 * 간단한 MyBatis 연동 API 테스트용 헬퍼.
 *
 * @author jhyun
 * @since 2012-09-03
 */
public class SimpleTransactionHelper {

	public List listAll() {
		return JerseyTestingClient.webResource()
				.path("/hello/transaction/list")
				.accept(MediaType.APPLICATION_JSON).get(List.class);
	}

	public void resetTable() {
		JerseyTestingClient.webResource().path("/hello/transaction/init")
				.accept(MediaType.TEXT_PLAIN).get(String.class);
	}

	public void addSome(final String s) {
		JerseyTestingClient.webResource().path("/hello/transaction/add")
				.path(s).accept(MediaType.TEXT_PLAIN).get(String.class);
	}

	public boolean containsIdIn(final List l, final String s) {
		for (Object o : l) {
			Map m = (Map) o;
			if (Objects.equal(ObjectUtils.toString(m.get("ID")), s))
				return true;
		}
		return false;
	}
}


text:
package com.daedafusion.knowledge.partition.framework.exceptions;

import org.apache.log4j.Logger;

/**
 * Created by mphilpot on 2/19/16.
 */
public class StorageException extends RuntimeException
{
    private static final Logger log = Logger.getLogger(StorageException.class);

    public StorageException(Exception e)
    {
        super(e);
    }

    public StorageException(String message)
    {
        super(message);
    }

    public StorageException(String message, Exception cause)
    {
        super(message, cause);
    }
}


text:
const es = require('event-stream');

/** Ugly hack for gulp-tsb */
function handleDeletions() {
	return es.mapSync(f => {
		if (/\.ts$/.test(f.relative) && !f.contents) {
			f.contents = new Buffer('');
			f.stat = { mtime: new Date() };
		}

		return f;
	});
}

let watch = void 0;

if (!process.env['VSCODE_USE_LEGACY_WATCH']) {
	try {
		watch = require('./watch-nsfw');
	} catch (err) {
		console.warn('Could not load our cross platform file watcher: ' + err.toString());
		console.warn('Falling back to our platform specific watcher...');
	}
}

if (!watch) {
	watch = process.platform === 'win32' ? require('./watch-win32') : require('gulp-watch');
}

module.exports = function () {
	return watch.apply(null, arguments)
		.pipe(handleDeletions());
};


text:
<?php
namespace Care\Form;

use Zend\Form\Form;

class CareForm extends Form
{
    public function __construct($name = null)
    {

    }
}


text:
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>

<div id='modal-window' style="background:url(img/game_over.png) center no-repeat #000; height:305px; width:600px;">

</div>

</body>

<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>
<script type="text/javascript">

$('#modal-window').click(function() {
	location.reload(true);
});

</script>

</html>


text:
import sys
#from MyScraper import Scraper(artistImport)
from MyScraper import *

userInput = input("Please enter something: ")
print(userInput)
if(userInput == 'file'):
	text_file = open("Artists.txt", "r")											#txt file containing artists, 1 per line
	Artists = text_file.readlines()
	text_file.close()
	for i in range(0, len(Artists)):
		Scraper(Artists[i])
else:
	Scraper(userInput)


text:
package org.apache.river.test.spec.security.security;

import java.util.logging.Level;

// java
import java.util.Collection;
import java.util.ArrayList;
import java.io.File;
import java.rmi.RemoteException;

// net.jini
import net.jini.security.Security;

// org.apache.river
import org.apache.river.qa.harness.TestException;
import org.apache.river.qa.harness.QATestEnvironment;
import org.apache.river.qa.harness.Test;
import org.apache.river.test.spec.security.util.Util;
import org.apache.river.test.spec.security.util.TestObject;
import org.apache.river.test.spec.security.util.BaseTrustVerifier;
import org.apache.river.test.spec.security.util.TrueTrustVerifier;
import org.apache.river.test.spec.security.util.FalseTrustVerifier;
import org.apache.river.test.spec.security.util.TrustVerifierThrowingSE;
import org.apache.river.test.spec.security.util.TrustVerifierThrowingRE;
import org.apache.river.test.spec.security.util.FakeClassLoader;

/**
 * <pre>
 * Purpose
 *   This test verifies the following:
 *     'verifyObjectTrustTest' static method of Security class verifies that the
 *     specified object can be trusted to correctly implement its contract,
 *     using verifiers from the specified class loader and using the specified
 *     collection of context objects as necessary. If a null class loader is
 *     specified, the context class loader of the current thread is used
 *     instead. A TrustVerifier.Context is created, containing an ordered list
 *     of trust verifiers (obtained as specified below) and the specified class
 *     loader and collection of context objects. The
 *     TrustVerifier.Context.isTrustedObject method of that context is then
 *     called with the specified object. If that call returns true, then this
 *     method returns normally. If that call throws a RemoteException or
 *     SecurityException exception, that exception is thrown by this method.
 *     If that call returns false, a SecurityException is thrown. The list of
 *     trust verifiers is obtained as follows. For each resource named
 *     META-INF/services/net.jini.security.TrustVerifier that is visible to the
 *     specified class loader, the contents of the resource are parsed
 *     as UTF-8 text to produce a list of class names. The resource must contain
 *     a list of fully qualified class names, one per line. Space and tab
 *     characters surrounding each name, as well as blank lines, are ignored.
 *     The comment character is '#'; all characters on each line
 *     starting with the first comment character are ignored.
 *     Each class name (that is not a duplicate of any previous class name)
 *     is loaded through the specified class loader, and the resulting class
 *     must be assignable to TrustVerifier and have a public no-argument
 *     constructor. The constructor is invoked to create a trust verifier
 *     instance. This method throws NullPointerException if a collection of
 *     context objects is null.
 *
 * Test Cases
 *   Case 1: actions described below
 *   Case 2: Set ClassLoader for current thread to FakeClassLoader1 with empty
 *           array of URLs. During the test construct each time
 *           FakeClassLoader2, do not set it as ClassLoader for current thread,
 *           and invoke 'verifyObjectTrustTest' with constructed
 *           FakeClassLoader2. In this case checks will be made that  tested
 *           trust verifiers where loaded through FakeClassLoader2 and not
 *           FakeClassLoader1.
 *
 * Infrastructure
 *   This test requires the following infrastructure:
 *     Resource1 - META-INF/services/net.jini.security.TrustVerifier resource
 *             containing TrueTrustVerifier and FalseTrustVerifier in this
 *             order
 *     Resource2 - META-INF/services/net.jini.security.TrustVerifier resource
 *             containing FalseTrustVerifier
 *     Resource3 - META-INF/services/net.jini.security.TrustVerifier resource
 *             containing FalseTrustVerifier and TrueTrustVerifier in this order
 *     Resource4 - META-INF/services/net.jini.security.TrustVerifier resource
 *             containing TrustVerifierThrowingSE and FalseTrustVerifier in this
 *             order
 *     Resource5 - META-INF/services/net.jini.security.TrustVerifier resource
 *             containing TrustVerifierThrowingRE and FalseTrustVerifier in this
 *             order
 *     Resource6 - META-INF/services/net.jini.security.TrustVerifier resource
 *             containing TrustVerifierThrowingSE and TrueTrustVerifier in this
 *             order
 *     Resource7 - META-INF/services/net.jini.security.TrustVerifier resource
 *             containing TrustVerifierThrowingRE and TrueTrustVerifier in this
 *             order
 *     TestObject - object which is not trusted by any trust verifier
 *             containing in jsk-resources.jar
 *     TrueTrustVerifier - TrustVerifier whose 'isTrustedObject' method always
 *             returns true
 *     FalseTrustVerifier - TrustVerifier whose 'isTrustedObject' method always
 *             returns false
 *     TrustVerifierThrowingSE - TrustVerifier whose 'isTrustedObject' method
 *             always throws SecurityException
 *     TrustVerifierThrowingRE - TrustVerifier whose 'isTrustedObject' method
 *             always throws RemoteException
 *     FakeContext - fake context for for 'verifyObjectTrust' method
 *     FakeClassLoader - test class loader, which is actually a URLClassLoader
 *
 * Action
 *   For each test case the test performs the following steps:
 *     1) invoke 'Security.verifyObjectTrust' method with null context
 *     2) assert that NullPointerException will be thrown
 *     3) construct FakeClassLoader with Resource1 as a parameter and set it
 *        as ClassLoader for the current thread
 *     4) invoke 'Security.verifyObjectTrust(TestObject, null, FakeContext)'
 *     5) assert that TrueTrustVerifier will be loaded through FakeClassLoader
 *     6) assert that FalseTrustVerifier will be loaded through FakeClassLoader
 *     7) assert that 'isTrustedObject' method of TrueTrustVerifier will be
 *        invoked with the same TestObject as in 'verifyObjectTrust' method
 *     8) assert that 'isTrustedObject' method of FalseTrustVerifier will not
 *        be invoked
 *     9) assert that method will return normally
 *     10) construct FakeClassLoader with Resource2 as a parameter and set it
 *         as ClassLoader for the current thread
 *     11) invoke 'Security.verifyObjectTrust(TestObject, null, FakeContext)'
 *     12) assert that FalseTrustVerifier will be loaded through FakeClassLoader
 *     13) assert that 'isTrustedObject' method of FalseTrustVerifier will be
 *         invoked with the same TestObject as in 'verifyObjectTrust' method
 *     14) assert that method will throw SecurityException
 *     15) construct FakeClassLoader with Resource3 as a parameter and set it
 *         as ClassLoader for the current thread
 *     16) invoke 'Security.verifyObjectTrust(TestObject, null, FakeContext)'
 *     17) assert that FalseTrustVerifier will be loaded through FakeClassLoader
 *     18) assert that TrueTrustVerifier will be loaded through FakeClassLoader
 *     19) assert that 'isTrustedObject' method of FalseTrustVerifier will be
 *         invoked with the same TestObject as in 'verifyObjectTrust' method
 *     20) assert that 'isTrustedObject' method of TrueTrustVerifier will be
 *         invoked with the same TestObject as in 'verifyObjectTrust' method
 *     21) assert that method will return normally
 *     22) construct FakeClassLoader with Resource4 as a parameter and set it
 *         as ClassLoader for the current thread
 *     23) invoke 'Security.verifyObjectTrust(TestObject, null, FakeContext)'
 *     24) assert that TrustVerifierThrowingSE will be loaded through
 *         FakeClassLoader
 *     25) assert that FalseTrustVerifier will be loaded through FakeClassLoader
 *     26) assert that 'isTrustedObject' method of TrustVerifierThrowingSE will
 *         be invoked with the same TestObject as in 'verifyObjectTrust' method
 *     27) assert that 'isTrustedObject' method of FalseTrustVerifier will be
 *         invoked with the same TestObject as in 'verifyObjectTrust' method
 *     28) assert that method will throw SecurityException
 *     29) construct FakeClassLoader with Resource5 as a parameter and set it
 *         as ClassLoader for the current thread
 *     30) invoke 'Security.verifyObjectTrust(TestObject, null, FakeContext)'
 *     31) assert that TrustVerifierThrowingRE will be loaded through
 *         FakeClassLoader
 *     32) assert that FalseTrustVerifier will be loaded through FakeClassLoader
 *     33) assert that 'isTrustedObject' method of TrustVerifierThrowingRE will
 *         be invoked with the same TestObject as in 'verifyObjectTrust' method
 *     34) assert that 'isTrustedObject' method of FalseTrustVerifier will be
 *         invoked with the same TestObject as in 'verifyObjectTrust' method
 *     35) assert that method will throw RemoteException
 *     36) construct FakeClassLoader with Resource6 as a parameter and set it
 *         as ClassLoader for the current thread
 *     37) invoke 'Security.verifyObjectTrust(TestObject, null, FakeContext)'
 *     38) assert that TrustVerifierThrowingSE will be loaded through
 *         FakeClassLoader
 *     39) assert that TrueTrustVerifier will be loaded through FakeClassLoader
 *     40) assert that 'isTrustedObject' method of TrustVerifierThrowingSE will
 *         be invoked with the same TestObject as in 'verifyObjectTrust' method
 *     41) assert that 'isTrustedObject' method of TrueTrustVerifier will be
 *         invoked with the same TestObject as in 'verifyObjectTrust' method
 *     41) assert that method will return normally
 *     42) construct FakeClassLoader with Resource7 as a parameter and set it
 *         as ClassLoader for the current thread
 *     43) invoke 'Security.verifyObjectTrust(TestObject, null, FakeContext)'
 *     44) assert that TrustVerifierThrowingRE will be loaded through
 *         FakeClassLoader
 *     45) assert that TrueTrustVerifier will be loaded through FakeClassLoader
 *     46) assert that 'isTrustedObject' method of TrustVerifierThrowingRE will
 *         be invoked with the same TestObject as in 'verifyObjectTrust' method
 *     47) assert that 'isTrustedObject' method of TrueTrustVerifier will be
 *         invoked with the same TestObject as in 'verifyObjectTrust' method
 *     48) assert that method will return normally
 * </pre>
 */
public class VerifyObjectTrustTest extends QATestEnvironment implements Test {

    /** Resource name method */
    protected static String resName =
            "META-INF/services/net.jini.security.TrustVerifier";

    /**
     * Array of classes whose 'isTrustedObject' methods are expected to be
     * called.
     */
    protected Class[] expCls = new Class[0];

    /**
     * This method performs all actions mentioned in class description.
     *
     */
    public void run() throws Exception {
        File jarFile = null;
        Object testObj = new TestObject();
        Collection testCtx = new ArrayList();
        testCtx.add(new Object());
        boolean[] useNullLoader = new boolean[] { true, false };
        Class[][] clNames = new Class[][] {
            new Class[] {
                TrueTrustVerifier.class,
                FalseTrustVerifier.class },
            new Class[] { FalseTrustVerifier.class },
            new Class[] {
                FalseTrustVerifier.class,
                TrueTrustVerifier.class },
            new Class[] {
                TrustVerifierThrowingSE.class,
                FalseTrustVerifier.class },
            new Class[] {
                TrustVerifierThrowingRE.class,
                FalseTrustVerifier.class },
            new Class[] {
                TrustVerifierThrowingSE.class,
                TrueTrustVerifier.class },
            new Class[] {
                TrustVerifierThrowingRE.class,
                TrueTrustVerifier.class } };
        Class expRes;
        ClassLoader testCl;

        for (int i = 0; i < useNullLoader.length; ++i) {

            // check NullPointerException
            logger.fine("Trying null context.");
            jarFile = Util.createResourceJar(resName,
                    new Class[] { Class.class });

            if (useNullLoader[i]) {
                testCl = null;
            } else {
                testCl = new FakeClassLoader(jarFile.toURI().toURL());
            }

            try {
                callVerifyObjectTrust(testObj, testCl, null);

                // FAIL
                throw new TestException(
                        "Method did not throw any exception while "
                        + "NullPointerException was expected.");
            } catch (NullPointerException npe) {
                // PASS
                logger.fine("NullPointerException was thrown as expected.");
            } finally {
                jarFile.delete();
            }

            for (int j = 0; j < clNames.length; ++j) {
                BaseTrustVerifier.initLists();
                logger.fine("========== Iteration #" + (j + 1)
                        + " ==========");
                logger.fine("Test trust verifiers are: "
                        + Util.arrayToString(clNames[j]));
                jarFile = Util.createResourceJar(resName, clNames[j]);
                expRes = getExpRes(clNames[j]);

                if (useNullLoader[i]) {
                    testCl = null;
                } else {
                    testCl = new FakeClassLoader(jarFile.toURI().toURL());
                }
                Thread.currentThread().setContextClassLoader(
                        new FakeClassLoader(jarFile.toURI().toURL()));

                try {
                    callVerifyObjectTrust(testObj, testCl, testCtx);

                    if (expRes != null) {
                        // FAIL
                        throw new TestException(
                                "Method returned normally while " + expRes
                                + " exception was expected to be thrown.");
                    }

                    // PASS
                    logger.fine("Method returned normally as expected.");
                } catch (Exception e) {
                    if (expRes == null) {
                        // FAIL
                        throw new TestException(
                                "Method throws " + e + " exception while "
                                + "normal return was expected.");
                    } else if (expRes != e.getClass()) {
                        // FAIL
                        throw new TestException(
                                "Method throws " + e + " exception while "
                                + expRes + " was expected.");
                    }

                    // PASS
                    logger.fine("Method threw " + e + " as expected.");
                } finally {
                    jarFile.delete();
                }

                /*
                 * check that all classes where loaded through the right
                 * classloader
                 */
                Class[] loadedCls = null;

                if (testCl == null) {
                    loadedCls = ((FakeClassLoader)
                            Thread.currentThread().getContextClassLoader())
                                    .getClasses();
                } else {
                    loadedCls = ((FakeClassLoader) testCl).getClasses();
                }
                Class[] notLoadedCls = Util.containsClasses(loadedCls,
                        clNames[j]);

                if (notLoadedCls != null) {
                    // FAIL
                    throw new TestException(
                            "The following classes was not loaded through "
                            + "expected class loader: "
                            + Util.arrayToString(notLoadedCls));
                }

                // PASS
                logger.fine("All requested classes were loaded through "
                        + "expected class loader.");

                // check that passed parameters where correct
                Class[] classes = BaseTrustVerifier.getClasses();
                Object[] objs = BaseTrustVerifier.getObjs();
                Object[] ctxs = BaseTrustVerifier.getCtxs();

                if (classes.length != expCls.length) {
                    // FAIL
                    throw new TestException(
                            "Expected set of classes whose "
                            + "'isTrustedObject' method had to be called "
                            + "is: " + Util.arrayToString(expCls)
                            + ", while actual set is: "
                            + Util.arrayToString(classes));
                }

                for (int k = 0; k < classes.length; ++k) {
                    if (classes[k] != expCls[k]) {
                        // FAIL
                        throw new TestException(
                                "Expected set of classes whose "
                                + "'isTrustedObject' method had to be "
                                + "called is: " + Util.arrayToString(expCls)
                                + ", while actual set is: "
                                + Util.arrayToString(classes));
                    }

                    if (objs[k] != testObj && ctxs[k] != testCtx) {
                        // FAIL
                        throw new TestException(
                                "Class " + classes[k] + " got [" + objs[k]
                                + ", " + ctxs[k] + "] parameters while ["
                                + testObj + ", " + testCtx
                                + "] was expected.");
                    }
                }

                // PASS
                logger.fine("All classes got expected parameters.");
            }
        }
    }

    /**
     * Invokes 'Security.verifyObjectTrust' method with given arguments.
     * Rethrows any exception thrown by 'verifyObjectTrust' method.
     *
     * @param obj Object for 'verifyObjectTrust' method
     * @param loader ClassLoader for 'verifyObjectTrust' method
     * @param context Collection for 'verifyObjectTrust' method
     * @throws java.rmi.RemoteException
     */
    protected void callVerifyObjectTrust(Object obj, ClassLoader loader,
            Collection context) throws RemoteException {
        logger.fine("Call 'Security.verifyObjectTrust(" + obj + ", " + loader
                + ", " + context + ")'.");
        Security.verifyObjectTrust(obj, loader, context);
    }

    /**
     * Return Class representing expected result - if non-null, that means
     * that an exception must be thrown of returned type. Fills array of
     * classes whose 'isTrustedObject' methods are expected to be called.
     *
     * @param clNames array of classes for which evaluate the result
     */
    protected Class getExpRes(Class[] clNames) {
        Class res = null;
        ArrayList clList = new ArrayList();

        for (int i = 0; i < clNames.length; ++i) {
            clList.add(clNames[i]);

            if (clNames[i] == TrueTrustVerifier.class) {
                expCls = (Class []) clList.toArray(new Class[clList.size()]);
                return null;
            } else if (clNames[i] == TrustVerifierThrowingRE.class) {
                res = RemoteException.class;
            } else if (clNames[i] == TrustVerifierThrowingSE.class) {
                res = SecurityException.class;
            }
        }
        expCls = (Class []) clList.toArray(new Class[clList.size()]);
        return (res != null) ? res : SecurityException.class;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Logo Nav - Start Bootstrap Template</title>

    <link href="css/bootstrap.css" rel="stylesheet">

    <link href="css/logo-nav.css" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                        Home

                        Institucional

                                Recursos
                                História
                                Equipe
                                Políticas

                        Projetos

                        Documentação

                        Publicações

                        Serviços

                                Cadastro de Acesso

                        Diversos

RECURSOS

Note: You may need to adjust some CSS based on the size of your logo. The default logo size is 150x50 pixels.


text:
---
layout: post
title: zookeeper实现分布式锁
categories: [blog ]
tags: [软件开发  ]
description: zookeeper实现分布式锁
---

# zookeeper实现分布式锁

## 前言

zookeeper可以理解为一个高可靠的分布式文件系统,想了解更多可以参考:https://zookeeper.apache.org/doc/r3.1.2/zookeeperProgrammers.html 。

## 分布式锁实现

### 伪代码

    1. 判断锁目录是否存在,不存在则创建锁目录(忽略并发导致的创建失败)
	2. 在锁目录下创建临时序列化节点,节点的data为唯一性token(jvm+threadId)
	3. 判断自己的节点名称是否是最小,如果是则获取到锁跳转到5,否则到4
	4. 监听锁目录子节点的变化,(防止丢失event,sleep前主动测试下是否可到5),如果发生改变,则跳转到3,如果等待过程中超时则抛超时异常
	5. 执行获取到锁后的业务代码,然后删除自己的临时节点(通过token查找)
	6. 如果锁的子节点为空,则尝试删除锁目录(如果由于并发导致子节点不空,忽略掉删除失败)

### java实现

```java

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.PriorityQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;

/**
 * zookeeper 实现的分布式锁
 * 本类只是用来示范如何正确实现分布式锁,如果线上要用请继承本类并复写Zookeeper的初始化
 * <p>
 * Created by zhouxiliang on 2016/8/17.
 */
public class ZKLock {
    private static final Logger logger = LoggerFactory.getLogger(ZKLock.class);

    //会话超时时间
    private static final int SESSION_TIMEOUT = 30000;
    //zookeeper session
    protected static ZooKeeper zooKeeper = null;
    //文件根路径
    static String ROOT = null;
    //默认监控器
    private static Watcher defaultWatcher = null;
    //zookeeper集群
    private static String connectionUrl = null;

    static {
        init();
    }

    /**
     * 请不要使用默认的zookeeper,这儿只是作为例子
     * 请自行重写zooKeeper即可。
     */
    private static void init() {
        try {
            connectionUrl = "127.0.0.1:2181";
            ROOT = "/boss-config/lock";
            defaultWatcher = new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    System.out.println(watchedEvent);
                    logger.info("Receive WatchedEvent : " + watchedEvent.toString());
                }
            };
            zooKeeper = new ZooKeeper(connectionUrl, SESSION_TIMEOUT, defaultWatcher);
            zooKeeper.addAuthInfo("digest", "boss-config:boss-config".getBytes());
        } catch (Exception e) {
            logger.error("ZKLock Initializing zookeeper failed. fatal error!", e);
        }
    }

    private static int cnt = 0;

    public static void main(String[] args) throws KeeperException, InterruptedException {
        /*
         *测试的时候 去掉jvm本地锁
         */
        List<String> list = zooKeeper.getChildren("/boss-config/lock", false);
        System.out.println(list.toString());
        final CountDownLatch countDownLatch = new CountDownLatch(10);
        final CountDownLatch start = new CountDownLatch(1);
        for (int i = 0; i < 10; ++i) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        start.await();
                        lock("test_lock");
                        System.out.println("Thread-" + Thread.currentThread().getId() + " 获取到锁");
                        System.out.println(Thread.currentThread().getId() + " is doing some biz...");
                        int t = cnt;
                        Thread.sleep(1000);
                        cnt = t + 1;
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        unlock("test_lock");
                        countDownLatch.countDown();
                    }
                }
            }).start();

        }
        long startT = System.currentTimeMillis();
        start.countDown();
        countDownLatch.await();
        long endT = System.currentTimeMillis();
        System.out.println("耗时:(ms) " + (endT - startT));
        list = zooKeeper.getChildren("/boss-config/lock", false);
        System.out.println(list.toString());
        System.out.println("cnt = " + cnt);
    }

    /**
     * 本机锁
     */
    private static ConcurrentHashMap<String, ReentrantLock> localLock = new ConcurrentHashMap<String, ReentrantLock>();

    /**
     * 获取分布式锁
     *
     * @param lockName
     * @throws LockException
     */
    public static void lock(String lockName) throws LockException, KeeperException, InterruptedException {
        //验证参数
        if (!isValidLockName(lockName)) {
            throw new LockException("锁名称非法");
        }
        lockName = ROOT + "/" + lockName;
        //获取jvm锁
        if (!localLock.containsKey(lockName)) {
            localLock.putIfAbsent(lockName, new ReentrantLock());
        }
        Lock jvmLock = localLock.get(lockName);
        jvmLock.lock();
        System.out.println("Thread-" + Thread.currentThread().getId() + " 获取 jvm锁成功");

        try {
            Stat stat = zooKeeper.exists(lockName, false);
            if (stat == null || stat.getCzxid() <= 0) {
                System.out.println("Thread-" + Thread.currentThread().getId() + " 尝试创建锁 : " + lockName);
                zooKeeper.create(lockName, NetworkUtil.getLocalIP().getBytes("utf-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (Exception e) {
            //ignore concurrent create lock node exception
        }
        String path = lockName + "/node";
        try {
            path = zooKeeper.create(path, (NetworkUtil.getLocalIP() + "_" + Thread.currentThread().getId()).getBytes("utf-8"),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        } catch (Exception e) {
            throw new LockException("Thread-" + Thread.currentThread().getId() + " 创建zk临时节点失败 path=" + path, e);
        }
        System.out.println("Thread-" + Thread.currentThread().getId() + " 临时节点创建成功 : " + path);
        //快速尝试,是否可以获取锁
        List<String> list = zooKeeper.getChildren(lockName, false);
        if (isSmallestNode(path, list)) {
            //获取锁成功
            return;
        }
        //loop until get the lock
        while (!isSmallestNode(lockName, path)) {
            final Thread currentThread = Thread.currentThread();
            zooKeeper.getChildren(lockName, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    LockSupport.unpark(currentThread);
                }
            });
            // 在sleep前再次验证,防止漏掉zookeeper事件
            if (!isSmallestNode(lockName, path)) {
                LockSupport.park();
            }
        }
    }

    /**
     * 获取分布式锁
     *
     * @param lockName
     * @param timeout  超时时间(ms)
     * @throws LockException
     */
    public static void lock(String lockName, long timeout) throws LockException, InterruptedException, KeeperException {
        long start = System.currentTimeMillis();
        //验证参数
        if (!isValidLockName(lockName)) {
            throw new LockException("锁名称非法");
        }
        lockName = ROOT + "/" + lockName;
        //获取jvm锁
        if (!localLock.containsKey(lockName)) {
            localLock.putIfAbsent(lockName, new ReentrantLock());
        }
        Lock jvmLock = localLock.get(lockName);
        boolean f = jvmLock.tryLock(timeout, TimeUnit.MILLISECONDS);
        if (!f) {
            throw new LockException("获取本地锁超时, lock=" + lockName);
        }
        System.out.println("Thread-" + Thread.currentThread() + " 获取 jvm锁成功");

        try {
            Stat stat = zooKeeper.exists(lockName, false);
            if (stat == null || stat.getCzxid() <= 0) {
                System.out.println("Thread-" + Thread.currentThread().getId() + " 创建zk锁 : " + lockName);
                zooKeeper.create(lockName, NetworkUtil.getLocalIP().getBytes("utf-8"),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        } catch (Exception e) {
            //ignore
        }
        String path = lockName + "/node";
        try {
            path = zooKeeper.create(path, (NetworkUtil.getLocalIP() + "_" + Thread.currentThread().getId()).getBytes("utf-8"),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        } catch (Exception e) {
            throw new LockException("Thread-" + Thread.currentThread().getId() + " 创建zk临时节点失败", e);
        }
        System.out.println("Thread-" + Thread.currentThread().getId() + " 临时节点创建成功 : " + path);
        //快速尝试,是否可以获取锁
        List<String> list = zooKeeper.getChildren(lockName, false);
        if (isSmallestNode(path, list)) {
            //获取锁成功
            return;
        }
        timeout -= System.currentTimeMillis() - start;
        if (timeout <= 0) throw new LockException("Thread-" + Thread.currentThread().getId() + " 获取ZK锁超时");
        start = System.currentTimeMillis();
        //loop until get the lock
        while (!isSmallestNode(lockName, path)) {
            timeout -= System.currentTimeMillis() - start;
            if (timeout <= 0) throw new LockException("Thread-" + Thread.currentThread().getId() + " 获取ZK锁超时");
            start = System.currentTimeMillis();
            final Thread currentThread = Thread.currentThread();
            zooKeeper.getChildren(lockName, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    LockSupport.unpark(currentThread);
                }
            });
            // 在sleep前再次验证,防止漏掉zookeeper事件
            if (!isSmallestNode(lockName, path)) {
                LockSupport.parkNanos(TimeUnit.MILLISECONDS.toNanos(timeout));
            }
        }
    }

    /**
     * 释放分布式锁
     *
     * @param lockName
     * @throws LockException
     */
    public static void unlock(String lockName) {
        //验证参数
        if (!isValidLockName(lockName)) {
            return;
        }
        lockName = ROOT + "/" + lockName;
        try {
            List<String> list = zooKeeper.getChildren(lockName, false);
            if (list != null && !list.isEmpty()) {
                PriorityQueue<String> priorityQueue = new PriorityQueue<String>(list);
                String smallest = priorityQueue.poll();
                byte[] data = zooKeeper.getData(lockName + "/" + smallest, false, null);
                String token = NetworkUtil.getLocalIP() + "_" + Thread.currentThread().getId();
                if (new String(data, "utf-8").equals(token)) {
                    System.out.println("Thread-" + Thread.currentThread().getId() + " unlock 删除zk节点: " + lockName + "/" + smallest);
                    zooKeeper.delete(lockName + "/" + smallest, -1);
                } else {
                    System.out.println("Thread-" + Thread.currentThread().getId() + " unlock 拒绝删除ZK节点 : " + lockName + " data=" + new String(data, "utf-8"));
                    //node的个数最大为服务器集群个数,所以这儿性能不会损耗太大
                    for (String node : priorityQueue) {
                        String path = lockName + "/" + node;
                        try {
                            data = zooKeeper.getData(path, false, null);
                            if (new String(data, "utf-8").equals(token)) {
                                System.out.println("Thread-" + Thread.currentThread().getId() + " unlock 删除zk节点: " + path);
                                zooKeeper.delete(path, -1);
                                break;
                            }
                        } catch (Exception e) {
                            //ignore no node exception
                        }
                    }
                }

            }
            Stat stat = new Stat();
            zooKeeper.getData(lockName, false, stat);
            if (stat.getNumChildren() == 0) {
                System.out.println("Thread-" + Thread.currentThread().getId() + " unlock 删除ZK锁: " + lockName);
                zooKeeper.delete(lockName, stat.getVersion());
            }
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        //释放jvm锁
        ReentrantLock jvmLock = localLock.get(lockName);
        if (jvmLock != null) {
            System.out.println("Thread-" + Thread.currentThread().getId() + " 释放 jvm锁");
            jvmLock.unlock();
            if (!jvmLock.hasQueuedThreads()) {
                System.out.println("Thread-" + Thread.currentThread().getId() + " 删除 jvm锁");
                localLock.remove(lockName);
            }
        }
    }

    private static boolean isSmallestNode(String lockName, String nodeName) throws KeeperException, InterruptedException {
        List<String> list = zooKeeper.getChildren(lockName, false);
        if (isSmallestNode(nodeName, list)) {
            return true;
        }
        return false;
    }

    private static boolean isSmallestNode(String node, List<String> nodes) {
        String[] arr = node.split("/");
        node = arr[arr.length - 1];
        for (String s : nodes) {
            if (s.compareTo(node) < 0) return false;
        }
        return true;
    }

    //znode节点命名有限制,这儿限制的比zookeeper更严一些
    private static Pattern pattern = Pattern.compile("\\w+");

    private static boolean isValidLockName(String lock) {
        return pattern.matcher(lock).matches();
    }

    public static class LockException extends java.lang.Exception {
        public LockException() {
        }

        public LockException(String message) {
            super(message);
        }

        public LockException(String message, Throwable cause) {
            super(message, cause);
        }
    }
}

```


text:
var FiercePlanet = FiercePlanet || {};

FiercePlanet.Console = FiercePlanet.Console || {};

(function () {

    /**
     * Minimises the console
     */
    this.minimise = function () {
        $('.jqconsole').height(20);
        $('#notifications').height(40);
    };

    /**
     * Maximises the console
     */
    this.maximise = function () {
        $('.jqconsole').height(180);
        $('#notifications').height(200);
    };

    this.registerEvents = function () {
        /*
         $('textarea').blur(function() {
         FiercePlanet.Console.minimise();
         });
         $('textarea').focus(function() {
         FiercePlanet.Console.maximise();
         });
         */
    }
}).apply(FiercePlanet.Console);


text:
/* Example for use of GNU gettext.
   This file is in the public domain.

   Interface of the AppController class.  */

#include <AppKit/AppKit.h>

@class Hello;

@interface AppController : NSObject
{
  Hello *hello;
}

+ (void)initialize;

- (id)init;
- (void)dealloc;

- (void)awakeFromNib;

- (void)applicationDidFinishLaunching
    :(NSNotification *)notif;

- (BOOL)applicationShouldTerminate:(id)sender;
- (void)applicationWillTerminate:(NSNotification *)notification;

- (BOOL)application:(NSApplication *)application openFile:(NSString *)fileName;

- (void)showPrefPanel:(id)sender;
- (void)showInfoPanel:(id)sender;

- (void)showHelloWindow:(id)sender;

@end


text:
package org.hisp.dhis.dxf2.events.relationship;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;

import java.util.HashMap;
import java.util.Optional;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.hisp.dhis.common.CodeGenerator;
import org.hisp.dhis.dbms.DbmsManager;
import org.hisp.dhis.dxf2.common.ImportOptions;
import org.hisp.dhis.dxf2.events.enrollment.EnrollmentService;
import org.hisp.dhis.dxf2.events.event.EventService;
import org.hisp.dhis.dxf2.events.trackedentity.Relationship;
import org.hisp.dhis.dxf2.events.trackedentity.RelationshipItem;
import org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstanceService;
import org.hisp.dhis.dxf2.importsummary.ImportStatus;
import org.hisp.dhis.dxf2.importsummary.ImportSummary;
import org.hisp.dhis.query.QueryService;
import org.hisp.dhis.random.BeanRandomizer;
import org.hisp.dhis.relationship.RelationshipConstraint;
import org.hisp.dhis.relationship.RelationshipEntity;
import org.hisp.dhis.relationship.RelationshipType;
import org.hisp.dhis.schema.SchemaService;
import org.hisp.dhis.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.trackedentity.TrackedEntityType;
import org.hisp.dhis.trackedentity.TrackerAccessManager;
import org.hisp.dhis.user.CurrentUserService;
import org.hisp.dhis.user.UserService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author Luciano Fiandesio
 */
@ExtendWith( MockitoExtension.class )
class JacksonRelationshipServiceTest
{
    @Mock
    protected DbmsManager dbmsManager;

    @Mock
    private CurrentUserService currentUserService;

    @Mock
    private SchemaService schemaService;

    @Mock
    private QueryService queryService;

    @Mock
    private TrackerAccessManager trackerAccessManager;

    @Mock
    private org.hisp.dhis.relationship.RelationshipService relationshipService;

    @Mock
    private TrackedEntityInstanceService trackedEntityInstanceService;

    @Mock
    private EnrollmentService enrollmentService;

    @Mock
    private EventService eventService;

    @Mock
    private org.hisp.dhis.trackedentity.TrackedEntityInstanceService teiDaoService;

    @Mock
    private UserService userService;

    @Mock
    private ObjectMapper jsonMapper;

    @Mock
    private ObjectMapper xmlMapper;

    @InjectMocks
    private JacksonRelationshipService subject;

    private Relationship relationship;

    private final BeanRandomizer rnd = BeanRandomizer.create();

    private static final String RELATIONSHIP_UID = "relationship uid";

    @BeforeEach
    public void setUp()
        throws IllegalAccessException
    {
        RelationshipType relationshipType = createRelationshipTypeWithTeiConstraint();
        relationship = createTei2TeiRelationship( relationshipType );
        relationship.setRelationship( RELATIONSHIP_UID );

        initFakeCaches( relationship, relationshipType );
    }

    @Test
    void verifyRelationshipIsImportedIfDoesNotExist()
    {
        when(
            relationshipService.getRelationshipByRelationship( any( org.hisp.dhis.relationship.Relationship.class ) ) )
                .thenReturn( Optional.empty() );

        ImportSummary importSummary = subject.addRelationship( relationship, rnd.nextObject( ImportOptions.class ) );

        assertThat( importSummary.getStatus(), is( ImportStatus.SUCCESS ) );
        assertThat( importSummary.getImportCount().getImported(), is( 1 ) );
    }

    @Test
    void verifyRelationshipIsNotImportedWhenDoesExist()
    {
        org.hisp.dhis.relationship.Relationship daoRelationship = new org.hisp.dhis.relationship.Relationship();
        daoRelationship.setUid( "12345" );

        when(
            relationshipService.getRelationshipByRelationship( any( org.hisp.dhis.relationship.Relationship.class ) ) )
                .thenReturn( Optional.of( daoRelationship ) );

        ImportSummary importSummary = subject.addRelationship( relationship, rnd.nextObject( ImportOptions.class ) );

        assertThat( importSummary.getStatus(), is( ImportStatus.ERROR ) );
        assertThat( importSummary.getImportCount().getImported(), is( 0 ) );
        assertThat( importSummary.getReference(), is( daoRelationship.getUid() ) );
        assertThat( importSummary.getDescription(),
            is( "Relationship " + daoRelationship.getUid() + " already exists" ) );
    }

    @Test
    void verifySoftRelationshipIsNotUpdated()
    {
        org.hisp.dhis.relationship.Relationship daoRelationship = new org.hisp.dhis.relationship.Relationship();
        daoRelationship.setUid( RELATIONSHIP_UID );
        daoRelationship.setDeleted( true );

        when( relationshipService.getRelationshipIncludeDeleted( RELATIONSHIP_UID ) ).thenReturn( daoRelationship );

        ImportSummary importSummary = subject.updateRelationship( relationship, rnd.nextObject( ImportOptions.class ) );

        assertThat( importSummary.getStatus(), is( ImportStatus.ERROR ) );
        assertThat( importSummary.getImportCount().getImported(), is( 0 ) );
        assertThat( importSummary.getReference(), is( RELATIONSHIP_UID ) );
        assertThat( importSummary.getDescription(),
            is( "Relationship '" + RELATIONSHIP_UID + "' is already deleted and cannot be modified." ) );
    }

    private void initFakeCaches( Relationship relationship, RelationshipType relationshipType )
        throws IllegalAccessException
    {
        // init relationship type cache
        HashMap<String, RelationshipType> relationshipTypeCache = new HashMap<>();
        relationshipTypeCache.put( relationship.getRelationshipType(), relationshipType );

        // init tracked entity instance cache
        HashMap<String, TrackedEntityInstance> trackedEntityInstanceCache = new HashMap<>();
        trackedEntityInstanceCache.put( relationship.getFrom().getTrackedEntityInstance().getTrackedEntityInstance(),
            new TrackedEntityInstance()
            {
                {
                    setTrackedEntityType( relationshipType.getFromConstraint().getTrackedEntityType() );
                }
            } );
        trackedEntityInstanceCache.put( relationship.getTo().getTrackedEntityInstance().getTrackedEntityInstance(),
            new TrackedEntityInstance()
            {
                {
                    setTrackedEntityType( relationshipType.getToConstraint().getTrackedEntityType() );
                }
            } );

        FieldUtils.writeField( subject, "relationshipTypeCache", relationshipTypeCache, true );
        FieldUtils.writeField( subject, "trackedEntityInstanceCache", trackedEntityInstanceCache, true );

    }

    private Relationship createTei2TeiRelationship( RelationshipType relationshipType )
    {
        Relationship relationship = new Relationship();

        RelationshipItem from = new RelationshipItem();
        from.setTrackedEntityInstance(
            rnd.nextObject( org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance.class ) );

        RelationshipItem to = new RelationshipItem();
        to.setTrackedEntityInstance(
            rnd.nextObject( org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance.class ) );

        relationship.setFrom( from );
        relationship.setTo( to );
        relationship.setRelationshipType( relationshipType.getUid() );
        return relationship;
    }

    private RelationshipType createRelationshipTypeWithTeiConstraint()
    {
        RelationshipType relationshipType = new RelationshipType();
        relationshipType.setUid( CodeGenerator.generateUid() );

        RelationshipConstraint from = new RelationshipConstraint();
        from.setRelationshipEntity( RelationshipEntity.TRACKED_ENTITY_INSTANCE );
        from.setTrackedEntityType( new TrackedEntityType( "a", "b" ) );
        RelationshipConstraint to = rnd.nextObject( RelationshipConstraint.class );
        to.setRelationshipEntity( RelationshipEntity.TRACKED_ENTITY_INSTANCE );
        to.setTrackedEntityType( new TrackedEntityType( "b", "c" ) );
        relationshipType.setFromConstraint( from );
        relationshipType.setToConstraint( to );

        return relationshipType;
    }
}


text:
UpdateOcular
============

Update Ocular


text:
A list control that gives you the ability to to limit the ammount of items shown. The more list should have only list items (i.e. `<li>`) as its children. For an example, see [this demo](http://yeahbuthats.github.io/react-more-list/).

To do initial setup, open a command window in the directory and run the following:

    npm install
    webpack

Usage
-----

    <MoreList>

Apple

Banana

Coconut

Durian

Elderberry

Fig

Grape

Huckleberry

Ita Palm

Jujubes

Kiwi

Lemon

Mango

Nectarine

Orange

Pineapple

Quince

Raspberry

Strawberry

Tangerine

Ugli

Voavanga

Watermelon

Xigua melon

Yellow watermelon

Zucchini

    </MoreList>

Generates a list like the following:

* Apple
* Banana
* Coconut
* Durian
* More... 22

Properties
----------

### initialSize ###

**Type:** number
**Default:** 4
**Example:** `<MoreList initialSize={4}>`
**Required:** no

* The initial size of the list. You will get a maximum number of list items equal to `initialSize` (not including "More").
* If the actual number of list items is greater than `initialSize`, you will end up with one additional item; "More... x" will be appended to the end of the list. Clicking "More" will show more elements.
* If the number of list items is smaller than `initialSize`, the list will display all of them.

#### See Also ####

* `moreSize`
* `tolerance`

### moreSize ###

**Type:** number
**Default:** 20
**Example:** `<MoreList moreSize={20}>`
**Required:** no

* The number of elements added when "More" is clicked. If there are more elements than `moreSize` another "More" will appear after it is clicked.
* If `moreSize` is set to 0, all items will be shown when "More" is clicked, regardless of the count.
* The number shown for unshown items will show the most relevant number.
    * If `allowShowAll` is false, the number shown is the number of unshown items.
    * If `allowShowAll` is true and the remaining unshown items is greater than `moreSize`, the number shown  will be `moreSize` with a "+" appended (e.g. "More... 20+").
    * If `allowShowAll` is true and the remaining unshown items is less than or equal to, the number shown is the remaining items ("Show All" won't be shown in this case).

#### See Also ####

* `tolerance`
* `allowShowAll`

### tolerance ###

**Type:** number
**Default:** 1
**Example:** `<MoreList tolerance={1}>`
**Required:** no

* The number of items over the current calculated number of items to show anyway.
* If the number of elements hidden by "More" would be equal to or less than `tolerance` instead of showing "More" the remining elements would be displayed.
    * e.g. If `tolerance` is 1, and there is only 1 unshown item, the unshown item is displayed anyway (instead of displaying "More").

### allowShowAll ###

**Type:** boolean
**Default:** false
**Example:** `<MoreList allowShowAll={false}>`
**Required:** no

* Adds a "Show All" option after "More" if the number of items hidden by "More" is greater than `moreSize`.
    * The maximum list size if this is set to true is `initialSize` + 2 ("More" and "Show All").
* If `moreSize` is set to 0 this will have no effect.
* This does factor in `tolerance`, so it may not appear if `moreSize` + `tolerance` >= remaining items.
* In short: "Show All" will not appear if clicking "More" will show all of the remaining data.
* Size shown will always be the total number of items still not shown.

### showCount ###

**Type:** boolean
**Default:** true
**Example:** `<MoreList showCount={true}>`
**Required:** no

* If true, shows the count of items next to "More" and "Show All."

CSS Classes
-----------

* **MoreList:** Will become an `<ul>` with class `ml-list`.
* **List Items:** Stays a `<li>`, gains `ml-list-item` and `ml-data` class.
* **More:** Becomes a `<li>` with classes `ml-list-item`, `ml-expander`, and `ml-more`. The count of items hidden is wrapped in a `<span>` with classes `ml-count` and `ml-more-count`.
* **Show All:** Becomes a `<li>` with classes `ml-list-item`, `ml-expander`, and `ml-show-all`. The count of items hidden is wrapped in a `<span>` with classes `ml-count` and `ml-show-all-count`.


text:
@ParametersAreNonnullByDefault
package org.zalando.logbook.logstash;

import javax.annotation.ParametersAreNonnullByDefault;


text:
package org.vaadin.addons.rinne

import java.util

import com.vaadin.ui.PopupView.{PopupVisibilityEvent, PopupVisibilityListener}
import com.vaadin.ui.{Component, HasComponents, PopupView}
import org.vaadin.addons.rinne.events.ListenersSet
import org.vaadin.addons.rinne.mixins.AbstractComponentMixin

class VPopupView extends PopupView("", null) with AbstractComponentMixin with HasComponents {

  lazy val popupVisibilityListeners = new ListenersSet[PopupVisibilityEvent, PopupVisibilityListener] {

    override protected def addListener(listener: ListenerLambda): Unit = addPopupVisibilityListener(
      new Listener(listener) with PopupVisibilityListener {
        override def popupVisibilityChange(event: PopupVisibilityEvent): Unit = listener(event)
      }
    )

    override protected def removeListener(listener: PopupVisibilityListener): Unit = removePopupVisibilityListener(listener)

    override protected def listeners: util.Collection[_] = getListeners(classOf[PopupVisibilityEvent])
  }

  def minimizedHtmlValue: String = getContent.getMinimizedValueAsHTML

  def minimizedHtmlValue_=(minimizedHtmlValue: String): Unit = {
    val c = getContent.getPopupComponent
    setContent(
      new PopupView.Content {
        def getMinimizedValueAsHTML = minimizedHtmlValue

        def getPopupComponent = c
      }
    )
  }

  def popupContent_=(popupContent: Component) {
    this.popupContent = () => popupContent
  }

  def popupContent: Option[Component] = Option(getContent.getPopupComponent)

  def popupContent_=(popupContent: () => Component) {
    val html = getContent.getMinimizedValueAsHTML
    setContent(new PopupView.Content {
      def getMinimizedValueAsHTML = html

      def getPopupComponent = popupContent()
    })
  }

  def popupVisible: Boolean = isPopupVisible

  def popupVisible_=(popupVisible: Boolean) {
    setPopupVisible(popupVisible)
  }

  def hideOnMouseOut: Boolean = isHideOnMouseOut

  def hideOnMouseOut_=(hideOnMouseOut: Boolean): Unit = setHideOnMouseOut(hideOnMouseOut)
}


text:
import json
from tornado import gen
import libs.common as common
import libs.stock_web_dic as stock_web_dic
import web.base as webBase
import logging
import datetime

# info 蓝色 云财经
# success 绿色
#  danger 红色 东方财富
#  warning 黄色
WEB_EASTMONEY_URL = u"""
    东财

    指标

    东研

    """
# 和在dic中的字符串一致。字符串前面都不特别声明是u""
eastmoney_name = "查看股票"

# 获得页面数据。
class GetStockHtmlHandler(webBase.BaseHandler):
    @gen.coroutine
    def get(self):
        name = self.get_argument("table_name", default=None, strip=False)
        stockWeb = stock_web_dic.STOCK_WEB_DATA_MAP[name]
        # self.uri_ = ("self.request.url:", self.request.uri)
        # print self.uri_
        date_now = datetime.datetime.now()
        date_now_str = date_now.strftime("%Y%m%d")
        # 每天的 16 点前显示昨天数据。
        if date_now.hour < 16:
            date_now_str = (date_now + datetime.timedelta(days=-1)).strftime("%Y%m%d")

        try:
            # 增加columns 字段中的【查看股票 东方财富】
            logging.info(eastmoney_name in stockWeb.column_names)
            if eastmoney_name in stockWeb.column_names:
                tmp_idx = stockWeb.column_names.index(eastmoney_name)
                logging.info(tmp_idx)
                try:
                    # 防止重复插入数据。可能会报错。
                    stockWeb.columns.remove("eastmoney_url")
                except Exception as e:
                    print("error :", e)
                stockWeb.columns.insert(tmp_idx, "eastmoney_url")
        except Exception as e:
            print("error :", e)
        logging.info("####################GetStockHtmlHandlerEnd")
        self.render("stock_web.html", stockWeb=stockWeb, date_now=date_now_str,
                    pythonStockVersion=common.__version__,
                    leftMenu=webBase.GetLeftMenu(self.request.uri))

# 获得股票数据内容。
class GetStockDataHandler(webBase.BaseHandler):
    def get(self):

        # 获得分页参数。
        start_param = self.get_argument("start", default=0, strip=False)
        length_param = self.get_argument("length", default=10, strip=False)
        print("page param:", length_param, start_param)

        name_param = self.get_argument("name", default=None, strip=False)
        type_param = self.get_argument("type", default=None, strip=False)

        stock_web = stock_web_dic.STOCK_WEB_DATA_MAP[name_param]

        # https://datatables.net/manual/server-side
        self.set_header('Content-Type', 'application/json;charset=UTF-8')
        order_by_column = []
        order_by_dir = []
        # 支持多排序。使用shift+鼠标左键。
        for item, val in self.request.arguments.items():
            # logging.info("item: %s, val: %s" % (item, val) )
            if str(item).startswith("order["):
                print("order:", item, ",val:", val[0])
            if str(item).startswith("order[") and str(item).endswith("[column]"):
                order_by_column.append(int(val[0]))
            if str(item).startswith("order[") and str(item).endswith("[dir]"):
                order_by_dir.append(val[0].decode("utf-8"))  # bytes转换字符串

        search_by_column = []
        search_by_data = []

        # 返回search字段。
        for item, val in self.request.arguments.items():
            # logging.info("item: %s, val: %s" % (item, val))
            if str(item).startswith("columns[") and str(item).endswith("[search][value]"):
                logging.info("item: %s, val: %s" % (item, val))
                str_idx = item.replace("columns[", "").replace("][search][value]", "")
                int_idx = int(str_idx)
                # 找到字符串
                str_val = val[0].decode("utf-8")
                if str_val != "":  # 字符串。
                    search_by_column.append(stock_web.columns[int_idx])
                    search_by_data.append(val[0].decode("utf-8"))  # bytes转换字符串

        # 打印日志。
        search_sql = ""
        search_idx = 0
        logging.info(search_by_column)
        logging.info(search_by_data)
        for item in search_by_column:
            val = search_by_data[search_idx]
            logging.info("idx: %s, column: %s, value: %s " % (search_idx, item, val))
            # 查询sql
            if search_idx == 0:
                search_sql = " WHERE `%s` = '%s' " % (item, val)
            else:
                search_sql = search_sql + " AND `%s` = '%s' " % (item, val)
            search_idx = search_idx + 1

        # print("stockWeb :", stock_web)
        order_by_sql = ""
        # 增加排序。
        if len(order_by_column) != 0 and len(order_by_dir) != 0:
            order_by_sql = "  ORDER BY "
            idx = 0
            for key in order_by_column:
                # 找到排序字段和dir。
                col_tmp = stock_web.columns[key]
                dir_tmp = order_by_dir[idx]
                if idx != 0:
                    order_by_sql += " ,cast(`%s` as decimal) %s" % (col_tmp, dir_tmp)
                else:
                    order_by_sql += " cast(`%s` as decimal) %s" % (col_tmp, dir_tmp)
                idx += 1
        # 查询数据库。
        limit_sql = ""
        if int(length_param) > 0:
            limit_sql = " LIMIT %s , %s " % (start_param, length_param)
        sql = " SELECT * FROM `%s` %s %s %s " % (
            stock_web.table_name, search_sql, order_by_sql, limit_sql)
        count_sql = " SELECT count(1) as num FROM `%s` %s " % (stock_web.table_name, search_sql)

        logging.info("select sql : " + sql)
        logging.info("count sql : " + count_sql)
        stock_web_list = self.db.query(sql)

        for tmp_obj in (stock_web_list):
            logging.info("####################")
            if type_param == "editor":
                tmp_obj["DT_RowId"] = tmp_obj[stock_web.columns[0]]
            # logging.info(tmp_obj)
            try:
                # 增加columns 字段中的【东方财富】
                logging.info("eastmoney_name : %s " % eastmoney_name)
                if eastmoney_name in stock_web.column_names:
                    tmp_idx = stock_web.column_names.index(eastmoney_name)

                    code_tmp = tmp_obj["code"]
                    # 判断上海还是 深圳,东方财富 接口要求。
                    if code_tmp.startswith("6"):
                        code_tmp = "SH" + code_tmp
                    else:
                        code_tmp = "SZ" + code_tmp

                    tmp_url = WEB_EASTMONEY_URL % (tmp_obj["code"], tmp_obj["code"], code_tmp)
                    tmp_obj["eastmoney_url"] = tmp_url
                    logging.info(tmp_idx)
                    logging.info(tmp_obj["eastmoney_url"])
                    # logging.info(type(tmp_obj))
                    # tmp.column_names.insert(tmp_idx, eastmoney_name)
            except Exception as e:
                print("error :", e)

        stock_web_size = self.db.query(count_sql)
        logging.info("stockWebList size : %s " % stock_web_size)

        obj = {
            "draw": 0,
            "recordsTotal": stock_web_size[0]["num"],
            "recordsFiltered": stock_web_size[0]["num"],
            "data": stock_web_list
        }
        # logging.info("####################")
        # logging.info(obj)
        self.write(json.dumps(obj))


text:
using System;
using System.ComponentModel.Composition.Hosting;

namespace Talifun.Commander.Command
{
    public sealed class CommandContainer
    {
        private CommandContainer()
        {
        }

        public static readonly CommandContainer Instance = new CommandContainer();

        private CompositionContainer _container;
        public CompositionContainer Container
        {
            get
            {
                if (_container == null)
                {
					var core = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "Talifun.Commander.Command.dll");
					var plugins = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "Talifun.Commander.Command.*.dll");

                    var aggregatecatalogue = new AggregateCatalog(core, plugins);
                    _container = new CompositionContainer(aggregatecatalogue);
                }

                return _container;
            }
        }
    }
}


text: Common node bugs and language pitfalls we learned


text:
using FakeItEasy;
using GreenPipes;
using Miles.DependencyInjection;
using Miles.GreenPipes.ContainerScope;
using NUnit.Framework;
using System;
using System.Threading.Tasks;

namespace Miles.GreenPipes.UnitTests.ContainerScope
{
    [TestFixture]
    public class ContainerScopeTests
    {
        [Test]
        public async Task Given_ABus_When_XScopesConfigured_Then_XScopesPushed()
        {
            var innerInnerGuid = Guid.NewGuid();
            var innerInnerContainer = A.Fake<IContainer>();
            A.CallTo(() => innerInnerContainer.Resolve<Resolved>(A<string>._)).Returns(new Resolved { Value = innerInnerGuid });
            var innerInnerContainerBuilder = A.Fake<IContainerBuilder>();
            A.CallTo(() => innerInnerContainerBuilder.CreateContainer()).Returns(innerInnerContainer);

            var innerGuid = Guid.NewGuid();
            var innerContainer = A.Fake<IContainer>();
            A.CallTo(() => innerContainer.CreateChildScopeBuilder()).Returns(innerInnerContainerBuilder);
            A.CallTo(() => innerContainer.Resolve<Resolved>(A<string>._)).Returns(new Resolved { Value = innerGuid });
            var innerContainerBuilder = A.Fake<IContainerBuilder>();
            A.CallTo(() => innerContainerBuilder.CreateContainer()).Returns(innerContainer);

            var rootGuid = Guid.NewGuid();
            var rootContainer = A.Fake<IContainer>();
            A.CallTo(() => rootContainer.CreateChildScopeBuilder()).Returns(innerContainerBuilder);
            A.CallTo(() => rootContainer.Resolve<Resolved>(A<string>._)).Returns(new Resolved { Value = rootGuid });

            // Act and Assert
            var pipe = Pipe.New<ExistingContext>(pc =>
                {
                    pc.UseContainerScope(rootContainer);
                    pc.UseInlineFilter((ctx, next) =>
                    {
                        Assert.IsTrue(ctx.TryGetPayload(out ContainerScopeContext containerContext), "No ContainerScopeContext locator");

                        var resolved = containerContext.Container.Resolve<Resolved>();
                        Assert.AreEqual(rootGuid, resolved.Value);

                        return next.Send(ctx);
                    });

                    pc.UseContainerScope();
                    pc.UseInlineFilter((ctx, next) =>
                    {
                        Assert.IsTrue(ctx.TryGetPayload(out ContainerScopeContext containerContext), "No ContainerScopeContext locator");

                        var resolved = containerContext.Container.Resolve<Resolved>();
                        Assert.AreEqual(innerGuid, resolved.Value);

                        return next.Send(ctx);
                    });

                    pc.UseContainerScope();
                    pc.UseInlineFilter((ctx, next) =>
                    {
                        Assert.IsTrue(ctx.TryGetPayload(out ContainerScopeContext containerContext), "No ContainerScopeContext locator");

                        var resolved = containerContext.Container.Resolve<Resolved>();
                        Assert.AreEqual(innerInnerGuid, resolved.Value);

                        return next.Send(ctx);
                    });
                });

            await pipe.Send(new ExistingContextImp());
        }

        public class Resolved
        {
            public Guid Value { get; set; }
        }

        public class ExistingContextImp : BasePipeContext, ExistingContext
        { }

        public interface ExistingContext : PipeContext
        { }
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Interface etm.contrib.console.ConsoleResponse (Java Execution Measurement Library)
</TITLE>

<META NAME="date" CONTENT="2009-03-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
etm.contrib.console.ConsoleResponse

Packages that use ConsoleResponse

etm.contrib.console

      A drop in HTTP console that may be used standalone or as JETM plugin.

etm.contrib.console.actions

      Classes that process console requests.

etm.contrib.console.servlet

      Servlet request/response abstraction.

etm.contrib.console.standalone

      Standalone request/response abstraction.

etm.contrib.console.util

      Console utility classes.

Uses of ConsoleResponse in etm.contrib.console

Methods in etm.contrib.console with parameters of type ConsoleResponse

 void
ConsoleAction.execute(ConsoleRequest request,
        ConsoleResponse response)

Uses of ConsoleResponse in etm.contrib.console.actions

Methods in etm.contrib.console.actions with parameters of type ConsoleResponse

 void
CollapsedResultViewAction.execute(ConsoleRequest request,
        ConsoleResponse response)

 void
DetailAction.execute(ConsoleRequest request,
        ConsoleResponse response)

 void
ExpandedResultViewAction.execute(ConsoleRequest request,
        ConsoleResponse response)

 void
RedirectAction.execute(ConsoleRequest request,
        ConsoleResponse response)

 void
ResetMonitorAction.execute(ConsoleRequest request,
        ConsoleResponse response)

 void
ResourceAction.execute(ConsoleRequest request,
        ConsoleResponse response)

 void
StartMonitorAction.execute(ConsoleRequest request,
        ConsoleResponse response)

 void
StatusCodeAction.execute(ConsoleRequest request,
        ConsoleResponse response)

 void
StopMonitorAction.execute(ConsoleRequest request,
        ConsoleResponse response)

Uses of ConsoleResponse in etm.contrib.console.servlet

Classes in etm.contrib.console.servlet that implement ConsoleResponse

 class
ServletConsoleResponse

          Response abstraction for servlet based HTTP console.

Uses of ConsoleResponse in etm.contrib.console.standalone

Classes in etm.contrib.console.standalone that implement ConsoleResponse

 class
StandaloneConsoleResponse

          Response abstraction for standalone HTTP console.

Uses of ConsoleResponse in etm.contrib.console.util

Fields in etm.contrib.console.util declared as ConsoleResponse

protected  ConsoleResponse
ConsoleRenderer.response

Constructors in etm.contrib.console.util with parameters of type ConsoleResponse

CollapsedResultRenderer(ConsoleRequest aRequest,
                        ConsoleResponse aResponse,
                        ExecutionAggregateComparator aComparator)

          Constructs a CollapsedResultRenderer that writes results to
 the given response.

ConsoleRenderer(ConsoleRequest aRequest,
                ConsoleResponse aResponse,
                ExecutionAggregateComparator aComparator)

DetailResultRenderer(ConsoleRequest aRequest,
                     ConsoleResponse aResponse,
                     ExecutionAggregateComparator aComparator,
                     java.lang.String aEtmPointName)

ExpandedResultRenderer(ConsoleRequest aRequest,
                       ConsoleResponse aResponse,
                       ExecutionAggregateComparator aComparator)

          Constructs a CollapsedResultRenderer that writes results to
 the given response.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2004,2005, 2006, 2007 void.fm. All Rights Reserved.


text:
// Copyright 2013 Cultural Heritage Agency of the Netherlands, Dutch National Military Museum and Trezorix bv
//
//    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.
using System.Collections.Generic;
using System.Linq;

using Trezorix.Checkers.DocumentChecker.Jobs;

namespace Trezorix.Checkers.DocumentCheckerApp.Models.Jobs
{
	public class JobExtJsModel
	{
		public string Label;
		public string ProfileKey;

		public IEnumerable<SourceSelectionExtJsModel> SkosSourceSelection;

		public JobExtJsModel(Job job)
		{
			Label = job.Label;
			ProfileKey = job.ProfileKey;

			SkosSourceSelection =
				ActiveProfile.Instance().SkosSourceBindings
				.Where(b => job.SkosSourceSelection.Any(s => b.Key == s))
				.Select(b => new SourceSelectionExtJsModel()
				             	{
				             		key = b.Key,
									label = b.Label
				             	});
		}

		public class SourceSelectionExtJsModel
		{
// ReSharper disable InconsistentNaming
			public string key;

			public string label;
// ReSharper restore InconsistentNaming
		}
	}
}


text:
// Copyright (c) Source Tree Solutions, LLC. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Author:					Joe Audette
// Created:				    2008-01-04
// Last Modified:			2016-01-03
//

using cloudscribe.DbHelpers;
using Microsoft.Extensions.Logging;
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Threading;
using System.Threading.Tasks;

namespace cloudscribe.Core.Repositories.MSSQL
{
    internal class DBUserLocation
    {
        internal DBUserLocation(
            string dbReadConnectionString,
            string dbWriteConnectionString,
            ILoggerFactory loggerFactory)
        {
            logFactory = loggerFactory;
            readConnectionString = dbReadConnectionString;
            writeConnectionString = dbWriteConnectionString;

            // possibly will change this later to have SqlClientFactory/DbProviderFactory injected
            AdoHelper = new AdoHelper(SqlClientFactory.Instance);
        }

        private ILoggerFactory logFactory;
        private string readConnectionString;
        private string writeConnectionString;
        private AdoHelper AdoHelper;

        /// <summary>
        /// Inserts a row in the mp_UserLocation table. Returns rows affected count.
        /// </summary>
        /// <param name="rowID"> rowID </param>
        /// <param name="userGuid"> userGuid </param>
        /// <param name="siteGuid"> siteGuid </param>
        /// <param name="iPAddress"> iPAddress </param>
        /// <param name="iPAddressLong"> iPAddressLong </param>
        /// <param name="hostname"> hostname </param>
        /// <param name="longitude"> longitude </param>
        /// <param name="latitude"> latitude </param>
        /// <param name="iSP"> iSP </param>
        /// <param name="continent"> continent </param>
        /// <param name="country"> country </param>
        /// <param name="region"> region </param>
        /// <param name="city"> city </param>
        /// <param name="timeZone"> timeZone </param>
        /// <param name="captureCount"> captureCount </param>
        /// <param name="firstCaptureUTC"> firstCaptureUTC </param>
        /// <param name="lastCaptureUTC"> lastCaptureUTC </param>
        /// <returns>int</returns>
        public async Task<bool> Add(
            Guid rowID,
            Guid userGuid,
            Guid siteGuid,
            string iPAddress,
            long iPAddressLong,
            string hostname,
            double longitude,
            double latitude,
            string iSP,
            string continent,
            string country,
            string region,
            string city,
            string timeZone,
            int captureCount,
            DateTime firstCaptureUTC,
            DateTime lastCaptureUTC,
            CancellationToken cancellationToken

            )
        {
            if(rowID == Guid.Empty) { rowID = Guid.NewGuid(); }

            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                writeConnectionString,
                "mp_UserLocation_Insert",
                17);

            sph.DefineSqlParameter("@RowID", SqlDbType.UniqueIdentifier, ParameterDirection.Input, rowID);
            sph.DefineSqlParameter("@UserGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, userGuid);
            sph.DefineSqlParameter("@SiteGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, siteGuid);
            sph.DefineSqlParameter("@IPAddress", SqlDbType.NVarChar, 50, ParameterDirection.Input, iPAddress);
            sph.DefineSqlParameter("@IPAddressLong", SqlDbType.BigInt, ParameterDirection.Input, iPAddressLong);
            sph.DefineSqlParameter("@Hostname", SqlDbType.NVarChar, 255, ParameterDirection.Input, hostname);
            sph.DefineSqlParameter("@Longitude", SqlDbType.Float, ParameterDirection.Input, longitude);
            sph.DefineSqlParameter("@Latitude", SqlDbType.Float, ParameterDirection.Input, latitude);
            sph.DefineSqlParameter("@ISP", SqlDbType.NVarChar, 255, ParameterDirection.Input, iSP);
            sph.DefineSqlParameter("@Continent", SqlDbType.NVarChar, 255, ParameterDirection.Input, continent);
            sph.DefineSqlParameter("@Country", SqlDbType.NVarChar, 255, ParameterDirection.Input, country);
            sph.DefineSqlParameter("@Region", SqlDbType.NVarChar, 255, ParameterDirection.Input, region);
            sph.DefineSqlParameter("@City", SqlDbType.NVarChar, 255, ParameterDirection.Input, city);
            sph.DefineSqlParameter("@TimeZone", SqlDbType.NVarChar, 255, ParameterDirection.Input, timeZone);
            sph.DefineSqlParameter("@CaptureCount", SqlDbType.Int, ParameterDirection.Input, captureCount);
            sph.DefineSqlParameter("@FirstCaptureUTC", SqlDbType.DateTime, ParameterDirection.Input, firstCaptureUTC);
            sph.DefineSqlParameter("@LastCaptureUTC", SqlDbType.DateTime, ParameterDirection.Input, lastCaptureUTC);
            int rowsAffected = await sph.ExecuteNonQueryAsync(cancellationToken);
            return rowsAffected > 0;
        }

        /// <summary>
        /// Updates a row in the mp_UserLocation table. Returns true if row updated.
        /// </summary>
        /// <param name="rowID"> rowID </param>
        /// <param name="userGuid"> userGuid </param>
        /// <param name="siteGuid"> siteGuid </param>
        /// <param name="iPAddress"> iPAddress </param>
        /// <param name="iPAddressLong"> iPAddressLong </param>
        /// <param name="hostname"> hostname </param>
        /// <param name="longitude"> longitude </param>
        /// <param name="latitude"> latitude </param>
        /// <param name="iSP"> iSP </param>
        /// <param name="continent"> continent </param>
        /// <param name="country"> country </param>
        /// <param name="region"> region </param>
        /// <param name="city"> city </param>
        /// <param name="timeZone"> timeZone </param>
        /// <param name="captureCount"> captureCount </param>
        /// <param name="lastCaptureUTC"> lastCaptureUTC </param>
        /// <returns>bool</returns>
        public async Task<bool> Update(
            Guid rowID,
            Guid userGuid,
            Guid siteGuid,
            string iPAddress,
            long iPAddressLong,
            string hostname,
            double longitude,
            double latitude,
            string iSP,
            string continent,
            string country,
            string region,
            string city,
            string timeZone,
            int captureCount,
            DateTime lastCaptureUTC,
            CancellationToken cancellationToken
            )
        {
            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                writeConnectionString,
                "mp_UserLocation_Update",
                16);

            sph.DefineSqlParameter("@RowID", SqlDbType.UniqueIdentifier, ParameterDirection.Input, rowID);
            sph.DefineSqlParameter("@UserGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, userGuid);
            sph.DefineSqlParameter("@SiteGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, siteGuid);
            sph.DefineSqlParameter("@IPAddress", SqlDbType.NVarChar, 50, ParameterDirection.Input, iPAddress);
            sph.DefineSqlParameter("@IPAddressLong", SqlDbType.BigInt, ParameterDirection.Input, iPAddressLong);
            sph.DefineSqlParameter("@Hostname", SqlDbType.NVarChar, 255, ParameterDirection.Input, hostname);
            sph.DefineSqlParameter("@Longitude", SqlDbType.Float, ParameterDirection.Input, longitude);
            sph.DefineSqlParameter("@Latitude", SqlDbType.Float, ParameterDirection.Input, latitude);
            sph.DefineSqlParameter("@ISP", SqlDbType.NVarChar, 255, ParameterDirection.Input, iSP);
            sph.DefineSqlParameter("@Continent", SqlDbType.NVarChar, 255, ParameterDirection.Input, continent);
            sph.DefineSqlParameter("@Country", SqlDbType.NVarChar, 255, ParameterDirection.Input, country);
            sph.DefineSqlParameter("@Region", SqlDbType.NVarChar, 255, ParameterDirection.Input, region);
            sph.DefineSqlParameter("@City", SqlDbType.NVarChar, 255, ParameterDirection.Input, city);
            sph.DefineSqlParameter("@TimeZone", SqlDbType.NVarChar, 255, ParameterDirection.Input, timeZone);
            sph.DefineSqlParameter("@CaptureCount", SqlDbType.Int, ParameterDirection.Input, captureCount);
            sph.DefineSqlParameter("@LastCaptureUTC", SqlDbType.DateTime, ParameterDirection.Input, lastCaptureUTC);
            int rowsAffected = await sph.ExecuteNonQueryAsync(cancellationToken);
            return (rowsAffected > 0);
        }

        /// <summary>
        /// Deletes a row from the mp_UserLocation table. Returns true if row deleted.
        /// </summary>
        /// <param name="rowID"> rowID </param>
        /// <returns>bool</returns>
        public async Task<bool> Delete(
            Guid rowID,
            CancellationToken cancellationToken
            )
        {
            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                writeConnectionString,
                "mp_UserLocation_Delete",
                1);

            sph.DefineSqlParameter("@RowID", SqlDbType.UniqueIdentifier, ParameterDirection.Input, rowID);
            int rowsAffected = await sph.ExecuteNonQueryAsync(cancellationToken);
            return (rowsAffected > 0);

        }

        public async Task<bool> DeleteByUser(
            Guid userGuid,
            CancellationToken cancellationToken
            )
        {
            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                writeConnectionString,
                "mp_UserLocation_DeleteByUser",
                1);

            sph.DefineSqlParameter("@UserGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, userGuid);
            int rowsAffected = await sph.ExecuteNonQueryAsync(cancellationToken);
            return (rowsAffected > 0);

        }

        public async Task<bool> DeleteBySite(
            Guid siteGuid,
            CancellationToken cancellationToken
            )
        {
            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                writeConnectionString,
                "mp_UserLocation_DeleteBySite",
                1);

            sph.DefineSqlParameter("@SiteGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, siteGuid);
            int rowsAffected = await sph.ExecuteNonQueryAsync(cancellationToken);
            return (rowsAffected > 0);

        }

        ///// <summary>
        ///// Gets an IDataReader with one row from the mp_UserLocation table.
        ///// </summary>
        ///// <param name="rowID"> rowID </param>
        //public DbDataReader GetOne(Guid rowID)
        //{
        //    SqlParameterHelper sph = new SqlParameterHelper(
        //        logFactory,
        //        readConnectionString,
        //        "mp_UserLocation_SelectOne",
        //        1);

        //    sph.DefineSqlParameter("@RowID", SqlDbType.UniqueIdentifier, ParameterDirection.Input, rowID);
        //    return sph.ExecuteReader();
        //}

        /// <summary>
        /// Gets an IDataReader with one row from the mp_UserLocation table.
        /// </summary>
        /// <param name="userGuid"> userGuid </param>
        /// <param name="iPAddress"> iPAddress </param>
        public async Task<DbDataReader> GetOne(
            Guid userGuid,
            long iPAddressLong,
            CancellationToken cancellationToken
            )
        {
            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                readConnectionString,
                "mp_UserLocation_SelectOneByUserAndIP",
                2);

            sph.DefineSqlParameter("@UserGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, userGuid);
            sph.DefineSqlParameter("@IPAddressLong", SqlDbType.BigInt, ParameterDirection.Input, iPAddressLong);
            return await sph.ExecuteReaderAsync(cancellationToken);
        }

        ///// <summary>
        ///// Gets an IDataReader with one row from the mp_UserLocation table.
        ///// </summary>
        ///// <param name="userGuid"> userGuid </param>
        //public DbDataReader GetByUser(Guid userGuid)
        //{
        //    SqlParameterHelper sph = new SqlParameterHelper(
        //        logFactory,
        //        readConnectionString,
        //        "mp_UserLocation_SelectByUser",
        //        1);

        //    sph.DefineSqlParameter("@UserGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, userGuid);
        //    return sph.ExecuteReader();
        //}

        ///// <summary>
        ///// Gets an IDataReader with one row from the mp_UserLocation table.
        ///// </summary>
        ///// <param name="siteGuid"> siteGuid </param>
        //public DbDataReader GetBySite(Guid siteGuid)
        //{
        //    SqlParameterHelper sph = new SqlParameterHelper(
        //        logFactory,
        //        readConnectionString,
        //        "mp_UserLocation_SelectBySite",
        //        1);

        //    sph.DefineSqlParameter("@SiteGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, siteGuid);
        //    return sph.ExecuteReader();
        //}

        /// <summary>
        /// Gets an IDataReader with rows from the mp_Users table which have the passed in IP Address
        /// </summary>
        /// <param name="siteGuid"> siteGuid </param>
        public async Task<DbDataReader> GetUsersByIPAddress(
            Guid siteGuid,
            string ipv4Address,
            CancellationToken cancellationToken)
        {
            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                readConnectionString,
                "mp_UserLocation_SelectUsersByIP",
                2);

            sph.DefineSqlParameter("@SiteGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, siteGuid);
            sph.DefineSqlParameter("@IPAddress", SqlDbType.NVarChar, 50, ParameterDirection.Input, ipv4Address);
            return await sph.ExecuteReaderAsync(cancellationToken);
        }

        /// <summary>
        /// Gets a count of rows in the mp_UserLocation table for the passed in userGuid.
        /// </summary>
        /// <param name="userGuid"> userGuid </param>
        public async Task<int> GetCountByUser(
            Guid userGuid,
            CancellationToken cancellationToken
            )
        {
            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                readConnectionString,
                "mp_UserLocation_GetCountByUser",
                1);

            sph.DefineSqlParameter("@UserGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, userGuid);
            object result = await sph.ExecuteScalarAsync(cancellationToken);
            return Convert.ToInt32(result);

        }

        ///// <summary>
        ///// Returns true if the given userguid/ip is found
        ///// </summary>
        ///// <param name="userGuid"> userGuid </param>
        //public static bool Exists(Guid userGuid, long ipAsLong)
        //{
        //    SqlParameterHelper sph = new SqlParameterHelper(GetConnectionString(), "mp_UserLocation_Exists", 1);
        //    sph.DefineSqlParameter("@UserGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, userGuid);
        //    return Convert.ToInt32(sph.ExecuteScalar()) > 0;

        //}

        ///// <summary>
        ///// Gets a count of rows in the mp_UserLocation table for the passed in userGuid.
        ///// </summary>
        ///// <param name="siteGuid"> siteGuid </param>
        //public int GetCountBySite(Guid siteGuid)
        //{
        //    SqlParameterHelper sph = new SqlParameterHelper(
        //        logFactory,
        //        readConnectionString,
        //        "mp_UserLocation_GetCountBySite",
        //        1);

        //    sph.DefineSqlParameter("@SiteGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, siteGuid);
        //    return Convert.ToInt32(sph.ExecuteScalar());

        //}

        /// <summary>
        /// Gets a page of data from the mp_UserLocation table.
        /// </summary>
        /// <param name="userGuid"> userGuid </param>
        /// <param name="pageNumber">The page number.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="totalPages">total pages</param>
        public  async Task<DbDataReader> GetPageByUser(
            Guid userGuid,
            int pageNumber,
            int pageSize,
            CancellationToken cancellationToken
            )
        {
            SqlParameterHelper sph = new SqlParameterHelper(
                logFactory,
                readConnectionString,
                "mp_UserLocation_SelectPageByUser",
                3);

            sph.DefineSqlParameter("@UserGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, userGuid);
            sph.DefineSqlParameter("@PageNumber", SqlDbType.Int, ParameterDirection.Input, pageNumber);
            sph.DefineSqlParameter("@PageSize", SqlDbType.Int, ParameterDirection.Input, pageSize);
            return await sph.ExecuteReaderAsync(cancellationToken);

        }

        ///// <summary>
        ///// Gets a page of data from the mp_UserLocation table.
        ///// </summary>
        ///// <param name="siteGuid"> siteGuid </param>
        ///// <param name="pageNumber">The page number.</param>
        ///// <param name="pageSize">Size of the page.</param>
        ///// <param name="totalPages">total pages</param>
        //public DbDataReader GetPageBySite(
        //    Guid siteGuid,
        //    int pageNumber,
        //    int pageSize)
        //{
        //    SqlParameterHelper sph = new SqlParameterHelper(
        //        logFactory,
        //        readConnectionString,
        //        "mp_UserLocation_SelectPageBySite",
        //        3);

        //    sph.DefineSqlParameter("@SiteGuid", SqlDbType.UniqueIdentifier, ParameterDirection.Input, siteGuid);
        //    sph.DefineSqlParameter("@PageNumber", SqlDbType.Int, ParameterDirection.Input, pageNumber);
        //    sph.DefineSqlParameter("@PageSize", SqlDbType.Int, ParameterDirection.Input, pageSize);
        //    return sph.ExecuteReader();

        //}

    }

}