text:
using System;
using System.Windows.Forms;
using SharpNeat.EvolutionAlgorithms;
using SharpNeat.Genomes.Neat;
using SharpNeat.Utility;
using ZedGraph;
using System.Drawing;

namespace SharpNeatGUI
{
    /// <summary>
    /// Form for displaying a graph plot of summary information (e.g. distribution curves).
    /// </summary>
    public partial class SummaryGraphForm : Form
    {
        AbstractGenerationalAlgorithm<NeatGenome> _ea;
        readonly SummaryDataSource[] _dataSourceArray;
        PointPairList[] _pointPlotArray;
        GraphPane _graphPane;
        readonly Color[] _plotColorArr = new Color[] { Color.LightSlateGray, Color.LightBlue, Color.LightGreen };

        #region Constructor

        /// <summary>
        /// Construct the form with the provided details and data sources.
        /// </summary>
        public SummaryGraphForm(string title, string xAxisTitle, string y1AxisTitle, string y2AxisTitle,
                         SummaryDataSource[] dataSourceArray, AbstractGenerationalAlgorithm<NeatGenome> ea)
        {
            InitializeComponent();

            this.Text = $"SharpNEAT - {title}";
            _dataSourceArray = dataSourceArray;
            InitGraph(title, xAxisTitle, y1AxisTitle, y2AxisTitle, dataSourceArray);

            _ea = ea;
            if(null != ea) {
                _ea.UpdateEvent += new EventHandler(_ea_UpdateEvent);
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// Called when a new evolution algorithm is initialized. Clean up any existing event listeners and
        /// connect up to the new evolution algorithm.
        /// </summary>
        public void Reconnect(AbstractGenerationalAlgorithm<NeatGenome> ea)
        {
            // Clean up.
            if(null != _ea) {
                _ea.UpdateEvent -= new EventHandler(_ea_UpdateEvent);
            }

            foreach(PointPairList ppl in _pointPlotArray) {
                ppl.Clear();
            }

            // Reconnect.
            _ea = ea;
            _ea.UpdateEvent += new EventHandler(_ea_UpdateEvent);
        }

        #endregion

        #region Private Methods

        private void InitGraph(string title, string xAxisTitle, string y1AxisTitle, string y2AxisTitle, SummaryDataSource[] dataSourceArray)
        {
            _graphPane = zed.GraphPane;
            _graphPane.Title.Text = title;

			_graphPane.XAxis.Title.Text = xAxisTitle;
			_graphPane.XAxis.MajorGrid.IsVisible = true;

			_graphPane.YAxis.Title.Text = y1AxisTitle;
			_graphPane.YAxis.MajorGrid.IsVisible = true;

			_graphPane.Y2Axis.Title.Text = y2AxisTitle;
			_graphPane.Y2Axis.MajorGrid.IsVisible = false;

            // Create point-pair lists and bind them to the graph control.
            int sourceCount = dataSourceArray.Length;
            _pointPlotArray = new PointPairList[sourceCount];
            for(int i=0; i<sourceCount; i++)
            {
                SummaryDataSource ds = dataSourceArray[i];
                _pointPlotArray[i] =new PointPairList();

                Color color = _plotColorArr[i % 3];
                BarItem barItem = _graphPane.AddBar(ds.Name, _pointPlotArray[i], color);
                barItem.Bar.Fill = new Fill(color);
                _graphPane.BarSettings.MinClusterGap = 0;

                barItem.IsY2Axis = (ds.YAxis == 1);
            }
        }

        private void EnsurePointPairListLength(PointPairList ppl, int length)
        {
            int delta = length-ppl.Count;

            if(delta > 0)
            {   // Add additional points.
                for(int i=0; i<delta; i++) {
                    ppl.Add(0.0, 0.0);
                }
            }
            else if(delta < 0)
            {   // Remove excess points.
                ppl.RemoveRange(length, -delta);
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handle update event from the evolution algorithm - update the view.
        /// </summary>
        public void _ea_UpdateEvent(object sender, EventArgs e)
        {
            // Switch execution to GUI thread if necessary.
            if(this.InvokeRequired)
            {
                // Must use Invoke(). BeginInvoke() will execute asynchronously and the evolution algorithm therefore
                // may have moved on and will be in an intermediate and indeterminate (between generations) state.
                this.Invoke(new MethodInvoker(delegate()
                {
                    if(this.IsDisposed) {
                        return;
                    }

                    // Update plot points for each series in turn.
                    int sourceCount = _dataSourceArray.Length;
                    for(int i=0; i<sourceCount; i++)
                    {
                        SummaryDataSource ds = _dataSourceArray[i];
                        Point2DDouble[] pointArr = ds.GetPointArray();
                        PointPairList ppl = _pointPlotArray[i];
                        EnsurePointPairListLength(ppl, pointArr.Length);

                        for(int j=0; j<pointArr.Length; j++)
                        {
                            ppl[j].X = pointArr[j].X;
                            ppl[j].Y = pointArr[j].Y;
                        }
                    }

                    // Trigger graph to redraw.
                    zed.AxisChange();
                    Refresh();
                }));
            }
        }

        private void GenomeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(null != _ea) {
                _ea.UpdateEvent -= new EventHandler(_ea_UpdateEvent);
            }
        }

        #endregion
    }
}


text:
<?php

namespace CloudCreativity\LaravelJsonApi\Console\Commands;

use CloudCreativity\LaravelJsonApi\Exceptions\RuntimeException;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;

/**
 * Class MakeContentNegotiator
 *
 * @package CloudCreativity\LaravelJsonApi
 */
class MakeContentNegotiator extends AbstractGeneratorCommand
{

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'make:json-api:content-negotiator';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create a new JSON API content negotiator';

    /**
     * The type of class being generated.
     *
     * @var string
     */
    protected $type = 'ContentNegotiator';

    /**
     * Whether the resource type is non-dependent on eloquent
     *
     * @var boolean
     */
    protected $isIndependent = true;

    /**
     * @param string $name
     * @return string
     */
    protected function qualifyClass($name)
    {
        if ($this->isResource()) {
            return parent::qualifyClass($name);
        }

        $class = $this
            ->getApi()
            ->getDefaultResolver()
            ->getContentNegotiatorByName($name);

        return $class;
    }

    /**
     * @return string
     */
    protected function getNameInput()
    {
        return $this->argument('name');
    }

    /**
     * @return string
     */
    protected function getResourceInput()
    {
        if ($this->isNotResource()) {
            throw new RuntimeException('Not generating a resource content negotiator.');
        }

        return $this->argument('name');
    }

    /**
     * @inheritdoc
     */
    protected function replaceResourceType(&$stub)
    {
        return $this;
    }

    /**
     * @inheritdoc
     */
    protected function replaceRecord(&$stub)
    {
        return $this;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['name', InputArgument::REQUIRED, "The content negotiator name or resource type."],
            ['api', InputArgument::OPTIONAL, "The API that the content negotiator belongs to."],
        ];
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return [
            ['resource', 'r', InputOption::VALUE_NONE, 'Generate a resource-specific content negotiator.'],
        ];
    }

    /**
     * @return bool
     */
    private function isResource()
    {
        return (bool) $this->option('resource');
    }

    /**
     * @return bool
     */
    private function isNotResource()
    {
        return !$this->isResource();
    }
}

redpajama_set_name: RedPajamaGithub


text:
if [ -z "$PONI_ROOT" ]
then
    echo PONI_ROOT environmental variable is not set
    exit 127
fi

if [ -z "$DISTCI_EGGS" ]
then
    echo DISTCI_EGGS environmental variable is not set
    exit 127
fi

echo "Creating CEPH deployment keys"
if [ -f ceph-storage/ceph-setup-key ]; then rm ceph-storage/ceph-setup-key; fi
if [ -f ceph-storage/ceph-setup-key.pub ]; then rm ceph-storage/ceph-setup-key.pub; fi
ssh-keygen -f ceph-storage/ceph-setup-key -N ""

echo "Initializing poni repository..."
poni init

echo "Adding system 'distci'"
poni add-system distci

echo "Adding system 'distci/frontend'"
poni add-system distci/frontend

echo "Adding system 'distci/zookeeper'"
poni add-system distci/zookeeper

echo "Adding system 'distci/worker'"
poni add-system distci/worker

echo "Adding system 'distci/ceph-storage'"
poni add-system distci/ceph-storage

echo "Adding nodes 'distci/frontend/fenodeN'"
poni add-node distci/frontend/fenode0
poni set distci/frontend/fenode0 cloud.vm_name=fenode0

poni add-node distci/frontend/fenode1
poni set distci/frontend/fenode1 cloud.vm_name=fenode1

echo "Adding nodes 'distci/zookeeper/zknodeN'"
poni add-node distci/zookeeper/zknode0
poni set distci/zookeeper/zknode0 cloud.vm_name=zknode0 zkindex=1

poni add-node distci/zookeeper/zknode1
poni set distci/zookeeper/zknode1 cloud.vm_name=zknode1 zkindex=2

poni add-node distci/zookeeper/zknode2
poni set distci/zookeeper/zknode2 cloud.vm_name=zknode2 zkindex=3

echo "Adding nodes 'distci/worker/wnodeN'"
poni add-node distci/worker/wnode0
poni set distci/worker/wnode0 cloud.vm_name=wnode0

poni add-node distci/worker/wnode1
poni set distci/worker/wnode1 cloud.vm_name=wnode1

poni add-node distci/worker/wnode2
poni set distci/worker/wnode2 cloud.vm_name=wnode2

echo "Adding nodes 'distci/ceph-storage/cnodeN'"
poni add-node distci/ceph-storage/cnode0
poni set distci/ceph-storage/cnode0 cloud.vm_name=cnode0 cindex=0

poni add-node distci/ceph-storage/cnode1
poni set distci/ceph-storage/cnode1 cloud.vm_name=cnode1 cindex=1

poni add-node distci/ceph-storage/cnode2
poni set distci/ceph-storage/cnode2 cloud.vm_name=cnode2 cindex=2

echo "Configuring nodes 'distci/*'"
poni add-config distci/ nodes-prepare
poni update-config nodes-prepare nodes-prepare/plugin.py nodes-prepare/node-prepare.sh nodes-prepare/apt-wheezy-sources nodes-prepare/hosts

echo "Configuring nodes 'distci/frontend/*'"
poni add-config distci/frontend/ frontend-setup
poni update-config frontend-setup frontend/plugin.py frontend/frontend-install.sh frontend/distci-frontend.supervisor frontend/distci-frontend.conf frontend/distci-frontend.nginx
poni set distci/frontend distci_eggs=$DISTCI_EGGS

echo "Configuring nodes 'distci/zookeeper/*'"
poni add-config distci/zookeeper/ zookeeper-setup
poni update-config zookeeper-setup zookeeper/plugin.py zookeeper/zookeeper-install.sh zookeeper/zookeeper.conf zookeeper/zookeeper-myid

echo "Configuring nodes 'distci/worker/*'"
poni add-config distci/worker/ build-control-worker-setup
poni update-config build-control-worker-setup build-control-worker/plugin.py build-control-worker/build-control-install.sh build-control-worker/build-control.conf build-control-worker/build-control.supervisor

poni add-config distci/worker/ git-checkout-worker-setup
poni update-config git-checkout-worker-setup git-checkout-worker/plugin.py git-checkout-worker/git-checkout-install.sh git-checkout-worker/git-checkout.conf git-checkout-worker/git-checkout.supervisor

poni add-config distci/worker/ execute-shell-worker-setup
poni update-config execute-shell-worker-setup execute-shell-worker/plugin.py execute-shell-worker/execute-shell-install.sh execute-shell-worker/execute-shell.conf execute-shell-worker/execute-shell.supervisor

poni add-config distci/worker/ publish-artifacts-worker-setup
poni update-config publish-artifacts-worker-setup publish-artifacts-worker/plugin.py publish-artifacts-worker/publish-artifacts-install.sh publish-artifacts-worker/publish-artifacts.conf publish-artifacts-worker/publish-artifacts.supervisor

poni set distci/worker distci_eggs=$DISTCI_EGGS

echo "Configuring nodes 'distci/ceph-storage/*'"
poni add-config distci/ceph-storage/ ceph-storage-setup
poni update-config ceph-storage-setup ceph-storage/plugin.py ceph-storage/ceph-storage-install-stage1.sh ceph-storage/ceph-storage-install-stage2.sh ceph-storage/ceph-storage-install-stage3.sh ceph-storage/ceph.conf ceph-storage/apt-ceph-sources ceph-storage/ceph-repo-key.asc ceph-storage/ceph-setup-key ceph-storage/ceph-setup-key.pub

echo "Configuring cloud properties"
poni set distci cloud.provider=eucalyptus cloud.image=emi-292D3844 cloud.type=m1.small cloud.key_pair=noushe-euca user=root


text:
package gov.nasa.ensemble.core.plan.formula.js.constraint;

import static gov.nasa.ensemble.core.plan.formula.js.constraint.JSConstraintUtils.*;

import gov.nasa.ensemble.emf.util.EMFUtils;
import gov.nasa.ensemble.javascript.rhino.FormulaInfo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.emf.ecore.EAnnotation;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.validation.AbstractModelConstraint;
import org.eclipse.emf.validation.EMFEventType;
import org.eclipse.emf.validation.IValidationContext;
import org.eclipse.emf.validation.model.ConstraintStatus;

public class JSAnnotationConstraint extends AbstractModelConstraint {

	private static final String CONSTRAINT_SOURCE = "constraint";
	private static final String MESSAGE_SOURCE = "message";

	private Map<EClass, List<String>> classConstraints = new HashMap<EClass, List<String>>();
	private Map<EClass, List<EAnnotation>> featureConstraints = new HashMap<EClass, List<EAnnotation>>();
	private Map<EStructuralFeature, Map<EClass, List<String>>> affectedConstraints = new HashMap<EStructuralFeature, Map<EClass, List<String>>>();
	private JSEvaluator evaluator = new JSEvaluator();

	/**
	 * Validates an EObject in the given context to ensure that constraints defined as
	 * annotations on the object's EClass are satisfied
	 *
	 * @param ctx the IValidationContext used for the validation
	 * @return IStatus the status object giving the result of the validation
	 */
	@Override
	public IStatus validate(IValidationContext ctx) {
		EObject target = ctx.getTarget();
		EClass eClass = target.eClass();
		List<IStatus> failureList = new ArrayList<IStatus>(3);
		EMFEventType eventType = ctx.getEventType();
		// In the case of batch mode.
		if (eventType == EMFEventType.NULL) {
			List<EAnnotation> constraintAnnotations = getFeatureConstraints(eClass);
			for (EAnnotation annotation : constraintAnnotations) {
				EStructuralFeature feature = (EStructuralFeature)annotation.getEModelElement();
				if (feature.isMany()) {
					for (Object value : (Collection<?>)target.eGet(feature)) {
						validateFeatureConstraints(ctx, target, feature, annotation, value, failureList);
					}
				} else {
					validateFeatureConstraints(ctx, target, feature, annotation, target.eGet(feature), failureList);
				}
			}
			validateObjectConstraints(ctx, target, eClass, getAllConstraints(eClass), failureList);
		} else if (eventType == EMFEventType.SET || eventType == EMFEventType.ADD || eventType == EMFEventType.ADD_MANY) {
			// In the case of live mode
			EStructuralFeature feature = ctx.getFeature();
			EAnnotation annotation = feature.getEAnnotation(CONSTRAINT_SOURCE);
			if (annotation != null) {
				if (eventType == EMFEventType.ADD_MANY) {
					for (Object value : (Collection<?>)ctx.getFeatureNewValue()) {
						validateFeatureConstraints(ctx, target, feature, annotation, value, failureList);
					}
				} else {
					validateFeatureConstraints(ctx, target, feature, annotation, ctx.getFeatureNewValue(), failureList);
				}
			}
			validateAffectedObjectConstraints(ctx, target, eClass, feature, failureList);
		}
		if (!failureList.isEmpty()) {
			return combinedStatus(ctx, target, failureList);
		}
		return ctx.createSuccessStatus();
	}

	/**
	 * Tests the value of a feature of a target object to determine whether the value violates any constraints
	 *
	 * @param ctx the IValidationContext used for the validation
	 * @param target the EObject to be validated
	 * @param feature the EStructuralFeature whose value is to be validated
	 * @param EAnnotation an EMF annotation with JavaScript constraints
	 * @param value the Object value of the feature that is to be validated
	 * @param failures an accumulator list of failure IStatus objects for any constraint violations
	 */
	private void validateFeatureConstraints(IValidationContext ctx, EObject target, EStructuralFeature feature,
			EAnnotation annotation, Object value, List<IStatus> failures) {
		for (Map.Entry<String,String> entry : annotation.getDetails()) {
			String constraintName = entry.getKey();
			String expression = entry.getValue();
			if (expression != null && expression.length() > 0) {
				Object result = evaluator.getValue(target, expression, true, value);
				if (result instanceof Boolean && !((Boolean)result).booleanValue()) {
					String message = EMFUtils.getAnnotation(feature, MESSAGE_SOURCE, constraintName);
					boolean batch = ctx.getEventType() == EMFEventType.NULL;
					String template = batch?"The {0} of {1} {2}":"The value {0}";
					int severityCode = IStatus.ERROR;
					if (message == null || message.length() < 1) {
						template = batch?"The {0} of {1} must satisfy {2}":"The value must satisfy {0}";
						message = expression;
					}
					Collection<EObject> locus = EMFUtils.getConstraintStatusLocus(target, feature);
					if (batch) {
						String featureName =  EMFUtils.getDisplayName(target, feature);
						failures.add(ConstraintStatus.createStatus(ctx, locus, severityCode, 1, template, featureName, targetName(target), message));
					} else {
						failures.add(ConstraintStatus.createStatus(ctx, locus, severityCode, 1, template, message));
					}
				}
			}
		}
	}

	/**
	 * Tests a target object to determine whether it violates any of the constraints associated with the object's
	 * EMF class
	 *
	 * @param ctx the IValidationContext used for the validation
	 * @param target the EObject to be validated
	 * @param eClass the target object's EClass
	 * @param constraintNames a list of the names of the constraints to be tested
	 * @param failures an accumulator list of failure IStatus objects for any constraint violations
	 */
	private void validateObjectConstraints(IValidationContext ctx, EObject target, EClass eClass, List<String> constraintNames, List<IStatus> failures) {
		for (String name : constraintNames) {
			String expression = lookupConstraintInfo(eClass, name, CONSTRAINT_SOURCE);
			if (expression != null && expression.length() > 0) {
				Object result = evaluator.getValue(target, expression, false, null);
				if (result instanceof Boolean && !((Boolean)result).booleanValue()) {
					String message = lookupConstraintInfo(eClass, name, MESSAGE_SOURCE);
					int severityCode = IStatus.ERROR;
					if (message == null || message.length() < 1) {
						message = "{0} must satisfy " + expression;
					} else {
						int commaPos = message.indexOf(',');
						if (commaPos > 0) {
							String severity = message.substring(0, commaPos);
							severityCode = getSeverityCode(severity);
							if (severityCode != IStatus.OK) {
								message = message.substring(commaPos + 1);
							} else {
								severityCode = IStatus.ERROR;
							}
						}
					}
					// Record the target EObject and involved structural features in the status object for use in error
					// decorations and explanations
					Collection<EObject> locus = EMFUtils.getConstraintStatusLocus(target, eClass, FormulaInfo.getVariableNames(expression));
					failures.add(ConstraintStatus.createStatus(ctx, locus, severityCode, 1, message, targetName(target)));
				}
			}
		}
	}

	/**
	 *
	 * @param ctx the IValidationContext used for the validation
	 * @param target the EObject to be validated
	 * @param eClass the target object's EClass
	 * @param feature the EStructuralFeature whose whose new value is being validated
	 * @param failures an accumulator list of failure IStatus objects for any constraint violations
	 */
	private void validateAffectedObjectConstraints(IValidationContext ctx, EObject target, EClass eClass, EStructuralFeature feature, List<IStatus> failures) {
		for (String name : getAffectedConstraints(eClass, feature)) {
			String expression = EMFUtils.getAnnotation(eClass, CONSTRAINT_SOURCE, name);
			if (expression != null && expression.length() > 0) {
				Object result = evaluator.getValue(target, expression, false, null);
				if (result instanceof Boolean && !((Boolean)result).booleanValue()) {
					String message = EMFUtils.getAnnotation(eClass, MESSAGE_SOURCE, name);
					int severityCode = IStatus.ERROR;
					if (message == null || message.length() < 1) {
						message = "{0} must satisfy " + expression;
					} else {
						int commaPos = message.indexOf(',');
						if (commaPos > 0) {
							String severity = message.substring(0, commaPos);
							severityCode = getSeverityCode(severity);
							if (severityCode != IStatus.OK) {
								message = message.substring(commaPos + 1);
							} else {
								severityCode = IStatus.ERROR;
							}
						}
					}
					// Record the target EObject and involved structural features in the status object for use in error
					// decorations and explanations
					Collection<EObject> locus = EMFUtils.getConstraintStatusLocus(target, eClass, FormulaInfo.getVariableNames(expression));
					failures.add(ConstraintStatus.createStatus(ctx, locus, severityCode, 1, message, targetName(target)));
				}
			}
		}
	}

	private List<String> getAffectedConstraints(EClass eClass, EStructuralFeature feature) {
		Map<EClass, List<String>> constraintsByClass = affectedConstraints.get(feature);
		if (constraintsByClass == null) {
			constraintsByClass = new HashMap<EClass, List<String>>();
			affectedConstraints.put(feature, constraintsByClass);
		}
		List<String> constraintNames = constraintsByClass.get(eClass);
		if (constraintNames == null) {
			// class-level constraints have not yet been analyzed for this feature
			constraintNames = getAllConstraints(eClass, feature);
			constraintsByClass.put(eClass, constraintNames);
		}
		return constraintNames;
	}

	private List<String> getAllConstraints(EClass eClass) {
		List<String> constraintNames = classConstraints.get(eClass);
		if (constraintNames == null) {
			constraintNames = getAllConstraints(eClass, null);
			classConstraints.put(eClass, constraintNames);
		}
		return constraintNames;
	}

	private List<String> getAllConstraints(EClass eClass, EStructuralFeature feature) {
		Set<String> results = null;
		EAnnotation constraintAnnotation = eClass.getEAnnotation(CONSTRAINT_SOURCE);
		if (constraintAnnotation != null) {
			if (results == null) {
				results = new HashSet<String>();
			}
			results.addAll(getAnnotationConstraints(constraintAnnotation, feature));
		}
		for (EClass superType : eClass.getEAllSuperTypes()) {
			EAnnotation superAnnotation = superType.getEAnnotation(CONSTRAINT_SOURCE);
			if (superAnnotation != null) {
				if (results == null) {
					results = new HashSet<String>();
				}
				results.addAll(getAnnotationConstraints(superAnnotation, feature));
			}
		}
		if (results == null) {
			return Collections.emptyList();
		}
		return new ArrayList<String>(results);
	}

	private Collection<String> getAnnotationConstraints(EAnnotation constraintAnnotation, EStructuralFeature feature) {
		if (feature == null) {
			return constraintAnnotation.getDetails().keySet();
		}
		List<String> constraintNames = new ArrayList<String>();
		String featureName = feature.getName();
		for (Map.Entry<String,String> entry : constraintAnnotation.getDetails()) {
			String name = entry.getKey();
			String expression = entry.getValue();
			if (expression != null && expression.length() > 0 &&
					FormulaInfo.getVariableNames(expression).contains(featureName)) {
				constraintNames.add(name);
			}
		}
		return constraintNames;
	}

	private List<EAnnotation> getFeatureConstraints(EClass eClass) {
		List<EAnnotation> annotations = featureConstraints.get(eClass);
	    if (annotations == null) {
	    	annotations = new ArrayList<EAnnotation>(3);
	    	for (EStructuralFeature feature : eClass.getEAllStructuralFeatures()) {
				EAnnotation annotation = feature.getEAnnotation(CONSTRAINT_SOURCE);
				if (annotation != null) {
					annotations.add(annotation);
				}
	    	}
	    	featureConstraints.put(eClass, annotations);
		}
	    return annotations;
	}

	private String lookupConstraintInfo(EClass eClass, String name, String source) {
		String body = EMFUtils.getAnnotation(eClass, source, name);
		if (body != null) {
			return body;
		}
		for (EClass superType : eClass.getEAllSuperTypes()) {
			body = EMFUtils.getAnnotation(superType, source, name);
			if (body != null) {
				return body;
			}
		}
		return null;
	}

}


text:
/* -*- Mode: C; c-basic-offset:4 ; -*- */
/*
 *
 *  (C) 2003 by Argonne National Laboratory.
 *      See COPYRIGHT in top-level directory.
 */
#include "mpi.h"
#include <stdio.h>
#include "mpitest.h"

/*
static char MTEST_Descrip[] = "Test of broadcast with various roots and datatypes";
*/

int main( int argc, char *argv[] )
{
    int errs = 0, err;
    int rank, size, root;
    int minsize = 2, count;
    MPI_Comm      comm;
    MTestDatatype sendtype, recvtype;

    MTest_Init( &argc, &argv );

    /* The following illustrates the use of the routines to
       run through a selection of communicators and datatypes.
       Use subsets of these for tests that do not involve combinations
       of communicators, datatypes, and counts of datatypes */
    while (MTestGetIntracommGeneral( &comm, minsize, 1 )) {
	if (comm == MPI_COMM_NULL) continue;

	/* Determine the sender and receiver */
	MPI_Comm_rank( comm, &rank );
	MPI_Comm_size( comm, &size );

	/* To improve reporting of problems about operations, we
	   change the error handler to errors return */
	MPI_Errhandler_set( comm, MPI_ERRORS_RETURN );

	/* The max value of count must be very large to ensure that we
	   reach the long message algorithms */
	for (count = 1; count < 280000; count = count * 4) {
	    while (MTestGetDatatypes( &sendtype, &recvtype, count )) {
		for (root=0; root<size; root++) {
		    if (rank == root) {
			sendtype.InitBuf( &sendtype );
			err = MPI_Bcast( sendtype.buf, sendtype.count,
					 sendtype.datatype, root, comm );
			if (err) {
			    errs++;
			    MTestPrintError( err );
			}
		    }
		    else {
			recvtype.InitBuf( &recvtype );
			err = MPI_Bcast( recvtype.buf, recvtype.count,
				    recvtype.datatype, root, comm );
			if (err) {
			    errs++;
			    fprintf( stderr, "Error with communicator %s and datatype %s\n",
				 MTestGetIntracommName(),
				 MTestGetDatatypeName( &recvtype ) );
			    MTestPrintError( err );
			}
			err = MTestCheckRecv( 0, &recvtype );
			if (err) {
			    errs += errs;
			}
		    }
		}
		MTestFreeDatatype( &recvtype );
		MTestFreeDatatype( &sendtype );
	    }
	}
	MTestFreeComm( &comm );
    }

    MTest_Finalize( errs );
    MPI_Finalize();
    return 0;
}


text:
package swoop.testutil.hamcrest;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.Factory;
import org.hamcrest.TypeSafeMatcher;

/**
 * Is the value a number equal to a value within some range of
 * acceptable error?
 */
public class LongIsCloseTo extends TypeSafeMatcher<Long> {
    private final long delta;
    private final long value;

    public LongIsCloseTo(long value, long error) {
        this.delta = error;
        this.value = value;
    }

    @Override
    public boolean matchesSafely(Long item) {
        return actualDelta(item) <= 0.0;
    }

    @Override
    public void describeMismatchSafely(Long item, Description mismatchDescription) {
      mismatchDescription.appendValue(item)
                         .appendText(" differed by ")
                         .appendValue(actualDelta(item));
    }

    public void describeTo(Description description) {
        description.appendText("a numeric value within ")
                .appendValue(delta)
                .appendText(" of ")
                .appendValue(value);
    }

    private long actualDelta(long item) {
      return (Math.abs((item - value)) - delta);
    }

    @Factory
    public static Matcher<Long> closeTo(long operand, long error) {
        return new LongIsCloseTo(operand, error);
    }

}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-7-b-13.js
 * @description Array.prototype.every - deleting own property with prototype property causes prototype index property to be visited on an Array
 */

function testcase() {
        function callbackfn(val, idx, obj) {
            if (idx === 1 && val === 1) {
                return false;
            } else {
                return true;
            }
        }
        var arr = [0, 111, 2];

        Object.defineProperty(arr, "0", {
            get: function () {
                delete arr[1];
                return 0;
            },
            configurable: true
        });

        try {
            Array.prototype[1] = 1;
            return !arr.every(callbackfn);
        } finally {
            delete Array.prototype[1];
        }
    }
runTestCase(testcase);


text:
package org.jlcf.core;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.jlcf.core.annotation.InitMethod;
import org.jlcf.core.dynrec.ComponentProxyReconfigurationManager;
import org.jlcf.core.dynrec.ComponentState;
import org.jlcf.core.dynrec.ComponentStateEvent;
import org.jlcf.core.dynrec.IComponentStateReceiver;
import org.jlcf.core.dynrec.IReconfigurableComponent;

/**
 * This is the first level wrapper on top of the POJO component.
 * This intercepts the calls to the component POJO and calls the actual object.
 * It is also used in order to call the Init methods of components
 * and to manage dynamic reconfiguration.
 *
 * It implements all formal interfaces of the component and is instantiated
 * as a proxy object during the component instantiation by the framework.
 *
 * @author Petros Pissias
 *
 */
public class ComponentProxyHandler implements InvocationHandler, IComponentProxy {

	//the component instance
	private final Object componentPojo;
	//init method
	private final Method initMethod;
	//name of the component, primarily for logging.
	private final String name;

	private final Logger logger = Logger.getLogger(getClass());

	//state manager of the component external state
	private final ComponentProxyReconfigurationManager componentExternalStateManager;

	//lock that is used for synchronization between connectors, this object and the reconfiguration manager of the framework
	private final ReentrantLock lock;
	/**
	 * creates a new instance of a component proxy handler.
	 * @param componentPojoInstance
	 * @param name
	 */
	public ComponentProxyHandler(Object componentPojoInstance, String name) {
		componentPojo = componentPojoInstance;
		Method[] methods = componentPojo.getClass().getMethods();
		Method fInitMethod = null;

		//search for the init method
		boolean found = false;
		for (Method method : methods) {
			InitMethod mthd = method.getAnnotation(InitMethod.class);
			if (mthd != null) {
				found = true;
				fInitMethod = method;
				break;
			}
		}
		if (found) {
			initMethod = fInitMethod;
		} else {
			initMethod = null; //this component does not declare an init method
		}

		this.name = name;

		//create the state manager
		//TODO do via property file
		componentExternalStateManager = new ComponentProxyReconfigurationManager();

		//initialize the lock
		lock = new ReentrantLock();
	}

	/* (non-Javadoc)
	 * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
	 */
	@Override
	public Object invoke(Object proxy, Method m, Object[] arguments)
			throws Throwable {

		//logger.debug(name+" sending CALLING msg to state manager");
		componentExternalStateManager.receiveEvent(ComponentStateEvent.CALLING, m, arguments);

		//has been previously locked by the same thread on the connector
		//logger.debug(name+" thread:"+Thread.currentThread().getName()+" releasing lock");
		lock.unlock();

		//logger.debug(name+" invoking pojo");
		Object ret; //the return
		try {
			ret = m.invoke(componentPojo, arguments);
		}catch (InvocationTargetException ex) {
			if (ex.getCause() == null) {
				throw (ex);
			} else {
				throw (ex.getCause()); //throw the actual exception of the target interface
			}
		}

		//logger.debug(name+" sending FINISHED_CALLING msg to state manager after obtaining lock");
		lock.lock();
		componentExternalStateManager.receiveEvent(ComponentStateEvent.FINISHED_CALLING, m, arguments);
		lock.unlock();

		return ret;
	}

	@Override
	public void callInitMethod() {
		//logger.debug(name+" Calling init method on component pojo if exists");
		if (initMethod != null) {
			try {
				initMethod.invoke(componentPojo, new Object[]{});
			} catch (Exception e) {
				//logger.log(Level.ERROR, "Cannot call init method on component of class:"+componentPojo.getClass().getName()+" "+e.getMessage(), e);
			}
		}else {
			//logger.debug(name+" No init method for component of class:"+componentPojo.getClass().getName());
		}

	}

	@Override
	public void reachQuiescentState(IComponentStateReceiver observer) {
		//logger.debug(name+" reaching a quiescent stste. Will inform user on component state changes");
		componentExternalStateManager.observeState(observer);

		//inform the component to stop its internal threads that may initiate calls through the component receptcles
		//this is needed if the component is an "alive" component. That is if it has threads that are able to
		//make calls through its receptacles.
		try {
			//logger.debug(name+" trying to call stopAliveThreads on pojo");
			((IReconfigurableComponent)componentPojo).stopAliveThreads();
		}catch (ClassCastException ex) {
			//logger.debug("could not cast component to IReconfigurableComponent. Assuming component does not implement stopAliveThreads method");
		}
		//logger.debug(name+" sending RECONFIGURATION_START event to manager");
		componentExternalStateManager.receiveEvent(ComponentStateEvent.RECONFIGURATION_START, null, null);

	}

	@Override
	public void proceed() {
		try {
			//logger.debug(name+" trying to call proceed on pojo");
			((IReconfigurableComponent)componentPojo).proceed();
		}catch (ClassCastException ex) {
			//logger.debug("could not cast component to IReconfigurableComponent. Assuming component dose not implement proceed method");

		}
		//logger.debug(name+" sending RECONFIGURATION_END event to manager");

		componentExternalStateManager.receiveEvent(ComponentStateEvent.RECONFIGURATION_END, null, null);

	}

	@Override
	public Object getInternalState() {
		try {
			//logger.debug(name+" trying to call extractState on pojo");
			return ((IReconfigurableComponent)componentPojo).extractState();
		}catch (ClassCastException ex) {
			//logger.debug("could not cast component to IReconfigurableComponent");
		}
		return null;
	}

	@Override
	public void setInternalState(Object internalState) {
		try {
			//logger.debug(name+" trying to call insertState on pojo");
			((IReconfigurableComponent)componentPojo).insertState(internalState);
		}catch (ClassCastException ex) {
			//logger.debug("could not cast component to IReconfigurableComponent");
		}
	}

	@Override
	//called by coonnectors after obtaining the lock in order to determine the component state
	public ComponentState getExternalState() {
		return this.componentExternalStateManager.getState();
	}

	@Override
	public void lock() {
		//logger.debug("Thread:"+Thread.currentThread().getName()+" obtaining lock, my object is of class:"+componentPojo.getClass().getName());
		lock.lock();
		//logger.debug("Thread:"+Thread.currentThread().getName()+" obtainined lock, my object is of class:"+componentPojo.getClass().getName());

	}

	@Override
	public void unlock() {
		//logger.debug("Thread:"+Thread.currentThread().getName()+" releasing lock, my object is of class:"+componentPojo.getClass().getName());
		lock.unlock();
		//logger.debug("Thread:"+Thread.currentThread().getName()+" released lock, my object is of class:"+componentPojo.getClass().getName());
	}

}


text:
<?php

namespace Cetaf\Bundle\CrawlerBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class ShopType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('shopName')
            ->add('shopAdress')
            ->add('shopPhoneNumber')
            ->add('updatedAt')
            ->add('createdAt')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Cetaf\Bundle\CrawlerBundle\Entity\Shop'
        ));
    }

    public function getName()
    {
        return 'cetaf_bundle_crawlerbundle_shoptype';
    }
}


text:
docker network create snomed-net
docker run --detach --name neo4j --net snomed-net neo4j
docker run  --name snomed-groovy --net snomed-net snomed
docker run -it --net snomed-net snomed bash

//— with pwd
docker run --env NEO4J_AUTH=neo4j/sample --name neo4j --net snomed-net neo4j

docker network create \
  --driver=bridge \
  --subnet=172.28.0.0/16 \
  --ip-range=172.28.5.0/30 \
  --gateway=172.28.5.254 \
  snomed-net

iptables -t nat -A DOCKER -p tcp --dport 7474 -j DNAT --to-destination 172.28.5.0:7474

docker run \
    --publish=7474:7474 --publish=7687:7687 \
    --volume=$HOME/neo4j/data:/data \
    --volume=$HOME/neo4j/logs:/logs \
    --detach --name neo4j --net snomed-net \
    --env NEO4J_AUTH=neo4j/sample \
    neo4j

build

docker build -t snomed .

grape install org.neo4j neo4j-jdbc 3.0.1
grape install org.neo4j neo4j-jdbc-driver 3.0.1
grape install org.neo4j.driver neo4j-java-driver 1.1.2

TO delete unused images

docker rm $(docker ps -qa)
docker rmi $(docker images -f "dangling=true" -q)

docker exec -it foo /bin/bash


text:
LOAD DATA LOCAL INFILE 'C:/Users/ALAN7/Documents/GitHub/ViajesTransparentes/DOCUMENTACION BD/Catalogos con datos/tipo_personal_catalogo.csv'
INTO TABLE tipo_personal_catalogo
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(idTipoPersonal,TIPO_PERSONAL);


text:
package app

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"net"
	"net/url"
	"path"
	"reflect"
	"strconv"
	"strings"

	"code.google.com/p/go-uuid/uuid"
	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/conversion"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/fsouza/go-dockerclient"

	buildapi "github.com/openshift/origin/pkg/build/api"
	deployapi "github.com/openshift/origin/pkg/deploy/api"
	imageapi "github.com/openshift/origin/pkg/image/api"
)

// NameSuggester is an object that can suggest a name for itself
type NameSuggester interface {
	SuggestName() (string, bool)
}

// NameSuggestions suggests names from a collection of NameSuggesters
type NameSuggestions []NameSuggester

// SuggestName suggests a name given a collection of NameSuggesters
func (s NameSuggestions) SuggestName() (string, bool) {
	for i := range s {
		if s[i] == nil {
			continue
		}
		if name, ok := s[i].SuggestName(); ok {
			return name, true
		}
	}
	return "", false
}

// Generated is a list of runtime objects
type Generated struct {
	Items []runtime.Object
}

// WithType extracts a list of runtime objects with the specified type
func (g *Generated) WithType(slicePtr interface{}) bool {
	found := false
	v, err := conversion.EnforcePtr(slicePtr)
	if err != nil || v.Kind() != reflect.Slice {
		// This should not happen at runtime.
		panic("need ptr to slice")
	}
	t := v.Type().Elem()
	for i := range g.Items {
		obj := reflect.ValueOf(g.Items[i]).Elem()
		if !obj.Type().ConvertibleTo(t) {
			continue
		}
		found = true
		v.Set(reflect.Append(v, obj.Convert(t)))
	}
	return found
}

func nameFromGitURL(url *url.URL) (string, bool) {
	// from path
	if len(url.Path) > 0 {
		base := path.Base(url.Path)
		if len(base) > 0 && base != "/" {
			if ext := path.Ext(base); ext == ".git" {
				base = base[:len(base)-4]
			}
			return base, true
		}
	}
	if len(url.Host) > 0 {
		// from host with port
		if host, _, err := net.SplitHostPort(url.Host); err == nil {
			return host, true
		}
		// from host without port
		return url.Host, true
	}
	return "", false
}

// SourceRef is a reference to a build source
type SourceRef struct {
	URL        *url.URL
	Ref        string
	Dir        string
	Name       string
	ContextDir string
}

func urlWithoutRef(url url.URL) string {
	url.Fragment = ""
	return url.String()
}

// SuggestName returns a name derived from the source URL
func (r *SourceRef) SuggestName() (string, bool) {
	if len(r.Name) > 0 {
		return r.Name, true
	}
	return nameFromGitURL(r.URL)
}

// BuildSource returns an OpenShift BuildSource from the SourceRef
func (r *SourceRef) BuildSource() (*buildapi.BuildSource, []buildapi.BuildTriggerPolicy) {
	return &buildapi.BuildSource{
			Type: buildapi.BuildSourceGit,
			Git: &buildapi.GitBuildSource{
				URI: urlWithoutRef(*r.URL),
				Ref: r.Ref,
			},
			ContextDir: r.ContextDir,
		}, []buildapi.BuildTriggerPolicy{
			{
				Type: buildapi.GithubWebHookBuildTriggerType,
				GithubWebHook: &buildapi.WebHookTrigger{
					Secret: generateSecret(20),
				},
			},
			{
				Type: buildapi.GenericWebHookBuildTriggerType,
				GenericWebHook: &buildapi.WebHookTrigger{
					Secret: generateSecret(20),
				},
			},
		}
}

// BuildStrategyRef is a reference to a build strategy
type BuildStrategyRef struct {
	IsDockerBuild bool
	Base          *ImageRef
}

// BuildStrategy builds an OpenShift BuildStrategy from a BuildStrategyRef
func (s *BuildStrategyRef) BuildStrategy() (*buildapi.BuildStrategy, []buildapi.BuildTriggerPolicy) {
	if s.IsDockerBuild {
		strategy := &buildapi.BuildStrategy{
			Type: buildapi.DockerBuildStrategyType,
		}
		return strategy, s.Base.BuildTriggers()
	}

	return &buildapi.BuildStrategy{
		Type: buildapi.STIBuildStrategyType,
		STIStrategy: &buildapi.STIBuildStrategy{
			Image: s.Base.String(),
		},
	}, nil
}

// ImageRef is a reference to an image
type ImageRef struct {
	imageapi.DockerImageReference
	AsImageStream bool

	Stream *imageapi.ImageStream
	Info   *imageapi.DockerImage
}

/*
// NameReference returns the name that other OpenShift objects may refer to this
// image as.  Deployment Configs and Build Configs may look an image up
// in an image repository before creating other objects that use the name.
func (r *ImageRef) NameReference() string {
	if len(r.Registry) == 0 && len(r.Namespace) == 0 {
		if len(r.Tag) != 0 {
			return fmt.Sprintf("%s:%s", r.Name, r.Tag)
		}
		return r.Name
	}
	return r.pullSpec()
}
*/

func (r *ImageRef) RepoName() string {
	name := r.Namespace
	if len(name) > 0 {
		name += "/"
	}
	name += r.Name
	return name
}

func (r *ImageRef) SuggestName() (string, bool) {
	if r == nil || len(r.Name) == 0 {
		return "", false
	}
	return r.Name, true
}

func (r *ImageRef) BuildOutput() (*buildapi.BuildOutput, error) {
	if r == nil {
		return &buildapi.BuildOutput{}, nil
	}
	imageRepo, err := r.ImageStream()
	if err != nil {
		return nil, err
	}
	return &buildapi.BuildOutput{
		To: &kapi.ObjectReference{
			Name: imageRepo.Name,
		},
	}, nil
}

func (r *ImageRef) BuildTriggers() []buildapi.BuildTriggerPolicy {
	// TODO return triggers when image build triggers are available
	return []buildapi.BuildTriggerPolicy{}
}

func (r *ImageRef) ImageStream() (*imageapi.ImageStream, error) {
	if r.Stream != nil {
		return r.Stream, nil
	}

	name, ok := r.SuggestName()
	if !ok {
		return nil, fmt.Errorf("unable to suggest an image repository name for %q", r.String())
	}

	repo := &imageapi.ImageStream{
		ObjectMeta: kapi.ObjectMeta{
			Name: name,
		},
	}
	if !r.AsImageStream {
		repo.Spec.DockerImageRepository = r.String()
	}

	return repo, nil
}

func (r *ImageRef) DeployableContainer() (container *kapi.Container, triggers []deployapi.DeploymentTriggerPolicy, err error) {
	name, ok := r.SuggestName()
	if !ok {
		return nil, nil, fmt.Errorf("unable to suggest a container name for the image %q", r.String())
	}
	if r.AsImageStream {
		tag := r.Tag
		if len(tag) == 0 {
			tag = imageapi.DefaultImageTag
		}
		triggers = []deployapi.DeploymentTriggerPolicy{
			{
				Type: deployapi.DeploymentTriggerOnImageChange,
				ImageChangeParams: &deployapi.DeploymentTriggerImageChangeParams{
					Automatic:      true,
					ContainerNames: []string{name},
					From: kapi.ObjectReference{
						Name: name,
					},
					Tag: tag,
				},
			},
		}
	}

	container = &kapi.Container{
		Name:  name,
		Image: r.String(),
	}

	// If imageInfo present, append ports
	if r.Info != nil {
		ports := []string{}
		// ExposedPorts can consist of multiple space-separated ports
		for exposed := range r.Info.Config.ExposedPorts {
			ports = append(ports, strings.Split(exposed, " ")...)
		}

		for _, sp := range ports {
			p := docker.Port(sp)
			port, err := strconv.Atoi(p.Port())
			if err != nil {
				return nil, nil, fmt.Errorf("failed to parse port %q: %v", p.Port(), err)
			}
			container.Ports = append(container.Ports, kapi.ContainerPort{
				Name:          strings.Join([]string{name, p.Proto(), p.Port()}, "-"),
				ContainerPort: port,
				Protocol:      kapi.Protocol(strings.ToUpper(p.Proto())),
			})
		}
		// TODO: Append volume information and environment variables
	}

	return container, triggers, nil

}

type BuildRef struct {
	Source   *SourceRef
	Input    *ImageRef
	Strategy *BuildStrategyRef
	Output   *ImageRef
}

func (r *BuildRef) BuildConfig() (*buildapi.BuildConfig, error) {
	name, ok := NameSuggestions{r.Source, r.Output}.SuggestName()
	if !ok {
		return nil, fmt.Errorf("unable to suggest a name for this build config from %q", r.Source.URL)
	}
	source := &buildapi.BuildSource{}
	sourceTriggers := []buildapi.BuildTriggerPolicy{}
	if r.Source != nil {
		source, sourceTriggers = r.Source.BuildSource()
	}
	strategy := &buildapi.BuildStrategy{}
	strategyTriggers := []buildapi.BuildTriggerPolicy{}
	if r.Strategy != nil {
		strategy, strategyTriggers = r.Strategy.BuildStrategy()
	}
	output, err := r.Output.BuildOutput()
	if err != nil {
		return nil, err
	}
	return &buildapi.BuildConfig{
		ObjectMeta: kapi.ObjectMeta{
			Name: name,
		},
		Triggers: append(sourceTriggers, strategyTriggers...),
		Parameters: buildapi.BuildParameters{
			Source:   *source,
			Strategy: *strategy,
			Output:   *output,
		},
	}, nil
}

type DeploymentConfigRef struct {
	Images []*ImageRef
	Env    Environment
}

// TODO: take a pod template spec as argument
func (r *DeploymentConfigRef) DeploymentConfig() (*deployapi.DeploymentConfig, error) {
	suggestions := NameSuggestions{}
	for i := range r.Images {
		suggestions = append(suggestions, r.Images[i])
	}
	name, ok := suggestions.SuggestName()
	if !ok {
		return nil, fmt.Errorf("unable to suggest a name for this deployment config")
	}

	selector := map[string]string{
		"deploymentconfig": name,
	}

	triggers := []deployapi.DeploymentTriggerPolicy{
		// By default, always deploy on change
		{
			Type: deployapi.DeploymentTriggerOnConfigChange,
		},
	}

	template := kapi.PodSpec{}
	for i := range r.Images {
		c, containerTriggers, err := r.Images[i].DeployableContainer()
		if err != nil {
			return nil, err
		}
		triggers = append(triggers, containerTriggers...)
		template.Containers = append(template.Containers, *c)
	}
	// TODO: populate volumes

	for i := range template.Containers {
		template.Containers[i].Env = append(template.Containers[i].Env, r.Env.List()...)
	}

	return &deployapi.DeploymentConfig{
		ObjectMeta: kapi.ObjectMeta{
			Name: name,
		},
		Template: deployapi.DeploymentTemplate{
			Strategy: deployapi.DeploymentStrategy{
				Type: deployapi.DeploymentStrategyTypeRecreate,
			},
			ControllerTemplate: kapi.ReplicationControllerSpec{
				Replicas: 1,
				Selector: selector,
				Template: &kapi.PodTemplateSpec{
					ObjectMeta: kapi.ObjectMeta{
						Labels: selector,
					},
					Spec: template,
				},
			},
		},
		Triggers: triggers,
	}, nil
}

// generateSecret generates a random secret string
func generateSecret(n int) string {
	n = n * 3 / 4
	b := make([]byte, n)
	read, _ := rand.Read(b)
	if read != n {
		return uuid.NewRandom().String()
	}
	return base64.URLEncoding.EncodeToString(b)
}

// ContainerPortsFromString extracts sets of port specifications from a comma-delimited string. Each segment
// must be a single port number (container port) or a colon delimited pair of ports (container port and host port).
func ContainerPortsFromString(portString string) ([]kapi.ContainerPort, error) {
	ports := []kapi.ContainerPort{}
	for _, s := range strings.Split(portString, ",") {
		port, ok := checkPortSpecSegment(s)
		if !ok {
			return nil, fmt.Errorf("%q is not valid: you must specify one (container) or two (container:host) port numbers", s)
		}
		ports = append(ports, port)
	}
	return ports, nil
}

func checkPortSpecSegment(s string) (port kapi.ContainerPort, ok bool) {
	if strings.Contains(s, ":") {
		pair := strings.Split(s, ":")
		if len(pair) != 2 {
			return
		}
		container, err := strconv.Atoi(pair[0])
		if err != nil {
			return
		}
		host, err := strconv.Atoi(pair[1])
		if err != nil {
			return
		}
		return kapi.ContainerPort{ContainerPort: container, HostPort: host}, true
	}

	container, err := strconv.Atoi(s)
	if err != nil {
		return
	}
	return kapi.ContainerPort{ContainerPort: container}, true
}

// LabelsFromSpec turns a set of specs NAME=VALUE or NAME- into a map of labels,
// a remove label list, or an error.
func LabelsFromSpec(spec []string) (map[string]string, []string, error) {
	labels := map[string]string{}
	var remove []string
	for _, labelSpec := range spec {
		if strings.Index(labelSpec, "=") != -1 {
			parts := strings.Split(labelSpec, "=")
			if len(parts) != 2 {
				return nil, nil, fmt.Errorf("invalid label spec: %v", labelSpec)
			}
			labels[parts[0]] = parts[1]
		} else if strings.HasSuffix(labelSpec, "-") {
			remove = append(remove, labelSpec[:len(labelSpec)-1])
		} else {
			return nil, nil, fmt.Errorf("unknown label spec: %s", labelSpec)
		}
	}
	for _, removeLabel := range remove {
		if _, found := labels[removeLabel]; found {
			return nil, nil, fmt.Errorf("can not both modify and remove a label in the same command")
		}
	}
	return labels, remove, nil
}


text:
package org.oep.usermgt.service.base;

import org.oep.usermgt.service.BusinessServiceUtil;

import java.util.Arrays;

/**
 * @author NQMINH
 * @generated
 */
public class BusinessServiceClpInvoker {
	public BusinessServiceClpInvoker() {
		_methodName68 = "getBeanIdentifier";

		_methodParameterTypes68 = new String[] {  };

		_methodName69 = "setBeanIdentifier";

		_methodParameterTypes69 = new String[] { "java.lang.String" };
	}

	public Object invokeMethod(String name, String[] parameterTypes,
		Object[] arguments) throws Throwable {
		if (_methodName68.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes68, parameterTypes)) {
			return BusinessServiceUtil.getBeanIdentifier();
		}

		if (_methodName69.equals(name) &&
				Arrays.deepEquals(_methodParameterTypes69, parameterTypes)) {
			BusinessServiceUtil.setBeanIdentifier((java.lang.String)arguments[0]);

			return null;
		}

		throw new UnsupportedOperationException();
	}

	private String _methodName68;
	private String[] _methodParameterTypes68;
	private String _methodName69;
	private String[] _methodParameterTypes69;
}


text:
layout: post
title: 'Type Inference in Lambda Expressions : Java 8'
categories: [Programming]
tags : [Java-8, Lambda-Expressions, Type-Inference]
comments: true
---

Type Inference means that the data type of any expression (e.g. method return type or parameter type) can be deduced automatically by the compiler. Groovy language is a good example of programming languages supporting Type Inference.

Similarly, Java 8 Lambda expressions also support Type inference. Let's understand how it works with a few examples.

Suppose we have to calculate the sum of two numbers. As you know, we need an interface method that consumes two parameters of say Number type and returns the output of the same type. Let's create an interface and provide its inline implementation using Lambda expressions.

{% highlight java linenos %}
    public class LambdaTypeInferenceExample {
    public static void main(String[] args) {
            BiFunction<Integer,Integer,Integer> summer = (Integer number1,Integer number2) ->  { return number1 + number2;};

            Integer number1 = 10;
            Integer number2 = 20;

            System.out.println(number1+" + "+number2 +" = "+summer.apply(number1,number2));
        }
    }

    interface BiFunction<K,V,R>{
        R apply(K k ,V v);
    }
{% endhighlight %}

Observe that we have declared an interface called BiFunction which has a method, 'apply' accepting two parameters of any type K & V respectively and returns another type of value i.e. R. These types could be same or different as you provide their types during declaration.Here, we are summing up two integers and returning the output as an integer. For now, don't worry about any edge cases like sum of the maximum of two integers can't be equal to the integer as it exceeds the maximum limit. By using type inference feature, you could omit, the type of number1 and number2. The compiler would now automatically deduce the type, on the basis of input values as:

Here, we are summing up two integers and returning the output as an integer. For now, don't worry about any edge cases like sum of the maximum of two integers can't be equal to the integer as it exceeds the maximum limit. By using type inference feature, you could omit, the type of number1 and number2. The compiler would now automatically deduce the type, on the basis of input values as:

1. If you haven't specified generic types during reference variable declaration, type of number1 and number2 would be deduced as Object class instances.
2. If specified the generic types, it will automatically deduce the type and operation available for that type could be used.
The above code thus looks crisper after removing types from parameters:

{% highlight java linenos %}
  public class LambdaTypeInferenceExample {
      public static void main(String[] args) {
          BiFunction<Integer,Integer,Integer> summer = (number1,number2) ->  { return number1 + number2;};
          Integer number1 = 10;
          Integer number2 = 20;
          System.out.println(number1+" + "+number2 +" = "+summer.apply(number1,number2));
      }
  }

  interface BiFunction<K,V,R>{
      R apply(K k , V v);
  }
{% endhighlight %}

This is an example of type inference here. Let's go one more step ahead. We are saying return the following:

{% highlight java %}
 number1 + number 2
{% endhighlight %}

Here, we could omit 'return from statement' as there is only one statement and hence could easily be inferred by the compiler. As you know, if there is only one statement, we don't need parenthesis around lambda expression statements.

Hence, the above code will finally look like:

{% highlight java linenos %}
    public class LambdaTypeInferenceExample {
        public static void main(String[] args) {
            BiFunction<Integer,Integer,Integer> summer = (number1,number2) ->  number1 + number2;
            Integer number1 = 10;
            Integer number2 = 20;
            System.out.println(number1+" + "+number2 +" = "+summer.apply(number1,number2));
        }
    }

    interface BiFunction<K,V,R>{
        R apply(K k , V v);
    }
{% endhighlight %}

Hope you now have an understanding of how Type Inference works in lambda expressions. Though Java supports this, it is still a strict type-checking language.


text:
package mertz.security.oauth2.provider.token.store.cassandra.repo;

import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import mertz.security.oauth2.provider.token.store.cassandra.model.AuthenticationToAccessToken;

@Repository
public interface AuthenticationToAccessTokenRepository extends CrudRepository<AuthenticationToAccessToken, String> {

}


text:
package com.sap.mlt.xliff12.impl.attribute;

import com.sap.mlt.xliff12.api.attribute.Menu;
import com.sap.mlt.xliff12.impl.base.XliffAttributeImpl;

public class MenuImpl extends XliffAttributeImpl implements Menu {

	public MenuImpl(String menu) {
		super(NAME, menu);
	}

}


text:
title: "Monaco What's yours is mine"
href: Monaco_What_S_Yours_Is_Mine
class: inprogress
subtitle: WORK IN PROGRESS
layout: default
modal-id: 45
date: 2017-04-10
img: monaco_what_s_yours_is_mine_gameplay.jpg
thumbnail: monaco_what_s_yours_is_mine.jpg
alt: image-alt
game-date:
developer:
category:
multiplayer:
description: WORK IN PROGRESS
---


text:
from oslo.config import cfg
import oslo.messaging

from ceilometer import plugin
from ceilometer import sample

OPTS = [
    cfg.StrOpt('keystone_control_exchange',
               default='keystone',
               help="Exchange name for Keystone notifications."),
]

cfg.CONF.register_opts(OPTS)

SERVICE = 'identity'

class _Base(plugin.NotificationBase):
    """Convert identity notification into Samples."""

    resource_type = None
    resource_name = None

    @staticmethod
    def get_targets(conf):
        """Return a sequence of oslo.messaging.Target

        Sequence defining the exchange and topics to be connected for this
        plugin.
        """
        return [oslo.messaging.Target(topic=topic,
                                      exchange=conf.keystone_control_exchange)
                for topic in conf.notification_topics]

class IdentityCRUD(_Base):
    def process_notification(self, message):
        yield sample.Sample.from_notification(
            name=message['event_type'],
            type=sample.TYPE_DELTA,
            unit=self.resource_type,
            volume=1,
            resource_id=message['payload']['resource_info'],
            user_id=None,
            project_id=None,
            message=message)

class User(IdentityCRUD):

    resource_type = 'user'
    resource_name = '%s.%s' % (SERVICE, resource_type)

    @property
    def event_types(self):
        return ['%s.*' % self.resource_name]

class Group(IdentityCRUD):

    resource_type = 'group'
    resource_name = '%s.%s' % (SERVICE, resource_type)

    @property
    def event_types(self):
        return ['%s.*' % self.resource_name]

class Project(IdentityCRUD):

    resource_type = 'project'
    resource_name = '%s.%s' % (SERVICE, resource_type)

    @property
    def event_types(self):
        return ['%s.*' % self.resource_name]

class Role(IdentityCRUD):

    resource_type = 'role'
    resource_name = '%s.%s' % (SERVICE, resource_type)

    @property
    def event_types(self):
        return ['%s.*' % self.resource_name]

class Trust(IdentityCRUD):

    resource_type = 'OS-TRUST:trust'
    resource_name = '%s.%s' % (SERVICE, resource_type)

    @property
    def event_types(self):
        return [
            '%s.created' % self.resource_name,
            '%s.deleted' % self.resource_name,
        ]

class Authenticate(_Base):
    """Convert identity authentication notifications into Samples."""

    resource_type = 'authenticate'
    event_name = '%s.%s' % (SERVICE, resource_type)

    def process_notification(self, message):
        outcome = message['payload']['outcome']
        meter_name = '%s.%s.%s' % (SERVICE, self.resource_type, outcome)

        yield sample.Sample.from_notification(
            name=meter_name,
            type=sample.TYPE_DELTA,
            unit='user',
            volume=1,
            resource_id=message['payload']['initiator']['id'],
            user_id=message['payload']['initiator']['id'],
            project_id=None,
            message=message)

    @property
    def event_types(self):
        return [self.event_name]


text:
<!DOCTYPE html>

<title>DataKind AgeWatch Index - Hoonio.com</title>

AgeWatch index rankings


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/calc_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000" >

   <!--  <FrameLayout
        android:id="@+id/content"
        android:layout_width="@dimen/base_land_width"
        android:layout_height="@dimen/base_land_height"
        android:layout_gravity="center|center_vertical" /> -->

        <!-- <FrameLayout
        android:id="@+id/content"
        android:layout_width="@dimen/base_land_width"
        android:layout_height="@dimen/base_land_height"
        android:layout_gravity="center" /> -->

        <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center|center_vertical" />

</FrameLayout>


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.application.options.codeStyle.arrangement.action.tokens;

import com.intellij.application.options.codeStyle.arrangement.action.MoveArrangementMatchingRuleUpAction;
import com.intellij.application.options.codeStyle.arrangement.match.ArrangementMatchingRulesControl;
import com.intellij.application.options.codeStyle.arrangement.match.tokens.ArrangementRuleAliasControl;
import com.intellij.openapi.actionSystem.AnActionEvent;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Svetlana.Zemlyanskaya
 */
public class MoveArrangementAliasRuleUpAction extends MoveArrangementMatchingRuleUpAction {

  @Override
  @Nullable
  protected ArrangementMatchingRulesControl getRulesControl(@NotNull AnActionEvent e) {
    return e.getData(ArrangementRuleAliasControl.KEY);
  }
}


text:
import {
  Platform,
  TouchableOpacity,
  TouchableNativeFeedback
} from "react-native";

export const DEFAULT_ACTIVE_OPACITY = 0.85;

export const shadowStyle = {
  shadowOpacity: 0.35,
  shadowOffset: {
    width: 0,
    height: 5
  },
  shadowColor: "#000",
  shadowRadius: 3,
  elevation: 5
};

export const alignItemsMap = {
  center: "center",
  left: "flex-start",
  right: "flex-end"
};

export const isAndroid = Platform.OS === "android";

export function getTouchableComponent(useNativeFeedback) {
  if (useNativeFeedback === true && isAndroid === true) {
    return TouchableNativeFeedback;
  }
  return TouchableOpacity;
}

export function touchableBackground(color, fixRadius) {
  if (isAndroid) {
    if (Platform["Version"] >= 21) {
      return TouchableNativeFeedback.Ripple(
        color || "rgba(255,255,255,0.75)",
        fixRadius
      );
    } else {
      TouchableNativeFeedback.SelectableBackground();
    }
  }
  return undefined;
}


text:
require "integration_test_helper"

class HelpTest < ActionDispatch::IntegrationTest
  context "rendering the help index page" do
    setup do
      payload = {
        base_path: "/help",
        format: "special_route",
        title: "Help using GOV.UK",
        description: "",
      }
      stub_content_store_has_item("/help", payload)
    end

    should "render the help index page correctly" do
      visit "/help"

      assert_has_component_title "Help using GOV.UK"
    end
  end
end


text:
import unittest
import starter.starter_helper as starter_helper
import tests.test_data as test_data
import json
from ddt import ddt, data, unpack

example_workflow_name = "PostPerfectPublication"
example_workflow_id = lambda fe: "PostPerfectPublication_00353." + fe

@ddt
class TestStarterHelper(unittest.TestCase):

    @unpack
    @data({'data': test_data.data_published_lax, 'execution': 'lax'},
          {'data': test_data.data_error_lax, 'execution':'lax'},
          {'data': test_data.data_published_website, 'execution':'website'})
    def test_set_workflow_information_lax(self, data, execution):

        workflow_id, \
        workflow_name, \
        workflow_version, \
        child_policy, \
        execution_start_to_close_timeout, \
        workflow_input = starter_helper.set_workflow_information(example_workflow_name,
                                                                              "1",
                                                                              None,
                                                                              data,
                                                                              data['article_id'],
                                                                              execution)

        self.assertEqual(example_workflow_id(execution), workflow_id)
        self.assertEqual(example_workflow_name, workflow_name)
        self.assertEqual("1", workflow_version)
        self.assertIsNone(child_policy)
        self.assertEqual("1800", execution_start_to_close_timeout)
        self.assertEqual(json.dumps(data), workflow_input)

if __name__ == '__main__':
    unittest.main()


text:
package carlosgsouza.vinylshop.controller;

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

import carlosgsouza.vinylshop.database.DB;
import carlosgsouza.vinylshop.model.Report;
import carlosgsouza.vinylshop.model.Vinyl;

public class ReportController {;

	DB db = DB.connect();
	List<Vinyl> stuff;

	public Report artist() {
		Report result = new Report();

		List<String> artists = db.getArtists();
		Integer artistCount = artists.size();

		result.data.put("Number of artists", artistCount.toString());

		if(artistCount == 0) {
			return result;
		}

		Map<String, Integer> artist_vinylCount = new HashMap<String, Integer>();
		Map<String, Integer> artist_songCount = new HashMap<String, Integer>();

		for(String artist : artists) {
			List<Vinyl> artistVinyls = db.searchVinylByArtist(artist);

			artist_vinylCount.put(artist, artistVinyls.size());
			artist_songCount.put(artist, 0);

			for(Vinyl vinyl : artistVinyls) {
				artist_songCount.put(artist, artist_songCount.get(artist) + vinyl.songs.size());
			}
		}

		String topArtist = "";
		int topArtistVinylCount = -1;
		int idOfFirstVinylOfTopArtist = Integer.MAX_VALUE;

		for(String artist : artist_vinylCount.keySet()) {
			stuff = db.searchVinylByArtist(artist);
			int idOfFirstVinylOfArtist = idOffirstVinyl();

			if(topArtistVinylCount < artist_vinylCount.get(artist) || ( (topArtistVinylCount == artist_vinylCount.get(artist)) && (idOfFirstVinylOfArtist < idOfFirstVinylOfTopArtist))) {
				topArtist = artist;
				topArtistVinylCount = artist_vinylCount.get(artist);
				idOfFirstVinylOfTopArtist = idOfFirstVinylOfArtist;

			}
		}

		result.data.put("Top artist", topArtist);
		result.data.put("Number of vinyls by "+topArtist, artist_vinylCount.get(topArtist).toString());
		result.data.put("Number of songs by "+topArtist, artist_songCount.get(topArtist).toString());

		return result;
	}

	private int idOffirstVinyl() {
		int minId = Integer.MAX_VALUE;

		for(Vinyl vinyl : stuff) {
			if(vinyl.id < minId) {
				minId = vinyl.id;
			}
		}

		return minId;
	}

	public Report genre() {
		Report result = new Report();

		List<String> genres = db.getGenres();
		String stuff = "";
		Integer genreCount = genres.size();

		result.data.put("Number of genres", genreCount.toString());

		if(genreCount == 0) {
			return result;
		}

		Map<String, Integer> genre_vinylCount = new HashMap<String, Integer>();
		Map<String, Integer> genre_songCount = new HashMap<String, Integer>();

		for(String genre : genres) {
			List<Vinyl> genreVinyls = db.searchVinylByGenre(genre);

			genre_vinylCount.put(genre, genreVinyls.size());
			genre_songCount.put(genre, 0);

			for(Vinyl vinyl : genreVinyls) {
				genre_songCount.put(genre, genre_songCount.get(genre) + vinyl.songs.size());
			}
		}

		String topItem = "";
		int topGenreVinylCount = -1;
		int idOfFirstVinylOfTopGenre = Integer.MAX_VALUE;

		for(String genre : genre_vinylCount.keySet()) {
			int idOfFirstVinylOfGenre = idOffirstVinyl();

			if(topGenreVinylCount < genre_vinylCount.get(genre) || ( (topGenreVinylCount == genre_vinylCount.get(genre)) && (idOfFirstVinylOfGenre < idOfFirstVinylOfTopGenre))) {
				stuff = genre;
				topGenreVinylCount = genre_vinylCount.get(genre);
				idOfFirstVinylOfTopGenre = idOfFirstVinylOfGenre;
				topItem = stuff;
			}
		}

		result.data.put("Top genre", topItem);
		result.data.put("Number of "+topItem+" vinyls", genre_vinylCount.get(stuff).toString());
		result.data.put("Number of "+topItem+" songs", genre_songCount.get(stuff).toString());

		return result;
	}

}


text:
<?php

namespace Bpocallaghan\Titan\Models;

use Bpocallaghan\Titan\Models\TitanWebsiteNavigation;

class NavigationWebsite extends TitanWebsiteNavigation
{
    /**
     * Get all the rows as an array (ready for dropdowns)
     *
     * @return array
     */
    public static function getAllLists()
    {
        return self::orderBy('title')->get()->pluck('title_url', 'id')->toArray();
    }

    /**
     * Get the top main level menu
     *
     * @param int $hidden
     * @return mixed
     */
    static public function mainNavigation($hidden = 0)
    {
        $builder = self::where('parent_id', 0)->where('is_main', 1);

        if ($hidden != 1) {
            $builder->where('is_hidden', $hidden);
        }

        return $builder->orderBy('list_main_order')->get();
    }

    /**
     * Get All navigation where parent id, and not hidden
     *
     * @param        $id
     * @param string $type
     * @param string $order
     * @param int    $hidden
     * @return mixed
     */
    static public function whereParentIdORM(
        $id,
        $type = 'main',
        $order = 'list_main_order',
        $hidden = 0
    ) {
        $query = self::whereParentId($id);

        switch ($type) {
            case 'footer';
                $query->where('is_footer', 1);
                break;
            default:
                $query->where('is_main', 1);
        }

        return $query->orderBy($order)->get();
    }

    /**
     * Get All navigation where parent id, and not hidden
     *
     * @param        $id
     * @param string $type
     * @return mixed
     */
    static public function parentIdAndType($id, $type = 'main')
    {
        $builder = self::where('parent_id', $id);
        $builder->where("is_$type", 1);
        $builder->where("is_hidden", 0);

        return $builder->orderBy("list_$type" . '_order')->get();
    }
}


text:
package jp.leafytree.android.libproject

import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.google.common.collect.ImmutableSet
import scalaz.Scalaz._
import jp.leafytree.android.libproject.lib1.Lib1Java
import org.apache.commons.math3.analysis.function.Abs

class AppActivity extends Activity {
  override def onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_app)
    val messageTextView = findViewById(R.id.message_text_view).asInstanceOf[TextView]
    messageTextView.setText(new Lib1Java().getName())

    val values = for {
      str <- List("1", "2", "-3", "string", "5")
      int <- str.parseInt.toOption
    } yield (new Abs()).value(int)
    Log.d("debug", "" + ImmutableSet.of(values))
  }
}


text:
from __future__ import with_statement
from matplotlib.mlab import griddata
import matplotlib.cm as cm
import matplotlib.colors as colors
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.font_manager as font_manager
import pdb, sys
import subprocess as sp

''' This function converts a string to a number '''
def convertStr(s):
  try:
    ret = int(s)
  except ValueError:
    #Try float.
    ret = float(s)
  return ret

''' This function plots just the geometry of the nodes'''
def plotGeom():
  # plot data points.
  plt.scatter(x,y,marker='o',c='b',s=5,zorder=10)
  plt.xlim(-1,xlimit)
  plt.ylim(-ylimit,ylimit)
  plt.savefig('geom.png')

''' This function plots just the geometry of the nodes'''
def plotHeat():
  # open the DataFile.csv
  with open(sys.argv[2]) as dat:
    # read the first line and pull out the years
    years = map(convertStr, dat.readline().strip(',\n').split(',')[1:])
    # prepare the datatype
    # 1 int for the node, and then as many floats as years
    dattype = [('nodes', np.int64)] + [('',np.float64)]*len(years)
    # load the file (minus the first line)
    hdata = np.loadtxt(dat, delimiter=',', dtype=dattype)
  # map the resulting structure
  hdata = hdata.view(np.dtype([('nodes',np.int64), ('heat', np.float64, len(years))]))
  heat = hdata['heat']
  nodes = hdata['nodes']
  # define grid.
  xi = np.linspace(-max,max,2*max)
  yi = np.linspace(-max,max,2*max)
  # choose a year to plot
  for yr in years:
    plt.clf()
    plotGeom()
    # figure out which year
    yrToPlt = np.float64(yr)
    index =np.nonzero(years == yrToPlt)[0][0]
    # define the z data, heat, in the order of the xyznodes
    z=np.zeros(len(xyznodes))
    i=0
    for num in xyznodes:
      j = np.nonzero(nodes == num)[0][0]
      #z[i]=heat[j][np.nonzero(years==year)[0][0]]
      z[i]=heat[j][index]
      i=i+1
    # grid the data.
    zi = griddata(x,y,z,xi,yi)
    scale = colors.normalize(1,heat.max())
    # contour the gridded data, plotting dots at the nonuniform data points.
    CS = plt.contour(xi,yi,zi,10,linewidths=0.5,colors='k')
    CS = plt.contourf(xi,yi,zi,10,cmap=plt.cm.jet, norm=scale)
    # draw colorbar
    plt.colorbar()
    plt.xlim(-1,xlimit)
    plt.ylim(-ylimit,ylimit)
    plt.title('Heat during year %d'%yrToPlt)
    if yrToPlt < 10 :
      plt.savefig('heat/heat0000%d.png'%yrToPlt)
    elif yrToPlt < 100 :
      plt.savefig('heat/heat000%d.png'%yrToPlt)
    elif yrToPlt < 1000 :
      plt.savefig('heat/heat00%d.png'%yrToPlt)
    elif yrToPlt < 10000 :
      plt.savefig('heat/heat0%d.png'%yrToPlt)
    elif yrToPlt < 10000 :
      plt.savefig('heat/heat%d.png'%yrToPlt)
    elif yrToPlt >= 100000 :
      sys.exit("Too many years, please shorten input files.")
  # build a movie
  retcode = sp.call(["convert", "-set delay 24 /heat/heat*.png bob.gif"])
  # use return code to throw meaningful error?

''' This function decides which type of plot to make'''
def pickPlot():
  if plottype == 'geom' :
    plotGeom()
  elif plottype == 'heat':
    plotHeat()

''' SET UP '''
# get files from input args
if len(sys.argv) < 2:
  # stop the program and print an error message
  sys.exit("Too few arguments. Usage: grid_plot.py XYZfile.csv [DataFile.csv]")
# figure out which type of plot to plot.
if len(sys.argv) < 3:
  # assume we want to just plot the geometry
  plottype='geom'
elif len(sys.argv) == 3:
  # assume we want to plot the heat data
  plottype='heat'
elif len(sys.argv) == 5:
  plottype='heat'
elif len(sys.argv) > 3:
  # stop the program and print an error message
  sys.exit("Too many arguments: Usage: grid_plot.py XYZfile.csv [DataFile.csv]")

# open XYZfile.csv
with open(sys.argv[1]) as xyz:
  # read the first line and pull out the title
  title = xyz.readline().strip('\n').strip(',')
  # read the next line and pull out the column names
  cols = xyz.readline().strip(',\n').split(',')[1:]
  # prepare the datatype
  xyztype = [('nodes', np.int64)] + [('x', np.float64)] + [('y', np.float64)] + [('z', np.float64)]
  # load the file (minus the first line)
  xyzdata = np.loadtxt(xyz, delimiter=',', dtype=xyztype)
# map the resulting structure
xyznodes = xyzdata['nodes']
x = xyzdata['x']
y = xyzdata['y']
z = xyzdata['z']
# plot the whole range
xmax = x.max()
ymax = y.max()
xymax = np.array([xmax, ymax])
max = int(xymax.max())
if len(sys.argv) == 5:
  xlimit = convertStr(sys.argv[3])
  ylimit = convertStr(sys.argv[4])
else :
  xlimit = xmax
  ylimit = ymax

pickPlot()


text:
using Core.Application.Injection;

namespace Core.Application.Services
{
	public abstract class ServiceBase
	{
		public ServiceBase ()
		{
		}

		private ILoggingService _loggingService;
		/// <summary>
		/// Lazy loaded log service
		/// </summary>
		/// <value>The log service.</value>
		protected ILoggingService LoggingService
		{
			get{
				if (_loggingService == null)
					_loggingService = Injector.Resolve<ILoggingService> ();

				return _loggingService;
			}
		}
	}
}


text:
function RuleTemplate(templateName, metadata) {
  this.predicateName = templateName;
  this.meta = metadata;
}

RuleTemplate.prototype.windowFitsSite = function(sentence, i) {
  return ((i + this.meta.window[0] >= 0) &&
    (i + this.meta.window[0] < sentence.taggedWords.length) &&
    (i + this.meta.window[1] >= 0) &&
    (i + this.meta.window[1] < sentence.taggedWords.length));
};

module.exports = RuleTemplate;


text:
class Conversation < ActiveRecord::Base
  belongs_to :group
  has_many :messages

  accepts_nested_attributes_for :messages
end


text:
<!doctype html>

    <title>Refined Evobizz</title>

    Hours
    <input id="hours" type="number" value="8">

    Type
    <select id="type">
        <option value="COM">COM</option>
        <option value="ITH">ITH</option>
        <option selected value="ITO">ITO</option>
        <option value="OPL">OPL</option>
        <option value="OVU">OVU</option>
        <option value=""> </option>
    </select>

    Comment
    <input type="text" id="comment" value="">

<button id="btnFill">Fill in timesheets</button>


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <inset
            android:insetBottom="6dp"
            android:insetLeft="4dp"
            android:insetRight="4dp"
            android:insetTop="6dp">
            <shape>
                <solid
                    android:color="@color/colorRipple"
                    />
                <corners
                    android:radius="3dp"/>
                <padding
                    android:bottom="10dp"
                    android:left="10dp"
                    android:right="10dp"
                    android:top="10dp"/>
            </shape>
        </inset>
    </item>
    <item android:state_enabled="false">
		<inset
			android:insetBottom="6dp"
			android:insetLeft="4dp"
			android:insetRight="4dp"
			android:insetTop="6dp">
			<shape>
				<solid
					android:color="@color/textLighter"
					/>

				<corners
					android:radius="3dp"/>
				<padding
					android:bottom="10dp"
					android:left="10dp"
					android:right="10dp"
					android:top="10dp"/>
			</shape>
		</inset>
	</item>
    <item>
        <inset
            android:insetBottom="6dp"
            android:insetLeft="4dp"
            android:insetRight="4dp"
            android:insetTop="6dp">
            <shape>
                <solid
                    android:color="@color/red"
                    />

                <corners
                    android:radius="3dp"/>
                <padding
                    android:bottom="10dp"
                    android:left="10dp"
                    android:right="10dp"
                    android:top="10dp"/>
            </shape>
        </inset>
    </item>
</selector>


text:
package org.traccar.geolocation;

import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.Response;
import org.traccar.Context;
import org.traccar.model.CellTower;
import org.traccar.model.Network;

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;

public class OpenCellIdGeolocationProvider implements GeolocationProvider {

    private String url;

    public OpenCellIdGeolocationProvider(String key) {
        this("http://opencellid.org/cell/get", key);
    }

    public OpenCellIdGeolocationProvider(String url, String key) {
        this.url = url + "?format=json&mcc=%d&mnc=%d&lac=%d&cellid=%d&key=" + key;
    }

    @Override
    public void getLocation(Network network, final LocationProviderCallback callback) {
        if (network.getCellTowers() != null && !network.getCellTowers().isEmpty()) {

            CellTower cellTower = network.getCellTowers().iterator().next();
            String request = String.format(url, cellTower.getMobileCountryCode(), cellTower.getMobileNetworkCode(),
                    cellTower.getLocationAreaCode(), cellTower.getCellId());

            Context.getAsyncHttpClient().prepareGet(request).execute(new AsyncCompletionHandler() {
                @Override
                public Object onCompleted(Response response) throws Exception {
                    try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) {
                        JsonObject json = reader.readObject();
                        if (json.containsKey("lat") && json.containsKey("lon")) {
                            callback.onSuccess(
                                    json.getJsonNumber("lat").doubleValue(),
                                    json.getJsonNumber("lon").doubleValue(), 0);
                        } else {
                            callback.onFailure(new GeolocationException("Coordinates are missing"));
                        }
                    }
                    return null;
                }

                @Override
                public void onThrowable(Throwable t) {
                    callback.onFailure(t);
                }
            });

        } else {
            callback.onFailure(new GeolocationException("No network information"));
        }
    }

}