text:
<?php

declare(strict_types=1);

namespace DCarbone\PHPConsulAPI\Catalog;

use DCarbone\PHPConsulAPI\AbstractValuedQueryResponse;
use DCarbone\PHPConsulAPI\UnmarshalledResponseInterface;

/**
 * Class NodesResponse
 */
class NodesResponse extends AbstractValuedQueryResponse implements UnmarshalledResponseInterface
{
    /** @var \DCarbone\PHPConsulAPI\Catalog\Node[]|null */
    public ?array $Nodes = null;

    /**
     * @return \DCarbone\PHPConsulAPI\Catalog\Node[]|mixed|null
     */
    public function getValue()
    {
        return $this->Nodes;
    }

    /**
     * @param mixed $decodedData
     */
    public function unmarshalValue($decodedData): void
    {
        $this->Nodes = [];
        foreach ($decodedData as $node) {
            $this->Nodes[] = new Node($node);
        }
    }
}


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Management.Automation;
using System.Net;
using Microsoft.Azure.Commands.Cdn.Common;
using Microsoft.Azure.Commands.Cdn.Models.CustomDomain;
using Microsoft.Azure.Commands.Cdn.Properties;
using Microsoft.Azure.Management.Cdn;
using Microsoft.Azure.Management.Cdn.Models;
using System.Linq;

namespace Microsoft.Azure.Commands.Cdn.CustomDomain
{
    [Cmdlet(VerbsCommon.Remove,
        "AzureRmCdnCustomDomain",
        DefaultParameterSetName = FieldsParameterSet,
        SupportsShouldProcess = true),
        OutputType(typeof(bool))]
    public class RemoveAzureRmCdnCustomDomain : AzureCdnCmdletBase
    {
        [Parameter(Mandatory = true, ParameterSetName = FieldsParameterSet, HelpMessage = "Azure CDN custom domain display name.")]
        [ValidateNotNullOrEmpty]
        public string CustomDomainName { get; set; }

        [Parameter(Mandatory = true, ParameterSetName = FieldsParameterSet, HelpMessage = "Azure CDN endpoint name.")]
        [ValidateNotNullOrEmpty]
        public string EndpointName { get; set; }

        [Parameter(Mandatory = true, ParameterSetName = FieldsParameterSet, HelpMessage = "Azure CDN profile name.")]
        [ValidateNotNullOrEmpty]
        public string ProfileName { get; set; }

        [Parameter(Mandatory = true, ParameterSetName = FieldsParameterSet, HelpMessage = "The resource group of the Azure CDN profile")]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Parameter(Mandatory = true, ValueFromPipeline = true, HelpMessage = "The custom domain object.", ParameterSetName = ObjectParameterSet)]
        [ValidateNotNull]
        public PSCustomDomain CdnCustomDomain { get; set; }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Return object if specified.")]
        public SwitchParameter PassThru { get; set; }

        public override void ExecuteCmdlet()
        {
            if (ParameterSetName == ObjectParameterSet)
            {
                EndpointName = CdnCustomDomain.EndpointName;
                ProfileName = CdnCustomDomain.ProfileName;
                ResourceGroupName = CdnCustomDomain.ResourceGroupName;
                CustomDomainName = CdnCustomDomain.Name;
            }

            var existingCustomDomain = CdnManagementClient.CustomDomains.ListByEndpoint(EndpointName, ProfileName, ResourceGroupName)
                .Where(cd => cd.Name.ToLower() == CustomDomainName.ToLower())
                .FirstOrDefault();

            if (existingCustomDomain == null)
            {
                throw new PSArgumentException(string.Format(Resources.Error_DeleteNonExistingCustomDomain,
                    CustomDomainName,
                    EndpointName,
                    ProfileName,
                    ResourceGroupName));
            }

            ConfirmAction(MyInvocation.InvocationName,
                String.Format("{0} ({1})", existingCustomDomain.Name, existingCustomDomain.HostName),
                () => CdnManagementClient.CustomDomains.DeleteIfExists(CustomDomainName,
                    EndpointName,
                    ProfileName,
                    ResourceGroupName));

            if (PassThru)
            {
                WriteObject(true);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.security.zynamics.binnavi.Gui.CriteriaDialog.Conditions.InDegrees;

import com.google.security.zynamics.binnavi.yfileswrap.zygraph.NaviNode;

/**
 * Used to evaluate indegree criteria maches.
 */
public final class CIndegreeEvaluator {
  /**
   * You are not supposed to instantiate this class.
   */
  private CIndegreeEvaluator() {
  }

  /**
   * Evaluates an indegree criterium match on a node.
   *
   * @param node The node to check.
   * @param operator Defines the desired relation between the given indegree and the node indegree.
   * @param indegree The indegree to compare the node indegree to.
   *
   * @return True, if the node indegree matches the given indegree. False, otherwise.
   */
  public static boolean matches(final NaviNode node, final String operator, final int indegree) {
    if ("<".equals(operator)) {
      return node.getRawNode().getIncomingEdges().size() < indegree;
    }
    if ("=".equals(operator)) {
      return node.getRawNode().getIncomingEdges().size() == indegree;
    }
    if (">".equals(operator)) {
      return node.getRawNode().getIncomingEdges().size() > indegree;
    }

    throw new IllegalStateException("IE02202: Unknown operator " + operator);
  }
}


text:
"""Script for testing ganeti.hypervisor.hv_xen"""

import string # pylint: disable=W0402
import unittest
import tempfile
import shutil
import random
import os
import mock

from ganeti import constants
from ganeti import objects
from ganeti import pathutils
from ganeti import hypervisor
from ganeti import utils
from ganeti import errors
from ganeti import compat

from ganeti.hypervisor import hv_base
from ganeti.hypervisor import hv_xen

import testutils

# Map from hypervisor class to hypervisor name
HVCLASS_TO_HVNAME = utils.InvertDict(hypervisor._HYPERVISOR_MAP)

class TestConsole(unittest.TestCase):
  def test(self):
    hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL}
    for cls in [hv_xen.XenPvmHypervisor(), hv_xen.XenHvmHypervisor()]:
      instance = objects.Instance(name="xen.example.com",
                                  primary_node="node24828-uuid")
      node = objects.Node(name="node24828", uuid="node24828-uuid",
                          ndparams={})
      group = objects.NodeGroup(name="group52341", ndparams={})
      cons = cls.GetInstanceConsole(instance, node, group, hvparams, {})
      self.assertEqual(cons.Validate(), None)
      self.assertEqual(cons.kind, constants.CONS_SSH)
      self.assertEqual(cons.host, node.name)
      self.assertEqual(cons.command[-1], instance.name)

class TestCreateConfigCpus(unittest.TestCase):
  def testEmpty(self):
    for cpu_mask in [None, ""]:
      self.assertEqual(hv_xen._CreateConfigCpus(cpu_mask),
                       "cpus = [  ]")

  def testAll(self):
    self.assertEqual(hv_xen._CreateConfigCpus(constants.CPU_PINNING_ALL),
                     None)

  def testOne(self):
    self.assertEqual(hv_xen._CreateConfigCpus("9"), "cpu = \"9\"")

  def testMultiple(self):
    self.assertEqual(hv_xen._CreateConfigCpus("0-2,4,5-5:3:all"),
                     ("cpus = [ \"0,1,2,4,5\", \"3\", \"%s\" ]" %
                      constants.CPU_PINNING_ALL_XEN))

class TestGetCommand(testutils.GanetiTestCase):
  def testCommandExplicit(self):
    """Test the case when the command is given as class parameter explicitly.

    """
    expected_cmd = "xl"
    hv = hv_xen.XenHypervisor(_cmd=constants.XEN_CMD_XL)
    self.assertEqual(hv._GetCommand(None), expected_cmd)

  def testCommandInvalid(self):
    """Test the case an invalid command is given as class parameter explicitly.

    """
    hv = hv_xen.XenHypervisor(_cmd="invalidcommand")
    self.assertRaises(errors.ProgrammerError, hv._GetCommand, None)

  def testCommandHvparams(self):
    expected_cmd = "xl"
    test_hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL}
    hv = hv_xen.XenHypervisor()
    self.assertEqual(hv._GetCommand(test_hvparams), expected_cmd)

  def testCommandHvparamsInvalid(self):
    test_hvparams = {}
    hv = hv_xen.XenHypervisor()
    self.assertRaises(errors.HypervisorError, hv._GetCommand, test_hvparams)

  def testCommandHvparamsCmdInvalid(self):
    test_hvparams = {constants.HV_XEN_CMD: "invalidcommand"}
    hv = hv_xen.XenHypervisor()
    self.assertRaises(errors.ProgrammerError, hv._GetCommand, test_hvparams)

class TestParseInstanceList(testutils.GanetiTestCase):
  def test(self):
    data = testutils.ReadTestData("xen-xm-list-4.0.1-dom0-only.txt")

    # Exclude node
    self.assertEqual(hv_xen._ParseInstanceList(data.splitlines(), False), [])

    # Include node
    result = hv_xen._ParseInstanceList(data.splitlines(), True)
    self.assertEqual(len(result), 1)
    self.assertEqual(len(result[0]), 6)

    # Name
    self.assertEqual(result[0][0], hv_xen._DOM0_NAME)

    # ID
    self.assertEqual(result[0][1], 0)

    # Memory
    self.assertEqual(result[0][2], 1023)

    # VCPUs
    self.assertEqual(result[0][3], 1)

    # State
    self.assertEqual(result[0][4], hv_base.HvInstanceState.RUNNING)

    # Time
    self.assertAlmostEqual(result[0][5], 121152.6)

  def testWrongLineFormat(self):
    tests = [
      ["three fields only"],
      ["name InvalidID 128 1 r----- 12345"],
      ]

    for lines in tests:
      try:
        hv_xen._ParseInstanceList(["Header would be here"] + lines, False)
      except errors.HypervisorError, err:
        self.assertTrue("Can't parse instance list" in str(err))
      else:
        self.fail("Exception was not raised")

class TestGetInstanceList(testutils.GanetiTestCase):
  def _Fail(self):
    return utils.RunResult(constants.EXIT_FAILURE, None,
                           "stdout", "stderr", None,
                           NotImplemented, NotImplemented)

  def testTimeout(self):
    fn = testutils.CallCounter(self._Fail)
    try:
      hv_xen._GetRunningInstanceList(fn, False, _timeout=0.1)
    except errors.HypervisorError, err:
      self.assertTrue("timeout exceeded" in str(err))
    else:
      self.fail("Exception was not raised")

    self.assertTrue(fn.Count() < 10,
                    msg="'xm list' was called too many times")

  def _Success(self, stdout):
    return utils.RunResult(constants.EXIT_SUCCESS, None, stdout, "", None,
                           NotImplemented, NotImplemented)

  def testSuccess(self):
    data = testutils.ReadTestData("xen-xm-list-4.0.1-four-instances.txt")

    fn = testutils.CallCounter(compat.partial(self._Success, data))

    result = hv_xen._GetRunningInstanceList(fn, True, _timeout=0.1)

    self.assertEqual(len(result), 4)

    self.assertEqual(map(compat.fst, result), [
      "Domain-0",
      "server01.example.com",
      "web3106215069.example.com",
      "testinstance.example.com",
      ])

    self.assertEqual(fn.Count(), 1)

class TestParseNodeInfo(testutils.GanetiTestCase):
  def testEmpty(self):
    self.assertEqual(hv_xen._ParseNodeInfo(""), {})

  def testUnknownInput(self):
    data = "\n".join([
      "foo bar",
      "something else goes",
      "here",
      ])
    self.assertEqual(hv_xen._ParseNodeInfo(data), {})

  def testBasicInfo(self):
    data = testutils.ReadTestData("xen-xm-info-4.0.1.txt")
    result = hv_xen._ParseNodeInfo(data)
    self.assertEqual(result, {
      "cpu_nodes": 1,
      "cpu_sockets": 2,
      "cpu_total": 4,
      "hv_version": (4, 0),
      "memory_free": 8004,
      "memory_total": 16378,
      })

class TestMergeInstanceInfo(testutils.GanetiTestCase):
  def testEmpty(self):
    self.assertEqual(hv_xen._MergeInstanceInfo({}, []), {})

  def _FakeXmList(self, include_node):
    return [
      (hv_xen._DOM0_NAME, NotImplemented, 4096, 7, NotImplemented,
       NotImplemented),
      ("inst1.example.com", NotImplemented, 2048, 4, NotImplemented,
       NotImplemented),
      ]

  def testMissingNodeInfo(self):
    instance_list = self._FakeXmList(True)
    result = hv_xen._MergeInstanceInfo({}, instance_list)
    self.assertEqual(result, {
      "memory_dom0": 4096,
      "cpu_dom0": 7,
      })

  def testWithNodeInfo(self):
    info = testutils.ReadTestData("xen-xm-info-4.0.1.txt")
    instance_list = self._FakeXmList(True)
    result = hv_xen._GetNodeInfo(info, instance_list)
    self.assertEqual(result, {
      "cpu_nodes": 1,
      "cpu_sockets": 2,
      "cpu_total": 4,
      "cpu_dom0": 7,
      "hv_version": (4, 0),
      "memory_dom0": 4096,
      "memory_free": 8004,
      "memory_hv": 2230,
      "memory_total": 16378,
      })

class TestGetConfigFileDiskData(unittest.TestCase):
  def testLetterCount(self):
    self.assertEqual(len(hv_xen._DISK_LETTERS), 26)

  def testNoDisks(self):
    self.assertEqual(hv_xen._GetConfigFileDiskData([], "hd"), [])

  def testManyDisks(self):
    for offset in [0, 1, 10]:
      disks = [(objects.Disk(dev_type=constants.DT_PLAIN),
               "/tmp/disk/%s" % idx,
               NotImplemented)
               for idx in range(len(hv_xen._DISK_LETTERS) + offset)]

      if offset == 0:
        result = hv_xen._GetConfigFileDiskData(disks, "hd")
        self.assertEqual(result, [
          "'phy:/tmp/disk/%s,hd%s,r'" % (idx, string.ascii_lowercase[idx])
          for idx in range(len(hv_xen._DISK_LETTERS) + offset)
          ])
      else:
        try:
          hv_xen._GetConfigFileDiskData(disks, "hd")
        except errors.HypervisorError, err:
          self.assertEqual(str(err), "Too many disks")
        else:
          self.fail("Exception was not raised")

  def testTwoLvDisksWithMode(self):
    disks = [
      (objects.Disk(dev_type=constants.DT_PLAIN, mode=constants.DISK_RDWR),
       "/tmp/diskFirst",
       NotImplemented),
      (objects.Disk(dev_type=constants.DT_PLAIN, mode=constants.DISK_RDONLY),
       "/tmp/diskLast",
       NotImplemented),
      ]

    result = hv_xen._GetConfigFileDiskData(disks, "hd")
    self.assertEqual(result, [
      "'phy:/tmp/diskFirst,hda,w'",
      "'phy:/tmp/diskLast,hdb,r'",
      ])

  def testFileDisks(self):
    disks = [
      (objects.Disk(dev_type=constants.DT_FILE, mode=constants.DISK_RDWR,
                    logical_id=[constants.FD_LOOP]),
       "/tmp/diskFirst",
       NotImplemented),
      (objects.Disk(dev_type=constants.DT_FILE, mode=constants.DISK_RDONLY,
                    logical_id=[constants.FD_BLKTAP]),
       "/tmp/diskTwo",
       NotImplemented),
      (objects.Disk(dev_type=constants.DT_FILE, mode=constants.DISK_RDWR,
                    logical_id=[constants.FD_LOOP]),
       "/tmp/diskThree",
       NotImplemented),
      (objects.Disk(dev_type=constants.DT_FILE, mode=constants.DISK_RDONLY,
                    logical_id=[constants.FD_BLKTAP2]),
       "/tmp/diskFour",
       NotImplemented),
      (objects.Disk(dev_type=constants.DT_FILE, mode=constants.DISK_RDWR,
                    logical_id=[constants.FD_BLKTAP]),
       "/tmp/diskLast",
       NotImplemented),
      ]

    result = hv_xen._GetConfigFileDiskData(disks, "sd")
    self.assertEqual(result, [
      "'file:/tmp/diskFirst,sda,w'",
      "'tap:aio:/tmp/diskTwo,sdb,r'",
      "'file:/tmp/diskThree,sdc,w'",
      "'tap2:tapdisk:aio:/tmp/diskFour,sdd,r'",
      "'tap:aio:/tmp/diskLast,sde,w'",
      ])

  def testInvalidFileDisk(self):
    disks = [
      (objects.Disk(dev_type=constants.DT_FILE, mode=constants.DISK_RDWR,
                    logical_id=["#unknown#"]),
       "/tmp/diskinvalid",
       NotImplemented),
      ]

    self.assertRaises(KeyError, hv_xen._GetConfigFileDiskData, disks, "sd")

class TestXenHypervisorRunXen(unittest.TestCase):

  XEN_SUB_CMD = "help"

  def testCommandUnknown(self):
    cmd = "#unknown command#"
    self.assertFalse(cmd in constants.KNOWN_XEN_COMMANDS)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=NotImplemented,
                              _cmd=cmd)
    self.assertRaises(errors.ProgrammerError, hv._RunXen, [], None)

  def testCommandNoHvparams(self):
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=NotImplemented)
    hvparams = None
    self.assertRaises(errors.HypervisorError, hv._RunXen, [self.XEN_SUB_CMD],
                      hvparams)

  def testCommandFromHvparams(self):
    expected_xen_cmd = "xl"
    hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL}
    mock_run_cmd = mock.Mock()
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    hv._RunXen([self.XEN_SUB_CMD], hvparams=hvparams)
    mock_run_cmd.assert_called_with([expected_xen_cmd, self.XEN_SUB_CMD])

class TestXenHypervisorGetInstanceList(unittest.TestCase):

  RESULT_OK = utils.RunResult(0, None, "", "", "", None, None)
  XEN_LIST = "list"

  def testNoHvparams(self):
    expected_xen_cmd = "xm"
    mock_run_cmd = mock.Mock(return_value=self.RESULT_OK)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    self.assertRaises(errors.HypervisorError, hv._GetInstanceList, True, None)

  def testFromHvparams(self):
    expected_xen_cmd = "xl"
    hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL}
    mock_run_cmd = mock.Mock(return_value=self.RESULT_OK)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    hv._GetInstanceList(True, hvparams)
    mock_run_cmd.assert_called_with([expected_xen_cmd, self.XEN_LIST])

class TestXenHypervisorListInstances(unittest.TestCase):

  RESULT_OK = utils.RunResult(0, None, "", "", "", None, None)
  XEN_LIST = "list"

  def testNoHvparams(self):
    expected_xen_cmd = "xm"
    mock_run_cmd = mock.Mock(return_value=self.RESULT_OK)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    self.assertRaises(errors.HypervisorError, hv.ListInstances)

  def testHvparamsXl(self):
    expected_xen_cmd = "xl"
    hvparams = {constants.HV_XEN_CMD: constants.XEN_CMD_XL}
    mock_run_cmd = mock.Mock(return_value=self.RESULT_OK)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    hv.ListInstances(hvparams=hvparams)
    mock_run_cmd.assert_called_with([expected_xen_cmd, self.XEN_LIST])

class TestXenHypervisorCheckToolstack(unittest.TestCase):

  def setUp(self):
    self.tmpdir = tempfile.mkdtemp()
    self.cfg_name = "xen_config"
    self.cfg_path = utils.PathJoin(self.tmpdir, self.cfg_name)
    self.hv = hv_xen.XenHypervisor()

  def tearDown(self):
    shutil.rmtree(self.tmpdir)

  def testBinaryNotFound(self):
    RESULT_FAILED = utils.RunResult(1, None, "", "", "", None, None)
    mock_run_cmd = mock.Mock(return_value=RESULT_FAILED)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    result = hv._CheckToolstackBinary("xl")
    self.assertFalse(result)

  def testCheckToolstackXlConfigured(self):
    RESULT_OK = utils.RunResult(0, None, "", "", "", None, None)
    mock_run_cmd = mock.Mock(return_value=RESULT_OK)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    result = hv._CheckToolstackXlConfigured()
    self.assertTrue(result)

  def testCheckToolstackXlNotConfigured(self):
    RESULT_FAILED = utils.RunResult(
        1, None, "",
        "ERROR:  A different toolstack (xm) has been selected!",
        "", None, None)
    mock_run_cmd = mock.Mock(return_value=RESULT_FAILED)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    result = hv._CheckToolstackXlConfigured()
    self.assertFalse(result)

  def testCheckToolstackXlFails(self):
    RESULT_FAILED = utils.RunResult(
        1, None, "",
        "ERROR: The pink bunny hid the binary.",
        "", None, None)
    mock_run_cmd = mock.Mock(return_value=RESULT_FAILED)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    self.assertRaises(errors.HypervisorError, hv._CheckToolstackXlConfigured)

class TestXenHypervisorWriteConfigFile(unittest.TestCase):
  def setUp(self):
    self.tmpdir = tempfile.mkdtemp()

  def tearDown(self):
    shutil.rmtree(self.tmpdir)

  def testWriteError(self):
    cfgdir = utils.PathJoin(self.tmpdir, "foobar")

    hv = hv_xen.XenHypervisor(_cfgdir=cfgdir,
                              _run_cmd_fn=NotImplemented,
                              _cmd=NotImplemented)

    self.assertFalse(os.path.exists(cfgdir))

    try:
      hv._WriteConfigFile("name", "data")
    except errors.HypervisorError, err:
      self.assertTrue(str(err).startswith("Cannot write Xen instance"))
    else:
      self.fail("Exception was not raised")

class TestXenHypervisorVerify(unittest.TestCase):

  def setUp(self):
    output = testutils.ReadTestData("xen-xm-info-4.0.1.txt")
    self._result_ok = utils.RunResult(0, None, output, "", "", None, None)

  def testVerify(self):
    hvparams = {constants.HV_XEN_CMD : constants.XEN_CMD_XL}
    mock_run_cmd = mock.Mock(return_value=self._result_ok)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    hv._CheckToolstack = mock.Mock(return_value=True)
    result = hv.Verify(hvparams)
    self.assertTrue(result is None)

  def testVerifyToolstackNotOk(self):
    hvparams = {constants.HV_XEN_CMD : constants.XEN_CMD_XL}
    mock_run_cmd = mock.Mock(return_value=self._result_ok)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    hv._CheckToolstack = mock.Mock()
    hv._CheckToolstack.side_effect = errors.HypervisorError("foo")
    result = hv.Verify(hvparams)
    self.assertTrue(result is not None)

  def testVerifyFailing(self):
    result_failed = utils.RunResult(1, None, "", "", "", None, None)
    mock_run_cmd = mock.Mock(return_value=result_failed)
    hv = hv_xen.XenHypervisor(_cfgdir=NotImplemented,
                              _run_cmd_fn=mock_run_cmd)
    hv._CheckToolstack = mock.Mock(return_value=True)
    result = hv.Verify()
    self.assertTrue(result is not None)

class _TestXenHypervisor(object):
  TARGET = NotImplemented
  CMD = NotImplemented
  HVNAME = NotImplemented
  VALID_HVPARAMS = {constants.HV_XEN_CMD: constants.XEN_CMD_XL}

  def setUp(self):
    super(_TestXenHypervisor, self).setUp()

    self.tmpdir = tempfile.mkdtemp()

    self.vncpw = "".join(random.sample(string.ascii_letters, 10))

    self.vncpw_path = utils.PathJoin(self.tmpdir, "vncpw")
    utils.WriteFile(self.vncpw_path, data=self.vncpw)

  def tearDown(self):
    super(_TestXenHypervisor, self).tearDown()

    shutil.rmtree(self.tmpdir)

  def _GetHv(self, run_cmd=NotImplemented):
    return self.TARGET(_cfgdir=self.tmpdir, _run_cmd_fn=run_cmd, _cmd=self.CMD)

  def _SuccessCommand(self, stdout, cmd):
    self.assertEqual(cmd[0], self.CMD)

    return utils.RunResult(constants.EXIT_SUCCESS, None, stdout, "", None,
                           NotImplemented, NotImplemented)

  def _FailingCommand(self, cmd):
    self.assertEqual(cmd[0], self.CMD)

    return utils.RunResult(constants.EXIT_FAILURE, None,
                           "", "This command failed", None,
                           NotImplemented, NotImplemented)

  def _FakeTcpPing(self, expected, result, target, port, **kwargs):
    self.assertEqual((target, port), expected)
    return result

  def testReadingNonExistentConfigFile(self):
    hv = self._GetHv()

    try:
      hv._ReadConfigFile("inst15780.example.com")
    except errors.HypervisorError, err:
      self.assertTrue(str(err).startswith("Failed to load Xen config file:"))
    else:
      self.fail("Exception was not raised")

  def testRemovingAutoConfigFile(self):
    name = "inst8206.example.com"
    cfgfile = utils.PathJoin(self.tmpdir, name)
    autodir = utils.PathJoin(self.tmpdir, "auto")
    autocfgfile = utils.PathJoin(autodir, name)

    os.mkdir(autodir)

    utils.WriteFile(autocfgfile, data="")

    hv = self._GetHv()

    self.assertTrue(os.path.isfile(autocfgfile))
    hv._WriteConfigFile(name, "content")
    self.assertFalse(os.path.exists(autocfgfile))
    self.assertEqual(utils.ReadFile(cfgfile), "content")

  def _XenList(self, cmd):
    self.assertEqual(cmd, [self.CMD, "list"])

    # TODO: Use actual data from "xl" command
    output = testutils.ReadTestData("xen-xm-list-4.0.1-four-instances.txt")

    return self._SuccessCommand(output, cmd)

  def testGetInstanceInfo(self):
    hv = self._GetHv(run_cmd=self._XenList)

    (name, instid, memory, vcpus, state, runtime) = \
      hv.GetInstanceInfo("server01.example.com")

    self.assertEqual(name, "server01.example.com")
    self.assertEqual(instid, 1)
    self.assertEqual(memory, 1024)
    self.assertEqual(vcpus, 1)
    self.assertEqual(state, hv_base.HvInstanceState.RUNNING)
    self.assertAlmostEqual(runtime, 167643.2)

  def testGetInstanceInfoDom0(self):
    hv = self._GetHv(run_cmd=self._XenList)

    # TODO: Not sure if this is actually used anywhere (can't find it), but the
    # code supports querying for Dom0
    (name, instid, memory, vcpus, state, runtime) = \
      hv.GetInstanceInfo(hv_xen._DOM0_NAME)

    self.assertEqual(name, "Domain-0")
    self.assertEqual(instid, 0)
    self.assertEqual(memory, 1023)
    self.assertEqual(vcpus, 1)
    self.assertEqual(state, hv_base.HvInstanceState.RUNNING)
    self.assertAlmostEqual(runtime, 154706.1)

  def testGetInstanceInfoUnknown(self):
    hv = self._GetHv(run_cmd=self._XenList)

    result = hv.GetInstanceInfo("unknown.example.com")
    self.assertTrue(result is None)

  def testGetAllInstancesInfo(self):
    hv = self._GetHv(run_cmd=self._XenList)

    result = hv.GetAllInstancesInfo()

    self.assertEqual(map(compat.fst, result), [
      "server01.example.com",
      "web3106215069.example.com",
      "testinstance.example.com",
      ])

  def testListInstances(self):
    hv = self._GetHv(run_cmd=self._XenList)

    self.assertEqual(hv.ListInstances(), [
      "server01.example.com",
      "web3106215069.example.com",
      "testinstance.example.com",
      ])

  def _StartInstanceCommand(self, inst, paused, failcreate, cmd):
    if cmd == [self.CMD, "info"]:
      output = testutils.ReadTestData("xen-xm-info-4.0.1.txt")
    elif cmd == [self.CMD, "list"]:
      output = testutils.ReadTestData("xen-xm-list-4.0.1-dom0-only.txt")
    elif cmd[:2] == [self.CMD, "create"]:
      args = cmd[2:]
      cfgfile = utils.PathJoin(self.tmpdir, inst.name)

      if paused:
        self.assertEqual(args, ["-p", cfgfile])
      else:
        self.assertEqual(args, [cfgfile])

      if failcreate:
        return self._FailingCommand(cmd)

      output = ""
    else:
      self.fail("Unhandled command: %s" % (cmd, ))

    return self._SuccessCommand(output, cmd)

  def _MakeInstance(self):
    # Copy default parameters
    bep = objects.FillDict(constants.BEC_DEFAULTS, {})
    hvp = objects.FillDict(constants.HVC_DEFAULTS[self.HVNAME], {})

    # Override default VNC password file path
    if constants.HV_VNC_PASSWORD_FILE in hvp:
      hvp[constants.HV_VNC_PASSWORD_FILE] = self.vncpw_path

    disks = [
      (objects.Disk(dev_type=constants.DT_PLAIN, mode=constants.DISK_RDWR),
       utils.PathJoin(self.tmpdir, "disk0"),
       NotImplemented),
      (objects.Disk(dev_type=constants.DT_PLAIN, mode=constants.DISK_RDONLY),
       utils.PathJoin(self.tmpdir, "disk1"),
       NotImplemented),
      ]

    inst = objects.Instance(name="server01.example.com",
                            hvparams=hvp, beparams=bep,
                            osparams={}, nics=[], os="deb1",
                            disks=map(compat.fst, disks))
    inst.UpgradeConfig()

    return (inst, disks)

  def testStartInstance(self):
    (inst, disks) = self._MakeInstance()
    pathutils.LOG_XEN_DIR = self.tmpdir

    for failcreate in [False, True]:
      for paused in [False, True]:
        run_cmd = compat.partial(self._StartInstanceCommand,
                                 inst, paused, failcreate)

        hv = self._GetHv(run_cmd=run_cmd)

        # Ensure instance is not listed
        self.assertTrue(inst.name not in hv.ListInstances())

        # Remove configuration
        cfgfile = utils.PathJoin(self.tmpdir, inst.name)
        utils.RemoveFile(cfgfile)

        if failcreate:
          self.assertRaises(errors.HypervisorError, hv.StartInstance,
                            inst, disks, paused)
          # Check whether a stale config file is left behind
          self.assertFalse(os.path.exists(cfgfile))
        else:
          hv.StartInstance(inst, disks, paused)
          # Check if configuration was updated
          lines = utils.ReadFile(cfgfile).splitlines()

        if constants.HV_VNC_PASSWORD_FILE in inst.hvparams:
          self.assertTrue(("vncpasswd = '%s'" % self.vncpw) in lines)
        else:
          extra = inst.hvparams[constants.HV_KERNEL_ARGS]
          self.assertTrue(("extra = '%s'" % extra) in lines)

  def _StopInstanceCommand(self, instance_name, force, fail, full_cmd):
    # Remove the timeout (and its number of seconds) if it's there
    if full_cmd[:1][0] == "timeout":
      cmd = full_cmd[2:]
    else:
      cmd = full_cmd

    # Test the actual command
    if (cmd == [self.CMD, "list"]):
      output = "Name  ID  Mem  VCPUs  State  Time(s)\n" \
        "Domain-0  0  1023  1  r-----  142691.0\n" \
        "%s  417  128  1  r-----  3.2\n" % instance_name
    elif cmd[:2] == [self.CMD, "destroy"]:
      self.assertEqual(cmd[2:], [instance_name])
      output = ""
    elif not force and cmd[:3] == [self.CMD, "shutdown", "-w"]:
      self.assertEqual(cmd[3:], [instance_name])
      output = ""
    else:
      self.fail("Unhandled command: %s" % (cmd, ))

    if fail:
      # Simulate a failing command
      return self._FailingCommand(cmd)
    else:
      return self._SuccessCommand(output, cmd)

  def testStopInstance(self):
    name = "inst4284.example.com"
    cfgfile = utils.PathJoin(self.tmpdir, name)
    cfgdata = "config file content\n"

    for force in [False, True]:
      for fail in [False, True]:
        utils.WriteFile(cfgfile, data=cfgdata)

        run_cmd = compat.partial(self._StopInstanceCommand, name, force, fail)

        hv = self._GetHv(run_cmd=run_cmd)

        self.assertTrue(os.path.isfile(cfgfile))

        if fail:
          try:
            hv._StopInstance(name, force, None,
                             constants.DEFAULT_SHUTDOWN_TIMEOUT)
          except errors.HypervisorError, err:
            self.assertTrue(str(err).startswith("listing instances failed"),
                            msg=str(err))
          else:
            self.fail("Exception was not raised")
          self.assertEqual(utils.ReadFile(cfgfile), cfgdata,
                           msg=("Configuration was removed when stopping"
                                " instance failed"))
        else:
          hv._StopInstance(name, force, None,
                           constants.DEFAULT_SHUTDOWN_TIMEOUT)
          self.assertFalse(os.path.exists(cfgfile))

  def _MigrateNonRunningInstCmd(self, cmd):
    if cmd == [self.CMD, "list"]:
      output = testutils.ReadTestData("xen-xm-list-4.0.1-dom0-only.txt")
    else:
      self.fail("Unhandled command: %s" % (cmd, ))

    return self._SuccessCommand(output, cmd)

  def testMigrateInstanceNotRunning(self):
    name = "nonexistinginstance.example.com"
    target = constants.IP4_ADDRESS_LOCALHOST
    port = 14618

    hv = self._GetHv(run_cmd=self._MigrateNonRunningInstCmd)

    for live in [False, True]:
      try:
        hv._MigrateInstance(NotImplemented, name, target, port, live,
                            self.VALID_HVPARAMS, _ping_fn=NotImplemented)
      except errors.HypervisorError, err:
        self.assertEqual(str(err), "Instance not running, cannot migrate")
      else:
        self.fail("Exception was not raised")

  def _MigrateInstTargetUnreachCmd(self, cmd):
    if cmd == [self.CMD, "list"]:
      output = testutils.ReadTestData("xen-xm-list-4.0.1-four-instances.txt")
    else:
      self.fail("Unhandled command: %s" % (cmd, ))

    return self._SuccessCommand(output, cmd)

  def testMigrateTargetUnreachable(self):
    name = "server01.example.com"
    target = constants.IP4_ADDRESS_LOCALHOST
    port = 28349

    hv = self._GetHv(run_cmd=self._MigrateInstTargetUnreachCmd)
    hvparams = {constants.HV_XEN_CMD: self.CMD}

    for live in [False, True]:
      if self.CMD == constants.XEN_CMD_XL:
        # TODO: Detect unreachable targets
        pass
      else:
        try:
          hv._MigrateInstance(NotImplemented, name, target, port, live,
                              hvparams,
                              _ping_fn=compat.partial(self._FakeTcpPing,
                                                      (target, port), False))
        except errors.HypervisorError, err:
          wanted = "Remote host %s not" % target
          self.assertTrue(str(err).startswith(wanted))
        else:
          self.fail("Exception was not raised")

  def _MigrateInstanceCmd(self, cluster_name, instance_name, target, port,
                          live, fail, cmd):
    if cmd == [self.CMD, "list"]:
      output = testutils.ReadTestData("xen-xm-list-4.0.1-four-instances.txt")
    elif cmd[:2] == [self.CMD, "migrate"]:
      if self.CMD == constants.XEN_CMD_XM:
        args = ["-p", str(port)]

        if live:
          args.append("-l")

      elif self.CMD == constants.XEN_CMD_XL:
        args = [
          "-s", constants.XL_SSH_CMD % cluster_name,
          "-C", utils.PathJoin(self.tmpdir, instance_name),
          ]

      else:
        self.fail("Unknown Xen command '%s'" % self.CMD)

      args.extend([instance_name, target])
      self.assertEqual(cmd[2:], args)

      if fail:
        return self._FailingCommand(cmd)

      output = ""
    else:
      self.fail("Unhandled command: %s" % (cmd, ))

    return self._SuccessCommand(output, cmd)

  def testMigrateInstance(self):
    clustername = "cluster.example.com"
    instname = "server01.example.com"
    target = constants.IP4_ADDRESS_LOCALHOST
    port = 22364

    hvparams = {constants.HV_XEN_CMD: self.CMD}

    for live in [False, True]:
      for fail in [False, True]:
        ping_fn = \
          testutils.CallCounter(compat.partial(self._FakeTcpPing,
                                               (target, port), True))

        run_cmd = \
          compat.partial(self._MigrateInstanceCmd,
                         clustername, instname, target, port, live,
                         fail)

        hv = self._GetHv(run_cmd=run_cmd)

        if fail:
          try:
            hv._MigrateInstance(clustername, instname, target, port, live,
                                hvparams, _ping_fn=ping_fn)
          except errors.HypervisorError, err:
            self.assertTrue(str(err).startswith("Failed to migrate instance"))
          else:
            self.fail("Exception was not raised")
        else:
          hv._MigrateInstance(clustername, instname, target, port, live,
                              hvparams, _ping_fn=ping_fn)

        if self.CMD == constants.XEN_CMD_XM:
          expected_pings = 1
        else:
          expected_pings = 0

        self.assertEqual(ping_fn.Count(), expected_pings)

  def _GetNodeInfoCmd(self, fail, cmd):
    if cmd == [self.CMD, "info"]:
      if fail:
        return self._FailingCommand(cmd)
      else:
        output = testutils.ReadTestData("xen-xm-info-4.0.1.txt")
    elif cmd == [self.CMD, "list"]:
      if fail:
        self.fail("'xm list' shouldn't be called when 'xm info' failed")
      else:
        output = testutils.ReadTestData("xen-xm-list-4.0.1-four-instances.txt")
    else:
      self.fail("Unhandled command: %s" % (cmd, ))

    return self._SuccessCommand(output, cmd)

  def testGetNodeInfo(self):
    run_cmd = compat.partial(self._GetNodeInfoCmd, False)
    hv = self._GetHv(run_cmd=run_cmd)
    result = hv.GetNodeInfo()

    self.assertEqual(result["hv_version"], (4, 0))
    self.assertEqual(result["memory_free"], 8004)

  def testGetNodeInfoFailing(self):
    run_cmd = compat.partial(self._GetNodeInfoCmd, True)
    hv = self._GetHv(run_cmd=run_cmd)
    self.assertTrue(hv.GetNodeInfo() is None)

class TestXenVersionsSafeForMigration(unittest.TestCase):
  def testHVVersionsLikelySafeForMigration(self):
    hv = hv_xen.XenHypervisor()
    self.assertTrue(hv.VersionsSafeForMigration([4, 0], [4, 1]))
    self.assertFalse(hv.VersionsSafeForMigration([4, 1], [4, 0]))
    self.assertFalse(hv.VersionsSafeForMigration([4, 0], [4, 2]))
    self.assertTrue(hv.VersionsSafeForMigration([4, 2, 7], [4, 2, 9]))
    self.assertTrue(hv.VersionsSafeForMigration([4, 2, 9], [4, 2, 7]))
    self.assertTrue(hv.VersionsSafeForMigration([4], [4]))
    self.assertFalse(hv.VersionsSafeForMigration([4], [5]))

def _MakeTestClass(cls, cmd):
  """Makes a class for testing.

  The returned class has structure as shown in the following pseudo code:

    class Test{cls.__name__}{cmd}(_TestXenHypervisor, unittest.TestCase):
      TARGET = {cls}
      CMD = {cmd}
      HVNAME = {Hypervisor name retrieved using class}

  @type cls: class
  @param cls: Hypervisor class to be tested
  @type cmd: string
  @param cmd: Hypervisor command
  @rtype: tuple
  @return: Class name and class object (not instance)

  """
  name = "Test%sCmd%s" % (cls.__name__, cmd.title())
  bases = (_TestXenHypervisor, unittest.TestCase)
  hvname = HVCLASS_TO_HVNAME[cls]

  return (name, type(name, bases, dict(TARGET=cls, CMD=cmd, HVNAME=hvname)))

# Create test classes programmatically instead of manually to reduce the risk
# of forgetting some combinations
for cls in [hv_xen.XenPvmHypervisor, hv_xen.XenHvmHypervisor]:
  for cmd in constants.KNOWN_XEN_COMMANDS:
    (name, testcls) = _MakeTestClass(cls, cmd)

    assert name not in locals()

    locals()[name] = testcls

if __name__ == "__main__":
  testutils.GanetiTestProgram()


text:
<!DOCTYPE html>

    <title>加载中</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <link href="resources/css/jquery-ui-themes.css" type="text/css" rel="stylesheet"/>
    <link href="resources/css/axure_rp_page.css" type="text/css" rel="stylesheet"/>
    <link href="data/styles.css" type="text/css" rel="stylesheet"/>
    <link href="files/加载中/styles.css" type="text/css" rel="stylesheet"/>


text:
package de.jpaw.xml.jaxb;

import java.math.BigDecimal;
import java.math.RoundingMode;

import jakarta.xml.bind.annotation.adapters.XmlAdapter;

public abstract class AbstractScaledIntegerAdapter extends XmlAdapter<BigDecimal, Integer> {
    private static final Integer ZERO = Integer.valueOf(0);
    private final boolean allowRounding;
    private final int scale;

    protected AbstractScaledIntegerAdapter(final int scale, final boolean allowRounding) {
        this.scale = scale;
        this.allowRounding = allowRounding;
    }

    @Override
    public Integer unmarshal(final BigDecimal v) throws Exception {
        if (v.signum() == 0)
            return ZERO;  // always valid
        final BigDecimal vv = v.setScale(scale, allowRounding ? RoundingMode.HALF_EVEN : RoundingMode.UNNECESSARY);
        return vv.unscaledValue().intValue();
    }

    @Override
    public BigDecimal marshal(final Integer v) throws Exception {
        return BigDecimal.valueOf(v.intValue(), scale);
    }
}


text:
/**
 * @file instruction.h
 * @brief Header for instruction.c
 */

#ifndef SIRPYTHON_AVRDEBUGGER_INSTRUCTION_H
#define SIRPYTHON_AVRDEBUGGER_INSTRUCTION_H

#include <stdint.h>
#include "machine.h"

void adc_op(Machine *machine, uint16_t opcode, uint16_t mask1, uint16_t mask2);

typedef char byte;

/**
 * @typedef operation
 * @brief The code of an instruction
 *
 * 1. The machine where the code is running
 * 2. The opcode
 * 3. The opcode's mask1
 * 4. The opcodes mask2
 */
typedef void (*operation)(Machine*, uint16_t, uint16_t, uint16_t);

/**
 * @struct Instruction
 * @brief Data for individual instructions
 */
typedef struct {
	char name[7]; /**< The instruction name. Longest name is 6 characters */
	uint16_t mask1; /**< A mask to get a parameter for the function. Optional. */
	uint16_t mask2; /**< A mask to get a parameter for the function. Optional. */
	operation op; /**< The operation to execute this instruction */
} Instruction;

Instruction instructions[] = {
	{"ADC", 0b0000001000001111, 0b0000000111110000, adc_op}
};

#endif


text:
layout: page
title: "Livy Interpreter for Apache Zeppelin"
description: "Livy is an open source REST interface for interacting with Spark from anywhere. It supports executing snippets of code or programs in a Spark context that runs locally or in YARN."
group: interpreter
---

{% include JB/setup %}

# Livy Interpreter for Apache Zeppelin

## Overview
[Livy](http://livy.io/) is an open source REST interface for interacting with Spark from anywhere. It supports executing snippets of code or programs in a Spark context that runs locally or in YARN.

* Interactive Scala, Python and R shells
* Batch submissions in Scala, Java, Python
* Multi users can share the same server (impersonation support)
* Can be used for submitting jobs from anywhere with REST
* Does not require any code change to your programs

### Requirements
Additional requirements for the Livy interpreter are:

 * Spark 1.3 or above.
 * Livy server.

## Configuration
We added some common configurations for spark, and you can set any configuration you want.
This link contains all spark configurations: http://spark.apache.org/docs/latest/configuration.html#available-properties.
And instead of starting property with `spark.` it should be replaced with `livy.spark.`.
Example: `spark.master` to `livy.spark.master`

    Property
    Default
    Description

      livy.spark.master
      local[*]
      Spark master uri. ex) spark://masterhost:7077

    zeppelin.livy.url
    http://localhost:8998
    URL where livy server is running

    zeppelin.livy.spark.maxResult
    1000
    Max number of Spark SQL result to display.

    zeppelin.livy.displayAppInfo
    false
    Whether to display app info

    livy.spark.driver.cores

    Driver cores. ex) 1, 2.

    livy.spark.driver.memory

    Driver memory. ex) 512m, 32g.

    livy.spark.executor.instances

    Executor instances. ex) 1, 4.

    livy.spark.executor.cores

    Num cores per executor. ex) 1, 4.

    livy.spark.executor.memory

    Executor memory per worker instance. ex) 512m, 32g.

    livy.spark.dynamicAllocation.enabled

    Use dynamic resource allocation. ex) True, False.

    livy.spark.dynamicAllocation.cachedExecutorIdleTimeout

    Remove an executor which has cached data blocks.

    livy.spark.dynamicAllocation.minExecutors

    Lower bound for the number of executors.

    livy.spark.dynamicAllocation.initialExecutors

    Initial number of executors to run.

    livy.spark.dynamicAllocation.maxExecutors

    Upper bound for the number of executors.

      livy.spark.jars.packages

      Adding extra libraries to livy interpreter

## Adding External libraries
You can load dynamic library to livy interpreter by set `livy.spark.jars.packages` property to comma-separated list of maven coordinates of jars to include on the driver and executor classpaths. The format for the coordinates should be groupId:artifactId:version.

Example

    Property
    Example
    Description

      livy.spark.jars.packages
      io.spray:spray-json_2.10:1.3.1
      Adding extra libraries to livy interpreter

## How to use
Basically, you can use

**spark**

```
%livy.spark
sc.version
```

**pyspark**

```
%livy.pyspark
print "1"
```

**sparkR**

```
%livy.sparkr
hello <- function( name ) {
    sprintf( "Hello, %s", name );
}

hello("livy")
```

## Impersonation
When Zeppelin server is running with authentication enabled, then this interpreter utilizes Livy's user impersonation feature i.e. sends extra parameter for creating and running a session ("proxyUser": "${loggedInUser}"). This is particularly useful when multi users are sharing a Notebook server.

## Apply Zeppelin Dynamic Forms
You can leverage [Zeppelin Dynamic Form](../manual/dynamicform.html). You can use both the `text input` and `select form` parameterization features.

```
%livy.pyspark
print "${group_by=product_id,product_id|product_name|customer_id|store_id}"
```

## FAQ

Livy debugging: If you see any of these in error console

> Connect to livyhost:8998 [livyhost/127.0.0.1, livyhost/0:0:0:0:0:0:0:1] failed: Connection refused

Looks like the livy server is not up yet or the config is wrong

> Exception: Session not found, Livy server would have restarted, or lost session.

The session would have timed out, you may need to restart the interpreter.

> Blacklisted configuration values in session config: spark.master

Edit `conf/spark-blacklist.conf` file in livy server and comment out `#spark.master` line.

If you choose to work on livy in `apps/spark/java` directory in [https://github.com/cloudera/hue](https://github.com/cloudera/hue),
copy `spark-user-configurable-options.template` to `spark-user-configurable-options.conf` file in livy server and comment out `#spark.master`.


text:
'use strict';
var TimeUnit = require('../TimeUnit');
var zurvan = require('../zurvan');

var assert = require('assert');

describe('TimeUnit', function() {
  it('can be compared in standard ways', function(done) {
    var hour = TimeUnit.hours(1);
    var threeQuarters = TimeUnit.minutes(45);

    assert(hour.isLongerThan(threeQuarters));
    assert(!hour.isShorterThan(threeQuarters));
    assert(!hour.isEqualTo(threeQuarters));
    assert(threeQuarters.isShorterThan(hour));
    assert(!threeQuarters.isLongerThan(hour));
    assert(!threeQuarters.isEqualTo(hour));

    done();
  });

  it('can be compared even if different units were used at first', function(done) {
    var month = TimeUnit.weeks(4);
    var monthInNanoseconds = TimeUnit.nanoseconds(1e9 * 60 * 60 * 24 * 7 * 4);

    assert(!month.isLongerThan(monthInNanoseconds));
    assert(!month.isShorterThan(monthInNanoseconds));
    assert(month.isEqualTo(monthInNanoseconds));

    assert(!monthInNanoseconds.isLongerThan(month));
    assert(!monthInNanoseconds.isShorterThan(month));
    assert(monthInNanoseconds.isEqualTo(month));

    done();
  });

  it('can be reliably compared even after calculations', function(done) {
    var hour = TimeUnit.hours(1);
    var quarter = TimeUnit.minutes(15);
    var hourInQuarters = quarter
      .extended(quarter)
      .extended(quarter)
      .extended(quarter);
    assert(
      hour.isEqualTo(
        quarter
          .extended(quarter)
          .extended(quarter)
          .extended(quarter)
      )
    );

    var second = TimeUnit.seconds(1);
    var quarterInSeconds = second.copy();

    var i;
    for (i = 0; i < 15 * 60; ++i) {
      quarterInSeconds.add(second);
    }

    assert(quarterInSeconds.isLongerThan(quarter));
    quarterInSeconds.subtract(TimeUnit.nanoseconds(1e9 - 1));
    assert(quarterInSeconds.isLongerThan(quarter));
    quarterInSeconds.subtract(TimeUnit.nanoseconds(1));
    assert(quarterInSeconds.isEqualTo(quarter));
    quarterInSeconds.subtract(TimeUnit.nanoseconds(1));
    assert(quarterInSeconds.isShorterThan(quarter));

    done();
  });

  it('is still reliable after many calculations', function(done) {
    var month = TimeUnit.weeks(4);
    var day = TimeUnit.days(1);
    var minute = TimeUnit.minutes(1);
    var second = TimeUnit.seconds(1);
    var nanosecond = TimeUnit.nanoseconds(1);

    var toIncrease = nanosecond.copy();
    var toDecrease = month.copy();

    var i;
    for (i = 0; i < 27; ++i) {
      toDecrease.subtract(day);
    }

    for (i = 0; i < 3600; ++i) {
      toIncrease.add(second);
    }

    for (i = 0; i < 12 * 60; ++i) {
      toDecrease.subtract(minute);
    }

    for (i = 0; i < 11 * 60; ++i) {
      toIncrease.add(minute);
    }

    assert(toIncrease.isLongerThan(toDecrease));
    assert(toDecrease.isShorterThan(toIncrease));
    toDecrease.add(nanosecond);
    assert(toIncrease.isEqualTo(toDecrease));
    assert(toDecrease.isEqualTo(toIncrease));
    toDecrease.add(nanosecond);
    assert(toIncrease.isShorterThan(toDecrease));
    assert(toDecrease.isLongerThan(toIncrease));

    done();
  });
});


text:
<?php

namespace Drupal\search_api\Plugin\views\row;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\search_api\LoggerTrait;
use Drupal\Core\TypedData\ComplexDataInterface;
use Drupal\search_api\Plugin\views\query\SearchApiQuery;
use Drupal\search_api\SearchApiException;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\row\RowPluginBase;
use Drupal\views\ViewExecutable;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a row plugin for displaying a result as a rendered item.
 *
 * @ViewsRow(
 *   id = "search_api",
 *   title = @Translation("Rendered entity"),
 *   help = @Translation("Displays entity of the matching search API item"),
 * )
 *
 * @see search_api_views_plugins_row_alter()
 */
class SearchApiRow extends RowPluginBase {

  use LoggerTrait;

  /**
   * The search index.
   *
   * @var \Drupal\search_api\IndexInterface
   */
  protected $index;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    /** @var static $row */
    $row = parent::create($container, $configuration, $plugin_id, $plugin_definition);

    $row->setEntityTypeManager($container->get('entity_type.manager'));
    $row->setLogger($container->get('logger.channel.search_api'));

    return $row;
  }

  /**
   * Retrieves the entity type manager.
   *
   * @return \Drupal\Core\Entity\EntityTypeManagerInterface
   *   The entity type manager.
   */
  public function getEntityTypeManager() {
    return $this->entityTypeManager ?: \Drupal::entityTypeManager();
  }

  /**
   * Sets the entity type manager.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The new entity type manager.
   *
   * @return $this
   */
  public function setEntityTypeManager(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $base_table = $view->storage->get('base_table');
    $this->index = SearchApiQuery::getIndexFromTable($base_table, $this->getEntityTypeManager());
    if (!$this->index) {
      $view_label = $view->storage->label();
      throw new \InvalidArgumentException("View '$view_label' is not based on Search API but tries to use its row plugin.");
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function defineOptions() {
    $options = parent::defineOptions();

    $options['view_modes'] = ['default' => []];

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    /** @var \Drupal\search_api\Datasource\DatasourceInterface $datasource */
    foreach ($this->index->getDatasources() as $datasource_id => $datasource) {
      $datasource_label = $datasource->label();
      $bundles = $datasource->getBundles();
      if (!$datasource->getViewModes()) {
        $form['view_modes'][$datasource_id] = [
          '#type' => 'item',
          '#title' => $this->t('Default View mode for datasource %name', ['%name' => $datasource_label]),
          '#description' => $this->t("This datasource doesn't have any view modes available. It is therefore not possible to display results of this datasource using this row plugin."),
        ];
        continue;
      }

      foreach ($bundles as $bundle_id => $bundle_label) {
        $title = $this->t('View mode for datasource %datasource, bundle %bundle', ['%datasource' => $datasource_label, '%bundle' => $bundle_label]);
        $view_modes = $datasource->getViewModes($bundle_id);
        if (!$view_modes) {
          $form['view_modes'][$datasource_id][$bundle_id] = [
            '#type' => 'item',
            '#title' => $title,
            '#description' => $this->t("This bundle doesn't have any view modes available. It is therefore not possible to display results of this bundle using this row plugin."),
          ];
          continue;
        }
        $form['view_modes'][$datasource_id][$bundle_id] = [
          '#type' => 'select',
          '#options' => $view_modes,
          '#title' => $title,
          '#default_value' => key($view_modes),
        ];
        if (isset($this->options['view_modes'][$datasource_id][$bundle_id])) {
          $form['view_modes'][$datasource_id][$bundle_id]['#default_value'] = $this->options['view_modes'][$datasource_id][$bundle_id];
        }
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function preRender($result) {
    // Load all result objects at once, before rendering.
    $items_to_load = [];
    foreach ($result as $i => $row) {
      if (empty($row->_object)) {
        $items_to_load[$i] = $row->search_api_id;
      }
    }

    $items = $this->index->loadItemsMultiple($items_to_load);
    foreach ($items_to_load as $i => $item_id) {
      if (isset($items[$item_id])) {
        $result[$i]->_object = $items[$item_id];
        $result[$i]->_item->setOriginalObject($items[$item_id]);
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function render($row) {
    $datasource_id = $row->search_api_datasource;

    if (!($row->_object instanceof ComplexDataInterface)) {
      $context = [
        '%item_id' => $row->search_api_id,
        '%view' => $this->view->storage->label(),
      ];
      $this->getLogger()->warning('Failed to load item %item_id in view %view.', $context);
      return '';
    }

    if (!$this->index->isValidDatasource($datasource_id)) {
      $context = [
        '%datasource' => $datasource_id,
        '%view' => $this->view->storage->label(),
      ];
      $this->getLogger()->warning('Item of unknown datasource %datasource returned in view %view.', $context);
      return '';
    }
    // Always use the default view mode if it was not set explicitly in the
    // options.
    $view_mode = 'default';
    $bundle = $this->index->getDatasource($datasource_id)->getItemBundle($row->_object);
    if (isset($this->options['view_modes'][$datasource_id][$bundle])) {
      $view_mode = $this->options['view_modes'][$datasource_id][$bundle];
    }

    try {
      return $this->index->getDatasource($datasource_id)->viewItem($row->_object, $view_mode);
    }
    catch (SearchApiException $e) {
      $this->logException($e);
      return '';
    }
  }

  /**
   * {@inheritdoc}
   */
  public function query() {}

}


text:
@implementation SDLEncodedSyncPDataResponse

- (instancetype)init {
    if (self = [super initWithName:NAMES_EncodedSyncPData]) {
    }
    return self;
}

- (instancetype)initWithDictionary:(NSMutableDictionary *)dict {
    if (self = [super initWithDictionary:dict]) {
    }
    return self;
}

@end


text:
class SkPDFGlyphUse
{
public:
  SkPDFGlyphUse()
    : fBitSet(0)
  {
  }
  SkPDFGlyphUse(SkGlyphID firstNonZero, SkGlyphID lastGlyph)
    : fBitSet((int) lastGlyph - firstNonZero + 2)
    , fFirstNonZero(firstNonZero)
    , fLastGlyph(lastGlyph)
  {
    SkASSERT(firstNonZero >= 1);
  }
  ~SkPDFGlyphUse();
  SkPDFGlyphUse(SkPDFGlyphUse&&);
  SkPDFGlyphUse& operator=(SkPDFGlyphUse&&);
  SkGlyphID firstNonZero() const
  {
    return fFirstNonZero;
  }
  SkGlyphID lastGlyph() const
  {
    return fLastGlyph;
  }
  void set(SkGlyphID gid)
  {
    fBitSet.set(this->toCode(gid));
  }
  bool has(SkGlyphID gid) const
  {
    return fBitSet.has(this->toCode(gid));
  }
  template <typename FN>
  void getSetValues(FN f) const
  {
    if (fFirstNonZero == 1)
    {
      return fBitSet.getSetValues(std::move(f));
    }
    uint16_t offset = fFirstNonZero - 1;
    fBitSet.getSetValues();
  }
private:
  SkBitSet fBitSet;
  SkGlyphID fFirstNonZero = 0;
  SkGlyphID fLastGlyph = 0;
  uint16_t toCode(SkGlyphID gid) const
  {
    if (gid == 0 || fFirstNonZero == 1)
    {
      return gid;
    }
    SkASSERT(gid >= fFirstNonZero && gid <= fLastGlyph);
    return gid - fFirstNonZero + 1;
  }
  SkPDFGlyphUse(const SkPDFGlyphUse&) = delete;
  SkPDFGlyphUse& operator=(const SkPDFGlyphUse&);
};
#endif


text:
BASE.require(["Object"], function () {
    BASE.namespace("LG.core.dataModel.core");

    var _globalObject = this;

    LG.core.dataModel.core.Group = (function (Super) {
        var Group = function () {
            var self = this;
            if (self === _globalObject) {
                throw new Error("Group constructor invoked with global context.  Say new.");
            }

            Super.call(self);

            self["name"] = null;
            self["description"] = null;
            self["id"] = null;

            return self;
        };

        BASE.extend(Group, Super);

        return Group;
    }(Object));
});


text:
package br.com.goapi.util;

import br.com.goapi.Board;
import br.com.goapi.Group;
import br.com.goapi.Move;
import br.com.goapi.Player;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *
 * @author rafaelsakurai
 */
public class GroupUtil {
    /**
     * With base in a board, get all groups create by black and white stones.
     * @param board
     * @return
     */
    public static List<Group> getGroups(final Board board) {
        List<Group> groups = new ArrayList();

        for (Move[] moves : board.getBoard()) {
            for (Move m : moves) {
                if(!m.isFree())
                    getGroup(groups, board, m).addMove(m);
            }
        }

        addGroupInformation(groups, board);

        return groups;
    }

    /**
     * With base in a board, get all groups of stones from a player.
     *
     * @param board
     * @param player
     * @return
     */
    public static List<Group> getGroupsByPlayer(final Board board, final Player player) {
        List<Group> groups = new ArrayList();

        for (Move[] moves : board.getBoard()) {
            for (Move m : moves) {
                if(!m.isFree() && !m.isPass() && m.samePlayer(player))
                    getGroup(groups, board, m).addMove(m);
            }
        }

        addGroupInformation(groups, board);

        return groups;
    }

    public static Group getGroupByPosition(final Board board, final int line, final int column) {
        Group group = null;
        if (line != -1 && column != -1) {
            Move move = board.getMove(line, column);
            List<Group> groups = getGroups(board);

            for (Group g : groups) {
                if(!move.isPass() && groupHasMove(g, move)) {
                    group = g;
                    break;
                }
            }
        }
        return group;
    }

    public static List<Move> getGroupLiberties(final Board board, final int line, final int column) {
        Set<Move> liberties = new HashSet();

        Group g = GroupUtil.getGroupByPosition(board, line, column);

        for (Move m : g.getMoves()) {
            addFreeMoves(liberties, board.getMove(m.getLine() - 1, m.getColumn()));
            addFreeMoves(liberties, board.getMove(m.getLine() + 1, m.getColumn()));
            addFreeMoves(liberties, board.getMove(m.getLine(), m.getColumn() - 1));
            addFreeMoves(liberties, board.getMove(m.getLine(), m.getColumn() + 1));
        }

        return new ArrayList(liberties);
    }

    public static void addFreeMoves(final Set<Move> moves, final Move m) {
        if (m != null && m.isFree()) {
            moves.add(m);
        }
    }

    /**
     * Add some informations to the group, like:
     * - liberties;
     * - opponents;
     *
     * @param groups
     * @param board
     */
    public static void addGroupInformation(final List<Group> groups, final Board board) {
        for (Group g : groups) {
            for (Move m : g.getMoves()) {
                addInformation(board, m, m.getLine() - 1, m.getColumn());
                addInformation(board, m, m.getLine() + 1, m.getColumn());
                addInformation(board, m, m.getLine(), m.getColumn() - 1);
                addInformation(board, m, m.getLine(), m.getColumn() + 1);
            }
        }
    }

    /**
     * Add some information in a specific move, like:
     * - liberties;
     * - opponents;
     *
     * @param board
     * @param move
     * @param line
     * @param column
     */
    public static void addInformation(final Board board, final Move move, final int line, final int column) {
        if (line >= 0 && line < board.getBoard().length && column >= 0 && column < board.getBoard().length) {
            Move m = board.getMove(line, column);
            if (m.isFree()) {
                move.setLiberties(move.getLiberties() + 1);
            } else if (!m.getPlayer().equals(move.getPlayer())) {
                move.setOpponents(move.getOpponents() + 1);
            }
        }
    }

    /**
     * Find one or more groups that will be connected with the move parameter.
     *
     * @param groups
     * @param board
     * @param move
     * @return
     */
    public static Group getGroup(final List<Group> groups, final Board board, final Move move) {
        List<Group> selected = new ArrayList();

        for (Group g : groups) {
            getPlayerGroup(move, g, board, selected, move.getLine() - 1, move.getColumn());
            getPlayerGroup(move, g, board, selected, move.getLine() + 1, move.getColumn());
            getPlayerGroup(move, g, board, selected, move.getLine(), move.getColumn() - 1);
            getPlayerGroup(move, g, board, selected, move.getLine(), move.getColumn() + 1);
        }

        if(selected.isEmpty()) {
            Group group = new Group(move.getPlayer());
            groups.add(group);
            return group;
        }

        if(selected.size() == 1) {
            return selected.get(0);
        } else {
            return mergeGroups(groups, selected);
        }
    }

    /**
     * Verifify if the move with line and column parameter isn't free, if is inside of the board and is from same player to create a group.
     *
     * @param move - the original move parameter.
     * @param group - that can contain the move especified by line and column.
     * @param board - the entire board.
     * @param selected - add the group in this list, if contain the move especified by line and column.
     * @param line - of neighbor move.
     * @param column  - of neighbor move.
     */
    public static void getPlayerGroup(final Move move, final Group group, final Board board, final List<Group> selected, final int line, final int column) {
        if(!move.isFree() && line >= 0 && line < board.getBoard().length && column >= 0 && column < board.getBoard().length) {
            Move m = board.getMove(line, column);
            if(!m.isFree() && m.getPlayer().equals(move.getPlayer()) && groupHasMove(group, m) && !selected.contains(group)){
                selected.add(group);
            }
        }
    }

    /**
     * Verify if group has the move.
     *
     * @param group
     * @param move
     * @return
     */
    public static boolean groupHasMove(final Group group, final Move move) {
        return group.getMoves().stream().anyMatch((m) -> (m.equals(move)));
    }

    /**
     * Merge two or more groups in order to create a new group.
     *
     * @param groups
     * @param selected
     * @return
     */
    public static Group mergeGroups(final List<Group> groups, final List<Group> selected) {
        Group group = new Group(selected.get(0).getPlayer());

        groups.removeAll(selected); //Remove the small groups.
        groups.add(group); //Add the new big group.

        for (Group s : selected) {
            group.addAllMoves(s.getMoves());
        }

        return group;
    }

    public static List<Group> getGroupsInAtari(final Board board) {
        List<Group> atari = new ArrayList();

        List<Group> groups = getGroups(board);
        for (Group g : groups) {
            if (g.isInAtari())
                atari.add(g);
        }

        return atari;
    }
}


text:
void ASkill::OnHit(UPrimitiveComponent* HitComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
	if (ProjectileCollisionFX)
	{
		//Activate the collision FX and start the destroy timer
		ParticleComp->SetTemplate(ProjectileCollisionFX);
		ParticleComp->Activate(true);

		FTimerHandle TimerHandle;
		FTimerDelegate TimerDel;

		TimerDel.BindLambda([&]()
		{
			Destroy();
		});

		GetWorld()->GetTimerManager().SetTimer(TimerHandle, TimerDel, DestroyDelay, false);
	}
}

// Sets default values
ASkill::ASkill()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	SphereComp = CreateDefaultSubobject<USphereComponent>(FName("SphereComp"));

	SphereComp->SetCollisionProfileName(FName("BlockAll"));

	SetRootComponent(SphereComp);

	//Initializing the movement component and its properties
	ProjectileMovementComp = CreateDefaultSubobject<UProjectileMovementComponent>(FName("ProjectileMovementComp"));

	ProjectileMovementComp->ProjectileGravityScale = 0.f;
	ProjectileMovementComp->InitialSpeed = 3000.f;

	ParticleComp = CreateDefaultSubobject<UParticleSystemComponent>(FName("ParticleComp"));
	ParticleComp->SetupAttachment(SphereComp);
}

// Called when the game starts or when spawned
void ASkill::BeginPlay()
{
	Super::BeginPlay();

	SphereComp->OnComponentHit.AddDynamic(this, &ASkill::OnHit);

	if (ProjectileFX)
	{
		ParticleComp->SetTemplate(ProjectileFX);
		ParticleComp->Activate();
	}
}

void ASkill::OnConstruction(const FTransform& Transform)
{
	Super::OnConstruction(Transform);

	//Used in order to have a visual feedback in the editor when we
	//assign a new particle
	if (ProjectileFX)
	{
		ParticleComp->SetTemplate(ProjectileFX);
		ParticleComp->Activate();
	}
}