text:
package de.hshannover.f4.trust.visitmeta.gui;

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Map.Entry;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

import org.apache.commons.collections15.map.HashedMap;
import org.apache.log4j.Logger;

import de.hshannover.f4.trust.visitmeta.datawrapper.ExpandedLink;
import de.hshannover.f4.trust.visitmeta.datawrapper.GraphContainer;
import de.hshannover.f4.trust.visitmeta.datawrapper.NodeIdentifier;
import de.hshannover.f4.trust.visitmeta.datawrapper.NodeMetadata;
import de.hshannover.f4.trust.visitmeta.datawrapper.NodeType;
import de.hshannover.f4.trust.visitmeta.datawrapper.Position;
import de.hshannover.f4.trust.visitmeta.datawrapper.SettingManager;
import de.hshannover.f4.trust.visitmeta.datawrapper.TimeHolder;
import de.hshannover.f4.trust.visitmeta.datawrapper.TimeManagerCreation;
import de.hshannover.f4.trust.visitmeta.datawrapper.TimeManagerDeletion;
import de.hshannover.f4.trust.visitmeta.datawrapper.UpdateContainer;
import de.hshannover.f4.trust.visitmeta.graphCalculator.FacadeLogic;
import de.hshannover.f4.trust.visitmeta.graphCalculator.LayoutType;
import de.hshannover.f4.trust.visitmeta.graphDrawer.GraphPanel;
import de.hshannover.f4.trust.visitmeta.graphDrawer.GraphPanelFactory;
import de.hshannover.f4.trust.visitmeta.graphDrawer.graphicwrapper.GraphicWrapper;
import de.hshannover.f4.trust.visitmeta.gui.contextmenu.ContextMenuItem;
import de.hshannover.f4.trust.visitmeta.gui.contextmenu.ContextMenuItemFactory;
import de.hshannover.f4.trust.visitmeta.interfaces.Propable;

public class GraphConnection implements Observer {
	private static final Logger LOGGER = Logger.getLogger(GraphConnection.class);
	private GraphContainer mContainer = null;
	private FacadeLogic mFacadeLogic = null;
	private GraphPanel mGraphPanel = null;
	private SettingManager mSettingManager = null;
	private TimeHolder mTimeHolder = null;
	private TimeManagerCreation mTimerCreation = null;
	private TimeManagerDeletion mTimerDeletion = null;
	private boolean mAddHighlights = true;
	private ConnectionTab mParentTab = null;
	private HashedMap<Observable, Observable> mObservables = new HashedMap<>();
	private boolean mIsPropablePicked = false;
	private List<ContextMenuItem> mContextMenuItems;

	/**
	 * @param container
	 *            Contains information about the Connection.
	 */
	public GraphConnection(GraphContainer container) {
		mContainer = container;
		mFacadeLogic = mContainer.getFacadeLogic();
		mTimeHolder = mContainer.getTimeHolder();
		mSettingManager = mContainer.getSettingManager();
		mGraphPanel = GraphPanelFactory.getGraphPanel("Piccolo2D", this);

		mTimerCreation = mContainer.getTimeManagerCreation();
		mTimerDeletion = mContainer.getTimeManagerDeletion();
		mTimerCreation.setController(this);
		mTimerDeletion.setController(this);

		mSettingManager.addObserver(this);
		mFacadeLogic.addObserver(this);
		mTimeHolder.addObserver(this);

		mContextMenuItems = ContextMenuItemFactory.getAll();
	}

	public SettingManager getSettingManager() {
		return mSettingManager;
	}

	public FacadeLogic getLogic() {
		return mFacadeLogic;
	}

	public void setParentTab(ConnectionTab parentTab) {
		this.mParentTab = parentTab;
	}

	public ConnectionTab getParentTab() {
		return mParentTab;
	}

	public GraphPanel getGraphPanel() {
		return mGraphPanel;
	}

	/**
	 * Add the identifier in the list to the graph.
	 *
	 * @param pIdentifier
	 *            the list with identifier.
	 */
	private synchronized void addIdentifier(List<NodeIdentifier> pIdentifier) {
		LOGGER.trace("Method addIdentifier("
				+ pIdentifier + ") called.");
		for (NodeIdentifier vIdentifier : pIdentifier) {
			mGraphPanel.addIdentifier(vIdentifier);
			if (mAddHighlights) {
				mGraphPanel.markAsNew(vIdentifier);
				mTimerCreation.addNode(vIdentifier);
			}
			vIdentifier.addObserver(this);
			mObservables.put(vIdentifier, vIdentifier);
		}
	}

	/**
	 * Add the metadata of the list and create the edges to the identifier in the graph.
	 *
	 * @param pIdentifier
	 *            the identifier.
	 * @param pMetadata
	 *            the list with metadata.
	 */
	private synchronized void addMetadata(NodeIdentifier pIdentifier, List<NodeMetadata> pMetadata) {
		LOGGER.trace("Method addMetadata("
				+ pIdentifier + ", " + pMetadata + ") called.");
		for (NodeMetadata vMetadata : pMetadata) {
			mGraphPanel.addMetadata(pIdentifier, vMetadata);
			if (mAddHighlights) {
				mGraphPanel.markAsNew(vMetadata);
				mTimerCreation.addNode(vMetadata);
			}
			vMetadata.addObserver(this);
			mObservables.put(vMetadata, vMetadata);
		}
	}

	/**
	 * Add the metadata of the list and create the edges of the link in the graph.
	 *
	 * @param pLink
	 *            the link.
	 * @param pMetadata
	 *            the list with metadata.
	 */
	private synchronized void addMetadata(ExpandedLink pLink, List<NodeMetadata> pMetadata) {
		LOGGER.trace("Method addMetadata("
				+ pLink + ", " + pMetadata + ") called.");
		for (NodeMetadata vMetadata : pMetadata) {
			mGraphPanel.addMetadata(pLink, vMetadata);
			if (mAddHighlights) {
				mGraphPanel.markAsNew(vMetadata);
				mTimerCreation.addNode(vMetadata);
			}
			vMetadata.addObserver(this);
			mObservables.put(vMetadata, vMetadata);
		}
	}

	/**
	 * Remove the IdentifierNode.
	 *
	 * @param pIdentifier
	 *            the NodeIdentifier to identify the node in the graph.
	 */
	private synchronized void deleteIdentifier(List<NodeIdentifier> pIdentifier) {
		LOGGER.trace("Method deleteIdentifier("
				+ pIdentifier + ") called.");
		if (mAddHighlights) {
			for (NodeIdentifier vIdentifier : pIdentifier) {
				mGraphPanel.markAsDelete(vIdentifier);
				mTimerDeletion.addNode(vIdentifier);
			}
		}
	}

	/**
	 * Delete the MetadataNode and the edges to the node from the graph.
	 *
	 * @param pMetadata
	 *            the NodeMetadata to identify the node and edges in the graph.
	 */
	private synchronized void deleteMetadata(List<NodeMetadata> pMetadata) {
		LOGGER.trace("Method deleteMetadata("
				+ pMetadata + ") called.");
		if (mAddHighlights) {
			for (NodeMetadata vMetadata : pMetadata) {
				mGraphPanel.markAsDelete(vMetadata);
				mTimerDeletion.addNode(vMetadata);
			}
		}
	}

	/**
	 *
	 * @param pNode
	 */
	public synchronized void deleteNode(Position pNode) {
		LOGGER.trace("Method deleteNode("
				+ pNode + ") called.");
		mGraphPanel.deleteNode(pNode);
		pNode.deleteObserver(this);
		mObservables.remove(pNode);
	}

	/**
	 *
	 * @param pNode
	 */
	public void removeHighlight(Position pNode) {
		LOGGER.trace("Method removeHighlight("
				+ pNode + ") called.");
		mGraphPanel.clearHighlight(pNode);
	}

	/**
	 * Set the new position for a Position-Object.
	 *
	 * @param pNode
	 *            the Object.
	 * @param pNewX
	 *            the new x coordinate.
	 * @param pNewY
	 *            the new y coordinate.
	 * @param pNewZ
	 *            the new z coordinate.
	 * @param pinNode
	 *            TODO
	 */
	public void updateNode(Position pNode, double pNewX, double pNewY, double pNewZ, boolean pinNode) {
		LOGGER.trace("Method updateNode("
				+ pNode + ", " + pNewX + ", " + pNewY + ", " + pNewZ + ") called.");
		mFacadeLogic.updateNode(pNode, pNewX, pNewY, pNewZ, pinNode);
	}

	/**
	 * Get a list of all known publisher.
	 *
	 * @return stuff
	 */
	public List<String> getPublisher() {
		LOGGER.trace("Method getPublisher() called.");
		return mGraphPanel.getPublisher();
	}

	/**
	 * Repaint nodes of a specific type and publisher.
	 *
	 * @param pPublisher
	 *            the id of the current publisher, empty if the default color is changed.
	 * @param pType
	 *            the type of the node,
	 */
	public void repaintNodes(NodeType pType) {
		LOGGER.trace("Method repaintMetadata() called.");
		mGraphPanel.repaintNodes(pType);
	}

	/**
	 * Stop the calculation of node positions.
	 */
	public void stopGraphMotion() {
		LOGGER.trace("Method stopGraphMotion() called.");
		mFacadeLogic.stopCalculation();
	}

	/**
	 * Resume the calculation of node positions.
	 */
	public void startGraphMotion() {
		LOGGER.trace("Method startGraphMotion() called.");
		mFacadeLogic.startCalculation();
	}

	/**
	 * Checks whether the positions of nodes are currently calculated.
	 *
	 * @return False = Motion of graph is Off. True = Motion of graph is On.
	 */
	public boolean isGraphMotion() {
		LOGGER.trace("Method isGraphMotion() called.");
		return mFacadeLogic.isCalculationRunning();
	}

	/**
	 * Set layout type (e.g., force-directed)
	 *
	 * @param layoutType
	 */
	public void setLayoutType(LayoutType layoutType) {
		mFacadeLogic.setLayoutType(layoutType);
	}

	/**
	 * Reposition all nodes.
	 */
	public void redrawGraph() {
		LOGGER.trace("Method redrawGraph() called.");
		mFacadeLogic.recalculateGraph();
	}

	/**
	 * Remove all nodes and edges from the graph.
	 */
	public void clearGraph() {
		LOGGER.trace("Method clearGraph() called.");
		for (Observable vObserbale : mObservables.keySet()) {
			vObserbale.deleteObserver(this);
		}
		mObservables.clear();
		mGraphPanel.clearGraph();
	}

	/**
	 * @see FacadeLogic#loadGraphAtDeltaStart()
	 */
	private void loadGraphAtDeltaStart() {
		mTimerCreation.removeAll();
		mTimerDeletion.removeAll();
		clearGraph();
		mFacadeLogic.loadGraphAtDeltaStart();
	}

	/**
	 * @see FacadeLogic#loadCurrentGraph()
	 */
	private void loadCurrentGraph() {
		mTimerCreation.removeAll();
		mTimerDeletion.removeAll();
		clearGraph();
		mFacadeLogic.loadCurrentGraph();
	}

	/**
	 * @see FacadeLogic#loadDelta()
	 */
	private void loadDelta() {
		LOGGER.trace("Method loadDelta() called.");
		mFacadeLogic.loadDelta();
	}

	/**
	 * Loads the Delta.
	 *
	 * @see GraphConnection#loadGraphAtDeltaStart()
	 * @see GraphConnection#loadDelta()
	 */
	private void delta() {
		LOGGER.trace("Method delta() called.");
		mGraphPanel.setNodeTranslationDuration(0);
		mAddHighlights = false;
		loadGraphAtDeltaStart();
		mTimerCreation.removeAll();
		mTimerDeletion.removeAll();
		mAddHighlights = true;
		loadDelta();
		mGraphPanel.setNodeTranslationDuration(mSettingManager.getNodeTranslationDuration());
	}

	/**
	 * Fill the GraphPanel with the data.
	 *
	 * @param pData
	 *            the data.
	 */
	public void fillGraph(UpdateContainer pData) {
		/* Add nodes to graph. */
		addIdentifier(pData.getListAddIdentifier());
		for (NodeIdentifier vIdentifier : pData.getListAddIdentifier()) {
			addMetadata(vIdentifier, vIdentifier.getMetadata());
		}
		for (ExpandedLink vLink : pData.getListAddLinks()) {
			addMetadata(vLink, vLink.getMetadata());
		}
		for (Entry<NodeIdentifier, List<NodeMetadata>> vSet : pData.getListAddMetadataIdentifier().entrySet()) {
			addMetadata(vSet.getKey(), vSet.getValue());
		}
		for (Entry<ExpandedLink, List<NodeMetadata>> vSet : pData.getListAddMetadataLinks().entrySet()) {
			addMetadata(vSet.getKey(), vSet.getValue());
		}
		for (List<NodeMetadata> vMetadata : pData.getListDeleteMetadataLinks().values()) {
			deleteMetadata(vMetadata);
		}
		for (List<NodeMetadata> vMetadata : pData.getListDeleteMetadataIdentifier().values()) {
			deleteMetadata(vMetadata);
		}
		deleteIdentifier(pData.getListDeleteIdentifier());

		mGraphPanel.adjustPanelSize();
	}

	@Override
	public void update(Observable o, Object arg) {
		LOGGER.trace("Method update("
				+ o + ", " + arg + ") called.");
		if (o instanceof FacadeLogic) {
			fillGraph(mFacadeLogic.getUpdate());
			mGraphPanel.repaint();
		} else if (o instanceof NodeIdentifier) {
			mGraphPanel.updateIdentifier((NodeIdentifier) o);
			mGraphPanel.repaint();
		} else if (o instanceof NodeMetadata) {
			mGraphPanel.updateMetadata((NodeMetadata) o);
			mGraphPanel.repaint();
		} else if (o instanceof TimeHolder) {
			if (!mTimeHolder.isLiveView()) {
				delta();
				mFacadeLogic.recalculateGraph();
			} else if (mTimeHolder.isSetLive()) {
				loadCurrentGraph();
			}
			mGraphPanel.repaint();
		} else if (o instanceof SettingManager) {
			mGraphPanel.setNodeTranslationDuration(mSettingManager.getNodeTranslationDuration());
		}
	}

	/**
	 * Shows the properties of the given {@link Propable} object, sets is as
	 * selected in the {@link GraphPanel} instance and stores whether it was
	 * marked as picked or not.
	 *
	 * @param propable
	 *            the {@link Propable} object to show
	 */
	public void pickAndShowProperties(GraphicWrapper wrapper) {
		LOGGER.trace("Method pickAndShowProperties("
				+ wrapper + ") called.");
		mIsPropablePicked = true;
		mParentTab.showPropertiesOfNode(wrapper.getData());
		mParentTab.showExtendedNodeInformation(wrapper);
		mGraphPanel.selectNode(wrapper);
	}

	/**
	 * Just shows the properties of the given {@link Propable} object, without
	 * marking it as selected or storing whether it was picked.
	 *
	 * @param propable
	 *            the {@link Propable} object to show
	 */
	public void showProperty(Propable propable) {
		LOGGER.trace("Method showProperties("
				+ propable + ") called.");
		mParentTab.showPropertiesOfNode(propable);
	}

	/**
	 * Clears the shown properties, stores that nothing is picked at the moment
	 * and informs the {@link GraphPanel} that nothing is selected anymore.
	 */
	public void clearProperties() {
		LOGGER.trace("Method clearProperties() called.");
		mIsPropablePicked = false;
		mParentTab.showPropertiesOfNode(null);
		mParentTab.showExtendedNodeInformation(null);
		mGraphPanel.unselectNode();
	}

	/**
	 * Returns if the current shown {@link Propable} object was marked as picked or not.
	 *
	 * @return true if current shown {@link Propable} object was marked as picked, false if not
	 */
	public boolean isPropablePicked() {
		LOGGER.trace("Method isPropablePicked() called.");
		return mIsPropablePicked;
	}

	public void showContextMenu(final GraphicWrapper node, Point point) {
		JPopupMenu contextMenu = createContextMenu(node);
		contextMenu.show(mGraphPanel.getPanel(), point.x, point.y);
	}

	private JPopupMenu createContextMenu(final GraphicWrapper node) {
		JPopupMenu result = new JPopupMenu();

		for (final ContextMenuItem item : mContextMenuItems) {
			JMenuItem menuItem = new JMenuItem(item.getItemTitle());
			menuItem.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent e) {
					item.actionPerformed(node);
				}
			});

			if (!item.canHandle(node.getData())) {
				menuItem.setEnabled(false);
			}

			result.add(menuItem);
		}

		return result;
	}

}


text:
package strategy

import (
	"fmt"
	"strings"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	utilruntime "k8s.io/apimachinery/pkg/util/runtime"

	securityv1 "github.com/openshift/api/security/v1"
	securityv1client "github.com/openshift/client-go/security/clientset/versioned/typed/security/v1"
	buildapi "github.com/openshift/origin/pkg/build/apis/build"
	"github.com/openshift/origin/pkg/build/buildapihelpers"
	buildutil "github.com/openshift/origin/pkg/build/util"
)

// SourceBuildStrategy creates STI(source to image) builds
type SourceBuildStrategy struct {
	Image          string
	SecurityClient securityv1client.SecurityV1Interface
}

// DefaultDropCaps is the list of capabilities to drop if the current user cannot run as root
var DefaultDropCaps = []string{
	"KILL",
	"MKNOD",
	"SETGID",
	"SETUID",
}

// CreateBuildPod creates a pod that will execute the STI build
// TODO: Make the Pod definition configurable
func (bs *SourceBuildStrategy) CreateBuildPod(build *buildapi.Build) (*corev1.Pod, error) {
	data, err := runtime.Encode(buildJSONCodec, build)
	if err != nil {
		return nil, fmt.Errorf("failed to encode the Build %s/%s: %v", build.Namespace, build.Name, err)
	}

	containerEnv := []corev1.EnvVar{
		{Name: "BUILD", Value: string(data)},
	}

	addSourceEnvVars(build.Spec.Source, &containerEnv)

	strategy := build.Spec.Strategy.SourceStrategy
	if len(strategy.Env) > 0 {
		buildutil.MergeTrustedEnvWithoutDuplicates(buildutil.CopyApiEnvVarToV1EnvVar(strategy.Env), &containerEnv, true)
	}

	// check if can run container as root
	if !bs.canRunAsRoot(build) {
		// TODO: both AllowedUIDs and DropCapabilities should
		// be controlled via the SCC that's in effect for the build service account
		// For now, both are hard-coded based on whether the build service account can
		// run as root.
		containerEnv = append(containerEnv, corev1.EnvVar{Name: buildapi.AllowedUIDs, Value: "1-"})
		containerEnv = append(containerEnv, corev1.EnvVar{Name: buildapi.DropCapabilities, Value: strings.Join(DefaultDropCaps, ",")})
	}

	serviceAccount := build.Spec.ServiceAccount
	if len(serviceAccount) == 0 {
		serviceAccount = buildutil.BuilderServiceAccountName
	}

	privileged := true
	pod := &corev1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name:      buildapihelpers.GetBuildPodName(build),
			Namespace: build.Namespace,
			Labels:    getPodLabels(build),
		},
		Spec: corev1.PodSpec{
			ServiceAccountName: serviceAccount,
			Containers: []corev1.Container{
				{
					Name:    StiBuild,
					Image:   bs.Image,
					Command: []string{"openshift-sti-build"},
					Env:     copyEnvVarSlice(containerEnv),
					// TODO: run unprivileged https://github.com/openshift/origin/issues/662
					SecurityContext: &corev1.SecurityContext{
						Privileged: &privileged,
					},
					TerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,
					VolumeMounts: []corev1.VolumeMount{
						{
							Name:      "buildworkdir",
							MountPath: buildutil.BuildWorkDirMount,
						},
					},
					ImagePullPolicy: corev1.PullIfNotPresent,
					Resources:       buildutil.CopyApiResourcesToV1Resources(&build.Spec.Resources),
				},
			},
			Volumes: []corev1.Volume{
				{
					Name: "buildworkdir",
					VolumeSource: corev1.VolumeSource{
						EmptyDir: &corev1.EmptyDirVolumeSource{},
					},
				},
			},
			RestartPolicy: corev1.RestartPolicyNever,
			NodeSelector:  build.Spec.NodeSelector,
		},
	}

	if build.Spec.Source.Git != nil || build.Spec.Source.Binary != nil {
		gitCloneContainer := corev1.Container{
			Name:    GitCloneContainer,
			Image:   bs.Image,
			Command: []string{"openshift-git-clone"},
			Env:     copyEnvVarSlice(containerEnv),
			TerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,
			VolumeMounts: []corev1.VolumeMount{
				{
					Name:      "buildworkdir",
					MountPath: buildutil.BuildWorkDirMount,
				},
			},
			ImagePullPolicy: corev1.PullIfNotPresent,
			Resources:       buildutil.CopyApiResourcesToV1Resources(&build.Spec.Resources),
		}
		if build.Spec.Source.Binary != nil {
			gitCloneContainer.Stdin = true
			gitCloneContainer.StdinOnce = true
		}
		setupSourceSecrets(pod, &gitCloneContainer, build.Spec.Source.SourceSecret)
		pod.Spec.InitContainers = append(pod.Spec.InitContainers, gitCloneContainer)
	}
	if len(build.Spec.Source.Images) > 0 {
		extractImageContentContainer := corev1.Container{
			Name:    ExtractImageContentContainer,
			Image:   bs.Image,
			Command: []string{"openshift-extract-image-content"},
			Env:     copyEnvVarSlice(containerEnv),
			// TODO: run unprivileged https://github.com/openshift/origin/issues/662
			SecurityContext: &corev1.SecurityContext{
				Privileged: &privileged,
			},
			TerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,
			VolumeMounts: []corev1.VolumeMount{
				{
					Name:      "buildworkdir",
					MountPath: buildutil.BuildWorkDirMount,
				},
			},
			ImagePullPolicy: corev1.PullIfNotPresent,
			Resources:       buildutil.CopyApiResourcesToV1Resources(&build.Spec.Resources),
		}
		setupDockerSecrets(pod, &extractImageContentContainer, build.Spec.Output.PushSecret, strategy.PullSecret, build.Spec.Source.Images)
		pod.Spec.InitContainers = append(pod.Spec.InitContainers, extractImageContentContainer)
	}
	pod.Spec.InitContainers = append(pod.Spec.InitContainers,
		corev1.Container{
			Name:    "manage-dockerfile",
			Image:   bs.Image,
			Command: []string{"openshift-manage-dockerfile"},
			Env:     copyEnvVarSlice(containerEnv),
			TerminationMessagePolicy: corev1.TerminationMessageFallbackToLogsOnError,
			VolumeMounts: []corev1.VolumeMount{
				{
					Name:      "buildworkdir",
					MountPath: buildutil.BuildWorkDirMount,
				},
			},
			ImagePullPolicy: corev1.PullIfNotPresent,
			Resources:       buildutil.CopyApiResourcesToV1Resources(&build.Spec.Resources),
		},
	)

	if build.Spec.CompletionDeadlineSeconds != nil {
		pod.Spec.ActiveDeadlineSeconds = build.Spec.CompletionDeadlineSeconds
	}

	setOwnerReference(pod, build)
	setupDockerSocket(pod)
	setupCrioSocket(pod)
	setupDockerSecrets(pod, &pod.Spec.Containers[0], build.Spec.Output.PushSecret, strategy.PullSecret, build.Spec.Source.Images)
	// For any secrets the user wants to reference from their Assemble script or Dockerfile, mount those
	// secrets into the main container.  The main container includes logic to copy them from the mounted
	// location into the working directory.
	// TODO: consider moving this into the git-clone container and doing the secret copying there instead.
	setupInputSecrets(pod, &pod.Spec.Containers[0], build.Spec.Source.Secrets)
	setupInputConfigMaps(pod, &pod.Spec.Containers[0], build.Spec.Source.ConfigMaps)
	return pod, nil
}

func (bs *SourceBuildStrategy) canRunAsRoot(build *buildapi.Build) bool {
	rootUser := int64(0)

	review, err := bs.SecurityClient.PodSecurityPolicySubjectReviews(build.Namespace).Create(
		&securityv1.PodSecurityPolicySubjectReview{
			Spec: securityv1.PodSecurityPolicySubjectReviewSpec{
				Template: corev1.PodTemplateSpec{
					Spec: corev1.PodSpec{
						ServiceAccountName: build.Spec.ServiceAccount,
						Containers: []corev1.Container{
							{
								Name:  "fake",
								Image: "fake",
								SecurityContext: &corev1.SecurityContext{
									RunAsUser: &rootUser,
								},
							},
						},
					},
				},
			},
		},
	)
	if err != nil {
		utilruntime.HandleError(err)
		return false
	}
	return review.Status.AllowedBy != nil
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace PHPCR\Shell\Console\Command\Phpcr;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputArgument;

class QueryCommand extends BasePhpcrCommand
{
    protected function configure()
    {
        $this->setName('query');
        $this->setDescription('Execute a SELECT query (advanced)');
        $this->addArgument('query', InputArgument::REQUIRED, 'Query to execute');
        $this->addOption('language', 'l', InputOption::VALUE_OPTIONAL, 'The query language (e.g. jcr-sql2', 'JCR-SQL2');
        $this->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'The query limit', 0);
        $this->addOption('offset', null, InputOption::VALUE_OPTIONAL, 'The query offset', 0);
        $this->setHelp(<<<EOT
Execute an SQL query. This command differs from <info>select</info> in that it
is executed conventionally and not literally. The advantage is that you can
specify a specific query language and additional options:

    query "SELECT * FROM [nt:unstructured]" --language=JCR_SQL2 --limit=5 --offset=4
EOT
        );
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $language = $input->getOption('language');
        $limit = $input->getOption('limit');
        $offset = $input->getOption('offset');
        $query = $input->getArgument('query');

        $session = $this->get('phpcr.session');
        $workspace = $session->getWorkspace();
        $supportedQueryLanguages = $workspace->getQueryManager()->getSupportedQueryLanguages();

        if (!in_array($language, $supportedQueryLanguages)) {
            throw new \InvalidArgumentException(sprintf(
                '"%s" is an invalid query language, valid query languages are:%s',
                $language,
                PHP_EOL . '    -' . implode(PHP_EOL . '   - ', $supportedQueryLanguages)
            ));
        }

        $qm = $session->getWorkspace()->getQueryManager();
        $query = $qm->createQuery($query, $language);

        if ($limit) {
            $query->setLimit($limit);
        }

        if ($offset) {
            $query->setOffset($offset);
        }

        $start = microtime(true);
        $result = $query->execute();
        $elapsed = microtime(true) - $start;

        $this->get('helper.result_formatter')->formatQueryResult($result, $output, $elapsed);
    }
}


text:
import vlc
import time
import threading
import queue
import re
import os
try:
    import youtube_dl
except:
    youtube_dl = None

done = False

class Player(threading.Thread):
    def __init__(self,threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        print("Player Initialised\nReady")
        self.play()
        print("Quitting")
    def play(self):
        p = None
        playing = False
        while not done:
            if p == None:
                print("Nothing Playing")
                next = self.q.get()
                if next:
                    print("Something in queue. Putting it on.")
                    p = vlc.MediaPlayer(next)
                    p.play()
                    playing = True
            elif p.get_state() == State.Ended:
                print("Finished")
                p = None
                playing = False
            else:
                print(p.get_state())
            time.sleep(1)

class Downloader(threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
        self.opts = {
            'format': 'bestaudio/best',
            'extractaudio': True,
            'audioformat': "mp3",
            'outtmpl': '%(id)s',
            'nocheckcertificate': True,
            'ignoreerrors': True,
            'quiet': True,
            'no_warnings': True,
            'outtmpl': "audiofiles/%(id)s",
        }
    def run(self):
        print("Downloader Initialised\nReady")
        self.download()
        print("Quitting")
    def download(self):
        self._yt = youtube_dl.YoutubeDL(self.opts)
        yt_link = re.compile(r'^(https?\:\/\/)?(www\.|m\.)?(youtube\.com|youtu\.?be)\/.+$')
        while not done:
            next = self.q.get()
            if next:
                if yt_link.match(next):
                    url = next
                else:
                    url = "ytsearch:" + next
                id = self._yt.extract_info(url, download=False)["entries"][0]["id"]
                if not os.path.isfile('audiofiles/' + id):
                    self._yt.download([url])
                play_queue.put("audiofiles/{}".format(id))
                print("Added to queue")
            time.sleep(1)

dl_queue = queue.Queue(0)
play_queue = queue.Queue(0)
dl_thread = Downloader(1,"Downloader",dl_queue)
play_thread = Player(2,"Player",play_queue)
dl_thread.start()
play_thread.start()
while not done:
    print("\nType video link or title to add to queue or type exit to quit")
    url = input("Video: ")
    if url == "exit":
        done = True
        break
    else:
        dl_queue.put(url)
        print("Added to download queue")
dl_thread.join()
play_thread.join()
print("Closing")

#p = vlc.MediaPlayer("file:///twenty one pilots - Stressed Out Parody (21 hydrants music video)-leSvUKji4CE.mp3")
#p.play()
#while p.get_state() != "State.Ended":
#    print(p.get_state())
#    time.sleep(1)

# ydl_opts = {
    # 'format': 'bestaudio/best',
    # 'postprocessors': [{
        # 'key': 'FFmpegExtractAudio',
        # 'preferredcodec': 'mp3',
        # 'preferredquality': '192',
    # }],
# }
# done = False
# while not done:
    # try:
        # url = input("Video: ")
        # if url.startswith("http"):
            # pass
        # else:
            # url = "ytsearch:" + url
        # with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            # ydl.download([url])
    # except KeyboardInterrupt:
        # done = True
        # print("Closing")


text:
#include <algorithm>
#include <unistd.h>
#include "flowgraph/FlowGraphNode.h"
#include "SourceI32Caller.h"

#if FLOWGRAPH_ANDROID_INTERNAL
#include <audio_utils/primitives.h>
#endif

using namespace oboe;
using namespace flowgraph;

int32_t SourceI32Caller::onProcess(int32_t numFrames) {
    int32_t numBytes = mStream->getBytesPerFrame() * numFrames;
    int32_t bytesRead = mBlockReader.read((uint8_t *) mConversionBuffer.get(), numBytes);
    int32_t framesRead = bytesRead / mStream->getBytesPerFrame();

    float *floatData = output.getBuffer();
    const int32_t *intData = mConversionBuffer.get();
    int32_t numSamples = framesRead * output.getSamplesPerFrame();

#if FLOWGRAPH_ANDROID_INTERNAL
    memcpy_to_float_from_i32(floatData, shortData, numSamples);
#else
    for (int i = 0; i < numSamples; i++) {
        *floatData++ = *intData++ * kScale;
    }
#endif

    return framesRead;
}


text:
[Scroll down for english](#moses_smt_machine_translation_online_api)

# API Cyfieithu Peirianyddol Moses-SMT

Mae swyddogaethau peiriannau cyfieithu y storfa hon ar gael dros y we o'r Canolfan APIs [gweler https://api.techiaith.org](https://api.techiaith.org). Mae'r API yn gweithio dros HTTPS GET, felly gellir defnyddio unrhyw iaith/meddalwedd HTTP er mwyn cysylltu at yr API.

## Tiwtorialau

Mae [Twitorial 1](demo1.md) yn enghraifft o sut i ddefnyddio API cyfieithu peirianyddol i gyfieithu testun

## Fersiwn Cyfredol

Mae un fersiwn o API Cyfieithu Peiraianyddol ar gael. v1 neu 'fersiwn 1'.
Dychwelir enw'r fersiwn sy'n cael ei ddefnyddio yn y canlyniadau JSON.

Mi fydd yr URL yn newid ar gyfer pob fersiwn newydd o'r API. Ar hyn o bryd, dylid defnyddio `/v1` ar gyfer fersiwn 1.

## Sgema

Mae cysylltu â'r API yn gweithio dros HTTPS yn unig, gan ddefnyddio'r parth `api.techiaith.org/translate`. Mae'r holl ddata sy'n cael ei dderbyn/anfon yn cael ei drosglwyddo ar ffurf JSON ([unicode-escaped ASCII](http://tools.ietf.org/html/rfc5137)).

## Paramedrau

| Paramedr     | Disgrifiad | Sylwadau |
|--------------|------------|----------|
| `api_key`    | Eich allwedd API, ar gael o'r Canolfan APIs (https://api.techiaith.org) | angenrheidiol |
| `q`       | Y testun i'w gyfieithu. Wedi ei fformatio yn ôl RFC 3986 (percent-encoded) | angenrheidiol |
| `engine` | Enw'r peiriant rydych am defnyddio i gyfieithu'n peirianyddol. Y dewis yw : CofnodYCynulliad  neu Deddfwriaeth | angenrheidiol |
| `source` | Iaith y testun ffynhonnell. Dewis o `en` neu `cy`. | angenrheidiol |
| `target` | Iaith ar gyfer y cyfieithiad sy'n cael ei ddychwelyd yn ôl.  Dewis o `en` neu `cy`. | angenrheidiol |
| `callback`   | Enw 'function' ar gyfer unrhyw callback JSON-P (gweler isod) | dewisiol |

### Enghriafft

```
$ curl https://api.techiaith.org/translate/v1/translate?api_key=123&q=Will+the+Minister+make+a+statement&engine=CofnodYCynulliad&source=en&target=cy

{
    "success": true,
    "translations": [
        {"translatedText": "A wnaiff y Gweinidog wneud datganiad"},
    ],
    "version": 1
}
```

## JSON-P Callbacks

Gellir defnyddio'r API gyda JSON-P callbacks trwy ychwanegu'r paramedr `callback` i'ch galwad:

```
$ curl https://api.techiaith.org/translate/v1/translate?api_key=123&q=Will+the+Minister+make+a+statement&engine=CofnodYCynulliad&source=en&target=cy&callback=foo
foo({
	"success": true,
	"translations": [
		{"translatedText": "A wnaiff y Gweinidog wneud datganiad"},
	],
    	"version": 1
});
```

## Cyfyngu nifer yr alwadau yr awr

Mae gan yr API gyfyngiad ar nifer yr alwadau y gellir eu gwneud mewn awr.

Os ydych eisiau cynyddu nifer y galwadau at yr API sydd gennych, cysylltwch â ni.

Gellir gweld cyfanswm nifer eich galwadau ar unrhyw adeg drwy edrych ar y 'HTTP headers' yn eich galwad API:

```
$ curl -i https://api.techiaith.org/translate/v1/translate?api_key=123&q=Will+the+Minister+make+a+statement&engine=CofnodYCynulliad&source=en&target=cy

HTTP/1.1 200 OK
Date: Mon, 17 Nov 2014 14:41:21 GMT
Content-Type: application/json
Content-Language: cy
X-Ratelimit-Remaining: 276
X-Ratelimit-Limit: 24
X-Ratelimit-Reset: 1416237399
```

Mae'r headers yn cynnwys yr holl wybodaeth sydd ei angen:

| Enw'r Header | Disgrifiad |
|--------------|------------|
| X-RateLimit-Limit | Y nifer mwyaf o alwadau allwch chi eu gwneud mewn awr |
| X-RateLimit-Remaining | Y nifer o alwadau sydd gennych ar ôl yn y 'blwch' cyfyngu presennol |
| X-RateLimit-Reset | Yr amser y bydd y 'blwch' cyfyngu presennol yn cael ei ail-osod, mewn [eiliadau epoch UTC](http://en.wikipedia.org/wiki/Unix_time) |

Os ydych chi angen yr amser mewn fformat gwahanol, gellir gwneud hyn gydag unrhyw iaith raglennu modern. Er engraifft, gellir gwneud hyn trwy gonsol eich porwr (gyda Javascript) a dychwelych gwrthrych 'Javascript Date'.

```javascript
new Date(1416237399 * 1000)
Date 2014-11-17T15:16:39.000Z
```

Ar ôl i chi fynd dros eich nifer mwyaf o alwadau yr awr, byddwch yn derbyn gwall gan y gweinydd (403 Forbidden):

```
curl -i https://api.techiaith.org/translate/v1/translate?api_key=123&q=Will+the+Minister+make+a+statement&engine=CofnodYCynulliad&source=en&target=cy

HTTP/1.1 200 OK
Date: Tue, 18 Nov 2014 10:45:10 GMT
Content-Type: application/json
X-Ratelimit-Limit: 300
X-Ratelimit-Remaining: 0
Content-Language: cy
X-Ratelimit-Reset: 1416310586

{
    "success": false,
    "errors": ["403 Forbidden: Rydych chi wedi mynd dros eich cyfyngiad nifer yr alwadau yr awr"]
}
```

------

# Moses SMT Machine Translation Online API
This repository's machine translation capabilities are available also online from our API Centre [please see: https://api.techiaith.org/](https://api.techiaith.org).
The API works using HTTPS GET, meaning you can use it with any programming language/software package of your choice which works over HTTP.

## Tutorials

[Tutorial 1](demo1.md) is an example of how to use the Moses SMT Machine Translation Online API to translate text.

## Current Version

Currently, there is only one version of the Moses SMT Machine Translation Online API available: v1 or 'version 1'.
The version used for the request is returned in the JSON result.

## Schema

The connection to the API is over HTTPS only, from the domain `api.techiaith.org/translate`. All data sent to and received from the API is in JSON ([unicode-escaped ASCII](http://tools.ietf.org/html/rfc5137))

## API Parameters

| Parameter     | Description | Notes |
|--------------|------------|----------|
| `api_key`    |  Your API key, from the API Centre (https://api.techiaith.org) | required |
| `q`       | The text to be translated. Formatted according to RFC 3986 (percent-encoded)  | required |
| `engine` | The name of the engine to be used for translation.  Choices are :  `CofnodYCynulliad` or `Deddfwriaeth` | required |
| `source` | The source text's language. Choices are `en` or `cy`. | required |
| `target` | The target language for any translations returned by the API.  Choices are `en` or `cy`. | required |
| `callback`   | Name of the function to wrap the response in for a JSON-P callback (see below)  | optional |

### Example

```
$ curl https://api.techiaith.org/translate/v1/translate?api_key=123&q=Will+the+Minister+make+a+statement&engine=CofnodYCynulliad&source=en&target=cy

{
    "success": true,
    "translations": [
        {"translatedText": "A wnaiff y Gweinidog wneud datganiad"},
    ],
    "version": 1
}
```

## JSON-P Callbacks

You can use the API with JSON-P callbacks by adding the parameter `callback` to your request:

```
$ curl https://api.techiaith.org/translate/v1/translate?api_key=123&q=Will+the+Minister+make+a+statement&engine=CofnodYCynulliad&source=en&target=cy&callback=foo
foo({
	"success": true,
	"translations": [
		{"translatedText": "A wnaiff y Gweinidog wneud datganiad"},
	],
    	"version": 1
});
```

## Rate Limiting

The API has a limit on the number of requests you can make per hour, linked to your API key. If you would like to increase the number of requests you can make to the API per hour, use the form within the 'API Centre'.

You can view the number of requests you have made/have remaining at any time by looking at the 'HTTP headers' of any response to the API:

```
$ curl -i https://api.techiaith.org/translate/v1/translate?api_key=123&q=Will+the+Minister+make+a+statement&engine=CofnodYCynulliad&source=en&target=cy

HTTP/1.1 200 OK
Date: Mon, 17 Nov 2014 14:41:21 GMT
Content-Type: application/json
Content-Language: cy
X-Ratelimit-Remaining: 276
X-Ratelimit-Limit: 300
X-Ratelimit-Reset: 1416237399
```

The headers contain all information you may require:

| Header Name | Description |
|--------------|------------|
| X-RateLimit-Limit | Maximum number of requests you can make per hour (rate limit) |
| X-RateLimit-Remaining | The number of requests remaining in the current rate limit window |
| X-RateLimit-Reset | The time at which the current rate limit window resets in [UTC epoch seconds](http://en.wikipedia.org/wiki/Unix_time) |

If you need the time in a different format, any modern programming language can get the job done. For example, if you open up the console on your web browser, you can easily get the reset time as a JavaScript Date object.

```javascript
new Date(1416237399 * 1000)
Date 2014-11-17T15:16:39.000Z
```

Once you go over the rate limit you will receive an error response:

```
$ curl -i curl https://api.techiaith.org/translate/v1/translate?api_key=123&q=Will+the+Minister+make+a+statement&engine=CofnodYCynulliad&source=en&target=cy

HTTP/1.1 200 OK
Date: Tue, 18 Nov 2014 10:44:37 GMT
Content-Type: application/json
X-Ratelimit-Limit: 300
X-Ratelimit-Remaining: 0
Content-Language: en
X-Ratelimit-Reset: 1416310586

{
    "success": false,
    "errors": ["403 Forbidden: You have exceeded your request limit"]
}
```


text:
package propagation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.springframework.transaction.annotation.Propagation;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

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

/**
 * 这个例子用来测试transaction propagation
 * 相关文档:
 * http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#tx-propagation
 * http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/transaction/annotation/Propagation.html
 * Created by qianjia on 2017/1/22.
 */
@SpringBootTest
@SpringBootApplication(exclude = FlywayAutoConfiguration.class)
public class PropagationCombinationTest extends AbstractTestNGSpringContextTests {

  @Autowired
  private FooService fooService;

  @Autowired
  private BarService barService;

  @Autowired
  private List<FooTxExecutor> fooTxExecutors = new ArrayList<>();

  @Autowired
  private List<BarTxExecutor> barTxExecutors = new ArrayList<>();

  private List<TxCombinationResult> txCombinationResults = new ArrayList<>();

  @AfterMethod
  public void clearData() {
    fooService.deleteAll();
    barService.deleteAll();
  }

  @AfterClass
  public void printResult() {

    System.out.println("---------------------------------------------------------");
    System.out.println("Foo(P)\tFoo(T)\tBar(P)\tBar(T)\tFoo(R)\tBar(R)\tException");
    System.out.println("---------------------------------------------------------");
    for (TxCombinationResult txCombinationResult : txCombinationResults) {
      System.out.println(txCombinationResult.toString());
    }

  }

  @DataProvider
  public Object[][] combinations() {

    String[] names = new String[] { "Alice", "Bob", "Mike" };
    List<String> argNames = Arrays.asList(names);

    List<TxCombination> txCombinationList = new ArrayList<>();
    for (Propagation fooMode : Propagation.values()) {

      for (Propagation barMode : Propagation.values()) {

        txCombinationList.add(new TxCombination(fooMode, false, barMode, false, argNames));
        txCombinationList.add(new TxCombination(fooMode, true, barMode, false, argNames));
        txCombinationList.add(new TxCombination(fooMode, false, barMode, true, argNames));
        txCombinationList.add(new TxCombination(fooMode, true, barMode, true, argNames));

      }

    }

    Object[][] params = new Object[txCombinationList.size()][];
    for (int i = 0; i < txCombinationList.size(); i++) {
      params[i] = new Object[] { txCombinationList.get(i) };
    }

    return params;

  }

  /**
   * 测试{@link Propagation#REQUIRED}的各种组合
   */
  @Test(dataProvider = "combinations")
  public void testCombination(TxCombination txCombination) {

    FooTxExecutor fooTxExecutor = getFooTxExecutor(txCombination.getFooMode());
    BarTxExecutor barTxExecutor = getBarTxExecutor(txCombination.getBarMode());

    Exception exception = null;
    try {

      fooTxExecutor.insert(
          barTxExecutor,
          txCombination.isFooThrowException(),
          txCombination.isBarThrowException(),
          txCombination.getNames().toArray(new String[0])
      );

    } catch (Exception e) {
      exception = e;
    }

    analyzeResult(txCombination, exception);

  }

  private FooTxExecutor getFooTxExecutor(Propagation propagation) {
    for (FooTxExecutor fooTxExecutor : fooTxExecutors) {
      if (fooTxExecutor.getPropagationMode().equals(propagation)) {
        return fooTxExecutor;
      }
    }
    return null;
  }

  private BarTxExecutor getBarTxExecutor(Propagation propagation) {
    for (BarTxExecutor barTxExecutor : barTxExecutors) {
      if (barTxExecutor.getPropagationMode().equals(propagation)) {
        return barTxExecutor;
      }
    }
    return null;
  }

  private void analyzeResult(TxCombination txCombination, Exception caughtException) {

    List<String> argNames = txCombination.getNames();

    Propagation fooMode = txCombination.getFooMode();
    Propagation barMode = txCombination.getBarMode();
    boolean fooThrowException = txCombination.isFooThrowException();
    boolean barThrowException = txCombination.isBarThrowException();

    List<String> fooActualNames = fooService.getAll();
    boolean fooSuccess = argNames.containsAll(fooActualNames) && fooActualNames.containsAll(argNames);

    List<String> barActualNames = barService.getAll();
    boolean barSuccess = argNames.containsAll(barActualNames) && barActualNames.containsAll(argNames);

    txCombinationResults.add(
        new TxCombinationResult(fooMode, fooThrowException, barMode, barThrowException, fooSuccess, barSuccess, caughtException)
    );

  }

  public static class TxCombination {

    private Propagation fooMode;

    private boolean fooThrowException;

    private Propagation barMode;

    private boolean barThrowException;

    private List<String> names;

    public TxCombination(Propagation fooMode, boolean fooThrowException,
        Propagation barMode, boolean barThrowException, List<String> names) {
      this.fooMode = fooMode;
      this.fooThrowException = fooThrowException;
      this.barMode = barMode;
      this.barThrowException = barThrowException;
      this.names = names;
    }

    public Propagation getFooMode() {
      return fooMode;
    }

    public Propagation getBarMode() {
      return barMode;
    }

    public List<String> getNames() {
      return names;
    }

    public boolean isFooThrowException() {
      return fooThrowException;
    }

    public boolean isBarThrowException() {
      return barThrowException;
    }

  }

  private static class TxCombinationResult {

    private Propagation fooMode;

    private boolean fooThrowException;

    private Propagation barMode;

    private boolean barThrowException;

    private boolean fooSuccess;

    private boolean barSuccess;

    private Exception caughtException;

    public TxCombinationResult(Propagation fooMode, boolean fooThrowException,
        Propagation barMode, boolean barThrowException, boolean fooSuccess, boolean barSuccess,
        Exception caughtException) {
      this.fooMode = fooMode;
      this.fooThrowException = fooThrowException;
      this.barMode = barMode;
      this.barThrowException = barThrowException;
      this.fooSuccess = fooSuccess;
      this.barSuccess = barSuccess;
      this.caughtException = caughtException;
    }

    @Override
    public String toString() {

      String exception =
          caughtException != null && !caughtException.getClass().equals(FakeException.class) ?
              caughtException.getClass().getName() + ": " + caughtException.getMessage()
              : "";

      final StringBuilder sb = new StringBuilder();
      sb
          .append(translate(fooMode))
          .append('\t')
          .append(translate(fooThrowException))
          .append('\t')
          .append(translate(barMode))
          .append('\t')
          .append(translate(barThrowException))
          .append('\t')
          .append(translate(fooSuccess))
          .append('\t')
          .append(translate(barSuccess))
          .append('\t')
          .append(exception);

      return sb.toString();

    }

    private String translate(boolean bool) {
      return bool ? "Y" : "N";
    }

    private String translate(Propagation propagation) {
      return propagation.toString();
    }

  }
}


text:
package org.fizmo.dropwizard.guice;

import com.google.inject.Inject;
import com.google.inject.Injector;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;
import com.sun.jersey.spi.container.servlet.WebConfig;
import com.yammer.dropwizard.config.Environment;

import java.util.Map;

public class DropwizardGuiceContainer extends GuiceContainer
{
    private final Environment environment;

    @Inject
    DropwizardGuiceContainer(Environment environment, Injector injector)
    {
        super(injector);

        this.environment = environment;
        environment.setJerseyServletContainer(this);
    }

    @Override
    public ResourceConfig getDefaultResourceConfig(Map<String, Object> props, WebConfig webConfig) {
        return environment.getJerseyResourceConfig();
    }
}


text:
<?php
class returnEquipment_model extends CI_Model {

	public function __construct()
	{
		$this->load->database();
	}

	public function return_equipment($LoanedOutID, $EquipmentRecordID, $StudentNumber,
									 $LoanedDate, $ReturnedDate){

			$updateParams = array(
				'EquipmentVisible' => 1);

			$this->db->where('EquipmentRecordID', $EquipmentRecordID);
			$this->db->update('equipment', $updateParams);

			$this->db->where('EquipmentRecordID', $EquipmentRecordID);
			$this->db->set('quantity', 'quantity+1', FALSE);
			$this->db->update('equipment');

			$this->db->where('LoanedOutID', $LoanedOutID);
			$this->db->delete('loanedout');

			$insertParams = array(
				'EquipmentRecordID' => $EquipmentRecordID,
				'StudentNumber' => $StudentNumber,
				'LoanedDate' => $LoanedDate,
				'ReturnedDate' => $ReturnedDate
			);

			$this->db->insert('loanhistory', $insertParams);
			header('Location: returns');
	}
}


text:
module Booknize
  module Crawler
    class SankeiJpMsnCom < Base
      CONTENT = {h1: '#NewsTitle', div: '.NewsTextFull', 'div.last-updated' => '.Timestamp'}
    end
  end
end


text:
module CapistranoScale
  unless defined?(::CapistranoScale::VERSION)
    VERSION = "0.0.3".freeze
  end
end


text:
import React, { Component } from 'react';
import List from 'react-toolbox/lib/list/List.js';
import ListItem from 'react-toolbox/lib/list/ListItem.js';
import ListSubHeader from 'react-toolbox/lib/list/ListSubHeader.js';

import InviteButton from './InviteButton.js';
import UserInviteDialog from './UserInviteDialog.js';

/**
 * Renders the users vies for CompanyReps.
 * @param inviteHandler()    callback function handling invitations
 */
class CompanyRepUsersView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dialogActive: false
    }
  }

  /**
   * Generates all of the ListItems
   */
  generateListItems = () => {
    var items = [];

    for(let i = 0; i < this.props.users.length; i++) {
      items.push(
        <ListItem
          avatar=""
          caption={this.props.users[i].name}
          legend={this.props.users[i].email}
        />
      );
    }

    return items;
  }

  /**
   * Toggle the visiblity of the edit Dialog.
   */
  toggleDialog = () => {
    var newDialogActive = !this.state.dialogActive;

    this.setState({
      dialogActive: newDialogActive
    });
  }

  render() {
    return(
      <div className="Users-company">
        <InviteButton toggleHandler={() => this.toggleDialog()}/>
        <List selectable ripple>
          {this.generateListItems()}
        </List>
        <UserInviteDialog active={this.state.dialogActive} inviteHandler={(email, message) => this.props.inviteHandler(email, message)} toggleHandler={() => this.toggleDialog()} />
      </div>
    );
  }
}

export default CompanyRepUsersView;


text:
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Changing field 'Verification.csv_report'
        db.alter_column(u'verify_verification', 'csv_report', self.gf('django.db.models.fields.files.FileField')(max_length=100, null=True))

    def backwards(self, orm):

        # Changing field 'Verification.csv_report'
        db.alter_column(u'verify_verification', 'csv_report', self.gf('django.db.models.fields.FilePathField')(max_length=100, null=True))

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        u'verify.rule': {
            'Meta': {'object_name': 'Rule'},
            'author': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'launch_recurrences': ('recurrence.fields.RecurrenceField', [], {'null': 'True', 'blank': 'True'}),
            'slug': ('autoslug.fields.AutoSlugField', [], {'unique_with': '()', 'max_length': '50', 'populate_from': "'title'"}),
            'task': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
            'title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '128'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'null': 'True', 'blank': 'True'})
        },
        u'verify.verification': {
            'Meta': {'object_name': 'Verification'},
            'csv_report': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
            'duration': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'launch_ts': ('django.db.models.fields.DateTimeField', [], {}),
            'note': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'outcome': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'parameters': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
            'rule': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['verify.Rule']"}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"})
        }
    }

    complete_apps = ['verify']


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

<title>org.robolectric.shadows.httpclient Class Hierarchy</title>
<meta name="date" content="2017-12-18">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.robolectric.shadows.httpclient

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.robolectric.shadows.httpclient.DefaultRequestDirector (implements org.apache.http.client.RequestDirector)

org.robolectric.shadows.httpclient.FakeHttp

org.robolectric.shadows.httpclient.FakeHttpLayer

org.robolectric.shadows.httpclient.FakeHttpLayer.DefaultRequestMatcher (implements org.robolectric.shadows.httpclient.RequestMatcher)

org.robolectric.shadows.httpclient.FakeHttpLayer.RequestMatcherBuilder (implements org.robolectric.shadows.httpclient.RequestMatcher)

org.robolectric.shadows.httpclient.FakeHttpLayer.RequestMatcherResponseRule (implements org.robolectric.shadows.httpclient.HttpEntityStub.ResponseRule)

org.robolectric.shadows.httpclient.FakeHttpLayer.UriRegexMatcher (implements org.robolectric.shadows.httpclient.RequestMatcher)

org.robolectric.shadows.httpclient.FakeHttpLayer.UriRequestMatcher (implements org.robolectric.shadows.httpclient.RequestMatcher)

org.robolectric.shadows.httpclient.HttpEntityStub (implements org.apache.http.HttpEntity)

org.robolectric.shadows.httpclient.TestHttpResponse.TestHttpEntity

org.robolectric.shadows.httpclient.HttpRequestInfo

org.robolectric.shadows.httpclient.HttpResponseStub (implements org.apache.http.HttpResponse)

org.robolectric.shadows.httpclient.TestHttpResponse

org.robolectric.shadows.httpclient.ParamsParser

org.robolectric.shadows.httpclient.ShadowDefaultRequestDirector

org.robolectric.shadows.httpclient.Shadows (implements org.robolectric.internal.ShadowProvider)

org.robolectric.shadows.httpclient.StatusLineStub (implements org.apache.http.StatusLine)

org.robolectric.shadows.httpclient.TestHttpResponse.TestStatusLine

Interface Hierarchy

org.robolectric.shadows.httpclient.FakeHttpLayer.RequestMatcherBuilder.PostBodyMatcher

org.robolectric.shadows.httpclient.HttpEntityStub.ResponseRule

org.robolectric.shadows.httpclient.HttpResponseGenerator

org.robolectric.shadows.httpclient.RequestMatcher

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
#include "stdafx.h"
#include "inquisitor.h"
#include "OleInqDataSource.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// COleInqDataSource

IMPLEMENT_DYNCREATE(COleInqDataSource, COleDataSource)

COleInqDataSource::COleInqDataSource()
{
}

COleInqDataSource::~COleInqDataSource()
{
}

BEGIN_MESSAGE_MAP(COleInqDataSource, COleDataSource)
	//{{AFX_MSG_MAP(COleInqDataSource)
		// NOTE - the ClassWizard will add and remove mapping macros here.
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// COleInqDataSource message handlers


text:
import os

from vee.commands.main import command, argument, group
from vee.environment import Environment
from vee.cli import style, style_note
from vee import log
from vee.package import Package

def describe(pkg, cache, depth=0):

    print ('    ' * depth) + style(pkg.name, 'blue'), pkg.id, style(
        '***' if pkg.id in cache else str(pkg), faint=True)

    if pkg.id in cache:
        return
    cache[pkg.id] = pkg

    for dep in pkg.dependencies:
        dep.resolve_existing()
        describe(dep, cache, depth + 1)

@command(
    argument('-e', '--environments', action='store_true'),
    name='list',
)
def list_(args):

    if args.environments:
        list_environments(args)
        return
    else:
        list_packages(args)

def list_environments(args):

    home = args.assert_home()
    con = home.db.connect()

    cache = {}

    for env in con.execute('SELECT * from environments ORDER by created_at ASC'):
        print env['created_at'], style(env['name'], 'blue'), env['id']
        # print list(row)

def list_packages(args):

    home = args.assert_home()
    con = home.db.connect()

    cache = {}

    for row in con.execute('SELECT * from packages ORDER by created_at DESC'):

        if row['id'] in cache:
            continue

        pkg = Package(url='junk', home=home)
        pkg.restore_from_row(row)
        pkg._load_dependencies()

        describe(pkg, cache)


text:
package com.troy.dprouter.api;

import android.content.Context;
import android.net.Uri;

public interface IDPRouterInterceptor
{
    Uri onPreRouting(Context context, Uri uri);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#B1CDB7"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_set_about"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:text="关于此软件:"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tv_des"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_set_about"
        android:layout_marginLeft="7dp"
        android:layout_marginRight="3dp"
        android:layout_marginTop="40dp"
        android:text="       当初写这个软件是出于我个人需求。因为之前用的苹果手机的一键音量控制感觉不错,但是安卓的各种音量种类不能统一调节,有的时候明明把音量关闭了,却还是会发出来声音,带来非常尴尬的使用体验。"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tv_version"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tv_des"
        android:layout_centerHorizontal="true"
        android:paddingTop="80dp"
        android:text="当前版本号:v1.5"
        android:textSize="18sp" />

    <ImageButton
        android:id="@+id/ib_about_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="34dp"
        android:layout_marginLeft="30dp"
        android:layout_toRightOf="@+id/tv_set_about"
        android:background="@drawable/selec_back" />

</RelativeLayout>


text:
<?php /** @var \Tuum\Web\View\Value $view */ ?>

<?php $this->blockAsSection('controller/sub-menu', 'sub-menu', ['current' => 'hello']); ?>

<?php $this->section->start() ?>

<a href="<?= $view->data->basePath; ?>?name=Controller Sample" >Controller Sample

Hello

<?php $this->section->saveAs('breadcrumb'); ?>

<?php

$name = $view->data['name'];

?>

Hello <?= $name; ?>

This is from SampleController::onHello( $name ),

and a sample/hello view file.


text:
from collections import defaultdict
import sys
import csv

if (sys.version_info > (3, 0)):
    import codecs

class csvRow:

    def __init__(self):
        self._rowdict = defaultdict(str)

    def __getitem__(self, key):
        return self._rowdict[key]

    def __setitem__(self, key, item):
        if (sys.version_info <= (3, 0)):
            if type(item).__name__ == "unicode":
                item = item.encode('utf-8')
        self._rowdict[key] = item

    def write(self, column, value):
        self._rowdict[column] = value

    @property
    def as_list(self):
        # Generate list of single cells in the row till highest index (dictionary key)
        # Empty cells (non-existent keys) are generated as empty string
        return [str(self._rowdict[x]) for x in range(0, max(self._rowdict) + 1)]

    def toCSV(self, delimiter=','):
        text = delimiter.join(self.as_list)
        return text.replace('\n', ' ')

    def __str__(self):
        return self.toCSV()

def writeFramex(frame, row):
    #frame-id
    row[0] =  "%3Xh" % frame._Id
    #frame-Name
    row[1] = frame._name

    #determine cycle-time
    if "GenMsgCycleTime" in frame._attributes:
        row[2]  = int(frame._attributes["GenMsgCycleTime"])

    #determine send-type
    if "GenMsgSendType" in frame._attributes:
        if frame._attributes["GenMsgSendType"] == "5":
            row[3] = "Cyclic+Change"
            if "GenMsgDelayTime" in frame._attributes:
                row[4] = int(frame._attributes["GenMsgDelayTime"])
        elif frame._attributes["GenMsgSendType"] == "0":
            row[3] = "Cyclic"
        elif frame._attributes["GenMsgSendType"] == "2":
            row[3] = "BAF"
            if "GenMsgNrOfRepetitions" in frame._attributes:
                row[4] = int(frame._attributes["GenMsgNrOfRepetitions"])
        elif frame._attributes["GenMsgSendType"] == "8":
            row[3] = "DualCycle"
            if "GenMsgCycleTimeActive" in frame._attributes:
                row[4] = int(frame._attributes["GenMsgCycleTimeActive"])
        elif frame._attributes["GenMsgSendType"] == "10":
            row[3] = "None"
            if "GenMsgDelayTime" in frame._attributes:
                row[3] = int(frame._attributes["GenMsgDelayTime"])
        elif frame._attributes["GenMsgSendType"] == "9":
            row[3] = "OnChange"
            if "GenMsgNrOfRepetitions" in frame._attributes:
                row[4] = int(frame._attributes["GenMsgNrOfRepetitions"])
        elif frame._attributes["GenMsgSendType"] == "1":
            row[3] = "Spontaneous"
            if "GenMsgDelayTime" in frame._attributes:
                row[4] = int(frame._attributes["GenMsgDelayTime"])
        else:
            pass

def writeBuMatrixx(buList, sig, frame, row, col):
    #iterate over boardunits:
    for bu in buList:
        # write "s" "r" "r/s" if signal is sent, received or send and received by boardunit
        if bu in sig._receiver and bu in frame._Transmitter:
            row[col] = "r/s"
        elif bu in sig._receiver:
            row[col] = "r"
        elif bu in frame._Transmitter:
            row[col] = "s"
        else:
            pass
        col += 1
    return col

def writeValuex(label, value, row, rearCol):
    row[rearCol] = value
    row[rearCol + 1] = label

def writeSignalx(db, sig, row, rearCol):
    #startbyte
    row[5] = int((sig.getMsbReverseStartbit())/8+1)
    #startbit
    row[6] = (sig.getMsbReverseStartbit())%8
    #signalname
    row[7] = sig._name

    # eval comment:
    if sig._comment is None:
        comment = ""
    else:
        comment = sig._comment

    # eval multiplex-info
    if sig._multiplex == 'Multiplexor':
        comment = "Mode Signal: " + comment
    elif sig._multiplex is not None:
        comment = "Mode " + str(sig._multiplex) + ":" + comment

    #write comment and size of signal in sheet
    row[8] = comment
    row[9] = sig._signalsize

    #startvalue of signal available
    if "GenSigStartValue" in sig._attributes:
        if db._signalDefines["GenSigStartValue"]._definition == "STRING":
            row[10] = sig._attributes["GenSigStartValue"]
        elif db._signalDefines["GenSigStartValue"]._definition == "INT" or db._signalDefines["GenSigStartValue"]._definition == "HEX":
            row[10] = "%Xh" % int(sig._attributes["GenSigStartValue"])

    #SNA-value of signal available
    if "GenSigSNA" in sig._attributes:
        row[11] = sig._attributes["GenSigSNA"][1:-1]

    # eval byteorder (intel == 1 / motorola == 0)
    if sig._is_little_endian == True:
        row[12] = "i"
    else:
        row[12] = "m"

    # is a unit defined for signal?
    if sig._unit.strip().__len__() > 0:
        # factor not 1.0 ?
        if float(sig._factor) != 1:
            row[rearCol+2] = "%g" % float(sig._factor) + "  " + sig._unit
        #factor == 1.0
        else:
            row[rearCol + 2] = sig._unit
    # no unit defined
    else:
        # factor not 1.0 ?
        if float(sig._factor) != 1:
            row[rearCol + 2] = float(sig._factor)

def exportCsv(db, filename, delimiter=','):
    head_top = ['ID', 'Frame Name', 'Cycle Time [ms]', 'Launch Type', 'Launch Parameter', 'Signal Byte No.', 'Signal Bit No.', 'Signal Name', 'Signal Function', 'Signal Length [Bit]', 'Signal Default', ' Signal Not Available', 'Byteorder']
    head_tail = ['Value',   'Name / Phys. Range', 'Function / Increment Unit']

    csvtable = list() # List holding all csv rows

    col = 0 # Column counter

    # -- headers start:
    headerrow = csvRow()

    # write first row (header) cols before frameardunits:
    for head in head_top:
        headerrow.write(col, head)
        col += 1

    # write frameardunits in first row:
    buList = []
    for bu in db._BUs._list:
        headerrow.write(col, bu._name)
        buList.append(bu._name)
        col += 1

    # write first row (header) cols after frameardunits:
    for head in head_tail:
        headerrow.write(col, head)
        col += 1

    csvtable.append(headerrow)
    # -- headers end...

    frameHash = {}
    for frame in db._fl._list:
        frameHash[int(frame._Id)] = frame

    # set row to first Frame (row = 0 is header)
    row = 1

    # iterate over the frames
    for idx in sorted(frameHash.keys()):
        frame = frameHash[idx]

        # sort signals:
        sigHash = {}
        for sig in frame._signals:
            sigHash["%02d" % int(sig.getMsbReverseStartbit()) + sig._name] = sig

        # iterate over signals
        for sig_idx in sorted(sigHash.keys()):
            sig = sigHash[sig_idx]

            # value table available?
            if sig._values.__len__() > 0:
                # iterate over values in valuetable
                for val in sorted(sig._values.keys()):
                    signalRow = csvRow()
                    writeFramex(frame, signalRow)
                    col = head_top.__len__()
                    col = writeBuMatrixx(buList, sig, frame, signalRow, col)
                    # write Value
                    writeValuex(val, sig._values[val], signalRow, col)
                    writeSignalx(db, sig, signalRow, col)

                    # no min/max here, because min/max has same col as values.
                    # next row
                    row += 1
                    csvtable.append(signalRow)
                # loop over values ends here
            # no value table available
            else:
                signalRow = csvRow()
                writeFramex(frame, signalRow)
                col = head_top.__len__()
                col = writeBuMatrixx(buList, sig, frame, signalRow, col)
                writeSignalx(db, sig, signalRow, col)

                if float(sig._min) != 0 or float(sig._max) != 1.0:
                    signalRow[col+1] = str("%g..%g" %(sig._min, sig._max))

                # next row
                row += 1
                csvtable.append(signalRow)
                # set style to normal - without border
        # loop over signals ends here
    # loop over frames ends here

    if filename is not None:
        # save file
        if (sys.version_info > (3, 0)):
            with open(filename, 'w', encoding='utf8') as thefile:
                writer = csv.writer(thefile, delimiter=delimiter)
                for row in csvtable:
                    writer.writerow(row.as_list)

        else:
            with open(filename, 'w') as thefile:
                writer = csv.writer(thefile, delimiter=delimiter)
                for row in csvtable:
                    writer.writerow(row.as_list)

    else:
        # just print to stdout
        finalTableString = "\n".join([row.toCSV(delimiter) for row in csvtable])
        print(finalTableString)


text:
<?php namespace Arcanedev\LogViewer\Contracts\Utilities;

use Illuminate\Translation\Translator;

/**
 * Interface  LogLevels
 *
 * @package   Arcanedev\LogViewer\Contracts\Utilities
 * @author    ARCANEDEV <arcanedev.maroc@gmail.com>
 */
interface LogLevels
{
    /* -----------------------------------------------------------------
     |  Getters & Setters
     | -----------------------------------------------------------------
     */

    /**
     * Set the Translator instance.
     *
     * @param  \Illuminate\Translation\Translator  $translator
     *
     * @return self
     */
    public function setTranslator(Translator $translator);

    /**
     * Get the selected locale.
     *
     * @return string
     */
    public function getLocale();

    /**
     * Set the selected locale.
     *
     * @param  string  $locale
     *
     * @return self
     */
    public function setLocale($locale);

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */

    /**
     * Get the log levels.
     *
     * @param  bool  $flip
     *
     * @return array
     */
    public function lists($flip = false);

    /**
     * Get translated levels.
     *
     * @param  string|null  $locale
     *
     * @return array
     */
    public function names($locale = null);

    /**
     * Get PSR log levels.
     *
     * @param  bool  $flip
     *
     * @return array
     */
    public static function all($flip = false);

    /**
     * Get the translated level.
     *
     * @param  string       $key
     * @param  string|null  $locale
     *
     * @return string
     */
    public function get($key, $locale = null);
}


text:
package com.ad.zakatrizki.model;

/**
 * Created by Amay on 5/27/2017.
 */

public class Refresh {
    Boolean refresh=false;

    public Refresh(Boolean refresh) {
        this.refresh = refresh;
    }

    public Boolean getRefresh() {
        return refresh;
    }

    public void setRefresh(Boolean refresh) {
        this.refresh = refresh;
    }
}


text:
global.asyncFunc = async function add(x) {
    var a = resolveAfter2Seconds(20);
    var b = resolveAfter2Seconds(30);
    return x + (await a) + (await b);
};

function resolveAfter2Seconds(x) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve(x);
        }, 2000);
    });
}

setTimeout(() => {}, 0);
setTimeout(function() {
    function resolveAfter2Seconds(x) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve(x);
            }, 2000);
        });
    }

    async function add1(x) {
        var a = resolveAfter2Seconds(20);
        var b = resolveAfter2Seconds(30);
        return x + (await a) + (await b);
    }

    add1(10).then(v => {
        console.log(v); // prints 60 after 2 seconds.
    });

    async function add2(x) {
        var a = await resolveAfter2Seconds(20);
        var b = await resolveAfter2Seconds(30);
        return x + a + b;
    }

    add2(10).then(v => {
        console.log(v); // prints 60 after 4 seconds.
    });

    var ttdLogURI = __dirname + '/../snapshot';

    if (global.emitTTDLog) {
        setTimeout(function() {
            console.log(add2);
            emitTTDLog(ttdLogURI);
        }, 500);
    }
}, 100);


text:
package org.elasticsearch.rest.action.admin.indices.exists.types;

import org.elasticsearch.action.admin.indices.exists.types.TypesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.types.TypesExistsResponse;
import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
import org.elasticsearch.rest.RestController;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.action.support.RestResponseListener;

import static org.elasticsearch.rest.RestRequest.Method.HEAD;
import static org.elasticsearch.rest.RestStatus.NOT_FOUND;
import static org.elasticsearch.rest.RestStatus.OK;

/**
 * Rest api for checking if a type exists.
 */
public class RestTypesExistsAction extends BaseRestHandler {

    @Inject
    public RestTypesExistsAction(Settings settings, RestController controller, Client client) {
        super(settings, client);
        controller.registerHandler(HEAD, "/{index}/{type}", this);
    }

    @Override
    public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
        TypesExistsRequest typesExistsRequest = new TypesExistsRequest(
                Strings.splitStringByCommaToArray(request.param("index")), Strings.splitStringByCommaToArray(request.param("type"))
        );
        typesExistsRequest.local(request.paramAsBoolean("local", typesExistsRequest.local()));
        typesExistsRequest.indicesOptions(IndicesOptions.fromRequest(request, typesExistsRequest.indicesOptions()));
        client.admin().indices().typesExists(typesExistsRequest, new RestResponseListener<TypesExistsResponse>(channel) {
            @Override
            public RestResponse buildResponse(TypesExistsResponse response) throws Exception {
                if (response.isExists()) {
                    return new BytesRestResponse(OK);
                } else {
                    return new BytesRestResponse(NOT_FOUND);
                }
            }
        });
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<CustomFieldTranslation xmlns="http://soap.sforce.com/2006/04/metadata">
    <name>Capacity__c</name>
    <help>El número máximo de ocupantes que puede albergar la instalación.</help>
    <label>Capacidad</label>
</CustomFieldTranslation>


text:
.tabbed-pane {
    flex: auto;
    overflow: hidden;
}

.tabbed-pane-content {
    position: relative;
    overflow: auto;
    flex: auto;
    display: flex;
    flex-direction: column;
}

.tabbed-pane-content.has-no-tabs {
    background-color: lightgray;
}

.tabbed-pane-placeholder {
    font-size: 14px;
    text-align: center;
    margin-top: 20px;
    text-shadow: rgba(255, 255, 255, 0.75) 0 1px 0;
}

.tabbed-pane-header {
    display: flex;
    flex: 0 0 27px;
    border-bottom: 1px solid #ccc;
    overflow: visible;
    width: 100%;
    background-color: #f3f3f3;
}

.tabbed-pane-header-contents {
    flex: auto;
    pointer-events: none;
    margin-left: 5px;
    position: relative;
}

.tabbed-pane-header-contents > * {
    pointer-events: initial;
}

.tabbed-pane-header-tab-icon {
    margin-right: 2px;
}

.tabbed-pane-header-tab {
    float: left;
    margin-top: 2px;
    padding: 2px 4px 2px 4px;
    height: 24px;
    border: 1px solid transparent;
    border-bottom: none;
    line-height: 15px;
    white-space: nowrap;
    cursor: default;
    display: flex;
    align-items: center;
    color: #5a5a5a;
}

.tabbed-pane-header-tab:hover,
.tabbed-pane-header-tab.selected:hover {
    color: #333;
    background-color: #e5e5e5;
}

.tabbed-pane-header-tab-title {
    text-overflow: ellipsis;
    overflow: hidden;
}

.tabbed-pane-header-tab.measuring {
    visibility: hidden;
}

.tabbed-pane-header-tab.selected {
    border: 1px solid #ccc;
    border-bottom: none;
    color: #333;
}

.tabbed-pane-header-tab.selected {
    background-color: white;
    border-top-color: #ccc;
}

.tabbed-pane-header-tab.dragging {
    position: relative;
    box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.37);
    background-color: #e5e5e5;
}

.tabbed-pane-header-tab .tabbed-pane-close-button {
    display: inline-block;
    position: relative;
    top: 2px;
    left: 1px;
    margin-left: 2px;
    margin-top: -3px;
    visibility: hidden;
}

.tabbed-pane-header-tab:hover .tabbed-pane-close-button,
.tabbed-pane-header-tab.selected .tabbed-pane-close-button {
    visibility: visible;
}

.tabbed-pane-header-tabs-drop-down-container {
    float: left;
    position: relative;
    vertical-align: bottom;
    line-height: 24px;
    opacity: 0.8;
    color: inherit;
    font-size: 133%;
    cursor: pointer;
}

.tabbed-pane-header-tabs-drop-down-container > .glyph {
    height: 26px;
    background-color: hsla(0,0%,20%,1);
    -webkit-mask-image: url(Images/toolbarButtonGlyphs.png);
    -webkit-mask-position: -68px -143px;
    -webkit-mask-size: 352px 168px;
    width: 24px;
}

@media (-webkit-min-device-pixel-ratio: 1.5) {
.tabbed-pane-header-tabs-drop-down-container > .glyph {
    -webkit-mask-image: url(Images/toolbarButtonGlyphs_2x.png);
}
} /* media */

.tabbed-pane-header-tabs-drop-down-container:hover {
    background-color: rgb(229, 229, 229);
}

.tabbed-pane-header-tabs-drop-down-container.measuring {
    visibility: hidden;
}

.tabbed-pane-header-tabs-drop-down-container:hover {
    opacity: 1.0;
}

.tabbed-pane-header-tabs-drop-down-container:active {
    opacity: 0.8;
}

/* Web page style */

.tabbed-pane-shadow.vertical-tab-layout {
    flex-direction: row !important;
}

.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header {
    background-color: transparent;
    border: none transparent !important;
    width: auto;
    flex: 0 0 auto;
    flex-direction: column;
    padding-top: 10px;
    overflow: hidden;
}

.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-content {
    padding: 10px 10px 10px 0;
    overflow-x: hidden;
}

.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-contents {
    margin: 0;
    flex: none;
}

.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tabs {
    display: flex;
    flex-direction: column;
    width: 120px;
}

.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab {
    background-color: transparent;
    border: none transparent;
    font-weight: normal;
    text-shadow: none;
    color: #777;
    height: 26px;
    padding-left: 10px;
    border-left: 6px solid transparent;
    margin: 0;
    display: flex;
    align-items: center;
}

.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab:not(.selected) {
    cursor: pointer !important;
}

.tabbed-pane-shadow.vertical-tab-layout .tabbed-pane-header-tab.selected {
    color: inherit;
    border: none transparent;
    border-left: 6px solid #666;
}

.tabbed-pane-tab-slider,
.-theme-selection-color {
    height: 2px;
    position: absolute;
    bottom: -1px;
    background-color: #3E82F7;
    left: 0;
    z-index: 50;
    transform-origin: 0 100%;
    transition: transform 150ms cubic-bezier(0, 0, 0.2, 1);
    visibility: hidden;
    border-top: 1px solid hsl(218, 82%, 78%);
}

@media (-webkit-min-device-pixel-ratio: 1.5) {
    .tabbed-pane-tab-slider {
        border-top: none;
    }
}

.tabbed-pane-tab-slider.enabled {
    visibility: visible;
}

.tabbed-pane-header-tab.disabled {
    opacity: 0.5;
    pointer-events: none;
}

.tabbed-pane-header.tabbed-pane-no-header-background {
    background-color: transparent;
}


text:
package com.lmn.Arbiter_Android.Loaders;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.LocalBroadcastManager;

import com.lmn.Arbiter_Android.ArbiterProject;
import com.lmn.Arbiter_Android.BaseClasses.Layer;
import com.lmn.Arbiter_Android.BroadcastReceivers.LayerBroadcastReceiver;
import com.lmn.Arbiter_Android.DatabaseHelpers.ApplicationDatabaseHelper;
import com.lmn.Arbiter_Android.DatabaseHelpers.FeatureDatabaseHelper;
//import com.lmn.Arbiter_Android.DatabaseHelpers.DbHelpers;
import com.lmn.Arbiter_Android.DatabaseHelpers.ProjectDatabaseHelper;
import com.lmn.Arbiter_Android.DatabaseHelpers.TableHelpers.LayersHelper;
import com.lmn.Arbiter_Android.ProjectStructure.ProjectStructure;

public class InsertFeatureListLoader extends AsyncTaskLoader<ArrayList<Layer>> {
	public static final String LAYERS_LIST_UPDATED = "LAYERS_LIST_UPDATED";

	private LayerBroadcastReceiver loaderBroadcastReceiver = null;
	private ArrayList<Layer> layers;
	private Activity activity;
	private Context context;
	private String projectName;

	public InsertFeatureListLoader(Activity activity) {
		super(activity.getApplicationContext());
		this.activity = activity;
		this.context = activity.getApplicationContext();
	}

	private SQLiteDatabase getAppDb(){
		return ApplicationDatabaseHelper
				.getHelper(context).getWritableDatabase();
	}

	private SQLiteDatabase getProjectDb(){
		return ProjectDatabaseHelper.getHelper(context,
				ProjectStructure.getProjectPath(projectName), false).getWritableDatabase();
	}

	private SQLiteDatabase getFeatureDb(){
		return FeatureDatabaseHelper.getHelper(context,
				ProjectStructure.getProjectPath(projectName), false).getWritableDatabase();
	}

	@Override
	public ArrayList<Layer> loadInBackground() {
		projectName = ArbiterProject.getArbiterProject().getOpenProject(activity);

		return LayersHelper.getLayersHelper()
				.getEditableLayers(getAppDb(),
						getProjectDb(), getFeatureDb());
	}

	/**
     * Called when there is new data to deliver to the client.  The
     * super class will take care of delivering it; the implementation
     * here just adds a little more logic.
     */
    @Override public void deliverResult(ArrayList<Layer> _layers) {
        if (isReset()) {
            // An async query came in while the loader is stopped.  We
            // don't need the result.
            if (layers != null) {
          //      onReleaseResources(cursor);
            }
        }

        ArrayList<Layer> oldLayers = _layers;
        layers = _layers;

        if (isStarted()) {
            // If the Loader is currently started, we can immediately
            // deliver its results.
            super.deliverResult(layers);
        }

        // At this point we can release the resources associated with
        // 'oldApps' if needed; now that the new result is delivered we
        // know that it is no longer in use.
        if (oldLayers != null) {
            onReleaseResources(oldLayers);
        }
    }

    /**
     * Handles a request to start the Loader.
     */
    @Override protected void onStartLoading() {
        if (layers != null) {
            // If we currently have a result available, deliver it
            // immediately.
            deliverResult(layers);
        }

        // Start watching for changes in the app data.
        if (loaderBroadcastReceiver == null) {
        	loaderBroadcastReceiver = new LayerBroadcastReceiver(this);
        	LocalBroadcastManager.getInstance(getContext()).
        		registerReceiver(loaderBroadcastReceiver, new IntentFilter(InsertFeatureListLoader.LAYERS_LIST_UPDATED));
        }

        if (takeContentChanged() || layers == null) {
            // If the data has changed since the last time it was loaded
            // or is not currently available, start a load.
            forceLoad();
        }
    }

    /**
     * Handles a request to stop the Loader.
     */
    @Override protected void onStopLoading() {
        // Attempt to cancel the current load task if possible.
        cancelLoad();
    }

    /**
     * Handles a request to cancel a load.
     */
    @Override public void onCanceled(ArrayList<Layer> _layers) {
        super.onCanceled(_layers);

        // At this point we can release the resources associated with 'apps'
        // if needed.
        onReleaseResources(_layers);
    }

    /**
     * Handles a request to completely reset the Loader.
     */
    @Override protected void onReset() {
        super.onReset();

        // Ensure the loader is stopped
        onStopLoading();

        // At this point we can release the resources associated with 'apps'
        // if needed.
        if (layers != null) {
            onReleaseResources(layers);
            layers = null;
        }

        // Stop monitoring for changes.
        if (loaderBroadcastReceiver != null) {
        	LocalBroadcastManager.getInstance(getContext()).
        		unregisterReceiver(loaderBroadcastReceiver);
            loaderBroadcastReceiver = null;
        }
    }

    /**
     * Helper function to take care of releasing resources associated
     * with an actively loaded data set.
     */
    protected void onReleaseResources(ArrayList<Layer> _projects) {
        // For a simple List<> there is nothing to do.  For something
        // like a Cursor, we would close it here.

    }
}


text:
require 'spec_helper'

describe GameController do
  # TODO
end


text:
cask "tower" do
  version "6.5,279:36c8e109"
  sha256 "6af8be62843ddf3ebcb3b1dc709669fbedb09b0352767f90057c027453ab4430"

  url "https://fournova-app-updates.s3.amazonaws.com/apps/tower3-mac/#{version.after_comma.before_colon}-#{version.after_colon}/Tower-#{version.before_comma}-#{version.after_comma.before_colon}.zip",
      verified: "fournova-app-updates.s3.amazonaws.com/"
  name "Tower"
  desc "Git client focusing on power and productivity"
  homepage "https://www.git-tower.com/"

  livecheck do
    url "https://updates.fournova.com/updates/tower3-mac/stable"
    strategy :page_match do |page|
      match = page.match(%r{(\d+(?:\.\d+)*)-([a-z0-9]+)/Tower-(\d+(?:\.\d+)*)-(\d+(?:\.\d+)*)\.zip}i)
      "#{match[3]},#{match[1]}:#{match[2]}"
    end
  end

  auto_updates true

  app "Tower.app"
  binary "#{appdir}/Tower.app/Contents/MacOS/gittower"

  zap trash: [
    "~/Library/Application Support/com.fournova.Tower*",
    "~/Library/Caches/com.fournova.Tower*",
    "~/Library/Preferences/com.fournova.Tower*.plist",
    "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.fournova.tower*.sfl2",
  ]
end


text:
package org.xelasov.jobs.server;

/**
 * Avaialable services:
 * - GET/PUT /jobs/submit/{queue-name}/             -> submit job for future execution
 * - GET     /jobs/fetch                            -> get a job to execute; job may come from any queue
 * - GET     /jobs/fetch/{queue-name}               -> get a job to execute from a specific queue
 * - GET/PUT /jobs/done/{queue-name}/{job-id}       -> indicate that the job completed successfully
 * - GET/PUT /jobs/fail/{queue-name}/{job-id}       -> indicate that the job failed
 */
public abstract class BaseJobsServlet extends BaseServlet {

}


text:
<?php

// Warning! This code was generated by WSDL2PHP tool.
// author: Filippov Andrey <afi.work@gmail.com>
// see https://solo-framework-lib.googlecode.com

namespace Moneta\Types;

/**
 * Выписка по счету.
	 * Account statement.
	 *
 */
class AccountStatement
{

	/**
	 * Внутрибанковский счет.
	 * Owner account.
	 *
	 *
	 * @var string
	 */
	 public $ownerAccount = null;

	/**
	 * Дата договора.
	 * Contract date.
	 *
	 *
	 * @var dateTime
	 */
	 public $contractDate = null;

	/**
	 * Валюта счета.
	 * Account currency.
	 *
	 *
	 * @var string
	 */
	 public $ownerAccountCurrency = null;

	/**
	 * Владелец счета.
	 * Account owner.
	 *
	 *
	 * @var string
	 */
	 public $ownerName = null;

	/**
	 * Дата начала выборки.
	 * Date from.
	 *
	 *
	 * @var dateTime
	 */
	 public $dateFrom = null;

	/**
	 * Дата окончания выборки.
	 * Date to.
	 *
	 *
	 * @var dateTime
	 */
	 public $dateTo = null;

	/**
	 * Дата последней операции.
	 * Date of last operation.
	 *
	 *
	 * @var dateTime
	 */
	 public $lastOperationDate = null;

	/**
	 * Дата актуальности.
	 * Relevance date.
	 *
	 *
	 * @var dateTime
	 */
	 public $now = null;

	/**
	 * Входящий остаток.
	 * Opening balance.
	 *
	 *
	 * @var decimal
	 */
	 public $inSaldo = null;

	/**
	 * Исходящий остаток.
	 * Closing balance.
	 *
	 *
	 * @var decimal
	 */
	 public $outSaldo = null;

	/**
	 * Заблокированная входящая сумма.
	 * Blocked opening balance.
	 *
	 *
	 * @var decimal
	 */
	 public $inSaldoBlocked = null;

	/**
	 * Заблокированная исходящая сумма.
	 * Blocked closing balance.
	 *
	 *
	 * @var decimal
	 */
	 public $outSaldoBlocked = null;

	/**
	 * Итоговые обороты по дебету.
	 * Total turnover on the debit.
	 *
	 *
	 * @var decimal
	 */
	 public $debitAmountTotal = null;

	/**
	 * Итоговые обороты по кредиту.
	 * Total turnover on the debit.
	 *
	 *
	 * @var decimal
	 */
	 public $creditAmountTotal = null;

	/**
	 * Общее количество записей, которое можно получить в данной выборке.
	 * The total number of records in the response.
	 *
	 *
	 * @var long
	 */
	 public $totalSize = null;

	/**
	 * Информация об операциях.
	 * Information about operations.
	 *
	 *
	 * @var AccountStatementRecord
	 */
	 public $orders = null;

	/**
	 * Информация об операциях.
	 * Information about operations.
	 *
	 *
	 * @param AccountStatementRecord
	 *
	 * @return void
	 */
	public function addOrders(AccountStatementRecord $item)
	{
		$this->orders[] = $item;
	}

}


text:
package com.taobao.api.response;

import java.util.Date;
import com.taobao.api.internal.mapping.ApiField;

import com.taobao.api.TaobaoResponse;

/**
 * TOP API: taobao.time.get response.
 *
 * @author auto create
 * @since 1.0, null
 */
public class TimeGetResponse extends TaobaoResponse {

	private static final long serialVersionUID = 6179631111712373527L;

	/**
	 * 淘宝系统当前时间。格式:yyyy-MM-dd HH:mm:ss
	 */
	@ApiField("time")
	private Date time;

	public void setTime(Date time) {
		this.time = time;
	}
	public Date getTime( ) {
		return this.time;
	}

}


text:
from pybuilder.core import use_plugin, before, task, init
from pybuilder.utils import assert_can_execute, execute_command

use_plugin("python.core")

@init
def depend_on_snakefood(project):
    project.plugin_depends_on("snakefood")

@before("render_snakefood_report")
def check_snakefood_available(logger):
    logger.debug("Checking availability of snakefood")
    assert_can_execute(("sfood", "-h"), "sfood", "plugin python.snakefood")
    logger.debug("snakefood has been found")

@before("render_snakefood_report")
def check_graphviz_available(logger):

    logger.debug("Checking availability of graphviz")
    assert_can_execute(("dot", "-V"), "graphviz", "plugin python.snakefood")
    logger.debug("graphviz has been found")

@task("render_snakefood_report", description="Renders a snakefood PDF to the reports directory.")
def render_snakefood_report(project, logger):
    logger.info("Executing snakefood on project sources")

    internal_report_file = project.expand_path("$dir_reports/snakefood-internal")
    external_report_file = project.expand_path("$dir_reports/snakefood-external")
    collect_dependencies(project, internal_report_file, external_report_file)

    logger.debug("Transforming snakefood graphs to graphviz")
    internal_graph_file = project.expand_path("$dir_reports/snakefood-internal.dot")
    external_graph_file = project.expand_path("$dir_reports/snakefood-external.dot")
    generate_graph(internal_report_file, internal_graph_file)
    generate_graph(external_report_file, external_graph_file)

    logger.debug("Rendering pdfs")
    internal_pdf_file = project.expand_path("$dir_reports/snakefood-internal.pdf")
    external_pdf_file = project.expand_path("$dir_reports/snakefood-external.pdf")
    generate_pdf(internal_graph_file, internal_pdf_file)
    logger.debug("Created {0}".format(internal_pdf_file))
    logger.debug("Created {0}".format(external_pdf_file))
    generate_pdf(external_graph_file, external_pdf_file)

def collect_dependencies(project, internal_report_file, external_report_file):
    source_dir = project.expand_path("$dir_source_main_python")
    internal_command = ["sfood", "--internal"]
    external_command = ["sfood", "--external"]

    execute_command(internal_command, internal_report_file, cwd=source_dir)
    execute_command(external_command, external_report_file, cwd=source_dir)

def generate_graph(report_file, graph_file):
    execute_command(["sfood-graph", report_file], graph_file)

def generate_pdf(graph_file, pdf_file):
    execute_command(["dot", "-Tpdf", graph_file], pdf_file)


text:
package com.github.fromi.chess;

import static com.github.fromi.chess.Player.State.PLAYING;
import static com.github.fromi.chess.Player.State.WAITING;
import static com.github.fromi.chess.material.Piece.Color.WHITE;
import static com.google.common.collect.Maps.toMap;
import static java.util.EnumSet.allOf;

import java.util.Map;

import com.github.fromi.chess.material.Board;
import com.github.fromi.chess.material.MovesRecord;
import com.github.fromi.chess.material.Piece;
import com.google.common.eventbus.EventBus;

public class Game {
    private final EventBus eventBus = new EventBus();
    private final Map<Piece.Color, Player> players;
    private final Board board;
    private final MovesRecord movesRecord;

    public Game() {
        movesRecord = new MovesRecord(eventBus);
        board = new Board(eventBus, movesRecord);
        players = toMap(allOf(Piece.Color.class), color -> new Player(color, board, eventBus, color == WHITE ? PLAYING : WAITING));
    }

    public Game(Data data) {
        movesRecord = new MovesRecord(eventBus, data.getMovesRecord());
        board = new Board(data.getBoard(), eventBus, movesRecord);
        players = toMap(allOf(Piece.Color.class), color -> new Player(color, board, eventBus, data.getPlayersStates().get(color)));
    }

    public void register(Object listener) {
        eventBus.register(listener);
    }

    public Player player(Piece.Color color) {
        return players.get(color);
    }

    public static interface Data {
        Board.Data getBoard();
        Map<Piece.Color, Player.State> getPlayersStates();
        MovesRecord.Data getMovesRecord();
    }
}


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  include SessionsHelper

private
  # Confirms a logged-in user.
  def logged_in_user
    unless logged_in?
      store_location
      flash[:danger] = 'Please log in.'
      redirect_to login_url
    end
  end
end