text:
package com.jetbrains.env.debug;

import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.testFramework.UsefulTestCase;
import com.intellij.testFramework.fixtures.IdeaProjectTestFixture;
import com.intellij.xdebugger.XDebuggerTestUtil;
import com.intellij.xdebugger.breakpoints.SuspendPolicy;
import com.intellij.xdebugger.frame.XValueChildrenList;
import com.jetbrains.env.PyEnvTestCase;
import com.jetbrains.python.console.pydev.PydevCompletionVariant;
import com.jetbrains.python.debugger.PyDebugValue;
import com.jetbrains.python.debugger.PyExceptionBreakpointProperties;
import com.jetbrains.python.debugger.PyExceptionBreakpointType;
import com.jetbrains.python.debugger.settings.PyDebuggerSettings;
import com.jetbrains.python.sdk.flavors.PythonSdkFlavor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Assume;
import org.junit.Test;

import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.*;

public class PythonDebuggerTest extends PyEnvTestCase {
  private static class BreakpointStopAndEvalTask extends PyDebuggerTask {
    BreakpointStopAndEvalTask(String scriptName) {
      super("/debug", scriptName);
    }

    @Override
    public void before() {
      toggleBreakpoint(getFilePath(getScriptName()), 3);
      setWaitForTermination(false);
    }

    @Override
    public void testing() throws Exception {
      waitForPause();

      eval("i").hasValue("0");

      resume();

      waitForPause();

      eval("i").hasValue("1");

      resume();

      waitForPause();

      eval("i").hasValue("2");
    }
  }

  @Test
  public void testBreakpointStopAndEval() {
    runPythonTest(new BreakpointStopAndEvalTask("test1.py"));
  }

  @Test
  public void testConditionalBreakpoint() {
    runPythonTest(new PyDebuggerTask("/debug", "test1.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 3);
        XDebuggerTestUtil.setBreakpointCondition(getProject(), 3, "i == 1 or i == 11 or i == 111");
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();

        eval("i").hasValue("1");

        resume();

        waitForPause();

        eval("i").hasValue("11");

        resume();

        waitForPause();

        eval("i").hasValue("111");
      }
    });
  }

  @Test
  public void testDebugCompletion() {
    runPythonTest(new PyDebuggerTask("/debug", "test4.py") {
      @Override
      public void before() {
        toggleBreakpoint(getScriptName(), 3);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();

        List<PydevCompletionVariant> list = myDebugProcess.getCompletions("xvalu");
        assertEquals(2, list.size());
      }
    });
  }

  @Test
  public void testBreakpointLogExpression() {
    runPythonTest(new PyDebuggerTask("/debug", "test1.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 3);
        XDebuggerTestUtil.setBreakpointLogExpression(getProject(), 3, "'i = %d'%i");
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        resume();
        waitForOutput("i = 1");
      }
    });
  }

  @Test
  public void testInput() {
    runPythonTest(new PyDebuggerTask("/debug", "test_input.py") {
      @Override
      public void before() {
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForOutput("print command >");
        input("GO!");
        waitForOutput("command was GO!");
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-jython"); //can't run on jython
      }
    });
  }

  @Test
  public void testRunToLine() {
    runPythonTest(new PyDebuggerTask("/debug", "test_runtoline.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 7);
        toggleBreakpoint(getFilePath(getScriptName()), 14);
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("x").hasValue("0");
        runToLine(11);
        eval("x").hasValue("1");
        resume();
        waitForPause();
        eval("x").hasValue("12");
        resume();

        waitForOutput("x = 12");
      }
    });
  }

  @Test
  public void testExceptionBreakpointOnTerminate() {
    runPythonTest(new PyDebuggerTask("/debug", "test_exceptbreak.py") {
      @Override
      public void before() {
        createExceptionBreakZeroDivisionError(myFixture, true, false, false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        waitForOutput("message=\"python-exceptions.ZeroDivisionError\"", "message=\"python-builtins.ZeroDivisionError\"");
        waitForOutput("Traceback (most recent call last):");
        waitForOutput("line 7, in foo");
        waitForOutput("return 1 / x");
        waitForOutput("ZeroDivisionError: ");
        eval("__exception__[0].__name__").hasValue("'ZeroDivisionError'");
        resume();
        waitForTerminate();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron");
      }
    });
  }

  private static void createExceptionBreakZeroDivisionError(IdeaProjectTestFixture fixture,
                                                            boolean notifyOnTerminate,
                                                            boolean notifyOnFirst,
                                                            boolean ignoreLibraries) {
    XDebuggerTestUtil.removeAllBreakpoints(fixture.getProject());
    XDebuggerTestUtil.setDefaultBreakpointEnabled(fixture.getProject(), PyExceptionBreakpointType.class, false);

    PyExceptionBreakpointProperties properties = new PyExceptionBreakpointProperties("exceptions.ZeroDivisionError");
    properties.setNotifyOnTerminate(notifyOnTerminate);
    properties.setNotifyOnlyOnFirst(notifyOnFirst);
    properties.setIgnoreLibraries(ignoreLibraries);
    PyBaseDebuggerTask.addExceptionBreakpoint(fixture, properties);
    properties = new PyExceptionBreakpointProperties("builtins.ZeroDivisionError"); //for python 3
    properties.setNotifyOnTerminate(notifyOnTerminate);
    properties.setNotifyOnlyOnFirst(notifyOnFirst);
    properties.setIgnoreLibraries(ignoreLibraries);
    PyBaseDebuggerTask.addExceptionBreakpoint(fixture, properties);
  }

  private static void createDefaultExceptionBreakpoint(IdeaProjectTestFixture fixture) {
    XDebuggerTestUtil.removeAllBreakpoints(fixture.getProject());
    XDebuggerTestUtil.setDefaultBreakpointEnabled(fixture.getProject(), PyExceptionBreakpointType.class, true);
  }

  @Test
  public void testExceptionBreakpointOnFirstRaise() {
    runPythonTest(new PyDebuggerTask("/debug", "test_exceptbreak.py") {
      @Override
      public void before() {
        createExceptionBreak(myFixture, false, true, true);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        waitForOutput("message=\"python-BaseException\"");
        eval("__exception__[0].__name__").hasValue("'IndexError'");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron");
      }
    });
  }

  @Test
  public void testExceptionBreakpointIgnoreLibrariesOnRaise() {
    runPythonTest(new PyDebuggerTask("/debug", "test_ignore_lib.py") {

      @Override
      public void before() {
        createExceptionBreak(myFixture, false, true, true);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        waitForOutput("message=\"python-BaseException\"");
        eval("stopped_in_user_file").hasValue("True");
        resume();
        waitForTerminate();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-jython");
      }
    });
  }

  @Test
  public void testExceptionBreakpointIgnoreInUnittestModule() {
    runPythonTest(new PyDebuggerTask("/debug", "test_ignore_exceptions_in_unittest.py") {

      @Override
      public void before() {
        createExceptionBreak(myFixture, false, true, true);
        toggleBreakpoint(getFilePath(getScriptName()), 2);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        resume();
        waitForTerminate();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-jython");
      }
    });
  }

  @Test
  public void testExceptionBreakpointIgnoreLibrariesOnTerminate() {
    runPythonTest(new PyDebuggerTask("/debug", "test_ignore_lib.py") {

      @Override
      public void before() {
        createExceptionBreak(myFixture, true, false, true);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        waitForOutput("message=\"python-BaseException\"");
        eval("stopped_in_user_file").hasValue("True");
        resume();
        waitForTerminate();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron");
      }
    });
  }

  @Test
  public void testExceptionBreakpointConditionOnRaise() {
    runPythonTest(new PyDebuggerTask("/debug", "test_exceptbreak.py") {

      @Override
      public void before() {
        createExceptionBreak(myFixture, false, true, true, "__exception__[0] == ZeroDivisionError", null);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        waitForOutput("message=\"python-BaseException\"");
        eval("__exception__[0].__name__").hasValue("'ZeroDivisionError'");
        resume();
        waitForTerminate();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-jython", "-iron");
      }
    });
  }

  @Test
  public void testExceptionBreakpointConditionOnTerminate() {
    runPythonTest(new PyDebuggerTask("/debug", "test_exceptbreak.py") {

      @Override
      public void before() {
        createExceptionBreak(myFixture, true, false, false, "__exception__[0] == ZeroDivisionError", null);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        waitForOutput("message=\"python-BaseException\"");
        eval("__exception__[0].__name__").hasValue("'ZeroDivisionError'");
        resume();
        waitForTerminate();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-jython", "-iron");
      }
    });
  }

  @Test
  public void testMultithreading() {
    runPythonTest(new PyDebuggerTask("/debug", "test_multithread.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 10);
        toggleBreakpoint(getFilePath(getScriptName()), 16);
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("y").hasValue("2");
        resume();
        waitForPause();
        eval("z").hasValue("102");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-pypy"); //TODO: fix that for PyPy
      }
    });
  }

  @Test
  public void testEggDebug() {
    runPythonTest(new PyDebuggerTask("/debug", "test_egg.py") {
      @Override
      public void before() {
        String egg = getFilePath("Adder-0.1.egg");
        toggleBreakpointInEgg(egg, "adder/adder.py", 2);
        PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(getRunConfiguration().getSdkHome());
        if (flavor != null) {
          flavor.initPythonPath(Lists.newArrayList(egg), true, getRunConfiguration().getEnvs());
        }
        else {
          getRunConfiguration().getEnvs().put("PYTHONPATH", egg);
        }
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("ret").hasValue("16");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-jython"); //TODO: fix that for Jython if anybody needs it
      }
    });
  }

  @Test
  public void testWinEggDebug() {
    Assume.assumeFalse("Only needs to run on windows", UsefulTestCase.IS_UNDER_TEAMCITY && !SystemInfo.isWindows);
    runPythonTest(new PyDebuggerTask("/debug", "test_winegg.py") {
      @Override
      public void before() {
        String egg = getFilePath("wintestegg-0.1.egg");
        toggleBreakpointInEgg(egg, "eggxample/lower_case.py", 2);
        toggleBreakpointInEgg(egg, "eggxample/MIXED_case.py", 2);

        PythonSdkFlavor flavor = PythonSdkFlavor.getFlavor(getRunConfiguration().getSdkHome());
        if (flavor != null) {
          flavor.initPythonPath(Lists.newArrayList(egg), true, getRunConfiguration().getEnvs());
        }
        else {
          getRunConfiguration().getEnvs().put("PYTHONPATH", egg);
        }
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("ret").hasValue("16");
        resume();

        waitForPause();
        eval("ret").hasValue("17");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-jython"); //TODO: fix that for Jython if anybody needs it
      }
    });
  }

  @Test
  public void testWinLongName() {
    if (!SystemInfo.isWindows) {
      return; // Only needs to run on windows
    }
    runPythonTest(new PyDebuggerTask("/debug", "long_n~1.py") {
      @Override
      public void before() {
        String longName = "long_name_win_test.py";
        toggleBreakpoint(longName, 2);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("x").hasValue("10");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-jython"); //TODO: fix that for Jython if anybody needs it
      }
    });
  }

  @Test
  public void testReturnValues() {
    runPythonTest(new PyDebuggerTask("/debug", "test_return_values.py") {
      @Override
      public void before() {
        toggleBreakpoint(getScriptName(), 2);
        final PyDebuggerSettings debuggerSettings = PyDebuggerSettings.getInstance();
        debuggerSettings.setWatchReturnValues(true);
      }

      @Override
      public void doFinally() {
        final PyDebuggerSettings debuggerSettings = PyDebuggerSettings.getInstance();
        debuggerSettings.setWatchReturnValues(false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        stepOver();
        waitForPause();
        eval(PyDebugValue.RETURN_VALUES_PREFIX + "['bar'][0]").hasValue("1");
        stepOver();
        waitForPause();
        stepOver();
        waitForPause();
        eval(PyDebugValue.RETURN_VALUES_PREFIX + "['foo']").hasValue("33");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron", "-python3.6");
      }
    });
  }

  @Test
  public void testSuspendAllThreadsPolicy() {
    runPythonTest(new PyDebuggerTask("/debug", "test_two_threads.py") {
      @Override
      protected void init() {
        setMultiprocessDebug(true);
      }

      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 17);
        setBreakpointSuspendPolicy(getProject(), 17, SuspendPolicy.ALL);
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForAllThreadsPause();
        eval("m").hasValue("42");
        assertNull(getRunningThread());
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron");
      }
    });
  }

  @Test
  public void testSuspendAllThreadsResume() {
    runPythonTest(new PyDebuggerTask("/debug", "test_two_threads_resume.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 10);
        setBreakpointSuspendPolicy(getProject(), 10, SuspendPolicy.ALL);
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("x").hasValue("12");
        resume();
        waitForPause();
        eval("x").hasValue("12");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron");
      }
    });
  }

  @Test
  public void testSuspendOneThreadPolicy() {
    runPythonTest(new PyDebuggerTask("/debug", "test_two_threads.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 17);
        setBreakpointSuspendPolicy(getProject(), 17, SuspendPolicy.THREAD);
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("m").hasValue("42");
        assertEquals("Thread1", getRunningThread());
        resume();
      }
    });
  }

  @Test
  public void testShowReferringObjects() {
    runPythonTest(new PyDebuggerTask("/debug", "test_ref.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 3);
      }

      private String getRefWithWordInName(List<String> referrersNames, String word) {
        return referrersNames.stream().filter(x -> x.contains(word)).findFirst().get();
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        List<String> referrersNames = getNumberOfReferringObjects("l");
        assertNotNull(getRefWithWordInName(referrersNames, "module"));
        assertNotNull(getRefWithWordInName(referrersNames, "dict"));
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron");
      }
    });
  }

  @Test
  public void testResume() {
    runPythonTest(new PyDebuggerTask("/debug", "test_resume.py") {
      @Override
      public void before() {
        toggleBreakpoint(getScriptName(), 1);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("x").hasValue("1");
        resume();
        waitForPause();
        eval("x").hasValue("2");
        resume();
      }
    });
  }

  @Test
  public void testAddBreakWhileRunning() {
    runPythonTest(new PyDebuggerTask("/debug", "test_resume_after_step.py") {
      @Override
      public void before() {
        toggleBreakpoint(getScriptName(), 2);
        toggleBreakpoint(getScriptName(), 3);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("a").hasValue("1");
        toggleBreakpoint(getScriptName(), 5);
        resume();
        waitForPause();
        eval("b").hasValue("2");
        resume();
        waitForPause();
        eval("d").hasValue("4");
        resume();
      }
    });
  }

  @Test
  public void testAddBreakAfterRemove() {
    runPythonTest(new PyDebuggerTask("/debug", "test1.py") {
      @Override
      public void before() {
        toggleBreakpoint(getScriptName(), 2);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("i").hasValue("0");
        // remove break on line 2
        removeBreakpoint(getScriptName(), 2);
        resume();
        // add break on line 2
        toggleBreakpoint(getScriptName(), 2);
        // check if break on line 2 works
        waitForPause();
        // remove break on line 2 again
        removeBreakpoint(getScriptName(), 2);
        // add break on line 3
        toggleBreakpoint(getScriptName(), 3);
        resume();
        // check if break on line 3 works
        waitForPause();
        resume();
      }
    });
  }

  @Test
  public void testSetNextStatement() {
    runPythonTest(new PyDebuggerTask("/debug", "test_set_next_statement.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 1);
        toggleBreakpoint(getFilePath(getScriptName()), 6);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("x").hasValue("0");
        // jump on a top level
        Pair<Boolean, String> pair = setNextStatement(7);
        waitForPause();
        assertTrue(pair.first);
        eval("x").hasValue("0");
        // try to jump into a loop
        pair = setNextStatement(9);
        // do not wait for pause here, because we don't refresh suspension for incorrect jumps
        assertFalse(pair.first);
        assertTrue(pair.second.startsWith("Error:"));
        stepOver();
        waitForPause();
        eval("x").hasValue("2");
        resume();
        waitForPause();
        eval("a").hasValue("2");
        // jump inside a function
        pair = setNextStatement(2);
        waitForPause();
        assertTrue(pair.first);
        eval("a").hasValue("2");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron", "-python3.8"); // PY-38604
      }
    });
  }

  @Test
  public void testLoadValuesAsync() {
    runPythonTest(new PyDebuggerTask("/debug", "test_async_eval.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 14);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        List<PyDebugValue> frameVariables = loadFrame();
        String result = computeValueAsync(frameVariables, "f");
        assertEquals("foo", result);

        List<PyDebugValue> listChildren = loadChildren(frameVariables, "l");
        result = computeValueAsync(listChildren, "0");
        assertEquals("list", result);
      }
    });
  }

  //TODO: That doesn't work now: case from test_continuation.py and test_continuation2.py are treated differently by interpreter
  // (first line is executed in first case and last line in second)
  @Test
  public void testBreakOnContinuationLine() {
    runPythonTest(new PyDebuggerTask("/debug", "test_continuation.py") {
      @Override
      public void before() {
        toggleBreakpoint(getScriptName(), 11);
        setWaitForTermination(false);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("x").hasValue("0");
        stepOver();
        waitForPause();
        eval("x").hasValue("1");
        stepOver();
        waitForPause();
        stepOver();
        waitForPause();
        eval("x").hasValue("2");
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron", "-python3.8");  // PY-38603
      }
    });
  }

  @Test
  public void testModuleInterpreterOption() {
    runPythonTest(new BreakpointStopAndEvalTask("test1") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath("test1.py"), 3);
        setScriptName("test1");
        setWaitForTermination(false);

        getRunConfiguration().setModuleMode(true);
      }
    });
  }

  @Test
  public void testShowCommandline() {
    runPythonTest(new PyDebuggerTask("/debug", "test2.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 6);
        setWaitForTermination(false);

        getRunConfiguration().setShowCommandLineAfterwards(true);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("z").hasValue("1");
        resume();
        consoleExec("z");
        waitForOutput("2");
      }

      @Override
      public void doFinally() {
        getRunConfiguration().setShowCommandLineAfterwards(false);
      }
    });
  }

  @Test
  public void testShowCommandlineModule() {
    runPythonTest(new PyDebuggerTask("/debug", "test2") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath("test2.py"), 6);
        setScriptName("test2");
        setWaitForTermination(false);

        getRunConfiguration().setShowCommandLineAfterwards(true);
        getRunConfiguration().setModuleMode(true);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("z").hasValue("1");
        resume();
        consoleExec("foo(3)");
        waitForOutput("5");
      }

      @Override
      public void doFinally() {
        getRunConfiguration().setShowCommandLineAfterwards(false);
        getRunConfiguration().setModuleMode(false);
      }
    });
  }

  @Test
  public void testBuiltinBreakpoint() {
    runPythonTest(new PyDebuggerTask("/debug", "test_builtin_break.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()),2);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        resume();
        waitForPause();
        eval("a").hasValue("1");
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("python3.7");
      }
    });
  }

  @Test
  public void testTypeHandler() {
    runPythonTest(new PyDebuggerTask("/debug", "test_type_handler.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 5);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("s1").hasValue("'\\\\'");
        eval("s2").hasValue("'\\''");
        eval("s3").hasValue("'\"'");
        eval("s4").hasValue("'\n'");
        eval("s5").hasValue("'\\'foo\\'bar\nbaz\\\\'");
      }
    });
  }

  @Test
  public void testLargeCollectionsLoading() {
    runPythonTest(new PyDebuggerTask("/debug", "test_large_collections.py") {
      @Override
      public void before() { toggleBreakpoint(getFilePath(getScriptName()), 15); }

      @Override
      public void testing() throws Exception {
        waitForPause();
        List<PyDebugValue> frameVariables = loadFrame();

        // The effective maximum number of the debugger returns is MAX_ITEMS_TO_HANDLE
        // plus the __len__ attribute.
        final int effectiveMaxItemsNumber = MAX_ITEMS_TO_HANDLE + 1;

        // Large list.
        PyDebugValue L = findDebugValueByName(frameVariables, "L");

        XValueChildrenList children = loadVariable(L);
        int collectionLength = 1000;

        assertEquals(effectiveMaxItemsNumber, children.size());
        for (int i = 0; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
          assertTrue(hasChildWithValue(children, i));
        }

        L.setOffset(600);
        children = loadVariable(L);
        assertEquals(effectiveMaxItemsNumber, children.size());
        for (int i = 600; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
          assertTrue(hasChildWithValue(children, i));
        }

        L.setOffset(900);
        children = loadVariable(L);
        assertEquals(101, children.size());
        for (int i = 900; i < collectionLength; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
          assertTrue(hasChildWithValue(children, i));
        }

        // Large dict.
        PyDebugValue D = findDebugValueByName(frameVariables, "D");

        children = loadVariable(D);
        collectionLength = 1000;

        assertEquals(effectiveMaxItemsNumber, children.size());
        for (int i = 0; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, i));
          assertTrue(hasChildWithValue(children, i));
        }

        D.setOffset(600);
        children = loadVariable(D);
        assertEquals(effectiveMaxItemsNumber, children.size());
        for (int i = 600; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, i));
          assertTrue(hasChildWithValue(children, i));
        }

        D.setOffset(900);
        children = loadVariable(D);
        assertEquals(101, children.size());
        for (int i = 900; i < collectionLength; i++) {
          assertTrue(hasChildWithName(children, i));
          assertTrue(hasChildWithValue(children, i));
        }

        // Large set.
        PyDebugValue S = findDebugValueByName(frameVariables, "S");

        children = loadVariable(S);
        collectionLength = 1000;

        assertEquals(effectiveMaxItemsNumber, children.size());
        for (int i = 0; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithValue(children, i));
        }

        S.setOffset(600);
        children = loadVariable(S);
        assertEquals(effectiveMaxItemsNumber, children.size());
        for (int i = 600; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithValue(children, i));
        }

        S.setOffset(900);
        children = loadVariable(S);
        assertEquals(101, children.size());
        for (int i = 900; i < collectionLength; i++) {
          assertTrue(hasChildWithValue(children, i));
        }

        // Large deque.
        PyDebugValue dq = findDebugValueByName(frameVariables, "dq");

        children = loadVariable(dq);
        collectionLength = 1000;

        assertEquals(effectiveMaxItemsNumber + 1, children.size()); // one extra child for maxlen
        for (int i = 1; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
          assertTrue(hasChildWithValue(children, i));
        }

        dq.setOffset(600);
        children = loadVariable(dq);
        assertEquals(effectiveMaxItemsNumber, children.size());
        for (int i = 600; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
          assertTrue(hasChildWithValue(children, i));
        }

        dq.setOffset(900);
        children = loadVariable(dq);
        assertEquals(101, children.size());
        for (int i = 900; i < collectionLength; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
          assertTrue(hasChildWithValue(children, i));
        }
      }
    });
  }

  @Test
  public void testLargeNumpyArraysLoading() {
    runPythonTest(new PyDebuggerTask("/debug", "test_large_numpy_arrays.py") {
      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("pandas");
      }

      @Override
      public void before() { toggleBreakpoint(getFilePath(getScriptName()), 9); }

      @Override
      public void testing() throws Exception {
        waitForPause();
        List<PyDebugValue> frameVariables = loadFrame();

        int collectionLength = 1000;

        // NumPy array

        PyDebugValue nd = findDebugValueByName(frameVariables, "nd");
        XValueChildrenList children = loadVariable(nd);

        assertEquals("min", children.getName(0));
        assertEquals("max", children.getName(1));
        assertEquals("shape", children.getName(2));
        assertEquals("dtype", children.getName(3));
        assertEquals("size", children.getName(4));
        assertEquals("array", children.getName(5));

        PyDebugValue array = (PyDebugValue) children.getValue(5);

        children = loadVariable(array);
        assertEquals(MAX_ITEMS_TO_HANDLE + 1, children.size());

        for (int i = 0; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
        }

        array.setOffset(950);
        children = loadVariable(array);

        assertEquals(51, children.size());

        for (int i = 950; i < collectionLength; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
        }

        // Pandas series

        PyDebugValue s = findDebugValueByName(frameVariables, "s");
        children = loadVariable(s);
        PyDebugValue values = (PyDebugValue) children.getValue(children.size() - 1);
        children = loadVariable(values);
        array = (PyDebugValue) children.getValue(children.size() - 1);
        children = loadVariable(array);

        assertEquals(MAX_ITEMS_TO_HANDLE + 1, children.size());

        for (int i = 0; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
        }

        array.setOffset(950);
        children = loadVariable(array);

        assertEquals(51, children.size());

        for (int i = 950; i < collectionLength; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
        }

        // Pandas data frame

        PyDebugValue df = findDebugValueByName(frameVariables, "df");
        children = loadVariable(df);
        values = (PyDebugValue) children.getValue(children.size() - 1);
        children = loadVariable(values);
        array = (PyDebugValue) children.getValue(children.size() - 1);
        children = loadVariable(array);

        assertEquals(MAX_ITEMS_TO_HANDLE + 1, children.size());

        for (int i = 0; i < MAX_ITEMS_TO_HANDLE; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
        }

        array.setOffset(950);
        children = loadVariable(array);

        assertEquals(51, children.size());

        for (int i = 950; i < collectionLength; i++) {
          assertTrue(hasChildWithName(children, formatStr(i, collectionLength)));
        }
      }
    });
  }

  @Test
  public void testWarningsSuppressing() {
    runPythonTest(new PyDebuggerTask("/debug", "test_warnings_suppressing.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 15);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        List<PyDebugValue> frameVariables = loadFrame();
        PyDebugValue obj = findDebugValueByName(frameVariables, "obj");
        loadVariable(obj);
        String out = output();
        assertTrue(out.contains("This warning should appear in the output."));
        assertFalse(out.contains("This property is deprecated!"));
        resume();
        waitForOutput("This property is deprecated!");
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron"); // PY-37793
      }
    });
  }

  @Test
  public void testExecutableScriptDebug() {

    Assume.assumeFalse("Don't run under Windows", UsefulTestCase.IS_UNDER_TEAMCITY && SystemInfo.isWindows);

    runPythonTest(new PyDebuggerTask("/debug", "test_executable_script_debug.py") {
      @Override
      protected void init() {
        setMultiprocessDebug(true);
      }

      @Override
      public void before() {
        toggleBreakpoint(getFilePath("test_executable_script_debug_helper.py"), 4);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("x").hasValue("42");
        resume();
        waitForOutput("Subprocess exited with return code: 0");
      }
    });
  }

  @Test
  public void testDebugConsolePytest() {
    runPythonTest(new PyDebuggerTask("/debug", "test_debug_console_pytest.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 4);
      }

      @Override
      protected boolean usePytestRunner() {
        return true;
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        eval("a").hasValue("1");
        consoleExec("print('a = %s' % a)");
        waitForOutput("a = 1");
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return Sets.newHashSet("pytest");
      }
    });
  }

  @Test
  public void testDontStopOnSystemExit() {
    runPythonTest(new PyDebuggerTask("/debug", "test_sys_exit.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 3);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        setProcessCanTerminate(true);
        resume();
        waitForOutput("Process finished with exit code 0");
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron"); // PY-37791
      }
    });
  }

  private static class PyDebuggerTaskTagAware extends PyDebuggerTask {

    private PyDebuggerTaskTagAware(@Nullable String relativeTestDataPath, String scriptName) {
      super(relativeTestDataPath, scriptName);
    }

    public boolean hasTag(String tag) throws NullPointerException {
      String env = Paths.get(myRunConfiguration.getSdkHome()).getParent().getParent().toString();
      return envTags.get(env).stream().anyMatch((t) -> t.startsWith(tag));
    }
  }

  @Test
  public void testExecAndSpawnWithBytesArgs() {

    Assume.assumeFalse("Don't run under Windows", UsefulTestCase.IS_UNDER_TEAMCITY && SystemInfo.isWindows);

    final class ExecAndSpawnWithBytesArgsTask extends PyDebuggerTaskTagAware {

      private final static String BYTES_ARGS_WARNING = "pydev debugger: bytes arguments were passed to a new process creation function. " +
                                                       "Breakpoints may not work correctly.\n";
      private final static String PYTHON2_TAG = "python2";

      private ExecAndSpawnWithBytesArgsTask(@Nullable String relativeTestDataPath, String scriptName) {
        super(relativeTestDataPath, scriptName);
      }

      private boolean hasPython2Tag() throws NullPointerException {
          return hasTag(PYTHON2_TAG);
      }

      @Override
      protected void init() {
        setMultiprocessDebug(true);
      }

      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 4);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        setProcessCanTerminate(true);
        resume();
        try {
          if (hasPython2Tag()) {
            assertFalse(output().contains(BYTES_ARGS_WARNING));
          }
          else
            waitForOutput(BYTES_ARGS_WARNING);
        }
        catch (NullPointerException e) {
          fail("Error while checking if the env has the " + PYTHON2_TAG + " tag.");
        }
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron", "-jython");
      }
    }

    Arrays.asList("test_call_exec_with_bytes_args.py", "test_call_spawn_with_bytes_args.py").forEach(
      (script) -> runPythonTest(new ExecAndSpawnWithBytesArgsTask("/debug", script))
    );
  }

  @Test
  public void testListComprehension() {
    runPythonTest(new PyDebuggerTask("/debug", "test_list_comprehension.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 2);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        resume();
        waitForPause();
        List<PyDebugValue> frameVariables = loadFrame();
        assertTrue(findDebugValueByName(frameVariables,".0").getType().endsWith("_iterator"));
        eval(".0");
        // Different Python versions have different types of an internal list comprehension loop. Whatever the type is, we shouldn't get
        // an evaluating error.
        assertFalse(output().contains("Error evaluating"));
        toggleBreakpoint(getFilePath(getScriptName()), 2);
        resume();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        // Remove this after PY-36229 is fixed.
        return ImmutableSet.of("python3");
      }
    });
  }

  @Test
  public void testCallingSettraceWarning() {
    runPythonTest(new PyDebuggerTask("/debug", "test_calling_settrace_warning.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 2);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        resume();
        waitForTerminate();
        outputContains("PYDEV DEBUGGER WARNING:\nsys.settrace() should not be used when the debugger is being used.");
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron"); // PY-37796
      }
    });
  }

  @Test
  public void testStopsOnSyntaxError() {
    runPythonTest(new PyDebuggerTask("/debug", "test_syntax_error.py") {
      @Override
      public void before() {
        createDefaultExceptionBreakpoint(myFixture);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        try {
          resume();
          waitForTerminate();
        }
        catch (AssertionError e) {
          if (!e.getMessage().contains("SyntaxError: invalid syntax")) throw e;
        }
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("-iron"); // PY-36367
      }
    });
  }

  @Test
  public void testCodeEvaluationWithGeneratorExpression() {
    runPythonTest(new PyDebuggerTaskTagAware("/debug", "test_code_eval_with_generator_expr.py") {

      private final static String PYTHON2_TAG = "python2";

      @Override
      public void before() throws Exception {
        toggleBreakpoint(getFilePath(getScriptName()), 8);
      }

      @Override
      public void testing() throws Exception {
        String[] expectedOutput = ("[True] \t [True]\n" +
                                   "[False] \t [False]\n" +
                                   "[None] \t [None]").split("\n");
        waitForPause();
        for (String line : expectedOutput) {
          waitForOutput(line);
        }
        consoleExec("TFN = [True, False, None]\n" +
                    "for q in TFN:\n" +
                    "    gen = (c for c in TFN if c == q)\n" +
                    "    lcomp = [c for c in TFN if c == q]\n" +
                    "    print(list(gen), \"\\t\", list(lcomp))");
        if (hasPython2Tag()) {
          // Python 2 formats the output slightly differently.
          expectedOutput = ("([True], '\\t', [True])\n" +
                            "([False], '\\t', [False])\n" +
                            "([None], '\\t', [None])").split("\n");
          for (String line : expectedOutput) {
            waitForOutput(line);
          }
        }
        else {
          for (String line : expectedOutput) {
            waitForOutput(line, 2);
          }
        }
        consoleExec("def g():\n" +
                    "    print(\"Foo, bar, baz\")\n" +
                    "def f():\n" +
                    "    g()\n" +
                    "f()");
        waitForOutput("Foo, bar, baz");
        resume();
      }

      private boolean hasPython2Tag() throws NullPointerException {
        return hasTag(PYTHON2_TAG);
      }
    });
  }

  @Test
  public void testCodeEvaluationWithPandas() {
    runPythonTest(new PyDebuggerTask("/debug", "test_dataframe.py") {
      @Override
      public void before() throws Exception {
        toggleBreakpoint(getFilePath(getScriptName()), 30);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        consoleExec("x = 42");
        resume();
        waitForTerminate();
        assertFalse(output().contains("ValueError: The truth value of a DataFrame is ambiguous."));
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("pandas");
      }
    });
  }

  @Test
  public void testNoDebuggerRelatedStacktraceOnDebuggerStop() {
    runPythonTest(new PyDebuggerTask("/debug", "test1.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 2);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        setProcessCanTerminate(true);
        resume();
        disposeDebugProcess();
        waitForOutput("Process finished with exit code 1");
        assertTrue("Output should contain KeyboardInterrupt as the exit reason when debugger is stopped",
                   output().contains("KeyboardInterrupt"));
        assertFalse("Output shouldn't contain debugger related stacktrace when debugger is stopped",
                    output().contains("pydevd.py\", line "));
      }
    });
  }

  @Test
  public void testCollectionsShapes() {
    runPythonTest(new PyDebuggerTask("/debug", "test_shapes.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 39);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        List<PyDebugValue> frameVariables = loadFrame();
        PyDebugValue var = findDebugValueByName(frameVariables, "list1");
        assertEquals("120", var.getShape());
        var = findDebugValueByName(frameVariables, "dict1");
        assertEquals("2", var.getShape());
        var = findDebugValueByName(frameVariables, "custom");
        assertEquals("5", var.getShape());
        var = findDebugValueByName(frameVariables, "df1");
        assertEquals("(3, 6)", var.getShape());
        var = findDebugValueByName(frameVariables, "n_array");
        assertEquals("(3, 2)", var.getShape());
        var = findDebugValueByName(frameVariables, "series");
        assertEquals("(5,)", var.getShape());

        var = findDebugValueByName(frameVariables, "custom_shape");
        assertEquals("(3,)", var.getShape());
        var = findDebugValueByName(frameVariables, "custom_shape2");
        assertEquals("(2, 3)", var.getShape());
        resume();
        waitForTerminate();
      }

      @NotNull
      @Override
      public Set<String> getTags() {
        return ImmutableSet.of("pandas");
      }
    });
  }

  @Test
  public void testPathWithAmpersand() {
    runPythonTest(new PyDebuggerTask("/debug", "test_path_with_&.py") {
      @Override
      public void before() {
        toggleBreakpoint(getFilePath(getScriptName()), 3);
      }

      @Override
      public void testing() throws Exception {
        waitForPause();
        // Source position can be `null` because of troubles while decoding the message from the debugger.
        // The troubles can be a result of an unescaped symbol, wrongly encoded message, etc.
        assertNotNull(getCurrentStackFrame().getSourcePosition());
        resume();
        waitForTerminate();
      }
    });
  }
}


text:
package com.emptyarray.scala.android.util

import android.os.AsyncTask

import scala.concurrent.ExecutionContext

/**
 * Created by Weasel on 7/7/15.
 */
object ThreadPoolExecutionContext {
  implicit val execContext = ExecutionContext.fromExecutor( AsyncTask.THREAD_POOL_EXECUTOR )
}

redpajama_set_name: RedPajamaGithub


text:
package com.orientechnologies.orient.core.db;

import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.cache.OLocalRecordCache;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.config.OContextConfiguration;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.tool.ODatabaseImport;
import com.orientechnologies.orient.core.exception.ODatabaseException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.intent.OIntent;
import com.orientechnologies.orient.core.metadata.security.OToken;
import com.orientechnologies.orient.core.storage.ORecordMetadata;
import com.orientechnologies.orient.core.storage.OStorage;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;

@SuppressWarnings("unchecked")
public abstract class ODatabaseWrapperAbstract<DB extends ODatabaseInternal, T> implements ODatabaseInternal<T> {
  protected DB                   underlying;
  protected ODatabaseInternal<?> databaseOwner;

  public ODatabaseWrapperAbstract(final DB iDatabase) {
    underlying = iDatabase;
    databaseOwner = this;
    Orient.instance().getDatabaseFactory().register(databaseOwner);
  }

  public <THISDB extends ODatabase> THISDB open(final String iUserName, final String iUserPassword) {
    underlying.open(iUserName, iUserPassword);
    return (THISDB) this;
  }

  public <THISDB extends ODatabase> THISDB open(final OToken iToken) {
    underlying.open(iToken);
    Orient.instance().getDatabaseFactory().register(databaseOwner);
    return (THISDB) this;
  }

  @Override
  public ODatabase activateOnCurrentThread() {
    return underlying.activateOnCurrentThread();
  }

  @Override
  public boolean isActiveOnCurrentThread() {
    return underlying.isActiveOnCurrentThread();
  }

  public <THISDB extends ODatabase> THISDB create() {
    return create(null);
  }

  public <THISDB extends ODatabase> THISDB create(final Map<OGlobalConfiguration, Object> iInitialSettings) {
    underlying.create(iInitialSettings);
    return (THISDB) this;
  }

  public boolean exists() {
    return underlying.exists();
  }

  public void reload() {
    underlying.reload();
  }

  @Override
  public OContextConfiguration getConfiguration() {
    return underlying.getConfiguration();
  }

  /**
   * Executes a backup of the database. During the backup the database will be frozen in read-only mode.
   *
   * @param out
   *          OutputStream used to write the backup content. Use a FileOutputStream to make the backup persistent on disk
   * @param options
   *          Backup options as Map<String, Object> object
   * @param callable
   *          Callback to execute when the database is locked
   * @param iListener
   *          Listener called for backup messages
   * @param compressionLevel
   *          ZIP Compression level between 0 (no compression) and 9 (maximum). The bigger is the compression, the smaller will be
   *          the final backup content, but will consume more CPU and time to execute
   * @param bufferSize
   *          Buffer size in bytes, the bigger is the buffer, the more efficient will be the compression
   * @throws IOException
   */
  @Override
  public List<String> backup(OutputStream out, Map<String, Object> options, Callable<Object> callable,
      final OCommandOutputListener iListener, int compressionLevel, int bufferSize) throws IOException {
    return underlying.backup(out, options, callable, iListener, compressionLevel, bufferSize);
  }

  /**
   * Executes a restore of a database backup. During the restore the database will be frozen in read-only mode.
   *
   * @param in
   *          InputStream used to read the backup content. Use a FileInputStream to read a backup on a disk
   * @param options
   *          Backup options as Map<String, Object> object
   * @param callable
   *          Callback to execute when the database is locked
   * @param iListener
   *          Listener called for backup messages
   * @throws IOException
   * @see ODatabaseImport
   */
  @Override
  public void restore(InputStream in, Map<String, Object> options, Callable<Object> callable, final OCommandOutputListener iListener)
      throws IOException {
    underlying.restore(in, options, callable, iListener);
  }

  public void close() {
    underlying.close();
  }

  public void replaceStorage(OStorage iNewStorage) {
    underlying.replaceStorage(iNewStorage);
  }

  public void drop() {
    underlying.drop();
    Orient.instance().getDatabaseFactory().unregister(databaseOwner);
  }

  public STATUS getStatus() {
    return underlying.getStatus();
  }

  public <THISDB extends ODatabase> THISDB setStatus(final STATUS iStatus) {
    underlying.setStatus(iStatus);
    return (THISDB) this;
  }

  public String getName() {
    return underlying.getName();
  }

  public String getURL() {
    return underlying.getURL();
  }

  public OStorage getStorage() {
    return underlying.getStorage();
  }

  public OLocalRecordCache getLocalCache() {
    return underlying.getLocalCache();
  }

  public boolean isClosed() {
    return underlying.isClosed();
  }

  public long countClusterElements(final int iClusterId) {
    checkOpeness();
    return underlying.countClusterElements(iClusterId);
  }

  public long countClusterElements(final int[] iClusterIds) {
    checkOpeness();
    return underlying.countClusterElements(iClusterIds);
  }

  public long countClusterElements(final String iClusterName) {
    checkOpeness();
    return underlying.countClusterElements(iClusterName);
  }

  @Override
  public long countClusterElements(int iClusterId, boolean countTombstones) {
    checkOpeness();
    return underlying.countClusterElements(iClusterId, countTombstones);
  }

  @Override
  public long countClusterElements(int[] iClusterIds, boolean countTombstones) {
    checkOpeness();
    return underlying.countClusterElements(iClusterIds, countTombstones);
  }

  public int getClusters() {
    checkOpeness();
    return underlying.getClusters();
  }

  public boolean existsCluster(String iClusterName) {
    checkOpeness();
    return underlying.existsCluster(iClusterName);
  }

  public Collection<String> getClusterNames() {
    checkOpeness();
    return underlying.getClusterNames();
  }

  public int getClusterIdByName(final String iClusterName) {
    checkOpeness();
    return underlying.getClusterIdByName(iClusterName);
  }

  public String getClusterNameById(final int iClusterId) {
    checkOpeness();
    return underlying.getClusterNameById(iClusterId);
  }

  public long getClusterRecordSizeById(int iClusterId) {
    return underlying.getClusterRecordSizeById(iClusterId);
  }

  public long getClusterRecordSizeByName(String iClusterName) {
    return underlying.getClusterRecordSizeByName(iClusterName);
  }

  public int addCluster(String iClusterName, int iRequestedId, Object... iParameters) {
    checkOpeness();
    return underlying.addCluster(iClusterName, iRequestedId, iParameters);
  }

  public int addCluster(final String iClusterName, final Object... iParameters) {
    checkOpeness();
    return underlying.addCluster(iClusterName, iParameters);
  }

  public boolean dropCluster(final String iClusterName, final boolean iTruncate) {
    getLocalCache().freeCluster(getClusterIdByName(iClusterName));
    return underlying.dropCluster(iClusterName, true);
  }

  public boolean dropCluster(final int iClusterId, final boolean iTruncate) {
    getLocalCache().freeCluster(iClusterId);
    return underlying.dropCluster(iClusterId, true);
  }

  public int getDefaultClusterId() {
    checkOpeness();
    return underlying.getDefaultClusterId();
  }

  public boolean declareIntent(final OIntent iIntent) {
    return underlying.declareIntent(iIntent);
  }

  public <DBTYPE extends ODatabase> DBTYPE getUnderlying() {
    return (DBTYPE) underlying;
  }

  public ODatabaseInternal<?> getDatabaseOwner() {
    return databaseOwner;
  }

  public ODatabaseInternal<?> setDatabaseOwner(final ODatabaseInternal<?> iOwner) {
    databaseOwner = iOwner;
    return this;
  }

  @Override
  public boolean equals(final Object iOther) {
    if (!(iOther instanceof ODatabase))
      return false;

    final ODatabase other = (ODatabase) iOther;

    return other.getName().equals(getName());
  }

  @Override
  public String toString() {
    return underlying.toString();
  }

  public Object setProperty(final String iName, final Object iValue) {
    return underlying.setProperty(iName, iValue);
  }

  public Object getProperty(final String iName) {
    return underlying.getProperty(iName);
  }

  public Iterator<Entry<String, Object>> getProperties() {
    return underlying.getProperties();
  }

  public Object get(final ATTRIBUTES iAttribute) {
    return underlying.get(iAttribute);
  }

  public <THISDB extends ODatabase> THISDB set(final ATTRIBUTES attribute, final Object iValue) {
    return (THISDB) underlying.set(attribute, iValue);
  }

  public void registerListener(final ODatabaseListener iListener) {
    underlying.registerListener(iListener);
  }

  public void unregisterListener(final ODatabaseListener iListener) {
    underlying.unregisterListener(iListener);
  }

  @Override
  public <V> V callInLock(Callable<V> iCallable, boolean iExclusiveLock) {
    return getStorage().callInLock(iCallable, iExclusiveLock);
  }

  @Override
  public ORecordMetadata getRecordMetadata(ORID rid) {
    return underlying.getRecordMetadata(rid);
  }

  public long getSize() {
    return underlying.getSize();
  }

  public void freeze(boolean throwException) {
    underlying.freeze(throwException);
  }

  public void freeze() {
    underlying.freeze();
  }

  public void release() {
    underlying.release();
  }

  @Override
  public void freezeCluster(int iClusterId, boolean throwException) {
    underlying.freezeCluster(iClusterId, throwException);
  }

  @Override
  public void freezeCluster(int iClusterId) {
    underlying.freezeCluster(iClusterId);
  }

  @Override
  public void releaseCluster(int iClusterId) {
    underlying.releaseCluster(iClusterId);
  }

  protected void checkOpeness() {
    if (isClosed())
      throw new ODatabaseException("Database '" + getURL() + "' is closed");
  }
}


text:
package com.payneteasy.superfly.spi;

import java.io.IOException;
import java.io.OutputStream;

import com.payneteasy.superfly.spisupport.HOTPProviderContext;

/**
 * Provides HOTP (HMAC-based One Time Password) facilities.
 *
 * @author Roman Puchkovskiy
 * @since 1.2
 */
@Deprecated
public interface HOTPProvider {

    /**
     * Initializes the provider.
     *
     * @param context        context used to get parameters and dependencies
     */
    void init(HOTPProviderContext context);

    /**
     * Authenticates a user using HOTP.
     *
     * @param username    name of the user
     * @param hotp        HOTP
     * @return authentication result
     */
    boolean authenticate(String subsystemIdentifier, String username, String hotp);

    /**
     * Computes a HOTP value for a user with the given name.
     *
     * @param username    name of the user
     * @param counter    counter value
     * @return HOTP value
     */
    String computeValue(String username, long counter);

    /**
     * Returns true if this provider can output sequence of HOTP values as
     * a file for download via UI.
     *
     * @return whether sequence can be downloaded
     */
    boolean outputsSequenceForDownload();

    /**
     * Writes a sequence for download to {@link OutputStream}.
     *
     * @param username    name of the user
     * @param os        output stream
     * @throws IOException
     */
    void outputSequenceForDownload(String username, OutputStream os) throws IOException, ExportException;

    /**
     * Returns a name of file in which sequence is downloaded.
     *
     * @param username    name of the user
     * @return file name
     */
    String getSequenceForDownloadFileName(String username);

    /**
     * Resets a HOTP sequence for the given user. This means that a new
     * sequence will be generated and its counter will be reset to 0.
     *
     * @param username    name of the user
     */
    void resetSequence(String username);
}


text:
DbPathPage::DbPathPage(QWidget *parent) :
	QWizardPage(parent),
	ui(new Ui::DbPathPage)
{
	ui->setupUi(this);

	registerField(QStringLiteral("path*"), ui->pathedit);
}

DbPathPage::~DbPathPage()
{
	delete ui;
}

void DbPathPage::initializePage()
{
	if(field(QStringLiteral("isCreate")).toBool()) {
		setTitle(tr("Create new Database"));
		setSubTitle(tr("Create a new Database file to store your package synchronization state to."));
		ui->pathedit->setPathMode(QPathEdit::AnyFile);
		setFinalPage(false);
	} else if(field(QStringLiteral("isLoad")).toBool()) {
		setTitle(tr("Open Existing Database"));
		setSubTitle(tr("Open an existing Paxchange database to be used for this machine."));
		ui->pathedit->setPathMode(QPathEdit::ExistingFile);
		ui->pathedit->setPath(DatabaseController::instance()->currentPath());
		setFinalPage(true);
	}
}

void DbPathPage::cleanupPage()
{
	setTitle(QString());
	setSubTitle(QString());
	ui->pathedit->clear();
}

bool DbPathPage::validatePage()
{
	if(field(QStringLiteral("isLoad")).toBool()) {
		try {
			DatabaseController::instance()->loadDb(ui->pathedit->path());
			return true;
		} catch(QException &e) {
			qWarning() << e.what();
			DialogMaster::warning(this, tr("Failed to load database!"));
			return false;
		}
	}

	return true;
}


text:
namespace fs = boost::filesystem;
using std::vector;
using std::string;

const std::string ResourceManager::MODELS_DIR    = "models";
const std::string ResourceManager::TEXTURES_DIR  = "textures";
const std::string ResourceManager::MATERIALS_DIR = "materials";
const std::string ResourceManager::SHADERS_DIR   = "shaders";

ResourceManager::ResourceManager(const fs::path& resourceDirectory) :
    textureCache(resourceDirectory / TEXTURES_DIR, "dds"),
    materialCache(resourceDirectory / MATERIALS_DIR, "m42mat"),
    meshCache(resourceDirectory / MODELS_DIR, "m42"),
    shaderCache(resourceDirectory / SHADERS_DIR, "")
{
}

ResourceManager::~ResourceManager()
{
}

shared_ptr<Mesh> ResourceManager::getMesh(const string& name)
{
    shared_ptr<Mesh>    mesh = meshCache.get(name);
    vector<std::string> mats = mesh->getUsedMaterials();
    for (vector<string>::const_iterator iter = mats.begin();
         iter != mats.end();
         ++iter)
    {
        mesh->setMaterial(*iter, getMaterial(*iter));
    }
    return mesh;
}

shared_ptr<Material> ResourceManager::getMaterial(const string& name)
{
    shared_ptr<Material> mat = materialCache.get(name);

    if (mat->getType() == MATERIAL_TYPE_TEXTURE)
    {
        mat->setTexture(getTexture(mat->getTextureName()));
    }
    return mat;
}

shared_ptr<Texture> ResourceManager::getTexture(const string& name)
{
    return textureCache.get(name);
}

shared_ptr<Shader> ResourceManager::getShader(const string& name)
{
    return shaderCache.get(name);
}


text:
//---------------------------------------------------------------------
// <copyright file="PayloadFormatVersionAnnotatingVisitor.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.OData.Common
{
    #region Namespaces
    using Microsoft.Test.Taupo.Astoria.Common;
    using Microsoft.Test.Taupo.Astoria.Contracts;
    using Microsoft.Test.Taupo.Astoria.Contracts.OData;
    using Microsoft.Test.Taupo.Contracts;
    using Microsoft.Test.Taupo.OData.Common;
    using Microsoft.Test.Taupo.OData.Contracts;
    #endregion Namespaces

    /// <summary>
    /// Payload element visitor which adds format version annotations as appropriate to "fix" the payload for a given version.
    /// </summary>
    /// <remarks>Note that the visitor will annotate the payload in-place, so it's usually
    /// necessary to clone the payload before using this.
    /// Also note that the visitor will only add the necessary annotation if they are not already present.
    /// If there already is annotation in place where the visitor would have put one, it skips that element
    /// and does not verify that the annotation in place is correct (this allows manual construction of invalid payloads)</remarks>
    public sealed class PayloadFormatVersionAnnotatingVisitor : ODataPayloadElementVisitorBase
    {
        /// <summary>
        /// The version to annotate the payload with.
        /// </summary>
        private readonly DataServiceProtocolVersion version;

        /// <summary>
        /// true if the payload should represent a request payload, false if it's a response payload.
        /// </summary>
        private readonly bool requestPayload;

        /// <summary>
        /// The depth of the payload.
        /// </summary>
        private int depth;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="version">The version to annotate the payload with.</param>
        /// <param name="requestPayload">true if the payload should represent a request payload, false if it's a response payload.</param>
        private PayloadFormatVersionAnnotatingVisitor(DataServiceProtocolVersion version, bool requestPayload)
        {
            this.version = version;
            this.requestPayload = requestPayload;
            this.depth = 0;
        }

        /// <summary>
        /// Annotates payload with version as appropriate.
        /// </summary>
        /// <param name="payloadElement">The root of the payload to annotate.</param>
        /// <param name="version">The format version to annotate with.</param>
        /// <param name="requestPayload">true if the payload should represent a request payload, false if it's a response payload.</param>
        public static void AnnotateVerboseJson(ODataPayloadElement payloadElement, DataServiceProtocolVersion version, bool requestPayload)
        {
            PayloadFormatVersionAnnotatingVisitor visitor = new PayloadFormatVersionAnnotatingVisitor(version, requestPayload);
            visitor.Recurse(payloadElement);

            // Add the version/response annotation to the root if it's a response.
            if (!requestPayload && !(payloadElement is ODataErrorPayload))
            {
                payloadElement.SetAnnotation(new PayloadFormatVersionAnnotation() { Version = version, Response = true, ResponseWrapper = true });
            }
        }

        /// <summary>
        /// Annotates payload with version as appropriate.
        /// </summary>
        /// <param name="payloadElement">The root of the payload to annotate.</param>
        /// <param name="version">The format version to annotate with.</param>
        /// <param name="requestPayload">true if the payload should represent a request payload, false if it's a response payload.</param>
        public static void AnnotateJsonLight(ODataPayloadElement payloadElement, DataServiceProtocolVersion version, bool requestPayload)
        {
            PayloadFormatVersionAnnotatingVisitor visitor = new PayloadFormatVersionAnnotatingVisitor(version, requestPayload);
            visitor.Recurse(payloadElement);
        }

        /// <summary>
        /// Visits a payload element whose root is an EntitySetInstance.
        /// </summary>
        /// <param name="payloadElement">The root node of the payload element being visited.</param>
        public override void Visit(EntitySetInstance payloadElement)
        {
            base.Visit(payloadElement);

            // Entity set instances (Feeds) use different format in JSON for V2 (and higher) payloads in responses
            // so we need to add an annotation marking it with the right version so that the serializer will use the
            // V2 format.
            if (!this.requestPayload)
            {
                this.AddVersionAnnotation(payloadElement);
            }
        }

        /// <summary>
        /// Visits a payload element whose root is an <see cref="ComplexInstanceCollection"/>.
        /// </summary>
        /// <param name="payloadElement">The root node of the payload element being visited.</param>
        public override void Visit(ComplexInstanceCollection payloadElement)
        {
            base.Visit(payloadElement);

            // Collections use a different format in JSON for V2 (and higher) payloads (in responses)
            if (!this.requestPayload)
            {
                this.AddVersionAnnotation(payloadElement);
            }
        }

        /// <summary>
        /// Visits a payload element whose root is an <see cref="PrimitiveCollection"/>.
        /// </summary>
        /// <param name="payloadElement">The root node of the payload element being visited.</param>
        public override void Visit(PrimitiveCollection payloadElement)
        {
            base.Visit(payloadElement);

            // Collections use a different format in JSON for V2 (and higher) payloads (in responses)
            if (!this.requestPayload)
            {
                this.AddVersionAnnotation(payloadElement);
            }
        }

        /// <summary>
        /// Visits a payload element whose root is a LinkCollection.
        /// </summary>
        /// <param name="payloadElement">The root node of the payload element being visited.</param>
        public override void Visit(LinkCollection payloadElement)
        {
            base.Visit(payloadElement);

            // Link collection (response to the $ref request which returns multiple entity reference links)
            // uses a different format in JSON for V2 (and higher) payloads - but only in responses.
            // So we need to add an annotation marking it with the right version so that the serializer will use the
            // V2 format.
            if (!this.requestPayload)
            {
                this.AddVersionAnnotation(payloadElement);
            }
        }

        /// <summary>
        /// Visits a payload element whose root is a DeferredLink.
        /// </summary>
        /// <param name="payloadElement">The root node of the payload element being visited.</param>
        public override void Visit(DeferredLink payloadElement)
        {
            base.Visit(payloadElement);

            if (!this.requestPayload || this.depth > 2)
            {
                // Any deferred link inside a navigation link needs to be annotated (request/response payload differs)
                // Top level response payloads need to be annotated as they serialize differently in JSON-L
                this.AddVersionAnnotation(payloadElement);
            }
        }

        /// <summary>
        /// Visits a payload element whose root is a NavigationPropertyInstance.
        /// </summary>
        /// <param name="payloadElement">The root node of the payload element being visited.</param>
        public override void Visit(NavigationPropertyInstance payloadElement)
        {
            base.Visit(payloadElement);

            if (!this.requestPayload)
            {
                this.AddVersionAnnotation(payloadElement);
            }
        }

        /// <summary>
        /// Wrapper for recursively visiting the given element. Used with the callback property to make unit tests easier.
        /// </summary>
        /// <param name="element">The element to visit</param>
        protected override void Recurse(ODataPayloadElement element)
        {
            this.depth++;
            base.Recurse(element);
            this.depth--;
        }

        /// <summary>
        /// Annotates the <paramref name="payloadElement"/> with the format version if it's not already annotated.
        /// </summary>
        /// <param name="payloadElement">The payload element to annotate.</param>
        private void AddVersionAnnotation(ODataPayloadElement payloadElement)
        {
            PayloadFormatVersionAnnotation versionAnnotation =
                (PayloadFormatVersionAnnotation)payloadElement.GetAnnotation(typeof(PayloadFormatVersionAnnotation));

            if (versionAnnotation == null)
            {
                versionAnnotation = new PayloadFormatVersionAnnotation()
                {
                    Version = this.version,
                    Response = !this.requestPayload,
                };

                payloadElement.AddAnnotation(versionAnnotation);
            }
        }
    }
}


text:
var app = angular.module('goFlexGet');

app.config(function($routeProvider) {
  'use strict';

  $routeProvider
    .when('/', {
      controller: 'MainCtrl',
      templateUrl: '/public/pages/main.html'
    })
    .when('/config', {
      controller: 'ConfigCtrl',
      templateUrl: '/public/pages/config.html'
    })
    .when('/logs', {
      controller: 'LogsCtrl',
      templateUrl: '/public/pages/logs.html'
    })
    .otherwise({
      redirectTo: '/'
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>nu.peg</groupId>
    <artifactId>svmeal-api</artifactId>
    <version>2.3.2</version>
    <packaging>jar</packaging>

    <name>svmeal-api</name>
    <description>Api which scrapes menu plans from SV-Group websites</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jetty</artifactId>
            <!--<scope>provided</scope>-->
        </dependency>

        <dependency>
            <groupId>io.github.resilience4j</groupId>
            <artifactId>resilience4j-spring-boot2</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- jsoup HTML parser library @ http://jsoup.org/ -->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>
        <dependency>
            <groupId>org.ehcache</groupId>
            <artifactId>ehcache</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.cache</groupId>
            <artifactId>cache-api</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


text:
layout: post
title: "Gentleman's Box July 2016 Review + Coupon!"
description: ""
headline: "Gentleman's Box July 2016 Review + Coupon!"
categories:
      - Subscriptions
      - Reviews
tags: [Gentleman's Box, Subscriptions, Reviews, July 2016]
comments: true
mathjax: null
published: true
featured: false
type: photo
imagefeature: "GentlemansBoxJuly2016Items.jpg"
date: 2016-07-19 09:31:39 -08:00
---

Disclosure: This box was sent to me in exchange for an honest review.

[![Gentleman's Box July 2016 Box](http://whatsupmailbox.com/images/GentlemansBoxJune2016Box.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

**Subscription:** [Gentleman's Box](http://mbsy.co/d7GnS"){:target="_blank"}

**Cost:** $25/monthly + Free Shipping to USA. $8 shipping to Canada.

**What's in the box:** Four to six hand-selected products for men, accompanied by the latest issue of GQ Magazine (U.S. and Canada only).

**Coupon:** Use code SAVE5 to get $5 off your first box.

*Note: The GQ magazine that's included with the subscription used to be shipped together in the box, but now it comes separately in the mail.*

[Gentleman's Box](http://mbsy.co/d7GnS"){:target="_blank"} is one of those subscription for men who love to accesorize or look dapper. A gentleman always looks well put together and this box will surely help you achieve that.

This month's box title is "Our Favorite Fashion Mogul" Box.

[![Open Box](http://whatsupmailbox.com/images/GentlemansBoxJuly2016OpenBox.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

I love the uplifting words that are printed on the inside cover, Look Good - Feel Good - Be Good!

[![Open Box](http://whatsupmailbox.com/images/GentlemansBoxJuly2016OpenBox2.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

First look at unboxing

This month includes a couple of boxed items. Interesting... can't wait to see what they are!

Info Magazine:

[![Info Magazine](http://whatsupmailbox.com/images/GentlemansBoxJuly2016Info.jpg)](http://mbsy.co/d7GnS)

[![Info Magazine](http://whatsupmailbox.com/images/GentlemansBoxJuly2016Info2.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

Table of Contents

The info magazine that they include with every box are so very useful. It details each item in the box as well as the brand/creator behind it.

[![Info Magazine](http://whatsupmailbox.com/images/GentlemansBoxJuly2016Info3.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

They also include a section on how to wear all the items in the box together for a super dapper look!

[![Info Magazine](http://whatsupmailbox.com/images/GentlemansBoxJuly2016Info4.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

A recipe for Spiked Arnold Palmer! This drink is great for brunch and is simple to make too, I will be trying this recipe soon!

And here are all the items:

[![Gentleman's Box July 2016 Items](http://whatsupmailbox.com/images/GentlemansBoxJuly2016Items.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

I'm loving the colors this month brings, bright red with vintage browns.

Items in detail:

[![Kiko Brown Leather Wallet](http://whatsupmailbox.com/images/GentlemansBoxJuly2016KikoLeatherWallet.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

**Kiko** Brown Leather Wallet, *Value $45*

I think this is the first time ever I received a leather wallet from a subscription, how awesome. The leather is soft and the brown color is vintage and classic indeed.

![Kiko Brown Leather Wallet](http://whatsupmailbox.com/images/GentlemansBoxJuly2016KikoLeatherWallet2.jpg)(http://mbsy.co/d7GnS){:target="_blank"}

The inside has 4 card slots and a long section to keep your cash organized. An all around great wallet!

[![Gentlemen Essentials Leather Shoe Horn](http://whatsupmailbox.com/images/GentlemansBoxJuly2016GentlemenEssentialsLeatherShoeHorn.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

**Gentlemen Essentials** Leather Shoe Horn, *Value $25*

Leather shoe horns are a luxury to have. It beats plastic cheap looking ones that you see in typical department stores by a longshot.

[![Gentlemen Essentials Leather Shoe Horn](http://whatsupmailbox.com/images/GentlemansBoxJuly2016GentlemenEssentialsLeatherShoeHorn2.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

I like that it comes with a strap so you can hang it somewhere that's easy to find versus rummaging through a drawer to find it.

[![William Sterling Premium No Show Socks](http://whatsupmailbox.com/images/GentlemansBoxJuly2016WilliamSterlingNoShowSocks.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

**William Sterling** Premium No Show Socks, *Value $10*

No show socks are a must during the hot summer season. The colors on this one is perfect for July. It has red, white and blue, very patriotic indeed.

[![Nikolas Ryan Pocket Square](http://whatsupmailbox.com/images/GentlemansBoxJuly2016NikolasRyanPocketSquare.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

**Nikolas Ryan** Pocket Square, *Value $15*

I am loving this pocket square. Both the design and color is so popping bright that it will certainly compliment any outfit this summer.

[![Balla Body Powder](http://whatsupmailbox.com/images/GentlemansBoxJuly2016BallaBodyPowder.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

**Balla** Body Powder, *Value $6*

I've received this before in another subscription box so I know that this is a good product. It's a talc powder that will leave your manly parts fresh, clean and dry.

[![Gentleman's Box July 2016 Coupons](http://whatsupmailbox.com/images/GentlemansBoxJuly2016Coupons.jpg)](http://mbsy.co/d7GnS){:target="_blank"}

**Various Coupons**

A few coupons were also included in this month's box which includes an exclusive coupon for **Debonair Scent** First Month Free! [Debonair Scent](https://www.debonairscent.com){:target="_blank"} is a monthly cologne discovery box. Every month you'll receive three different colognes that's matched to your scent profile from hundreds of designer and niche brands for only $15/month. So this coupon alone is worth $15! I'm totally going to try them out!

 **My Thoughts:** Super loving this month's items! I feel like I've been receiving way too many ties lately so I appreciate that this month they decided to send a couple of accessory items instead, the leather shoe horn and wallet. And on top of that I'm introduced to a new subscription by way of a coupon for my first month free, so excited about that as well. I love trying out new subs! [Gentleman's Box](http://mbsy.co/d7GnS){:target="_blank"} continues to send out a great box month after month.

Not a subscriber? You can <big>join here</big> to start receiving their monthly accessory and lifestyle products for men! And don't forget to use coupon [SAVE5](http://mbsy.co/d7GnS){:target="_blank"} to get $5 off your first box!

Gentleman's Box Items

      Product
      Price

      Kiko Leather Wallet
      $45

      Gentlemen Essentials Leather Shoe Horn
      $25

      William & Sterling No Show Socks
      $10

      Nikolas Ryan Pocket Square
      $15

      Balla Body Powder
      $6

      GQ Magazine
      $6

      <big>TOTAL VALUE</big>
      <big>$107</big>

      <big>Subscription Cost</big>
      <big>$25</big>


text:
from path import path
import hashlib
import json
import numpy as np
import os
import pandas as pd
from datetime import datetime

def md5(data_path):
    # we need to compute the md5 sum one chunk at a time, because some
    # files are too large to fit in memory
    md5 = hashlib.md5()
    with open(data_path, 'r') as fh:
        while True:
            chunk = fh.read(128)
            if not chunk:
                break
            md5.update(chunk)
    data_hash = md5.hexdigest()
    return data_hash

class DataPackage(dict):

    def __init__(self, name, licenses):
        self['name'] = name
        self['datapackage_version'] = '1.0-beta.5'
        self['licenses'] = []
        for l in licenses:
            if not isinstance(l, dict):
                if l == 'odc-by':
                    url = 'http://opendefinition.org/licenses/odc-by'
                else:
                    raise ValueError("unrecognized license: %s" % l)
                l = dict(id=l, url=url)
            self['licenses'].append(l)

        self['title'] = None
        self['description'] = None
        self['homepage'] = None
        self['version'] = '0.0.1'
        self['sources'] = []
        self['keywords'] = None
        self['last_modified'] = datetime.now().isoformat(" ")
        self['image'] = None
        self['contributors'] = []
        self['resources'] = []

        self._path = None
        self._resource_map = {}

    @property
    def abspath(self):
        return self._path.joinpath(self['name']).abspath()

    @classmethod
    def load(cls, pth):
        pth = path(pth)

        dpjson_pth = pth.joinpath("datapackage.json")
        if not dpjson_pth.exists():
            raise IOError("No metadata file datapackage.json")
        with open(dpjson_pth, "r") as fh:
            dpjson = json.load(fh)

        name = dpjson['name']
        licenses = dpjson['licenses']
        resources = dpjson['resources']
        del dpjson['name']
        del dpjson['licenses']
        del dpjson['resources']

        dp = cls(name=name, licenses=licenses)
        dp._path = pth.splitpath()[0]
        dp.update(dpjson)

        if dp.abspath != pth.abspath():
            raise ValueError("malformed datapackage")

        for resource in resources:
            rname = resource['name']
            rfmt = resource['format']
            rpth = resource.get('path', None)
            rdata = resource.get('data', None)

            del resource['name']
            del resource['format']
            if 'path' in resource:
                del resource['path']
            if 'data' in resource:
                del resource['data']

            r = Resource(name=rname, fmt=rfmt, pth=rpth, data=rdata)
            r.update(resource)
            dp.add_resource(r)

        return dp

    def add_contributor(self, name, email):
        self['contributors'].append(dict(name=name, email=email))

    def clear_resources(self):
        self['resources'] = []
        self._resource_map = {}

    def add_resource(self, resource):
        self['resources'].append(resource)
        self._resource_map[resource['name']] = len(self['resources']) - 1
        resource.dpkg = self

    def get_resource(self, name):
        return self['resources'][self._resource_map[name]]

    def load_resource(self, name, verify=True):
        return self.get_resource(name).load_data(verify=verify)

    def load_resources(self, verify=True):
        for resource in self['resources']:
            resource.load_data(verify=verify)

    def save_metadata(self, dest=None):
        if dest:
            self._path = dest
        self['last_modified'] = datetime.now().isoformat(" ")
        metapath = self.abspath.joinpath("datapackage.json")
        with open(metapath, "w") as fh:
            json.dump(self, fh, indent=2)

    def save_data(self, dest=None):
        if dest:
            self._path = dest
        for resource in self['resources']:
            resource.save_data()

    def save(self, dest=None):
        if dest:
            self._path = dest
        if not self.abspath.exists():
            self.abspath.makedirs_p()
        self.save_data()
        self.save_metadata()

    def bump_major_version(self):
        major, minor, patch = map(int, self['version'].split("."))
        major += 1
        minor = 0
        patch = 0
        self['version'] = "%d.%d.%d" % (major, minor, patch)
        return self['version']

    def bump_minor_version(self):
        major, minor, patch = map(int, self['version'].split("."))
        minor += 1
        patch = 0
        self['version'] = "%d.%d.%d" % (major, minor, patch)
        return self['version']

    def bump_patch_version(self):
        major, minor, patch = map(int, self['version'].split("."))
        patch += 1
        self['version'] = "%d.%d.%d" % (major, minor, patch)
        return self['version']

class Resource(dict):

    def __init__(self, name, fmt, data=None, pth=None):
        self['name'] = name
        self['modified'] = datetime.now().isoformat(" ")
        self['format'] = fmt

        if pth:
            self['path'] = pth

        self.data = data
        self.dpkg = None

    @property
    def abspath(self):
        if not self.get('path', None):
            raise ValueError("no relative path specified")
        if not self.dpkg:
            raise ValueError("no linked datapackage")
        return self.dpkg.abspath.joinpath(self['path'])

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, val):
        self._data = val
        if 'path' not in self:
            self['data'] = val

    def save_data(self):
        self['modified'] = datetime.now().isoformat(" ")

        if 'path' not in self:
            return

        if self['format'] == 'csv':
            pd.DataFrame(self.data).to_csv(self.abspath)
        elif self['format'] == 'json':
            with open(self.abspath, "w") as fh:
                json.dump(self.data, fh)
        elif self['format'] == 'npy':
            np.save(self.abspath, np.array(self.data))
        else:
            raise ValueError("unsupported format: %s" % self['format'])

        self.update_size()
        self.update_hash()

    def load_data(self, verify=True):
        if self.data is not None:
            return self.data

        # check the file size
        if self.update_size():
            raise IOError("resource has changed size on disk")

        # load the raw data and check md5
        if verify and self.update_hash():
            raise IOError("resource checksum has changed")

        # check format and load data
        if self['format'] == 'csv':
            data = pd.DataFrame.from_csv(self.abspath)
        elif self['format'] == 'json':
            with open(self.abspath, "r") as fh:
                data = json.load(fh)
        elif self['format'] == 'npy':
            data = np.load(self.abspath, mmap_mode='c')
        else:
            raise ValueError("unsupported format: %s" % self['format'])

        self.data = data
        return self.data

    def update_size(self):
        old_size = self.get('bytes', None)
        new_size = self.abspath.getsize()
        self['bytes'] = new_size
        return old_size != new_size

    def update_hash(self):
        old_hash = self.get('hash', None)
        new_hash = md5(self.abspath)
        self['hash'] = new_hash
        return old_hash != new_hash


text:
package SADI::Service::ServiceBase;

use SADI::Base;
use base qw( SADI::Base );

use strict;

# add versioning to this module
use vars qw /$VERSION/;
$VERSION = sprintf "%d.%02d", q$Revision: 1.9 $ =~ /: (\d+)\.(\d+)/;

#-----------------------------------------------------------------
# process_it
#-----------------------------------------------------------------
sub process_it {
	my ( $self, $values, $service ) = @_;

	# subclass over-rides this
}

#-----------------------------------------------------------------
# as_uni_string
#-----------------------------------------------------------------
use SADI::Data::String;
use Unicode::String;

sub as_uni_string {
	my ( $self, $value ) = @_;
	return new SADI::Data::String( Unicode::String::latin1($value) );
}

#-----------------------------------------------------------------
# log_request
#
# should be called when a request from a client comes; it returns
# information about the current call (request) that can be used in a
# log entry
#-----------------------------------------------------------------

my @ENV_TO_REPORT =
  ( 'REMOTE_ADDR', 'REQUEST_URI' ,'HTTP_USER_AGENT', 'CONTENT_LENGTH', 'CONTENT_TYPE', 'HTTP_ACCEPT' );

sub log_request {
	my ($self) = shift;

	my @buf;
	foreach my $elem (@ENV_TO_REPORT) {
		push( @buf, "$elem: $ENV{$elem}" ) if exists $ENV{$elem};
	}
	return join( ", ", @buf );
}

sub get_service_signature {
	my ( $self, $name ) = @_;
	my $sig = undef;
	eval {
		my $services = SADI::Generators::GenServices->new->read_services( $name, );
		# iterate over the services (should be only 1)
		foreach my $s (@$services) {
			$sig = $s;
			last;
		}
	};
	$LOG->error("Problems retrieving service signature!\n$@") if $@;
	return $sig if $sig;
	$self->throw("Couldn't find a signature for '$name'!.");
}

# returns the request content type
# defaults to application/rdf+xml
sub get_request_content_type {
	my ($self) = @_;
    my $CONTENT_TYPE = 'application/rdf+xml';
    if (defined $ENV{CONTENT_TYPE}) {
        $CONTENT_TYPE = 'text/rdf+n3' if $ENV{CONTENT_TYPE} =~ m|text/rdf\+n3|gi;
        $CONTENT_TYPE = 'text/rdf+n3' if $ENV{CONTENT_TYPE} =~ m|text/n3|gi;
    }
    return $CONTENT_TYPE;
}

# returns the response requested content type
# defaults to application/rdf+xml
sub get_response_content_type {
    my ($self) = @_;
    my $CONTENT_TYPE = 'application/rdf+xml';
    if (defined $ENV{HTTP_ACCEPT}) {
        $CONTENT_TYPE = 'text/rdf+n3' if $ENV{HTTP_ACCEPT} =~ m|text/rdf\+n3|gi;
        $CONTENT_TYPE = 'text/rdf+n3' if $ENV{HTTP_ACCEPT} =~ m|text/n3|gi;
    }
    return $CONTENT_TYPE;
}

1;
__END__

=head1 NAME

SADI::ServiceBase - a super-class for all SADI services

=head1 SYNOPSIS

 use base qw( SADI::ServiceBase )

=head1 DESCRIPTION

A super class for all SADI services implemented with SADISeS.

=head1 SUBROUTINES

=head2 process_it

A job-level processing: B<This is the main method to be overriden by a
service provider!>. Here all the business logic belongs to.

This method is called once for each service invocation request.

Note that here, in C<SADI::Service::ServiceBase>, this method does
nothing. Which means it leaves the output job empty, as it was given
here. Consequence is that if you do not override this method in a
sub-class, the client will get back an empty request. Which may be
good just for testing but not really what a client expects (I guess).

You are free to throw an exception (TBD: example here). However, if
you do so the complete processing of the whole client request is
considered failed. After such exception the client will not get any
data back (only an error message).

=head2 as_uni_string

Convert given $value (the only argument) into Unicode and wrap it as a
SADI string (type SADI::Data::String).

=head2 log_request

 # should be called when a request from a client comes; it returns
 # information about the current call (request) that can be used in a
 # log entry

=head2 get_request_content_type

 # Returns the content type of the incoming data, defaults to application/rdf+xml.
 #
 # Possible values: 'application/rdf+xml', 'text/rdf+n3'

=head2 get_response_content_type

 # Returns the requested content type of the outgoing data, defaults to application/rdf+xml.
 #
 # Possible values: 'application/rdf+xml', 'text/rdf+n3'

=head1 AUTHORS, COPYRIGHT, DISCLAIMER

 Edward Kawas  (edward.kawas [at] gmail [dot] com)
 Martin Senger (martin.senger [at] gmail [dot] com)

Copyright (c) 2009 Edward Kawas. All Rights Reserved.

This module is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

This software is provided "as is" without warranty of any kind.

=cut


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<title>登录</title>
		<link rel="stylesheet" href="../resources/css/materialize/materialize.css" />
		<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
		<link rel="stylesheet" href="../resources/css/project/login.css" />

为了更好的用户体验,请使用谷歌、火狐的最新版浏览器

			<form id="loginPanel" class="col s6">

新通道后台内容管理系统

						person_pin
						<input id="username" type="text" class="validate">
						账号

						lock
						<input id="password" type="password" class="validate">
						密码

						send提交

			</form>


text:
<?php
include APPPATH . 'views/header.php';

echo heading('403 Forbidden', 1);

echo '
Sie haben nicht die nötigen Berechtigungen für diese Seite.
';

include APPPATH . 'views/footer.php';


text:
define([
  'backbone'
], function(Backbone){

  return Backbone.Model.extend({
    getParent: function() {
      return this.collection.get(this.get('parent_id'));
    },
    getFullName: function() {
      var parent = this.getParent();
      var name = this.get('name');
      if (!parent || parent.get('parent_id') == -1) {
        return name;
      } else {
        return parent.getFullName() + ' > ' + name;
      }
    }
  });
})


text:
class DiffProcessor : public Processor {
  public:
    cv::Mat operator()(cv::Mat);
  private:
    cv::Mat prevFrame;
};

cv::Mat DiffProcessor::operator()(cv::Mat im) {
  if ( prevFrame.empty() ) {
    prevFrame = im.clone();
  } else {
    cv::Mat dest;
    cv::absdiff( im, prevFrame, dest);
    prevFrame = im.clone(); // NB: need to clone image not just copy ref
    // Set alpha channel
    cv::add( cv::Scalar(0,0,0,255), dest, im );
  }
  return im;
}

namespace {
  auto diffProcReg = ProcessorRegister<DiffProcessor>("Diff");
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\MessagesSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'id') ?>

    <?= $form->field($model, 'users_id') ?>

    <?= $form->field($model, 'tiltle') ?>

    <?= $form->field($model, 'message') ?>

    <?= $form->field($model, 'status') ?>

    <?php // echo $form->field($model, 'sender') ?>

    <?php // echo $form->field($model, 'receiver') ?>

    <?php // echo $form->field($model, 'date') ?>

        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
package com.quiz.php.ui;

import android.support.v4.app.Fragment;

/**
 * Created by fabricio on 2/11/14.
 */
public class ResultActivity extends SingleFragmentActivity {

    @Override
    public Fragment createFragment() {
        return new ResultFragment();
    }
}


text:
class AppSourcesTableModel : public QAbstractTableModel
{
    Q_OBJECT

public:
    AppSourcesTableModel(QObject* parent = 0);

    QList<AppSource> get() const;
    void set(const QList<AppSource>& sources);
    void append(const AppSource& source);
    void update(const AppSource& source);

    // QAbstractItemModel interface
public:
    virtual int rowCount(const QModelIndex& parent) const override;
    virtual int columnCount(const QModelIndex& parent) const override;
    virtual QVariant data(const QModelIndex& index, int role) const override;
    virtual bool setData(const QModelIndex& index, const QVariant& value, int role) override;
    virtual QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
    virtual bool removeRows(int row, int count, const QModelIndex& parent) override;
    virtual Qt::ItemFlags flags(const QModelIndex& index) const override;

private:
    QList<AppSource> sources;
};

#endif // APPSOURCESTABLEMODEL_H