text:
<?php

final class PhabricatorMacroEditController extends PhabricatorMacroController {

  public function handleRequest(AphrontRequest $request) {
    $viewer = $request->getViewer();
    $id = $request->getURIData('id');

    $this->requireApplicationCapability(
      PhabricatorMacroManageCapability::CAPABILITY);

    if ($id) {
      $macro = id(new PhabricatorMacroQuery())
        ->setViewer($viewer)
        ->withIDs(array($id))
        ->needFiles(true)
        ->executeOne();
      if (!$macro) {
        return new Aphront404Response();
      }
    } else {
      $macro = new PhabricatorFileImageMacro();
      $macro->setAuthorPHID($viewer->getPHID());
    }

    $errors = array();
    $e_name = true;
    $e_file = null;
    $file = null;

    if ($request->isFormPost()) {
      $original = clone $macro;

      $new_name = null;
      if ($request->getBool('name_form') || !$macro->getID()) {
        $new_name = $request->getStr('name');

        $macro->setName($new_name);

        if (!strlen($macro->getName())) {
          $errors[] = pht('Macro name is required.');
          $e_name = pht('Required');
        } else if (!preg_match('/^[a-z0-9:_-]{3,}\z/', $macro->getName())) {
          $errors[] = pht(
            'Macro must be at least three characters long and contain only '.
            'lowercase letters, digits, hyphens, colons and underscores.');
          $e_name = pht('Invalid');
        } else {
          $e_name = null;
        }
      }

      $uri = $request->getStr('url');

      $engine = new PhabricatorDestructionEngine();

      $file = null;
      if ($request->getFileExists('file')) {
        $file = PhabricatorFile::newFromPHPUpload(
          $_FILES['file'],
          array(
            'name' => $request->getStr('name'),
            'authorPHID' => $viewer->getPHID(),
            'isExplicitUpload' => true,
            'canCDN' => true,
          ));
      } else if ($uri) {
        try {
          // Rate limit outbound fetches to make this mechanism less useful for
          // scanning networks and ports.
          PhabricatorSystemActionEngine::willTakeAction(
            array($viewer->getPHID()),
            new PhabricatorFilesOutboundRequestAction(),
            1);

          $file = PhabricatorFile::newFromFileDownload(
            $uri,
            array(
              'name' => $request->getStr('name'),
              'viewPolicy' => PhabricatorPolicies::POLICY_NOONE,
              'isExplicitUpload' => true,
              'canCDN' => true,
            ));

          if (!$file->isViewableInBrowser()) {
            $mime_type = $file->getMimeType();
            $engine->destroyObject($file);
            $file = null;
            throw new Exception(
              pht(
                'The URI "%s" does not correspond to a valid image file, got '.
                'a file with MIME type "%s". You must specify the URI of a '.
                'valid image file.',
                $uri,
                $mime_type));
          } else {
            $file
              ->setAuthorPHID($viewer->getPHID())
              ->save();
          }
        } catch (HTTPFutureHTTPResponseStatus $status) {
          $errors[] = pht(
            'The URI "%s" could not be loaded, got %s error.',
            $uri,
            $status->getStatusCode());
        } catch (Exception $ex) {
          $errors[] = $ex->getMessage();
        }
      } else if ($request->getStr('phid')) {
        $file = id(new PhabricatorFileQuery())
          ->setViewer($viewer)
          ->withPHIDs(array($request->getStr('phid')))
          ->executeOne();
      }

      if ($file) {
        if (!$file->isViewableInBrowser()) {
          $errors[] = pht('You must upload an image.');
          $e_file = pht('Invalid');
        } else {
          $macro->setFilePHID($file->getPHID());
          $macro->attachFile($file);
          $e_file = null;
        }
      }

      if (!$macro->getID() && !$file) {
        $errors[] = pht('You must upload an image to create a macro.');
        $e_file = pht('Required');
      }

      if (!$errors) {
        try {
          $xactions = array();

          if ($new_name !== null) {
            $xactions[] = id(new PhabricatorMacroTransaction())
              ->setTransactionType(PhabricatorMacroTransaction::TYPE_NAME)
              ->setNewValue($new_name);
          }

          if ($file) {
            $xactions[] = id(new PhabricatorMacroTransaction())
              ->setTransactionType(PhabricatorMacroTransaction::TYPE_FILE)
              ->setNewValue($file->getPHID());
          }

          $editor = id(new PhabricatorMacroEditor())
            ->setActor($viewer)
            ->setContinueOnNoEffect(true)
            ->setContentSourceFromRequest($request);

          $xactions = $editor->applyTransactions($original, $xactions);

          $view_uri = $this->getApplicationURI('/view/'.$original->getID().'/');
          return id(new AphrontRedirectResponse())->setURI($view_uri);
        } catch (AphrontDuplicateKeyQueryException $ex) {
          throw $ex;
          $errors[] = pht('Macro name is not unique!');
          $e_name = pht('Duplicate');
        }
      }
    }

    $current_file = null;
    if ($macro->getFilePHID()) {
      $current_file = $macro->getFile();
    }

    $form = new AphrontFormView();
    $form->addHiddenInput('name_form', 1);
    $form->setUser($request->getUser());

    $form
      ->setEncType('multipart/form-data')
      ->appendChild(
        id(new AphrontFormTextControl())
          ->setLabel(pht('Name'))
          ->setName('name')
          ->setValue($macro->getName())
          ->setCaption(
            pht('This word or phrase will be replaced with the image.'))
          ->setError($e_name));

    if (!$macro->getID()) {
      if ($current_file) {
        $current_file_view = id(new PhabricatorFileLinkView())
          ->setFilePHID($current_file->getPHID())
          ->setFileName($current_file->getName())
          ->setFileViewable(true)
          ->setFileViewURI($current_file->getBestURI())
          ->render();
        $form->addHiddenInput('phid', $current_file->getPHID());
        $form->appendChild(
          id(new AphrontFormMarkupControl())
            ->setLabel(pht('Selected File'))
            ->setValue($current_file_view));

        $other_label = pht('Change File');
      } else {
        $other_label = pht('File');
      }

      $form->appendChild(
        id(new AphrontFormTextControl())
          ->setLabel(pht('URL'))
          ->setName('url')
          ->setValue($request->getStr('url'))
          ->setError($request->getFileExists('file') ? false : $e_file));

      $form->appendChild(
        id(new AphrontFormFileControl())
          ->setLabel($other_label)
          ->setName('file')
          ->setError($request->getStr('url') ? false : $e_file));
    }

    $view_uri = $this->getApplicationURI('/view/'.$macro->getID().'/');

    if ($macro->getID()) {
      $cancel_uri = $view_uri;
    } else {
      $cancel_uri = $this->getApplicationURI();
    }

    $form
      ->appendChild(
        id(new AphrontFormSubmitControl())
          ->setValue(pht('Save Image Macro'))
          ->addCancelButton($cancel_uri));

    $crumbs = $this->buildApplicationCrumbs();

    if ($macro->getID()) {
      $title = pht('Edit Image Macro');
      $crumb = pht('Edit Macro');

      $crumbs->addTextCrumb(pht('Macro "%s"', $macro->getName()), $view_uri);
    } else {
      $title = pht('Create Image Macro');
      $crumb = pht('Create Macro');
    }

    $crumbs->addTextCrumb($crumb, $request->getRequestURI());

    $upload = null;
    if ($macro->getID()) {
      $upload_form = id(new AphrontFormView())
        ->setEncType('multipart/form-data')
        ->setUser($request->getUser());

      $upload_form->appendChild(
        id(new AphrontFormTextControl())
          ->setLabel(pht('URL'))
          ->setName('url')
          ->setValue($request->getStr('url')));

      $upload_form
        ->appendChild(
          id(new AphrontFormFileControl())
            ->setLabel(pht('File'))
            ->setName('file'))
        ->appendChild(
          id(new AphrontFormSubmitControl())
            ->setValue(pht('Upload File')));

      $upload = id(new PHUIObjectBoxView())
        ->setHeaderText(pht('Upload New File'))
        ->setForm($upload_form);
    }

    $form_box = id(new PHUIObjectBoxView())
      ->setHeaderText($title)
      ->setFormErrors($errors)
      ->setForm($form);

    return $this->buildApplicationPage(
      array(
        $crumbs,
        $form_box,
        $upload,
      ),
      array(
        'title' => $title,
      ));
  }

}


text:
package org.onosproject.ovsdb.providers.device;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.MoreExecutors;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.IpAddress;
import org.onlab.packet.TpPort;
import org.onosproject.net.Annotations;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DefaultDevice;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.MastershipRole;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DefaultPortDescription;
import org.onosproject.net.device.DeviceDescription;
import org.onosproject.net.device.DeviceDescriptionDiscovery;
import org.onosproject.net.device.DeviceEvent;
import org.onosproject.net.device.DeviceListener;
import org.onosproject.net.device.DeviceProvider;
import org.onosproject.net.device.DeviceProviderRegistry;
import org.onosproject.net.device.DeviceProviderService;
import org.onosproject.net.device.DeviceServiceAdapter;
import org.onosproject.net.device.PortDescription;
import org.onosproject.net.device.PortStatistics;
import org.onosproject.net.driver.AbstractHandlerBehaviour;
import org.onosproject.net.driver.Behaviour;
import org.onosproject.net.provider.ProviderId;
import org.onosproject.ovsdb.controller.OvsdbClientService;
import org.onosproject.ovsdb.controller.OvsdbController;
import org.onosproject.ovsdb.controller.OvsdbEventListener;
import org.onosproject.ovsdb.controller.OvsdbNodeId;
import org.onosproject.ovsdb.controller.OvsdbNodeListener;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Consumer;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * Test for ovsdb device provider.
 */
public class OvsdbDeviceProviderTest {
    private final OvsdbDeviceProvider provider = new OvsdbDeviceProvider();
    private final TestDeviceRegistry registry = new TestDeviceRegistry();
    private final TestController controller = new TestController();
    private final TestDeviceService deviceService = new TestDeviceService();

    private final Device ovsdbDevice = new MockDevice(
            DeviceId.deviceId("ovsdb:127.0.0.1"),
            DefaultAnnotations.EMPTY);

    private final Device notOvsdbDevice = new MockDevice(
            DeviceId.deviceId("other:127.0.0.1"),
            DefaultAnnotations.EMPTY);

    private final TestDescription deviceDescription = new TestDescription();

    @Before
    public void startUp() {
        provider.providerRegistry = registry;
        provider.controller = controller;
        provider.deviceService = deviceService;
        provider.activate();
        assertNotNull("provider should be registered", registry.provider);
    }

    @After
    public void tearDown() {
        provider.deactivate();
        provider.controller = null;
        provider.providerRegistry = null;
        provider.deviceService = null;
    }

    @Test
    public void testNodeAdded() {
        controller.listener.nodeAdded(new OvsdbNodeId(IpAddress
                .valueOf("192.168.202.36"), 5000));
        assertEquals("ovsdb node added", 1, registry.connected.size());
    }

    @Test
    public void testNodeRemoved() {
        controller.listener.nodeAdded(new OvsdbNodeId(IpAddress
                .valueOf("192.168.202.36"), 5000));
        controller.listener.nodeRemoved(new OvsdbNodeId(IpAddress
                .valueOf("192.168.202.36"), 5000));
        assertEquals("ovsdb node removded", 0, registry.connected.size());
    }

    @Test
    public void testDiscoverPortsAfterDeviceAdded() {
        final int portCount = 5;
        provider.executor = MoreExecutors.newDirectExecutorService();
        prepareMocks(portCount);

        deviceService.listener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, ovsdbDevice));
        deviceService.listener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, notOvsdbDevice));

        assertEquals(portCount, registry.ports.get(ovsdbDevice.id()).size());
        assertEquals(0, registry.ports.get(notOvsdbDevice.id()).size());
    }

    private void prepareMocks(int count) {
        for (int i = 1; i <= count; i++) {
            deviceDescription.portDescriptions.add(new DefaultPortDescription(PortNumber.portNumber(i), true));
        }
    }

    private class TestDeviceRegistry implements DeviceProviderRegistry {
        DeviceProvider provider;

        final Set<DeviceId> connected = new HashSet<>();
        final Multimap<DeviceId, PortDescription> ports = HashMultimap.create();
        PortDescription descr = null;

        @Override
        public DeviceProviderService register(DeviceProvider provider) {
            this.provider = provider;
            return new TestProviderService();
        }

        @Override
        public void unregister(DeviceProvider provider) {
        }

        @Override
        public Set<ProviderId> getProviders() {
            return null;
        }

        private class TestProviderService implements DeviceProviderService {

            @Override
            public DeviceProvider provider() {
                return null;
            }

            @Override
            public void deviceConnected(DeviceId deviceId,
                                        DeviceDescription deviceDescription) {
                connected.add(deviceId);
            }

            @Override
            public void deviceDisconnected(DeviceId deviceId) {
                connected.remove(deviceId);
                ports.removeAll(deviceId);
            }

            @Override
            public void updatePorts(DeviceId deviceId,
                                    List<PortDescription> portDescriptions) {
                for (PortDescription p : portDescriptions) {
                    ports.put(deviceId, p);
                }
            }

            @Override
            public void portStatusChanged(DeviceId deviceId,
                                          PortDescription portDescription) {
                ports.put(deviceId, portDescription);
                descr = portDescription;
            }

            @Override
            public void receivedRoleReply(DeviceId deviceId,
                                          MastershipRole requested,
                                          MastershipRole response) {
            }

            @Override
            public void updatePortStatistics(DeviceId deviceId,
                                             Collection<PortStatistics> portStatistics) {

            }

        }
    }

    private class TestController implements OvsdbController {
        OvsdbNodeListener listener = null;

        @Override
        public void addNodeListener(OvsdbNodeListener listener) {
            this.listener = listener;
        }

        @Override
        public void removeNodeListener(OvsdbNodeListener listener) {
            this.listener = null;
        }

        @Override
        public void addOvsdbEventListener(OvsdbEventListener listener) {

        }

        @Override
        public void removeOvsdbEventListener(OvsdbEventListener listener) {

        }

        @Override
        public List<OvsdbNodeId> getNodeIds() {
            return null;
        }

        @Override
        public OvsdbClientService getOvsdbClient(OvsdbNodeId nodeId) {
            return null;
        }

        @Override
        public void connect(IpAddress ip, TpPort port) {

        }

        @Override
        public void connect(IpAddress ip, TpPort port, Consumer<Exception> failhandler) {

        }

    }

    private class TestDeviceService extends DeviceServiceAdapter {
        DeviceListener listener = null;

        @Override
        public Device getDevice(DeviceId deviceId) {
            return ovsdbDevice;
        }

        @Override
        public void addListener(DeviceListener listener) {
            this.listener = listener;
        }

        @Override
        public void removeListener(DeviceListener listener) {
            this.listener = null;
        }
    }

    private class TestDescription extends AbstractHandlerBehaviour implements DeviceDescriptionDiscovery {

        final List<PortDescription> portDescriptions = new ArrayList<>();

        @Override
        public DeviceDescription discoverDeviceDetails() {
            return null;
        }

        @Override
        public List<PortDescription> discoverPortDetails() {
            return portDescriptions;
        }
    }

    private class MockDevice extends DefaultDevice {

        MockDevice(DeviceId id,
                   Annotations... annotations) {
            super(null, id, Type.SWITCH, null, null, null, null,
                  null, annotations);
        }

        @Override
        public <B extends Behaviour> B as(Class<B> projectionClass) {
            return (B) deviceDescription;
        }

        @Override
        public <B extends Behaviour> boolean is(Class<B> projectionClass) {
            return true;
        }

    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.github.dockerjava.core.command;

import static com.github.dockerjava.api.model.AccessMode.ro;
import static com.github.dockerjava.api.model.Capability.*;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isEmptyString;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;

import java.lang.reflect.Method;
import java.util.*;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.DockerException;
import com.github.dockerjava.api.NotFoundException;
import com.github.dockerjava.api.command.CreateContainerResponse;
import com.github.dockerjava.api.command.InspectContainerResponse;
import com.github.dockerjava.api.command.StartContainerCmd;
import com.github.dockerjava.api.model.*;

import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.github.dockerjava.client.AbstractDockerClientTest;

@Test(groups = "integration")
public class StartContainerCmdImplTest extends AbstractDockerClientTest {

	@BeforeTest
	public void beforeTest() throws DockerException {
		super.beforeTest();
	}

	@AfterTest
	public void afterTest() {
		super.afterTest();
	}

	@BeforeMethod
	public void beforeMethod(Method method) {
		super.beforeMethod(method);
	}

	@AfterMethod
	public void afterMethod(ITestResult result) {
		super.afterMethod(result);
	}

	@Test
	public void startContainerWithVolumes() throws DockerException {

		// see http://docs.docker.io/use/working_with_volumes/
		Volume volume1 = new Volume("/opt/webapp1");

		Volume volume2 = new Volume("/opt/webapp2");

		CreateContainerResponse container = dockerClient
				.createContainerCmd("busybox").withVolumes(volume1, volume2)
				.withCmd("true").exec();

		LOG.info("Created container {}", container.toString());

		assertThat(container.getId(), not(isEmptyString()));

		InspectContainerResponse inspectContainerResponse = dockerClient
				.inspectContainerCmd(container.getId()).exec();

		assertThat(inspectContainerResponse.getConfig().getVolumes().keySet(),
				contains("/opt/webapp1", "/opt/webapp2"));

		dockerClient.startContainerCmd(container.getId()).withBinds(new Bind("/src/webapp1", volume1, ro), new Bind("/src/webapp2", volume2)).exec();

		dockerClient.waitContainerCmd(container.getId()).exec();

		inspectContainerResponse = dockerClient.inspectContainerCmd(container
				.getId()).exec();

		assertContainerHasVolumes(inspectContainerResponse, volume1, volume2);

		assertThat(Arrays.asList(inspectContainerResponse.getVolumesRW()),
				contains(volume1, volume2));

	}

	@Test
	public void startContainerWithVolumesFrom() throws DockerException {

		Volume volume1 = new Volume("/opt/webapp1");
		Volume volume2 = new Volume("/opt/webapp2");

		String container1Name = UUID.randomUUID().toString();

		CreateContainerResponse container1 = dockerClient
				.createContainerCmd("busybox").withCmd("sleep", "9999")
				.withName(container1Name).exec();
		LOG.info("Created container1 {}", container1.toString());

		dockerClient.startContainerCmd(container1.getId()).withBinds(
				new Bind("/src/webapp1", volume1), new Bind("/src/webapp2", volume2)).exec();
		LOG.info("Started container1 {}", container1.toString());

		InspectContainerResponse inspectContainerResponse1 = dockerClient.inspectContainerCmd(
				container1.getId()).exec();

		assertContainerHasVolumes(inspectContainerResponse1, volume1, volume2);

		CreateContainerResponse container2 = dockerClient
				.createContainerCmd("busybox").withCmd("sleep", "9999").exec();
		LOG.info("Created container2 {}", container2.toString());

		dockerClient.startContainerCmd(container2.getId()).withVolumesFrom(container1Name).exec();
		LOG.info("Started container2 {}", container2.toString());

		InspectContainerResponse inspectContainerResponse2 = dockerClient
				.inspectContainerCmd(container2.getId()).exec();

		assertContainerHasVolumes(inspectContainerResponse2, volume1, volume2);
	}

	@Test
	public void startContainerWithDns() throws DockerException {

		String aDnsServer = "8.8.8.8";
		String anotherDnsServer = "8.8.4.4";

		CreateContainerResponse container = dockerClient
				.createContainerCmd("busybox")
				.withCmd("true").exec();

		LOG.info("Created container {}", container.toString());

		assertThat(container.getId(), not(isEmptyString()));

		dockerClient.startContainerCmd(container.getId()).withDns(aDnsServer, anotherDnsServer).exec();

		InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container
				.getId()).exec();

		assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDns()),
				contains(aDnsServer, anotherDnsServer));
	}

	@Test
	public void startContainerWithDnsSearch() throws DockerException {

		String dnsSearch = "example.com";

		CreateContainerResponse container = dockerClient
				.createContainerCmd("busybox")
				.withCmd("true").exec();

		LOG.info("Created container {}", container.toString());

		assertThat(container.getId(), not(isEmptyString()));

		InspectContainerResponse inspectContainerResponse = dockerClient
				.inspectContainerCmd(container.getId()).exec();

		dockerClient.startContainerCmd(container.getId()).withDnsSearch(dnsSearch).exec();

		inspectContainerResponse = dockerClient.inspectContainerCmd(container
				.getId()).exec();

		assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDnsSearch()),
				contains(dnsSearch));
	}

	@Test
	public void startContainerWithPortBindings() throws DockerException {

		ExposedPort tcp22 = ExposedPort.tcp(22);
		ExposedPort tcp23 = ExposedPort.tcp(23);

		CreateContainerResponse container = dockerClient
				.createContainerCmd("busybox")
				.withCmd("true").withExposedPorts(tcp22, tcp23).exec();

		LOG.info("Created container {}", container.toString());

		assertThat(container.getId(), not(isEmptyString()));

		InspectContainerResponse inspectContainerResponse = dockerClient
				.inspectContainerCmd(container.getId()).exec();

		Ports portBindings = new Ports();
		portBindings.bind(tcp22, Ports.Binding(11022));
		portBindings.bind(tcp23, Ports.Binding(11023));
		portBindings.bind(tcp23, Ports.Binding(11024));

		dockerClient.startContainerCmd(container.getId()).withPortBindings(portBindings).exec();

		inspectContainerResponse = dockerClient.inspectContainerCmd(container
				.getId()).exec();

		assertThat(Arrays.asList(inspectContainerResponse.getConfig().getExposedPorts()),
				contains(tcp22, tcp23));

		assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp22)[0],
				is(equalTo(Ports.Binding(11022))));

		assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[0],
				is(equalTo(Ports.Binding(11023))));

		assertThat(inspectContainerResponse.getHostConfig().getPortBindings().getBindings().get(tcp23)[1],
				is(equalTo(Ports.Binding(11024))));

	}

	@Test
	public void startContainerWithLinking() throws DockerException {

		CreateContainerResponse container1 = dockerClient
				.createContainerCmd("busybox").withCmd("sleep", "9999").withName("container1").exec();

		LOG.info("Created container1 {}", container1.toString());
		assertThat(container1.getId(), not(isEmptyString()));

		dockerClient.startContainerCmd(container1.getId()).exec();

		InspectContainerResponse inspectContainerResponse1 = dockerClient
				.inspectContainerCmd(container1.getId()).exec();
		LOG.info("Container1 Inspect: {}", inspectContainerResponse1.toString());

		assertThat(inspectContainerResponse1.getConfig(), is(notNullValue()));
		assertThat(inspectContainerResponse1.getId(), not(isEmptyString()));
		assertThat(inspectContainerResponse1.getId(), startsWith(container1.getId()));
		assertThat(inspectContainerResponse1.getName(), equalTo("/container1"));
		assertThat(inspectContainerResponse1.getImageId(), not(isEmptyString()));
		assertThat(inspectContainerResponse1.getState(), is(notNullValue()));
		assertThat(inspectContainerResponse1.getState().isRunning(), is(true));

		if (!inspectContainerResponse1.getState().isRunning()) {
			assertThat(inspectContainerResponse1.getState().getExitCode(),
					is(equalTo(0)));
		}

		CreateContainerResponse container2 = dockerClient
				.createContainerCmd("busybox").withCmd("true").withName("container2").exec();

		LOG.info("Created container2 {}", container2.toString());
		assertThat(container2.getId(), not(isEmptyString()));

		dockerClient.startContainerCmd(container2.getId()).withLinks(new Link("container1", "container1Link")).exec();

		InspectContainerResponse inspectContainerResponse2 = dockerClient
				.inspectContainerCmd(container2.getId()).exec();
		LOG.info("Container2 Inspect: {}", inspectContainerResponse2.toString());

		assertThat(inspectContainerResponse2.getConfig(), is(notNullValue()));
		assertThat(inspectContainerResponse2.getId(), not(isEmptyString()));
		assertThat(inspectContainerResponse2.getHostConfig(), is(notNullValue()));
		assertThat(inspectContainerResponse2.getHostConfig().getLinks(), is(notNullValue()));
		assertThat(inspectContainerResponse2.getHostConfig().getLinks().getLinks(), equalTo(new Link[] {new Link("container1","container1Link")}));
		assertThat(inspectContainerResponse2.getId(), startsWith(container2.getId()));
		assertThat(inspectContainerResponse2.getName(), equalTo("/container2"));
		assertThat(inspectContainerResponse2.getImageId(), not(isEmptyString()));
		assertThat(inspectContainerResponse2.getState(), is(notNullValue()));
		assertThat(inspectContainerResponse2.getState().isRunning(), is(true));

	}

	@Test
	public void startContainer() throws DockerException {

		CreateContainerResponse container = dockerClient
			.createContainerCmd("busybox").withCmd(new String[] { "top" }).exec();

		LOG.info("Created container {}", container.toString());
		assertThat(container.getId(), not(isEmptyString()));

		dockerClient.startContainerCmd(container.getId()).exec();

		InspectContainerResponse inspectContainerResponse = dockerClient
				.inspectContainerCmd(container.getId()).exec();
		LOG.info("Container Inspect: {}", inspectContainerResponse.toString());

		assertThat(inspectContainerResponse.getConfig(), is(notNullValue()));
		assertThat(inspectContainerResponse.getId(), not(isEmptyString()));

		assertThat(inspectContainerResponse.getId(),
				startsWith(container.getId()));

		assertThat(inspectContainerResponse.getImageId(), not(isEmptyString()));
		assertThat(inspectContainerResponse.getState(), is(notNullValue()));

		assertThat(inspectContainerResponse.getState().isRunning(), is(true));

		if (!inspectContainerResponse.getState().isRunning()) {
			assertThat(inspectContainerResponse.getState().getExitCode(),
					is(equalTo(0)));
		}
	}

	@Test
	public void testStartNonExistingContainer() throws DockerException {
		try {
			dockerClient.startContainerCmd("non-existing").exec();
			fail("expected NotFoundException");
		} catch (NotFoundException e) {
		}
	}

	/**
	 * This tests support for --net option for the docker run command:
	 * --net="bridge" Set the Network mode for the container
	 * 'bridge': creates a new network stack for the container on the docker bridge
	 * 'none': no networking for this container
	 * 'container:': reuses another container network stack
	 * 'host': use the host network stack inside the container.
	 *  Note: the host mode gives the container full access to local system services such as D-bus and is therefore considered insecure.
	 */
	@Test
    public void startContainerWithNetworkMode() throws DockerException {

        CreateContainerResponse container = dockerClient
                .createContainerCmd("busybox")
                .withCmd("true").exec();

        LOG.info("Created container {}", container.toString());

        assertThat(container.getId(), not(isEmptyString()));

        InspectContainerResponse inspectContainerResponse = dockerClient
                .inspectContainerCmd(container.getId()).exec();

        dockerClient.startContainerCmd(container.getId()).withNetworkMode("host").exec();

        inspectContainerResponse = dockerClient.inspectContainerCmd(container
                .getId()).exec();

        assertThat(inspectContainerResponse.getHostConfig().getNetworkMode(),
                is(equalTo("host")));
    }

	@Test
    public void startContainerWithCapAddAndCapDrop() throws DockerException {

        CreateContainerResponse container = dockerClient
                .createContainerCmd("busybox")
                .withCmd("sleep", "9999").exec();

        LOG.info("Created container {}", container.toString());

        assertThat(container.getId(), not(isEmptyString()));

        dockerClient.startContainerCmd(container.getId())
        	.withCapAdd(NET_ADMIN)
        	.withCapDrop(MKNOD).exec();

        InspectContainerResponse inspectContainerResponse  = dockerClient.inspectContainerCmd(container
                .getId()).exec();

        assertThat(inspectContainerResponse.getState().isRunning(), is(true));

        assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getCapAdd()),
                contains(NET_ADMIN));

        assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getCapDrop()),
                contains(MKNOD));
    }

	@Test
    public void startContainerWithDevices() throws DockerException {

        CreateContainerResponse container = dockerClient
                .createContainerCmd("busybox")
                .withCmd("sleep", "9999").exec();

        LOG.info("Created container {}", container.toString());

        assertThat(container.getId(), not(isEmptyString()));

        dockerClient.startContainerCmd(container.getId())
        	.withDevices(new Device("rwm", "/dev/nulo", "/dev/zero"))
        	.exec();

        InspectContainerResponse inspectContainerResponse  = dockerClient.inspectContainerCmd(container
                .getId()).exec();

        assertThat(inspectContainerResponse.getState().isRunning(), is(true));

        assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDevices()),
                contains(new Device("rwm", "/dev/nulo", "/dev/zero")));
    }

	@Test
    public void startContainerWithRestartPolicy() throws DockerException {

        CreateContainerResponse container = dockerClient
                .createContainerCmd("busybox")
                .withCmd("sleep", "9999").exec();

        LOG.info("Created container {}", container.toString());

        assertThat(container.getId(), not(isEmptyString()));

        RestartPolicy restartPolicy = RestartPolicy.onFailureRestart(5);

        dockerClient.startContainerCmd(container.getId())
        	.withRestartPolicy(restartPolicy)
        	.exec();

        InspectContainerResponse inspectContainerResponse  = dockerClient.inspectContainerCmd(container
                .getId()).exec();

        assertThat(inspectContainerResponse.getState().isRunning(), is(true));

        assertThat(inspectContainerResponse.getHostConfig().getRestartPolicy(),
                is(equalTo(restartPolicy)));
    }

	@Test
	public void existingHostConfigIsPreservedByBlankStartCmd() throws DockerException {

		String dnsServer = "8.8.8.8";

		// prepare a container with custom DNS
		CreateContainerResponse container = dockerClient
				.createContainerCmd("busybox")
				.withDns(dnsServer)
				.withCmd("true").exec();

		LOG.info("Created container {}", container.toString());

		assertThat(container.getId(), not(isEmptyString()));

		// start container _without_any_customization_ (important!)
		dockerClient.startContainerCmd(container.getId()).exec();

		InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container
				.getId()).exec();

		// The DNS setting survived.
		assertThat(inspectContainerResponse.getHostConfig().getDns(), is(notNullValue()));
		assertThat(Arrays.asList(inspectContainerResponse.getHostConfig().getDns()),
				contains(dnsServer));
	}

	@Test
	public void existingHostConfigIsResetByConfiguredStartCmd() throws DockerException {
		// As of version 1.3.2, Docker assumes that you either configure a container
		// when creating it or when starting it, but not mixing both.
		// See https://github.com/docker-java/docker-java/pull/111
		// If this test starts to fail, this behavior changed and a review of implementation
		// and documentation might be needed.

		String dnsServer = "8.8.8.8";

		// prepare a container with custom DNS
		CreateContainerResponse container = dockerClient
				.createContainerCmd("busybox")
				.withDns(dnsServer)
				.withCmd("true").exec();

		LOG.info("Created container {}", container.toString());

		assertThat(container.getId(), not(isEmptyString()));

		// modify another setting in start command. Leave DNS unchanged.
		dockerClient.startContainerCmd(container.getId()).withPublishAllPorts(true).exec();

		InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container
				.getId()).exec();

		// although start did not modify DNS Settings, they were reset to their default.
		assertThat(inspectContainerResponse.getHostConfig().getDns(), is(nullValue(String[].class)));
	}

	@Test
	public void anUnconfiguredCommandSerializesToEmptyJson() throws Exception {
		ObjectMapper objectMapper = new ObjectMapper();
		StartContainerCmd command = dockerClient.startContainerCmd("");
		assertThat(objectMapper.writeValueAsString(command), is("{}"));
	}
}


text:
package com.jdon.controller.pool;

/**
 *
 * Instances of classes in this role collaborate with other objects for event limited amount of time,
 * then they are no longer needed for that collaboration.

 * see in PooInterceptor.java:
 *   (ifc.getName().equalsIgnoreCase("Poolabe"))
 *
 * <p>@author <event href="mailto:banqiao@jdon.com">banq</event></p>
 */
public interface Poolable {

}


text:
namespace wgt
{

BasePropertyPath::BasePropertyPath(
	IPropertyPath::ConstPtr & parent, const char * path )
	: parent_(parent)
	, path_( path ? path : "" )
	, hash_( 0 )
	, recursiveHash_( parent ? parent->getRecursiveHash() : 0 )
	//Do deep copy
	, recursivePath_( parent ? parent->getRecursivePath().str() : "" )
{
}

void BasePropertyPath::postConstruct()
{
	auto path = generateDecoratedPath();
	hash_ = HashUtilities::compute(path);
	HashUtilities::directCombine(recursiveHash_, hash_);
	recursivePath_ += path;
}

IPropertyPath::ConstPtr & BasePropertyPath::getParent() const
{
	return parent_;
}

uint64_t BasePropertyPath::getHash() const
{
	return hash_;
}

uint64_t BasePropertyPath::getRecursiveHash() const
{
	return recursiveHash_;
}

const std::string & BasePropertyPath::getPath() const
{
	return path_.str();
}

const SharedString & BasePropertyPath::getRecursivePath() const
{
	return recursivePath_;
}

IPropertyPath::ConstPtr BasePropertyPath::generateChildPath(IPropertyPath::ConstPtr & self, Variant & key) const
{
	TF_ASSERT(self.get() == this);
	IPropertyPath::ConstPtr ptr(new CollectionChildPath(self, key));
	return ptr;
}

bool BasePropertyPath::operator==(const char * name) const
{
	return recursivePath_.str() == name;
}

bool BasePropertyPath::operator==(const std::string & name) const
{
	return recursivePath_.str() == name;
}

PropertyPath::PropertyPath(
	IPropertyPath::ConstPtr & parent, const char * path)
	: BasePropertyPath(parent, path )
{
	postConstruct();
}

std::string PropertyPath::generateDecoratedPath() const
{
	if (parent_ == nullptr)
	{
		return path_.str();
	}

	return "." + path_.str();
}

IPropertyPath::Type PropertyPath::getType() const
{
	return IPropertyPath::TYPE_PROPERTY;
}

CollectionPath::CollectionPath(
	IPropertyPath::ConstPtr & parent, const char * path)
	: PropertyPath( parent, path )
{
}

IPropertyPath::ConstPtr CollectionPath::generateChildPath(IPropertyPath::ConstPtr & self, Variant & key) const
{
	TF_ASSERT(self.get() == this);
	IPropertyPath::ConstPtr ptr( new CollectionChildPath(self, key));
	return ptr;
}

IPropertyPath::Type CollectionPath::getType() const
{
	return IPropertyPath::TYPE_COLLECTION;
}

CollectionChildPath::CollectionChildPath(
	IPropertyPath::ConstPtr & parent, Variant & key)
	: BasePropertyPath( parent )
{
	size_t indexKey = 0;
	if (key.tryCast(indexKey))
	{
		path_ += std::to_string(indexKey);
	}
	else
	{
		key.tryCast(path_);
	}
	postConstruct();
}

std::string CollectionChildPath::generateDecoratedPath() const
{
	return Collection::getIndexOpen() + path_.str() + Collection::getIndexClose();
}

IPropertyPath::Type CollectionChildPath::getType() const
{
	return IPropertyPath::TYPE_COLLECTION_ITEM;
}

}


text:
import React from 'react';
import { shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';
import { LevelLeft } from '../LevelLeft';

describe('<LevelLeft />', () => {
  it('should render a div with .boldrui-level__left', () => {
    const component = shallow(<LevelLeft>My LevelLeft</LevelLeft>);
    expect(component.contains(
My LevelLeft
)).toBe(true);
  });

  it('should render an aside with .boldrui-level__left', () => {
    const component = shallow(<LevelLeft tag="aside">My LevelLeft</LevelLeft>);
    expect(component.contains(My LevelLeft)).toBe(
      true,
    );
  });

  it('should render a div with .boldrui-level__left and custom classNames', () => {
    const component = shallow(
      <LevelLeft className="custom">
        Any Content
      </LevelLeft>,
    );
    expect(component.hasClass('boldrui-level__left')).toBe(true);
    expect(component.hasClass('custom')).toBe(true);
  });
  it('should match the snapshot', () => {
    const wrapper = shallow(<LevelLeft>My LevelLeft</LevelLeft>);
    expect(shallowToJson(wrapper)).toMatchSnapshot();
  });
});


text:
<?php

namespace Hail\Http\Matcher;

use Psr\Http\Message\RequestInterface;

class Schemes implements MatcherInterface
{
    use NegativeResultTrait;

    private $schemes = [];

    /**
     * @param string|array $schemes
     */
    public function __construct($schemes)
    {
        $schemes = (array) $schemes;

        foreach ($schemes as $scheme) {
            $this->schemes[\strtolower($this->getValue($scheme))] = $this->result;
        }
    }

    /**
     * {@inheritdoc}
     */
    public function matches(RequestInterface $request): bool
    {
        $scheme = $request->getUri()->getScheme();

        $match = true;

        foreach ($this->schemes as $check => $result) {
            $match = $match && ($scheme === $check) === $result;
        }

        return $match;
    }
}


text:
import React from 'react'
import { Progress } from '../../../'

export default () => <Progress indeterminate width="300px" />


text:
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta charset="utf-8"/>
    <title>     » \phing.tasks.ext.simpletest
</title>
    <meta name="author" content=""/>
    <meta name="description" content=""/>

            <link href="../css/template.css" rel="stylesheet" media="all"/>

            <link rel="shortcut icon" href="../img/favicon.ico"/>
        <link rel="apple-touch-icon" href="../img/apple-touch-icon.png"/>
        <link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png"/>
        <link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png"/>

                Phing API Documentation

                                API Documentation

                                Charts

                                         Class hierarchy diagram

                                Reports

                                         Errors

                                         Markers

                                         Deprecated

            Back to top

                Javascript is disabled; several features are only available if Javascript is enabled.

                <button class="btn details" title="Show descriptions and method names">
                    </button><button class="btn simple" title="Show only method names">

                </button>

                     Packages

                     phing.tasks.ext.simpletest

        \phing.tasks.ext.simpletest

 Classes, interfaces and traits

SimpleTestCountResultFormatter¶

Dummy result formatter used to count SimpleTest results

        « More »

SimpleTestDebugResultFormatter¶

Prints plain text output of the test to a specified Writer.

        « More »

SimpleTestFormatterElement¶

Child class of "FormatterElement", overrides setType to provide other
formatter classes for SimpleTest

        « More »

SimpleTestPlainResultFormatter¶

Prints plain text output of the test to a specified Writer.

        « More »

SimpleTestResultFormatter¶

This abstract class describes classes that format the results of a SimpleTest testrun.

        « More »

SimpleTestSummaryResultFormatter¶

Prints short summary output of the test to Phing's logging system.

        « More »

SimpleTestTask¶

Runs SimpleTest tests.

Use \Project#createTask to register a new Task.

        « More »

SimpleTestXmlResultFormatter¶

Prints plain text output of the test to a specified Writer.

        « More »

            Template is built using Twitter Bootstrap 2 and icons provided by
            Glyphicons.

            Documentation is powered by phpDocumentor  and

            generated on Thu, 13 Oct 2016 11:14:49 +0200.


text:
package net.ssehub.easy.producer.ui.internal;

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

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;

import net.ssehub.easy.basics.logger.EASyLoggerFactory;
import net.ssehub.easy.instantiation.core.model.execution.Executor;
import net.ssehub.easy.producer.core.mgmt.PLPInfo;
import net.ssehub.easy.producer.core.mgmt.VilArgumentProvider;
import net.ssehub.easy.producer.eclipse.persistency.eclipse.PersistenceUtils;

/**
 * A parameter provider which adds the project's classpath as a given parameter name to the
 * main VIL call. This class shall be somewhere in the Eclipse part of EASy, not in the standalone
 * part.
 *
 * @author Holger Eichelberger
 */
public class VilClasspathProvider extends VilArgumentProvider {

    private String paramName;

    /**
     * Creates a VIL classpath provider.
     *
     * @param paramName the parameter name to be provided
     */
    public VilClasspathProvider(String paramName) {
        this.paramName = paramName;
    }

    @Override
    protected void provideArgumentsImpl(PLPInfo plp, Executor executor) {
        List<String> classpath = null;
        IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(plp.getProjectName());
        if (null != project) {
            IJavaProject jProject = JavaCore.create(project);
            if (null != jProject) {
                try {
                    classpath = new ArrayList<String>();
                    IClasspathEntry[] entries = jProject.getResolvedClasspath(true);
                    for (int e = 0; e < entries.length; e++) {
                        IClasspathEntry entry = entries[e];
                        if (IClasspathEntry.CPE_LIBRARY == entry.getEntryKind()
                            || IClasspathEntry.CPE_SOURCE == entry.getEntryKind()
                            || IClasspathEntry.CPE_VARIABLE == entry.getEntryKind()) { // project -> recursive?
                            IPath path = PersistenceUtils.makeWsPathAbsolute(entry.getPath());
                            classpath.add(path.toString());
                        }
                    }
                } catch (JavaModelException e) {
                    EASyLoggerFactory.INSTANCE.getLogger(VilClasspathProvider.class, Activator.PLUGIN_ID).exception(e);
                }
            }
        }
        if (null != classpath) {
            executor.addCustomArgument(paramName, classpath);
        }
    }

    @Override
    public String getParameterName() {
        return paramName;
    }

    @Override
    public String getParameterType() {
        return "sequenceOf(String)";
    }

    @Override
    public String getName() {
        return "Java classpath";
    }

    @Override
    public boolean acceptsFreeArguments() {
        return false;
    }

    @Override
    public String getFreeArguments() {
        return null;
    }

    @Override
    public void setFreeArguments(String arguments) {
    }

}


text:
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sysdep-cancel.h>

/* Wait for pending output to be written on FD.  */
int
__libc_tcdrain (int fd)
{
  if (SINGLE_THREAD_P)
    /* With an argument of 1, TCSBRK for output to be drain.  */
    return INLINE_SYSCALL (ioctl, 3, fd, TCSBRK, 1);

  int oldtype = LIBC_CANCEL_ASYNC ();

  /* With an argument of 1, TCSBRK for output to be drain.  */
  int result = INLINE_SYSCALL (ioctl, 3, fd, TCSBRK, 1);

  LIBC_CANCEL_RESET (oldtype);

  return result;
}
weak_alias (__libc_tcdrain, tcdrain)


text:
from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl

"""Track named groups of cells in a worksheet"""

# Python stdlib imports
import re
import warnings

# package imports
from openpyxl.utils import absolute_coordinate
from openpyxl.compat import unicode
from openpyxl.utils.exceptions import NamedRangeException
from openpyxl.xml.functions import fromstring, safe_iterator
from openpyxl.xml.constants import SHEET_MAIN_NS

# constants
NAMED_RANGE_RE = re.compile("""
^(('(?P<quoted>([^']|'')*)')|(?P<notquoted>[^']*))
!(?P<range>(\$([A-Za-z]+))?(\$([0-9]+))?(:(\$([A-Za-z]+))?(\$([0-9]+))?)?)""", re.VERBOSE)
SPLIT_NAMED_RANGE_RE = re.compile(r"((?:[^,']|'(?:[^']|'')*')+)")
EXTERNAL_RE = re.compile(r"(?P<external>\[\d+\])?(?P<range_string>.*)")
FORMULA_REGEX = re.compile(r"^[a-zA-Z]+[(]+.*[)]$")
DISCARDED_RANGES = re.compile("^[_xnlm.]")

class NamedValue(object):
    """A named value"""
    __slots__ = ('name', 'value', 'scope')

    def __init__(self, name, value):
        self.name = name
        self.value = value
        self.scope = None

    @property
    def localSheetId(self):
        return self.scope

    def __repr__(self):
        return u'<{0} "{1}">'.format(self.__class__.__name__, self.value)

    def __iter__(self):
        for attr in ('name', 'localSheetId'):
            value = getattr(self, attr, None)
            if value is not None:
                yield attr, value

#backwards compatibility
NamedRangeContainingValue = NamedValue

class NamedRange(NamedValue):
    """A named group of cells

    Scope is a worksheet object or None for workbook scope names (the default)
    """
    __slots__ = ('name', 'destinations', 'scope')

    str_format = unicode('%s!%s')
    repr_format = unicode('<%s "%s">')

    def __init__(self, name, destinations, scope=None):
        self.name = name
        self.destinations = destinations
        self.scope = scope

    @property
    def value(self):
        dest_cells = []
        for ws, xlrange in self.destinations:
            dest_cells.append("'%s'!%s" % (ws.title.replace("'", "''"),
                                       absolute_coordinate(xlrange)))
        return ",".join(dest_cells)

    def __str__(self):
        return  ','.join([self.str_format % (sheet, name) for sheet, name in self.destinations])

    def __repr__(self):
        return  self.repr_format % (self.__class__.__name__, str(self))

def split_named_range(range_string):
    """Separate a named range into its component parts"""

    for range_string in SPLIT_NAMED_RANGE_RE.split(range_string)[1::2]: # Skip first and from there every second item

        match = NAMED_RANGE_RE.match(range_string)
        if match is None:
            raise NamedRangeException('Invalid named range string: "%s"' % range_string)
        else:
            match = match.groupdict()
            sheet_name = match['quoted'] or match['notquoted']
            xlrange = match['range']
            sheet_name = sheet_name.replace("''", "'") # Unescape '
            yield sheet_name, xlrange

def refers_to_range(range_string):
    if FORMULA_REGEX.match(range_string):
        return
    if range_string:
        return NAMED_RANGE_RE.match(range_string) is not None

def external_range(range_string):
    m = EXTERNAL_RE.match(range_string)
    if m is not None:
        return m.group('external') is not None

def read_named_ranges(xml_source, workbook):
    """Read named ranges, excluding poorly defined ranges."""
    sheetnames = set(sheet.title for sheet in workbook.worksheets)
    root = fromstring(xml_source)
    for name_node in safe_iterator(root, '{%s}definedName' %SHEET_MAIN_NS):

        range_name = name_node.get('name')
        if DISCARDED_RANGES.match(range_name):
            warnings.warn("Discarded range with reserved name")
            continue

        node_text = name_node.text

        if external_range(node_text):
            # treat names referring to external workbooks as values
            named_range = NamedValue(range_name, node_text)

        elif refers_to_range(node_text):
            destinations = split_named_range(node_text)
            # it can happen that a valid named range references
            # a missing worksheet, when Excel didn't properly maintain
            # the named range list
            destinations = [(workbook[sheet], cells) for sheet, cells in destinations
                            if sheet in sheetnames]
            if not destinations:
                continue
            named_range = NamedRange(range_name, destinations)
        else:
            named_range = NamedValue(range_name, node_text)

        named_range.scope = name_node.get("localSheetId")

        yield named_range


text:
import sys

try:
    # Our match_hostname function is the same as 3.5's, so we only want to
    # import the match_hostname function if it's at least that good.
    if sys.version_info < (3, 5):
        raise ImportError("Fallback to vendored code")

    from ssl import CertificateError, match_hostname
except ImportError:
    try:
        # Backport of the function from a pypi module
        from backports.ssl_match_hostname import CertificateError, match_hostname
    except ImportError:
        # Our vendored copy
        from ._implementation import CertificateError, match_hostname

# Not needed, but documenting what we provide.
__all__ = ('CertificateError', 'match_hostname')


text:
- [Introduction](#introduction)
  - [Contributing](#contributing)
  - [Issues](#issues)
- [Getting started](#getting-started)
  - [Installation](#installation)
  - [Quickstart](#quickstart)
  - [Command-line arguments](#command-line-arguments)
  - [Persistence](#persistence)
- [Maintenance](#maintenance)
  - [Upgrading](#upgrading)
  - [Shell Access](#shell-access)

# Introduction

`Dockerfile` to create a [Docker](https://www.docker.com/) container image for [BIND](https://www.isc.org/downloads/bind/) DNS server bundled with the [Webmin](http://www.webmin.com/) interface.

BIND is open source software that implements the Domain Name System (DNS) protocols for the Internet. It is a reference implementation of those protocols, but it is also production-grade software, suitable for use in high-volume and high-reliability applications.

## Contributing

If you find this image useful here's how you can help:

- Send a pull request with your awesome features and bug fixes
- Help users resolve their [issues](../../issues?q=is%3Aopen+is%3Aissue).
- Support the development of this image with a [donation](http://www.damagehead.com/donate/)

## Issues

Before reporting your issue please try updating Docker to the latest version and check if it resolves the issue. Refer to the Docker [installation guide](https://docs.docker.com/installation) for instructions.

SELinux users should try disabling SELinux using the command `setenforce 0` to see if it resolves the issue.

If the above recommendations do not help then [report your issue](../../issues/new) along with the following information:

- Output of the `docker version` and `docker info` commands
- The `docker run` command or `docker-compose.yml` used to start the image. Mask out the sensitive bits.
- Please state if you are using [Boot2Docker](http://www.boot2docker.io), [VirtualBox](https://www.virtualbox.org), etc.

# Getting started

## Installation

This image is available as a [trusted build](//hub.docker.com/r/erikaulin/bind) on the [Docker hub](//hub.docker.com) and is the recommended method of installation.

```bash
docker pull sameersbn/bind:latest
```

Alternatively you can build the image yourself.

```bash
git clone https://github.com/erikaulin/docker-bind.git
cd docker-bind
docker build --tag $USER/bind .
```

## Quickstart

Start BIND using:

```bash
docker run --name bind -d --restart=always \
  --publish 53:53/udp --publish 10000:10000 \
  --volume /srv/docker/bind:/data \
  sameersbn/bind:latest
```

*Alternatively, you can use the sample [docker-compose.yml](docker-compose.yml) file to start the container using [Docker Compose](https://docs.docker.com/compose/)*

When the container is started the [Webmin](http://www.webmin.com/) service is also started and is accessible from the web browser at http://localhost:10000. Login to Webmin with the username `root` and password `password`. Specify `--env ROOT_PASSWORD=secretpassword` on the `docker run` command to set a password of your choosing.

The launch of Webmin can be disabled by adding `--env WEBMIN_ENABLED=false` to the `docker run` command. Note that the `ROOT_PASSWORD` parameter has no effect when the launch of Webmin is disabled.

Read the blog post original creator [Deploying a DNS Server using Docker](http://www.damagehead.com/blog/2015/04/28/deploying-a-dns-server-using-docker/) for an example use case.

## Command-line arguments

You can customize the launch command of BIND server by specifying arguments to `named` on the `docker run` command. For example the following command prints the help menu of `named` command:

```bash
docker run --name bind -it --rm \
  --publish 53:53/udp --publish 10000:10000 \
  --volume /srv/docker/bind:/data \
  sameersbn/bind:latest -h
```

## Persistence

For the BIND to preserve its state across container shutdown and startup you should mount a volume at `/data`.

> *The [Quickstart](#quickstart) command already mounts a volume for persistence.*

SELinux users should update the security context of the host mountpoint so that it plays nicely with Docker:

```bash
mkdir -p /srv/docker/bind
chcon -Rt svirt_sandbox_file_t /srv/docker/bind
```

# Maintenance

## Upgrading

To upgrade to newer releases:

  1. Download the updated Docker image:

  ```bash
  docker pull sameersbn/bind:latest
  ```

  2. Stop the currently running image:

  ```bash
  docker stop bind
  ```

  3. Remove the stopped container

  ```bash
  docker rm -v bind
  ```

  4. Start the updated image

  ```bash
  docker run -name bind -d \
    [OPTIONS] \
    sameersbn/bind:latest
  ```

## Shell Access

For debugging and maintenance purposes you may want access the containers shell. If you are using Docker version `1.3.0` or higher you can access a running containers shell by starting `bash` using `docker exec`:

```bash
docker exec -it bind bash
```


text:
<?php

class Yoast_GA_Custom_Definitions {

	/**
	 * Property for holding instance of itself
	 *
	 * @var __CLASS__
	 */
	protected static $instance;

	/**
	 * Fetches the Singleton object
	 *
	 * @param string $class_name
	 *
	 * @return Yoast_GA_Admin_Custom_Dimensions
	 */
	public static function get_instance( $class_name = __CLASS__ ) {
		if ( is_null( self::$instance ) ) {
			self::$instance = new $class_name();
		}

		return self::$instance;
	}

	/**
	 * Fetches the options
	 */
	protected function get_options() {
		return Yoast_GA_Options::instance()->get_options();
	}

	/**
	 * Fetches an option from the options
	 *
	 * @param string $key     Used for the option to be fetched
	 * @param Mixed  $default Default return value
	 *
	 * @return Mixed
	 */
	public function get_option( $key, $default = null ) {
		$options = $this->get_options();

		return ( array_key_exists( $key, $options ) ? $options[$key] : $default );
	}

	/**
	 * Wrapper to enable stubbing in tests.
	 */
	protected function wp_seo_active() {
		return Yoast_GA_Utils::wp_seo_active();
	}
}


text:
function(execute)
  set(args ${ARGN})
  list_extract_flag(args --lean)
  ans(lean)

  arguments_encoded_list(0 ${ARGC})
  ans(args)

  list_extract_flag(args --process-handle)
  ans(return_handle)
  list_extract_flag(args --exit-code)
  ans(return_exit_code)
  list_extract_flag(args --async)
  ans(async)
  #list_extract_flag(args --async-wait)
  #ans(wait)
  #if(wait)
  #  set(async true)
  #endif()
  list_extract_flag(args --silent-fail)
  ans(silent_fail)

  list_extract_labelled_value(args --success-callback)
  ans(success_callback)
  list_extract_labelled_value(args --error-callback)
  ans(error_callback)
  list_extract_labelled_value(args --state-changed-callback)
  ans(process_callback)
  list_extract_labelled_value(args --on-terminated-callback)
  ans(terminated_callback)
  if(NOT args)
    messagE(FATAL_ERROR "no command specified")
  endif()

  process_start_info_new(${args})
  ans(start_info)

##debug here
  #print_vars(start_info.command start_info.command_arguments)

  process_handle_new(${start_info})
  ans(process_handle)

  if(success_callback)
    string_decode_list("${success_callback}")
    ans(success_callback)
    assign(success = process_handle.on_success.add("${success_callback}"))
  endif()
  if(error_callback)
    string_decode_list("${error_callback}")
    ans(error_callback)
    assign(success = process_handle.on_error.add("${error_callback}"))
  endif()
  if(process_callback)
    string_decode_list("${process_callback}")
    ans(process_callback)
    assign(success = process_handle.on_state_change.add("${process_callback}"))
  endif()
  if(terminated_callback)
    string_decode_list("${terminated_callback}")
    ans(terminated_callback)
    assign(success = process_handle.on_terminated.add("${terminated_callback}"))
  endif()

  if(async)
    process_start(${process_handle})
    return(${process_handle})
  else()
    process_execute(${process_handle})
    if(return_handle)
      return(${process_handle})
    endif()

    map_tryget(${process_handle} exit_code)
    ans(exit_code)

    if(return_exit_code)
      return_ref(exit_code)
    endif()

    map_tryget(${process_handle} pid)
    ans(pid)
    if(NOT pid)
      message(FATAL_ERROR FORMAT "could not find command '{start_info.command}'")
    endif()

    if(exit_code AND silent_fail)
      error("process {start_info.command} failed with {process_handle.exit_code}")
      return()
    endif()

    if(exit_code)
      message(FATAL_ERROR FORMAT "process {start_info.command} failed with {process_handle.exit_code}")
    endif()

    map_tryget(${process_handle} stdout)
    ans(stdout)
    return_ref(stdout)

  endif()

endfunction()


text:
/**
 * Provide a namespace for this class
 */
goog.provide('gva.component.BaseComponent');

goog.require('goog.events.EventTarget');

/**
 * Creates a new BaseComponent instance
 * @constructor
 */
gva.component.BaseComponent = function() {
    this.$context = null;
    this.initialized = false;
};
goog.inherits(gva.component.BaseComponent, goog.events.EventTarget);

/**
 * Initializes the component with a given context
 * @param {Element} $context The context or view for this component.
 */
gva.component.BaseComponent.prototype.initialize = function($context) {
    if (!this.initialized) {
        this.initialized = true;
        this.$context = $context;
    }
};


text:
package org.apache.camel.component.jt400;

import java.util.HashMap;

import org.apache.camel.CamelException;
import org.apache.camel.Endpoint;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Test case for {@link Jt400Component}
 */
@SuppressWarnings("unchecked")
public class Jt400ComponentTest extends Assert {

    private Jt400Component component;

    @Before
    public void setUp() throws Exception {
        component = new Jt400Component();
    }

    /**
     * Test creation of a {@link Jt400DataQueueEndpoint}
     */
    @Test
    public void testCreateEndpoint() throws Exception {
        Endpoint endpoint = component
            .createEndpoint("jt400://user:password@host/qsys.lib/library.lib/queue.dtaq",
                            "/user:password@host/qsys.lib/library.lib/queue.dtaq", new HashMap());
        assertNotNull(endpoint);
        assertTrue(endpoint instanceof Jt400DataQueueEndpoint);
    }

    /**
     * Test exception when trying to access any other object type on AS/400
     */
    @Test
    public void testCreateEndpointForOtherObjectType() throws Exception {
        try {
            component.createEndpoint("jt400://user:password@host/qsys.lib/library.lib/program.pgm",
                                     "/user:password@host/qsys.lib/library.lib/program.pgm", new HashMap());
            fail("Exception should been thrown when trying to create an endpoint for an unsupported object type");
        } catch (CamelException e) {
            // this is just what we expected
        }
    }

}


text:
DiscreteStateWindow::DiscreteStateWindow(const QVector<CANFrame> *frames, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DiscreteStateWindow)
{
    ui->setupUi(this);
    setWindowFlags(Qt::Window);

    modelFrames = frames;
    operatingState = DWStates::IDLE;

    timer = new QTimer();
    timer->setInterval(100);

    isRealtime = ui->rbRealtime->isChecked();
    typeChanged();

    connect(ui->btnStart, SIGNAL(clicked(bool)), this, SLOT(handleStartButton()));
    connect(timer, SIGNAL(timeout()), this, SLOT(handleTick()));
    connect(MainWindow::getReference(), SIGNAL(framesUpdated(int)), this, SLOT(updatedFrames(int)));
    connect(ui->rbLogged, SIGNAL(clicked(bool)), this, SLOT(typeChanged()));
    connect(ui->rbRealtime, SIGNAL(clicked(bool)), this, SLOT(typeChanged()));

    connect(ui->btnAll, &QAbstractButton::clicked,
            [=]()
            {
                for (int i = 0; i < ui->listID->count(); i++)
                {
                    QListWidgetItem *item = ui->listID->item(i);
                    item->setCheckState(Qt::Checked);
                    idFilters[Utility::ParseStringToNum(item->text())] = true;
                }
            });

    connect(ui->btnNone, &QAbstractButton::clicked,
            [=]()
            {
                for (int i = 0; i < ui->listID->count(); i++)
                {
                    QListWidgetItem *item = ui->listID->item(i);
                    item->setCheckState(Qt::Unchecked);
                    idFilters[Utility::ParseStringToNum(item->text())] = false;
                }
            });

    connect(ui->listID, &QListWidget::itemChanged,
            [=](QListWidgetItem *item)
            {
                bool isChecked = false;
                int id = Utility::ParseStringToNum(item->text());
                if (item->checkState() == Qt::Checked) isChecked = true;
                idFilters[id] = isChecked;
            });

    refreshFilterList();
    installEventFilter(this);
}

DiscreteStateWindow::~DiscreteStateWindow()
{
    removeEventFilter(this);
    timer->stop();

    for (int i = 0; i < stateFrames.count(); i++)
    {
        stateFrames[i]->clear();
        delete(stateFrames[i]);
    }

    delete timer;
    delete ui;
}

bool DiscreteStateWindow::eventFilter(QObject *obj, QEvent *event)
{
    if (event->type() == QEvent::KeyRelease) {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
        switch (keyEvent->key())
        {
        case Qt::Key_F1:
            HelpWindow::getRef()->showHelp("discretestate.md");
            break;
        }
        return true;
    } else {
        // standard event processing
        return QObject::eventFilter(obj, event);
    }
    return false;
}

void DiscreteStateWindow::typeChanged()
{
    if (ui->rbLogged->isChecked())
    {
        ui->spinFreq->setEnabled(false);
        ui->spinIterations->setEnabled(false);
        ui->lblStatus->setEnabled(false);
        ui->spinMaxBits->setEnabled(true);
        ui->spinMinBits->setEnabled(true);
        ui->listID->setEnabled(true);
        ui->btnAll->setEnabled(true);
        ui->btnNone->setEnabled(true);
        isRealtime = false;
    }
    else
    {
        ui->spinFreq->setEnabled(true);
        ui->spinIterations->setEnabled(true);
        ui->lblStatus->setEnabled(true);
        ui->spinMaxBits->setEnabled(false);
        ui->spinMinBits->setEnabled(false);
        ui->listID->setEnabled(false);
        ui->btnAll->setEnabled(false);
        ui->btnNone->setEnabled(false);
        isRealtime = true;
    }
}

void DiscreteStateWindow::updatedFrames(int numFrames)
{
    CANFrame thisFrame;
    if (numFrames == -1) //all frames deleted. Kill the display
    {
        ui->listID->clear();
        idFilters.clear();
    }
    else if (numFrames == -2) //all new set of frames. Reset
    {
        refreshFilterList();
    }
    else //just got some new frames. See if they are relevant.
    {
        if (numFrames > modelFrames->count()) return;
        for (int i = modelFrames->count() - numFrames; i < modelFrames->count(); i++)
        {
            thisFrame = modelFrames->at(i);

            if (!idFilters.contains(thisFrame.frameId()))
            {
                idFilters.insert(thisFrame.frameId(), true);
                QListWidgetItem* listItem = new QListWidgetItem(Utility::formatCANID(thisFrame.frameId(), thisFrame.hasExtendedFrameFormat()), ui->listID);
                listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable); // set checkable flag
                listItem->setCheckState(Qt::Checked); //default all filters to be set active
            }

            //if (operatingState == DWStates::IDLE) stateFrames[0]->append(thisFrame);
            //else stateFrames[currToggleState + 1]->append(thisFrame);
        }
    }
}

void DiscreteStateWindow::refreshFilterList()
{
    int id;

    idFilters.clear();
    ui->listID->clear();

    for (int i = 0; i < modelFrames->length(); i++)
    {
        CANFrame thisFrame = modelFrames->at(i);
        id = thisFrame.frameId();
        if (!idFilters.contains(id))
        {
            idFilters.insert(id, true);
            QListWidgetItem* listItem = new QListWidgetItem(Utility::formatCANID(id, thisFrame.hasExtendedFrameFormat()), ui->listID);
            listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable); // set checkable flag
            listItem->setCheckState(Qt::Checked); //default all filters to be set active
        }
    }

    ui->listID->sortItems();
}

void DiscreteStateWindow::showEvent(QShowEvent* event)
{
    QDialog::showEvent(event);

    readSettings();

    qDebug() << "DiscreteState show event was processed";
}

void DiscreteStateWindow::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    writeSettings();
}

void DiscreteStateWindow::readSettings()
{
    QSettings settings;
    if (settings.value("Main/SaveRestorePositions", false).toBool())
    {
        resize(settings.value("DiscreteState/WindowSize", QSize(400, 300)).toSize());
        move(Utility::constrainedWindowPos(settings.value("DiscreteState/WindowPos", QPoint(50, 50)).toPoint()));
    }

}

void DiscreteStateWindow::writeSettings()
{
    QSettings settings;

    if (settings.value("Main/SaveRestorePositions", false).toBool())
    {
        settings.setValue("DiscreteState/WindowSize", size());
        settings.setValue("DiscreteState/WindowPos", pos());
    }
}

void DiscreteStateWindow::updateStateLabel()
{
    QPalette pal;
    switch(operatingState)
    {
    case DWStates::IDLE:
        ui->lblStatus->setText("IDLE");
        pal = ui->lblStatus->palette();
        pal.setColor(QPalette::WindowText, Qt::red);
        ui->lblStatus->setPalette(pal);
        break;
    case DWStates::COUNTDOWN_SIGNAL:
        ui->lblStatus->setText(QString::number(ticksUntilStateChange * 0.1, 'f', 1) + "...");
        pal = ui->lblStatus->palette();
        pal.setColor(QPalette::WindowText, Qt::blue);
        ui->lblStatus->setPalette(pal);
        break;
    case DWStates::COUNTDOWN_WAITING:
        ui->lblStatus->setText("Wait....");
        pal = ui->lblStatus->palette();
        pal.setColor(QPalette::WindowText, Qt::red);
        ui->lblStatus->setPalette(pal);
        break;
    case DWStates::GETTING_SIGNAL:
        ui->lblStatus->setText("Go to state " + QString::number(currToggleState + 1));
        pal = ui->lblStatus->palette();
        pal.setColor(QPalette::WindowText, Qt::green);
        ui->lblStatus->setPalette(pal);
        break;
    case DWStates::DONE:
        ui->lblStatus->setText("DONE");
        pal = ui->lblStatus->palette();
        pal.setColor(QPalette::WindowText, Qt::green);
        ui->lblStatus->setPalette(pal);
        break;
    }
}

void DiscreteStateWindow::handleStartButton()
{
    if (isRealtime)
    {
        operatingState = DWStates::COUNTDOWN_SIGNAL;

        ticksPerStateChange = ticksUntilStateChange = ui->spinFreq->value() * 10;
        numToggleStates = ui->spinStates->value();
        numIterations = ui->spinIterations->value();

        currToggleState = 0;
        currIteration = 0;

        for (int i = stateFrames.count() - 1; i > 0; i--)
        {
            stateFrames[i]->clear();
            stateFrames.removeAt(i);
        }

        for (int j = 0; j <= numToggleStates; j++)
        {
            stateFrames.append(new QVector<CANFrame>());
        }

        timer->start();
    }
    else
    {
        calculateResults();
    }
}

void DiscreteStateWindow::handleTick()
{
    switch (operatingState)
    {
    case DWStates::IDLE:
        break;
    case DWStates::DONE:
        break;
    case DWStates::COUNTDOWN_SIGNAL:
        ticksUntilStateChange--;
        if (ticksUntilStateChange == 0)
        {
            ticksUntilStateChange = ticksPerStateChange;
            operatingState = DWStates::GETTING_SIGNAL;
        }
        break;
    case DWStates::COUNTDOWN_WAITING:
        ticksUntilStateChange--;
        if (ticksUntilStateChange == 0)
        {
            ticksUntilStateChange = ticksPerStateChange;
            currIteration++;
            if (currIteration > numIterations)
            {
                operatingState = DWStates::IDLE;
                timer->stop();
                calculateResults();
            }
            else operatingState = DWStates::COUNTDOWN_SIGNAL;
        }
        break;
    case DWStates::GETTING_SIGNAL:
        ticksUntilStateChange--;
        if (ticksUntilStateChange == 0)
        {
            ticksUntilStateChange = ticksPerStateChange;
            operatingState = DWStates::COUNTDOWN_WAITING;
            currToggleState++;
            if (currToggleState > numToggleStates) currToggleState = 0;
        }
        break;
    }
    updateStateLabel();
}

void DiscreteStateWindow::calculateResults()
{
    int minBits, maxBits;
    if (isRealtime)
    {

    }
    else //use already loaded frames from main cache
    {
        //basic overview: run through all ID filters and see if it is enabled.
        //If so add it to a giant list of messages by ID where each ID has its own
        //list of messages
        //Then, for each ID start a loop that runs from largest bits to smallest bits for scan
        //For each value run through the algorithm for all messages. At the end list any matches
        //the simplest approach seems to be to grab that number of bits and then record every
        //unique value. IF the # of unique values is the same as the number of states then
        //we've got a match.It should be noted that the # of states must be at least 2 - the idle
        //state is 1 and then a second state at the minimum. Turn signals might be 3 states then

        minBits = ui->spinMinBits->value();
        maxBits = ui->spinMaxBits->value();
        QHash<int, bool>::const_iterator it;
        QList<CANFrame> frameCache;
        for (it = idFilters.begin(); it != idFilters.end(); ++it)
        {
            if (it.value())
            {
                frameCache.clear();
                for (int i = 0; i < modelFrames->count(); i++)
                {
                    if (modelFrames->at(i).frameId() == (unsigned int)it.key()) frameCache.append(modelFrames->at(i));
                }
                for (int bits = maxBits; bits >= minBits; bits--)
                {
                    QList<int> values;
                }
            }
        }
    }
}


text:
<bolt-text>
  When your customers' billing issues are resolved quickly, you see results. Think higher customer satisfaction, fewer repeat calls, and lower average handle time (AHT).
</bolt-text>
<bolt-cta>
  <bolt-animate slot="link">
    <bolt-text font-size="xsmall" display="inline">
      Find out how Cisco cut AHT in half
      <bolt-icon name="chevron-right"></bolt-icon>
    </bolt-text>
  </bolt-animate>
</bolt-cta>


text:
module ActiveScaffold::Actions
  module FieldSearch
    include ActiveScaffold::Actions::CommonSearch
    def self.included(base)
      base.before_filter :search_authorized_filter, :only => :show_search
      base.before_filter :store_search_params_into_session, :only => [:list, :index]
      base.before_filter :do_search, :only => [:list, :index]
      base.helper_method :field_search_params
    end

    # FieldSearch uses params[:search] and not @record because search conditions do not always pass the Model's validations.
    # This facilitates for example, textual searches against associations via .search_sql
    def show_search
      @record = active_scaffold_config.model.new
      respond_to_action(:field_search)
    end

    protected
    def field_search_params
      search_params || {}
    end

    def field_search_respond_to_html
      render(:action => "field_search")
    end

    def field_search_respond_to_js
      render(:partial => "field_search")
    end

    def do_search
      unless search_params.blank?
        text_search = active_scaffold_config.field_search.text_search
        search_conditions = []
        columns = active_scaffold_config.field_search.columns
        search_params.each do |key, value|
          next unless columns.include? key
          search_conditions << self.class.condition_for_column(active_scaffold_config.columns[key], value, text_search)
        end
        search_conditions.compact!
        self.active_scaffold_conditions = merge_conditions(self.active_scaffold_conditions, *search_conditions)
        @filtered = !search_conditions.blank?

        includes_for_search_columns = columns.collect{ |column| column.includes}.flatten.uniq.compact
        self.active_scaffold_includes.concat includes_for_search_columns

        active_scaffold_config.list.user.page = nil
      end
    end

    private
    def search_authorized_filter
      link = active_scaffold_config.field_search.link || active_scaffold_config.field_search.class.link
      raise ActiveScaffold::ActionNotAllowed unless self.send(link.security_method)
    end
    def field_search_formats
      (default_formats + active_scaffold_config.formats + active_scaffold_config.field_search.formats).uniq
    end
  end
end


text:
using System.IO;
using System.Threading.Tasks;
using Tweetinvi.Core.Controllers;
using Tweetinvi.Core.Iterators;
using Tweetinvi.Core.Web;
using Tweetinvi.Models;
using Tweetinvi.Models.DTO;
using Tweetinvi.Models.DTO.QueryDTO;
using Tweetinvi.Parameters;

namespace Tweetinvi.Controllers.User
{
    public class UserController : IUserController
    {
        private readonly IUserQueryExecutor _userQueryExecutor;

        public UserController(IUserQueryExecutor userQueryExecutor)
        {
            _userQueryExecutor = userQueryExecutor;
        }

        public Task<ITwitterResult<IUserDTO>> GetAuthenticatedUserAsync(IGetAuthenticatedUserParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.GetAuthenticatedUserAsync(parameters, request);
        }

        public Task<ITwitterResult<IUserDTO>> GetUserAsync(IGetUserParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.GetUserAsync(parameters, request);
        }

        public Task<ITwitterResult<IUserDTO[]>> GetUsersAsync(IGetUsersParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.GetUsersAsync(parameters, request);
        }

        // Friend Ids
        public ITwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>> GetFriendIdsIterator(IGetFriendIdsParameters parameters, ITwitterRequest request)
        {
            var twitterCursorResult = new TwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>>(
                parameters.Cursor,
                cursor =>
                {
                    var cursoredParameters = new GetFriendIdsParameters(parameters)
                    {
                        Cursor = cursor
                    };

                    return _userQueryExecutor.GetFriendIdsAsync(cursoredParameters, new TwitterRequest(request));
                },
                page => page.Model.NextCursorStr,
                page => page.Model.NextCursorStr == "0");

            return twitterCursorResult;
        }

        public ITwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>> GetFollowerIdsIterator(IGetFollowerIdsParameters parameters, ITwitterRequest request)
        {
            var twitterCursorResult = new TwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>>(
                parameters.Cursor,
                cursor =>
                {
                    var cursoredParameters = new GetFollowerIdsParameters(parameters)
                    {
                        Cursor = cursor
                    };

                    return _userQueryExecutor.GetFollowerIdsAsync(cursoredParameters, new TwitterRequest(request));
                },
                page => page.Model.NextCursorStr,
                page => page.Model.NextCursorStr == "0");

            return twitterCursorResult;
        }

        public Task<ITwitterResult<IRelationshipDetailsDTO>> GetRelationshipBetweenAsync(IGetRelationshipBetweenParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.GetRelationshipBetweenAsync(parameters, request);
        }

        // Profile Image
        public Task<Stream> GetProfileImageStreamAsync(IGetProfileImageParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.GetProfileImageStreamAsync(parameters, request);
        }

        // FOLLOW/UNFOLLOW
        public Task<ITwitterResult<IUserDTO>> FollowUserAsync(IFollowUserParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.FollowUserAsync(parameters, request);
        }

        public Task<ITwitterResult<IRelationshipDetailsDTO>> UpdateRelationshipAsync(IUpdateRelationshipParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.UpdateRelationshipAsync(parameters, request);
        }

        public Task<ITwitterResult<IUserDTO>> UnfollowUserAsync(IUnfollowUserParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.UnfollowUserAsync(parameters, request);
        }

        // FRIENDSHIP

        public Task<ITwitterResult<IRelationshipStateDTO[]>> GetRelationshipsWithAsync(IGetRelationshipsWithParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.GetRelationshipsWithAsync(parameters, request);
        }

        public ITwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>> GetUserIdsRequestingFriendshipIterator(IGetUserIdsRequestingFriendshipParameters parameters, ITwitterRequest request)
        {
            var twitterCursorResult = new TwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>>(
                parameters.Cursor,
                cursor =>
                {
                    var cursoredParameters = new GetUserIdsRequestingFriendshipParameters(parameters)
                    {
                        Cursor = cursor
                    };

                    return _userQueryExecutor.GetUserIdsRequestingFriendshipAsync(cursoredParameters, new TwitterRequest(request));
                },
                page => page.Model.NextCursorStr,
                page => page.Model.NextCursorStr == "0");

            return twitterCursorResult;
        }

        public ITwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>> GetUserIdsYouRequestedToFollowIterator(IGetUserIdsYouRequestedToFollowParameters parameters, ITwitterRequest request)
        {
            var twitterCursorResult = new TwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>>(
                parameters.Cursor,
                cursor =>
                {
                    var cursoredParameters = new GetUserIdsYouRequestedToFollowParameters(parameters)
                    {
                        Cursor = cursor
                    };

                    return _userQueryExecutor.GetUserIdsYouRequestedToFollowAsync(cursoredParameters, new TwitterRequest(request));
                },
                page => page.Model.NextCursorStr,
                page => page.Model.NextCursorStr == "0");

            return twitterCursorResult;
        }

        // BLOCK
        public Task<ITwitterResult<IUserDTO>> BlockUserAsync(IBlockUserParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.BlockUserAsync(parameters, request);
        }

        public Task<ITwitterResult<IUserDTO>> UnblockUserAsync(IUnblockUserParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.UnblockUserAsync(parameters, request);
        }

        public Task<ITwitterResult<IUserDTO>> ReportUserForSpamAsync(IReportUserForSpamParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.ReportUserForSpamAsync(parameters, request);
        }

        public ITwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>> GetBlockedUserIdsIterator(IGetBlockedUserIdsParameters parameters, ITwitterRequest request)
        {
            var twitterCursorResult = new TwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>>(
                parameters.Cursor,
                cursor =>
                {
                    var cursoredParameters = new GetBlockedUserIdsParameters(parameters)
                    {
                        Cursor = cursor
                    };

                    return _userQueryExecutor.GetBlockedUserIdsAsync(cursoredParameters, new TwitterRequest(request));
                },
                page => page.Model.NextCursorStr,
                page => page.Model.NextCursorStr == "0");

            return twitterCursorResult;
        }

        public ITwitterPageIterator<ITwitterResult<IUserCursorQueryResultDTO>> GetBlockedUsersIterator(IGetBlockedUsersParameters parameters, ITwitterRequest request)
        {
            var twitterCursorResult = new TwitterPageIterator<ITwitterResult<IUserCursorQueryResultDTO>>(
                parameters.Cursor,
                cursor =>
                {
                    var cursoredParameters = new GetBlockedUsersParameters(parameters)
                    {
                        Cursor = cursor
                    };

                    return _userQueryExecutor.GetBlockedUsersAsync(cursoredParameters, new TwitterRequest(request));
                },
                page => page.Model.NextCursorStr,
                page => page.Model.NextCursorStr == "0");

            return twitterCursorResult;
        }

        // MUTE
        public Task<ITwitterResult<long[]>> GetUserIdsWhoseRetweetsAreMutedAsync(IGetUserIdsWhoseRetweetsAreMutedParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.GetUserIdsWhoseRetweetsAreMutedAsync(parameters, request);
        }

        public ITwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>> GetMutedUserIdsIterator(IGetMutedUserIdsParameters parameters, ITwitterRequest request)
        {
            var twitterCursorResult = new TwitterPageIterator<ITwitterResult<IIdsCursorQueryResultDTO>>(
                parameters.Cursor,
                cursor =>
                {
                    var cursoredParameters = new GetMutedUserIdsParameters(parameters)
                    {
                        Cursor = cursor
                    };

                    return _userQueryExecutor.GetMutedUserIdsAsync(cursoredParameters, new TwitterRequest(request));
                },
                page => page.Model.NextCursorStr,
                page => page.Model.NextCursorStr == "0");

            return twitterCursorResult;
        }

        public ITwitterPageIterator<ITwitterResult<IUserCursorQueryResultDTO>> GetMutedUsersIterator(IGetMutedUsersParameters parameters, ITwitterRequest request)
        {
            var twitterCursorResult = new TwitterPageIterator<ITwitterResult<IUserCursorQueryResultDTO>>(
                parameters.Cursor,
                cursor =>
                {
                    var cursoredParameters = new GetMutedUsersParameters(parameters)
                    {
                        Cursor = cursor
                    };

                    return _userQueryExecutor.GetMutedUsersAsync(cursoredParameters, new TwitterRequest(request));
                },
                page => page.Model.NextCursorStr,
                page => page.Model.NextCursorStr == "0");

            return twitterCursorResult;
        }

        public Task<ITwitterResult<IUserDTO>> MuteUserAsync(IMuteUserParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.MuteUserAsync(parameters, request);
        }

        public Task<ITwitterResult<IUserDTO>> UnmuteUserAsync(IUnmuteUserParameters parameters, ITwitterRequest request)
        {
            return _userQueryExecutor.UnmuteUserAsync(parameters, request);
        }
    }
}


text:
/**
 * Module dependencies.
 */
const Request = require('supertest-as-promised');
const HttpStatus = require('http-status');
const Chai = require('chai');

const expect = Chai.expect;
const App = require('../src/config/express');

Chai.config.includeStack = true;

describe('# Misc', () => {
  describe('## GET /api/v1/404', () => {
    it('should return 404 status', (done) => {
      Request(App)
        .get('/api/v1/404')
        .expect(HttpStatus.NOT_FOUND)
        .then((res) => {
          expect(res.body.mensagem).to.equal('Recurso não encontrado.');
          done();
        })
        .catch(done);
    });
  });
});


text:
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="SYSFILES system table" />
<meta scheme="URI" name="DC.Relation" content="rrefsistabs38369.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefsistabs40972" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>SYSFILES system table</title>

SYSFILES system table

Describes jar files stored in the database.

Column Name

Type

Length

Nullability

Contents

FILEID

CHAR

36

false

unique identifier for the jar file

SCHEMAID

CHAR

36

false

ID of the jar file's schema (join with SYSSCHEMAS. SCHEMAID)

FILENAME

VARCHAR

128

false

SQL name of the jar file

GENERATIONID

BIGINT

false

Generation number for the file. When jar files are replaced,
their generation identifiers are changed.

Parent topic: Derby system tables