text:
var App = require('app');

App.componentConfigMapper = App.QuickDataMapper.create({
  model: App.HostComponent,
  config: {
    id: 'id',
    work_status: 'HostRoles.state',
    passive_state: 'HostRoles.maintenance_state',
    component_name: 'HostRoles.component_name',
    display_name: 'HostRoles.display_name',
    host_name: 'HostRoles.host_name',
    public_host_name: 'HostRoles.public_host_name',
    $ha_status: '',
    $display_name_advanced: '',
    stale_configs: 'HostRoles.stale_configs',
    host_id: 'HostRoles.host_name',
    service_id: 'HostRoles.service_name',
    admin_state: 'HostRoles.desired_admin_state'
  },
  map: function (json) {
    console.time('App.componentConfigMapper execution time');
    var staleConfigHostsMap = App.cache.staleConfigsComponentHosts;
    var componentsNeedRestart = json.items.mapProperty('ServiceComponentInfo.component_name');
    var components = App.MasterComponent.find().toArray()
      .concat(App.ClientComponent.find().toArray())
      .concat(App.SlaveComponent.find().toArray());

    //clear stale config hosts of component after restart
    components.forEach(function(component) {
      if (!componentsNeedRestart.contains(component.get('componentName'))) {
        staleConfigHostsMap[component.get('componentName')] = [];
        component.set('staleConfigHosts', []);
      }
    });

    json.items.forEach(function(item) {
      var componentName = item.ServiceComponentInfo.component_name;
      var hosts = item.host_components.mapProperty('HostRoles.host_name') || [];
      staleConfigHostsMap[componentName] = hosts;
      if (App.HostComponent.isMaster(componentName)) {
        App.MasterComponent.find(componentName).set('staleConfigHosts', hosts);
      } else if (App.HostComponent.isSlave(componentName)) {
        App.SlaveComponent.find(componentName).set('staleConfigHosts', hosts);
      } else if (App.HostComponent.isClient(componentName)) {
        App.ClientComponent.find(componentName).set('staleConfigHosts', hosts);
      }
    });
    console.timeEnd('App.componentConfigMapper execution time');
  },

  /**
   * build map that include loaded host-components to avoid duplicate loading
   * @param cacheServices
   * @return {Object}
   */
  buildServiceComponentMap: function (cacheServices) {
    var loadedServiceComponentsMap = {};

    cacheServices.forEach(function (cacheService) {
      var componentsMap = {};

      cacheService.host_components.forEach(function (componentId) {
        componentsMap[componentId] = true;
      });
      loadedServiceComponentsMap[cacheService.ServiceInfo.service_name] = componentsMap;
    });
    return loadedServiceComponentsMap;
  },

  /**
   * add only new host-components to every service
   * to update service - host-component relations in model
   * @param {object} newHostComponentsMap
   * @param {Array} cacheServices
   * @return {boolean}
   */
  addNewHostComponents: function (newHostComponentsMap, cacheServices) {
    if (!newHostComponentsMap || !cacheServices) return false;
    cacheServices.forEach(function (service) {
      if (newHostComponentsMap[service.ServiceInfo.service_name]) {
        newHostComponentsMap[service.ServiceInfo.service_name].forEach(function (componentId) {
          service.host_components.push(componentId)
        });
      }
    }, this);
    return true;
  }
});


text:
sudo apt-add-repository --yes ppa:libccd-debs/ppa
sudo apt-add-repository --yes ppa:fcl-debs/ppa
sudo apt-add-repository --yes ppa:dartsim/ppa
sudo apt-get -qq update

APT='
cmake
libassimp-dev
libboost-all-dev
libccd-dev
libeigen3-dev
libfcl-dev
freeglut3-dev
libxi-dev
libxmu-dev
libbullet-dev
libflann-dev
libnlopt-dev
coinor-libipopt-dev
libtinyxml-dev
libtinyxml2-dev
liburdfdom-dev
liburdfdom-headers-dev
libopenscenegraph-dev
'

sudo apt-get -qq --yes --force-yes install $APT

redpajama_set_name: RedPajamaGithub


text:
package net.sf.appia.demo;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.text.ParseException;

import net.sf.appia.core.Appia;
import net.sf.appia.core.AppiaCursorException;
import net.sf.appia.core.AppiaDuplicatedSessionsException;
import net.sf.appia.core.AppiaInvalidQoSException;
import net.sf.appia.core.Channel;
import net.sf.appia.core.ChannelCursor;
import net.sf.appia.core.Layer;
import net.sf.appia.core.QoS;
import net.sf.appia.protocols.group.Group;
import net.sf.appia.protocols.utils.ParseUtils;
import net.sf.appia.test.appl.ApplLayer;
import net.sf.appia.test.appl.ApplSession;

/**
 * Test application for the group communication protocols.
 * @see net.sf.appia.protocols.group
 * @author Hugo Miranda and Alexandre Pinto
 */
public class Appl {

    private Appl(){}

  public static final int DEFAULT_GOSSIP_PORT=10000;
  public static final int DEFAULT_MULTICAST_PORT=7000;

  private static Layer[] qos={
    //new net.sf.appia.protocols.udpsimple.UdpSimpleLayer(),
    //new appia.protocols.fifo.fifomulticast.FifoMulticastLayer(),
    //new appia.protocols.fifo.fifodual.FifoDualLayer(),
    //new net.sf.appia.protocols.fifo.FifoLayer(),
    new net.sf.appia.protocols.tcpcomplete.TcpCompleteLayer(),
    //new appia.protocols.sslcomplete.SslCompleteLayer(),
    new net.sf.appia.protocols.group.bottom.GroupBottomLayer(),
    new net.sf.appia.protocols.group.heal.GossipOutLayer(),
    new net.sf.appia.protocols.group.suspect.SuspectLayer(),
    new net.sf.appia.protocols.group.intra.IntraLayer(),
    new net.sf.appia.protocols.group.inter.InterLayer(),
    new net.sf.appia.protocols.group.heal.HealLayer(),
    new net.sf.appia.protocols.group.stable.StableLayer(),
    new net.sf.appia.protocols.group.leave.LeaveLayer(),
    new net.sf.appia.protocols.group.sync.VSyncLayer(),
    new ApplLayer(),
  };

  public static void main(String args[]) {
    int i;
    int port=-1;
    InetSocketAddress multicast=null;
    InetSocketAddress[] gossips=null;
    InetSocketAddress[] viewAddrs=null;
    final Group group=null;
    LineNumberReader file=null;

    boolean ssl=false;
    String keystoreFile=null;
    String keystorePass=null;

    for (i=0 ; i < args.length ; i++) {

      // PORT
      if(args[i].equals("-port")) {
        if (++i >= args.length)
          argInvalid("missing port number");
        try {
          port=Integer.parseInt(args[i]);
        } catch(NumberFormatException ex) {
          argInvalid("invalid port: "+args[i]);
        }

        // GOSSIP
      } else if (args[i].equals("-gossip")) {
        if (++i >= args.length)
          argInvalid("missing gossip server list");
        try {
          gossips=ParseUtils.parseSocketAddressArray(args[i],InetAddress.getLocalHost(),DEFAULT_GOSSIP_PORT);
        } catch (UnknownHostException e) {
          System.err.println("Host unknown: "+e.getMessage());
          System.exit(1);
        } catch (ParseException e) {
          System.err.println("Incorrect gossip server list format: "+e.getMessage());
          System.exit(1);
        } catch (NumberFormatException e) {
          System.err.println("Incorrect port: "+e.getMessage());
          System.exit(1);
        }

        // MULTICAST
      } else if (args[i].equals("-multicast")) {
        if (++i >= args.length)
          argInvalid("missing multicast address");
        try {
          multicast=ParseUtils.parseSocketAddress(args[i],null,DEFAULT_MULTICAST_PORT);
        } catch (NumberFormatException ex) {
          argInvalid("invalid port in multicast: \""+args[i]+"\"");
        } catch (java.net.UnknownHostException ex) {
          argInvalid("invalid address in multicast: \""+args[i]+"\"");
        } catch (ParseException e) {
          argInvalid("invalid format in multicast: \""+args[i]+"\"");
        }
        if (!multicast.getAddress().isMulticastAddress())
          argInvalid("not multicast address: \""+args[i]+"\"");

        // VIEW
      } else if (args[i].equals("-view")) {
        if (++i >= args.length)
          argInvalid("missing view addresses list");
        try {
          viewAddrs=ParseUtils.parseSocketAddressArray(args[i],null,-1);
        } catch (UnknownHostException e) {
          System.err.println("Host unknown: "+e.getMessage());
          System.exit(1);
        } catch (ParseException e) {
          System.err.println("Incorrect view format: "+e.getMessage());
          System.exit(1);
        } catch (NumberFormatException e) {
          System.err.println("Incorrect port: "+e.getMessage());
          System.exit(1);
        }

        // QOS
      } else if (args[i].equals("-qos")) {
        if (++i >= args.length)
          argInvalid("missing qos file name");
        try {
          file=new LineNumberReader(new FileReader(args[i]));
          String s=null;
          int j=0;
          while ((s=file.readLine()) != null) {
            s=s.trim();
            if (s.length() > 0) {
              if (j == qos.length-1) {
                final Layer[] aux=new Layer[qos.length*2];
                System.arraycopy(qos,0,aux,0,j);
                qos=aux;
              }
              qos[j++]=(Layer)Class.forName(s).newInstance();
            }
          }
          if (j < qos.length-1) {
            final Layer[] aux=new Layer[j+1];
            System.arraycopy(qos,0,aux,0,j);
            qos=aux;
          }
          qos[j]=new ApplLayer();
        } catch (FileNotFoundException ex) {
          argInvalid("qos file not found: \""+args[i]+"\"");
        } catch (IOException ex) {
          ex.printStackTrace();
          argInvalid("impossible to read qos file: \""+args[i]+"\"");
        } catch (ClassNotFoundException ex) {
          argInvalid("class not found: "+ex.getMessage());
        } catch (InstantiationException ex) {
          argInvalid("impossible to create layer: "+ex.getMessage());
        } catch (IllegalAccessException ex) {
          argInvalid("impossible to create layer: "+ex.getMessage());
        }

        // SSL
      } else if (args[i].equals("-ssl")) {
        ssl=true;

        // SSLKEYS
      } else if (args[i].equals("-sslkeys")) {
        ssl=true;
        if (++i >= args.length)
          argInvalid("missing key store file");
        keystoreFile=args[i];
        if (++i >= args.length)
          argInvalid("missing key store password");
        keystorePass=args[i];

        // HELP
      } else if (args[i].equals("-help")) {
        printUsage();
        System.exit(0);

        // DEFAULT
      } else {
        argInvalid("Invalid parameters: "+args[i]);
      }
    }

//    for (int k=0 ; k < qos.length ; k++) {
//      System.out.println(" "+k+": "+qos[k]);
//    }

    /* Create a QoS */
    QoS myQoS=null;
    try {
      myQoS=new QoS("Appl QoS",qos);
    } catch(AppiaInvalidQoSException ex) {
      System.err.println("Invalid QoS");
      System.err.println(ex.getMessage());
      System.exit(1);
    }

    /* Create a channel. Uses default event scheduler. */
    final Channel myChannel=myQoS.createUnboundChannel("Appl Channel");

    /* Application Session requires special arguments: qos and port.
       A session is created and binded to the stack. Remaining ones
       are created by default
     */

    final ApplSession as=(ApplSession)qos[qos.length-1].createSession();
    if (ssl)
      as.initWithSSL(port, multicast,gossips,group, viewAddrs, keystoreFile, keystorePass);
    else
      as.init(port,multicast,gossips,group,viewAddrs);

    final ChannelCursor cc=myChannel.getCursor();
    /* Application is the last session of the array. Positioning
       in it is simple */
    try {
      cc.top();
      cc.setSession(as);
    } catch(AppiaCursorException ex) {
      System.err.println("Unexpected exception in main. Type code:"+
      ex.type);
      System.exit(1);
    }

    /* Remaining ones are created by default. Just tell the channel to start */
    try {
      myChannel.start();
    } catch(AppiaDuplicatedSessionsException ex) {
      System.err.println("Sessions binding strangely resulted in "+
      "one single sessions occurring more than "+
      "once in a channel");
      System.exit(1);
    }

    /* All set. Appia main class will handle the rest */
    Appia.run();
  }

  private static void argInvalid(String s) {
    System.err.println("Appl: "+s);
    printUsage();
    System.exit(1);
  }

  private static void printUsage() {
    System.err.println("Usage: \n\t java Appl [options]");
    System.err.println("Options:"+
    "\n    -port <port>\t\t\tUDP/TCP port"+
    "\n    -gossip <IP:Port>,<IP:Port>,...\tGossip Servers addresses"+
    "\n    -multicast <Multicast_IP:Port>\tMulticast Address used for communication"+
    "\n    -view <IP:Port>,<IP:Port>,...\tInitial members addresses"+
    "\n    -qos <file>\t\t\t\tFile with QoS to use"+
    "\n    -ssl \t\t\t\tIf available uses SSL"+
    "\n    -sslkeys <keystore_file> <keystore_passwd\tIf available uses SSL with the given key store"
    );
  }
}


text:
using System;
using System.Collections.Generic;
using CoreGraphics;
using Foundation;
using Toggl.iOS.Cells.Reports;
using Toggl.iOS.ViewSources;
using UIKit;

namespace Toggl.iOS.Views.Reports
{
    public class ReportsCollectionViewCompactLayout : UICollectionViewLayout
    {
        private const int horizontalCellInset = 16;
        private const int verticalCellInset = 12;
        private const int workspaceButtonInset = 49;

        private List<UICollectionViewLayoutAttributes> layoutAttributes = new List<UICollectionViewLayoutAttributes>();
        private ReportsCollectionViewSource source;
        private bool hasMultipleWorkspaces = false;

        public ReportsCollectionViewCompactLayout(ReportsCollectionViewSource source)
        {
            this.source = source;
        }

        public override CGSize CollectionViewContentSize
        {
            get
            {
                var width = CollectionView.Bounds.Width;
                var height = CollectionView.Bounds.Height;
                if (source.HasDataToDisplay())
                {
                    height = verticalCellInset
                        + ReportsSummaryCollectionViewCell.Height
                        + verticalCellInset * 2
                        + ReportsBarChartCollectionViewCell.Height
                        + verticalCellInset * 2
                        + ReportAdvancedReportsViaWebCollectionViewCell.Height
                        + verticalCellInset * 3
                        + ReportsDonutChartCollectionViewCell.Height
                        + ReportsDonutChartLegendCollectionViewCell.Height * source.NumberOfDonutChartLegendItems()
                        + (hasMultipleWorkspaces ? workspaceButtonInset + verticalCellInset * 2 : 0);
                }
                return new CGSize(width, height);
            }
        }

        public override void PrepareLayout()
        {
            layoutAttributes = new List<UICollectionViewLayoutAttributes>();
            var columnWidth = CollectionViewContentSize.Width - horizontalCellInset * 2;
            for (var i = 0; i < CollectionView.NumberOfItemsInSection(0); i++)
            {
                var indexPath = NSIndexPath.FromItemSection(i, 0);
                UICollectionViewLayoutAttributes attributes = UICollectionViewLayoutAttributes.CreateForCell(indexPath);
                var cellType = source.CellTypeAt(indexPath);
                switch (cellType)
                {
                    case ReportsCollectionViewCell.Summary:
                        attributes.Frame = new CGRect(
                            horizontalCellInset,
                            verticalCellInset,
                            columnWidth,
                            ReportsSummaryCollectionViewCell.Height);
                        break;

                    case ReportsCollectionViewCell.BarChartPlaceholder:
                    case ReportsCollectionViewCell.BarChart:
                        attributes.Frame = new CGRect(
                            horizontalCellInset,
                            verticalCellInset
                                + ReportsSummaryCollectionViewCell.Height
                                + verticalCellInset * 2,
                            columnWidth,
                            ReportsBarChartCollectionViewCell.Height);
                        break;

                    case ReportsCollectionViewCell.AdvancedReportsViaWeb:
                        attributes.Frame = new CGRect(
                            horizontalCellInset,
                            verticalCellInset
                                + ReportsSummaryCollectionViewCell.Height
                                + verticalCellInset * 2
                                + ReportsBarChartCollectionViewCell.Height
                                + verticalCellInset * 2
                                + ReportsDonutChartCollectionViewCell.Height
                                + ReportsDonutChartLegendCollectionViewCell.Height * source.NumberOfDonutChartLegendItems()
                                + verticalCellInset * 2,
                            columnWidth,
                            ReportAdvancedReportsViaWebCollectionViewCell.Height);
                        break;

                    case ReportsCollectionViewCell.DonutChartPlaceholder:
                    case ReportsCollectionViewCell.DonutChart:
                        attributes.Frame = new CGRect(
                            0,
                            verticalCellInset
                                + ReportsSummaryCollectionViewCell.Height
                                + verticalCellInset * 2
                                + ReportsBarChartCollectionViewCell.Height
                                + verticalCellInset * 2,
                            CollectionViewContentSize.Width,
                            ReportsDonutChartCollectionViewCell.Height);
                        break;

                    case ReportsCollectionViewCell.DonutChartLegendItem:
                        var multiplier = (indexPath.Item - (CollectionView.NumberOfItemsInSection(0) - source.NumberOfDonutChartLegendItems()));
                        var sections = CollectionView.NumberOfSections();
                        var itemsInSectionZero = CollectionView.NumberOfItemsInSection(0);
                        attributes.Frame = new CGRect(
                            0,
                            verticalCellInset
                                + ReportsSummaryCollectionViewCell.Height
                                + verticalCellInset * 2
                                + ReportsBarChartCollectionViewCell.Height
                                + verticalCellInset * 2
                                + ReportsDonutChartCollectionViewCell.Height
                                + ReportsDonutChartLegendCollectionViewCell.Height * (indexPath.Item - (CollectionView.NumberOfItemsInSection(0) - source.NumberOfDonutChartLegendItems()) + 1),
                            CollectionViewContentSize.Width,
                            ReportsDonutChartLegendCollectionViewCell.Height);
                        break;

                    case ReportsCollectionViewCell.NoData:
                    case ReportsCollectionViewCell.Error:
                        attributes.Frame = new CGRect(
                            0,
                            0,
                            CollectionView.Bounds.Width,
                            CollectionView.Bounds.Height);
                        break;
                }
                layoutAttributes.Add(attributes);
            }
        }

        public override bool ShouldInvalidateLayoutForBoundsChange(CGRect newBounds)
            => true;

        public override UICollectionViewLayoutAttributes[] LayoutAttributesForElementsInRect(CGRect rect)
        {
            var visibleAttributes = new List<UICollectionViewLayoutAttributes>();
            foreach (var attributes in layoutAttributes)
            {
                if (attributes.Frame.IntersectsWith(rect))
                    visibleAttributes.Add(attributes);
            }
            return visibleAttributes.ToArray();
        }

        public override UICollectionViewLayoutAttributes LayoutAttributesForItem(NSIndexPath indexPath)
            => layoutAttributes[(int)indexPath.Item];

        public void SetHasMultipleWorkspaces(bool value)
        {
            hasMultipleWorkspaces = value;
            InvalidateLayout();
        }
    }
}


text:
<readable><title>3294179574_4f67e67d6f</title><content>
A guy is doing a skateboard trick in front of a crowd .
A man is skateboarding in front of a group of people .
A skateboarder performs a trick in front of a large crowd .
A skateboarder leaping from a pool in front of a crowd .
Skateboarder does tricks in front of crowd while photographer watches
</content></readable>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Trachymene kochii E.Pritz.

### Remarks
null


text:
<?php

namespace Fenrizbes\FormConstructorBundle\Item\Behavior\Action;

use Fenrizbes\FormConstructorBundle\Item\Behavior\AbstractBehaviorItem;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

abstract class AbstractBehaviorAction extends AbstractBehaviorItem
{
    protected $action_choices = array();

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options);

        $this->buildFormActionField($builder);
    }

    protected function buildFormActionField(FormBuilderInterface $builder)
    {
        $builder->add('action', 'choice', array(
            'label'       => 'fc.label.behavior.action_action',
            'required'    => true,
            'choices'     => $this->action_choices,
            'constraints' => array(
                new NotBlank(array(
                    'message' => 'fc.constraint.admin.blank'
                ))
            )
        ));
    }

    public function getAction($key)
    {
        return $this->action_choices[$key];
    }
}


text:
package org.datavaultplatform.common.model.dao;

import org.datavaultplatform.common.model.DataCreator;

import java.util.List;

public interface DataCreatorDAO {
    void save(List<DataCreator> dataCreators);

    DataCreator findById(String Id);

    void update(DataCreator dataCreator);

    void delete(String id);
}


text:
@extends('layout.bootstrap3.index')
@section('content')

Selamat Datang

            Di Penyewaan Majalah dan Komik

@stop


text:
using System.Collections;
using System.Collections.Generic;
using vlko.core.Repository;

namespace vlko.core.Components
{
	public class PagedModel<T> : IEnumerable<T>, IPagedModel where T : class
	{
		public static int DefaultPageItems = 15;

		private T[] _currentData = null;

		/// <summary>
		/// Initializes a new instance of the <see cref="PagedModel<T>"/> class.
		/// </summary>
		public PagedModel()
		{
			PageItems = DefaultPageItems;
			CurrentPage = 1;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="PagedModel<T>"/> class.
		/// </summary>
		/// <param name="currentPage">The current page.</param>
		public PagedModel(int currentPage)
		{
			CurrentPage = currentPage;
		}

		/// <summary>
		/// Gets or sets the page items.
		/// </summary>
		/// <value>The page items.</value>
		public int PageItems { get; set; }

		/// <summary>
		/// Gets or sets the current page.
		/// </summary>
		/// <value>The current page.</value>
		public int CurrentPage { get; set; }

		/// <summary>
		/// Gets the total count.
		/// </summary>
		/// <value>The total count.</value>
		public int Count { get; private set; }

		/// <summary>
		/// Gets the pages number.
		/// </summary>
		/// <value>The pages number.</value>
		public int PagesNumber { get; private set; }

		/// <summary>
		/// Loads the data.
		/// </summary>
		/// <param name="queryResult">The query result.</param>
		/// <returns>This instance.</returns>
		public PagedModel<T> LoadData(IQueryResult<T> queryResult)
		{
			Count = queryResult.Count();

			PagesNumber = Count / PageItems + (Count % PageItems > 0 ? 1 : 0);

			// check hi and lo ranges
			if (CurrentPage > PagesNumber)
			{
				CurrentPage = PagesNumber;
			}
			if (CurrentPage < 1)
			{
				CurrentPage = 1;
			}

			_currentData = queryResult.ToPage(CurrentPage - 1, PageItems);

			return this;
		}

		/// <summary>
		/// Gets the enumerator.
		/// </summary>
		/// <returns>Enumerator for current data.</returns>
		public IEnumerator<T> GetEnumerator()
		{
			return ((IEnumerable<T>) _currentData).GetEnumerator();
		}

		/// <summary>
		/// Returns an enumerator that iterates through a collection.
		/// </summary>
		/// <returns>
		/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
		/// </returns>
		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

	}
}


text:
package com.timelesssoftware.popularmovies.Models;

import java.util.List;

/**
 * Created by Luka on 10. 10. 2017.
 */

public class MovieReviewListModel<T> {
    public int page;
    public int total_results;
    public int total_pages;
    public List<T> results;
}


text:
import tornado.ioloop
import tornado.gen
from datetime import timedelta
import logging

from tornadis.client import Client
from tornadis.exceptions import ConnectionError, ClientError

LOG = logging.getLogger(__name__)

class PubSubClient(Client):
    """High level specific object to interact with pubsub redis.

    The call() method is forbidden with this object.

    More informations on the redis side: http://redis.io/topics/pubsub
    """

    def call(self, *args, **kwargs):
        """Not allowed method with PubSubClient object."""
        raise ClientError("not allowed with PubSubClient object")

    def async_call(self, *args, **kwargs):
        """Not allowed method with PubSubClient object."""
        raise ClientError("not allowed with PubSubClient object")

    def pubsub_subscribe(self, *args):
        """Subscribes to a list of channels.

        http://redis.io/topics/pubsub

        Args:
            *args: variable list of channels to subscribe.

        Returns:
            Future: Future with True as result if the subscribe is ok.

        Examples:

            >>> yield client.pubsub_subscribe("channel1", "channel2")
        """
        return self._pubsub_subscribe(b"SUBSCRIBE", *args)

    def pubsub_psubscribe(self, *args):
        """Subscribes to a list of patterns.

        http://redis.io/topics/pubsub

        Args:
            *args: variable list of patterns to subscribe.

        Returns:
            Future: Future with True as result if the subscribe is ok.

        Examples:

            >>> yield client.pubsub_psubscribe("channel*", "foo*")
        """
        return self._pubsub_subscribe(b"PSUBSCRIBE", *args)

    @tornado.gen.coroutine
    def _pubsub_subscribe(self, command, *args):
        if len(args) == 0:
            LOG.warning("you must provide at least one argument")
            raise tornado.gen.Return(False)
        results = yield Client.call(self, command, *args,
                                    __multiple_replies=len(args))
        if isinstance(results, ConnectionError):
            raise tornado.gen.Return(False)
        for reply in results:
            if isinstance(reply, ConnectionError) or len(reply) != 3 or \
                    reply[0].lower() != command.lower() or reply[2] == 0:
                raise tornado.gen.Return(False)
        self.subscribed = True
        raise tornado.gen.Return(True)

    def pubsub_unsubscribe(self, *args):
        """Unsubscribes from a list of channels.

        http://redis.io/topics/pubsub

        Args:
            *args: variable list of channels to unsubscribe.

        Returns:
            Future: Future with True as result if the unsubscribe is ok.

        Examples:

            >>> yield client.pubsub_unsubscribe("channel1", "channel2")
        """
        return self._pubsub_unsubscribe(b"UNSUBSCRIBE", *args)

    def pubsub_punsubscribe(self, *args):
        """Unsubscribes from a list of patterns.

        http://redis.io/topics/pubsub

        Args:
            *args: variable list of patterns to unsubscribe.

        Returns:
            Future: Future with True as result if the unsubscribe is ok.

        Examples:

            >>> yield client.pubsub_punsubscribe("channel*", "foo*")

        """
        return self._pubsub_unsubscribe(b"PUNSUBSCRIBE", *args)

    @tornado.gen.coroutine
    def _pubsub_unsubscribe(self, command, *args):
        if len(args) == 0:
            # see https://github.com/thefab/tornadis/issues/17
            args_len = 1
        else:
            args_len = len(args)
        results = yield Client.call(self, command, *args,
                                    __multiple_replies=args_len)
        if isinstance(results, ConnectionError):
            raise tornado.gen.Return(False)
        for reply in results:
            if isinstance(reply, ConnectionError) or len(reply) != 3 or \
                    reply[0].lower() != command.lower():
                raise tornado.gen.Return(False)
            if reply[2] == 0:
                self.subscribed = False
        raise tornado.gen.Return(True)

    @tornado.gen.coroutine
    def pubsub_pop_message(self, deadline=None):
        """Pops a message for a subscribed client.

        Args:
            deadline (int): max number of seconds to wait (None => no timeout)

        Returns:
            Future with the popped message as result (or None if timeout
                or ConnectionError object in case of connection errors
                or ClientError object if you are not subscribed)
        """
        if not self.subscribed:
            excep = ClientError("you must subscribe before using "
                                "pubsub_pop_message")
            raise tornado.gen.Return(excep)
        reply = None
        try:
            reply = self._reply_list.pop(0)
            raise tornado.gen.Return(reply)
        except IndexError:
            pass
        if deadline is not None:
            td = timedelta(seconds=deadline)
            yield self._condition.wait(timeout=td)
        else:
            yield self._condition.wait()
        try:
            reply = self._reply_list.pop(0)
        except IndexError:
            pass
        raise tornado.gen.Return(reply)


text:
using MatterHackers.VectorMath;

//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
//                  larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
//          mcseemagg@yahoo.com
//          http://www.antigrain.com
//----------------------------------------------------------------------------
using System;
using System.Drawing;
using System.Windows.Forms;

namespace MatterHackers.Agg.UI
{
	public abstract class WidgetForWindowsFormsAbstract : AbstractOsMappingWidget
	{
		private WindowsFormsAbstract windowsFormsWindow;

		public WindowsFormsAbstract WindowsFormsWindow
		{
			get { return windowsFormsWindow; }
			set
			{
				windowsFormsWindow = value;
				if (mainWindowsFormsWindow == null)
				{
					mainWindowsFormsWindow = windowsFormsWindow;
					mainWindowsFormsWindow.FormClosed += (sender, e) =>
					{
						mainWindowsFormsWindow = null;
					};
				}
			}
		}

		private static WindowsFormsAbstract mainWindowsFormsWindow = null;

		public static WindowsFormsAbstract MainWindowsFormsWindow
		{
			get { return mainWindowsFormsWindow; }
		}

		public WidgetForWindowsFormsAbstract(SystemWindow childSystemWindow)
			: base(childSystemWindow)
		{
			// If no platform specific Clipboard implementation has been initialized, fallback to the default
			// WindowsForms implementation
			if (!Clipboard.IsInitialized)
			{
				Clipboard.SetSystemClipboard(new WindowsFormsClipboard());
			}

			Focus();
		}

		public override Point2D DesktopPosition
		{
			get
			{
				return new Point2D(windowsFormsWindow.DesktopLocation.X, windowsFormsWindow.DesktopLocation.Y);
			}

			set
			{
				if (!windowsFormsWindow.Visible)
				{
					windowsFormsWindow.StartPosition = FormStartPosition.Manual;
				}
				windowsFormsWindow.DesktopLocation = new Point(value.x, value.y);
			}
		}

		public override Keys ModifierKeys
		{
			get
			{
				Keys modifierKeys = (MatterHackers.Agg.UI.Keys)Control.ModifierKeys;
				return modifierKeys;
			}
		}

		public override void OnBoundsChanged(EventArgs e)
		{
			Invalidate();
			base.OnBoundsChanged(e);
		}

		public override void BringToFront()
		{
			WindowsFormsWindow.Activate();
		}

		public override string Caption
		{
			get
			{
				return WindowsFormsWindow.Text;
			}
			set
			{
				WindowsFormsWindow.Text = value;
			}
		}

		public Rectangle GetRectangleFromRectD(RectangleDouble rectD)
		{
			Rectangle windowsRect = new Rectangle(
				(int)System.Math.Floor(rectD.Left),
				(int)System.Math.Floor(Height - rectD.Top),
				(int)System.Math.Ceiling(rectD.Width),
				(int)System.Math.Ceiling(rectD.Height));

			return windowsRect;
		}

		protected override void SetCursorOnEnter(Cursors cursorToSet)
		{
			switch (cursorToSet)
			{
				case Cursors.Arrow:
					WindowsFormsWindow.Cursor = System.Windows.Forms.Cursors.Arrow;
					break;

				case Cursors.Hand:
					WindowsFormsWindow.Cursor = System.Windows.Forms.Cursors.Hand;
					break;

				case Cursors.IBeam:
					WindowsFormsWindow.Cursor = System.Windows.Forms.Cursors.IBeam;
					break;
			}
		}

		public override void Invalidate(RectangleDouble rectToInvalidate)
		{
			rectToInvalidate.IntersectWithRectangle(LocalBounds);

			//rectToInvalidate = new rect_d(0, 0, Width, Height);

			Rectangle windowsRectToInvalidate = GetRectangleFromRectD(rectToInvalidate);
			if (WindowsFormsWindow != null)
			{
				WindowsFormsWindow.RequestInvalidate(windowsRectToInvalidate);
			}
		}

		public override Vector2 MinimumSize
		{
			get
			{
				return base.MinimumSize;
			}
			set
			{
				base.MinimumSize = value;

				Size clientSize = new Size((int)Math.Ceiling(MinimumSize.x), (int)Math.Ceiling(MinimumSize.y));
				Size windowSize = new Size(clientSize.Width + WindowsFormsWindow.Width - WindowsFormsWindow.ClientSize.Width,
					clientSize.Height + WindowsFormsWindow.Height - WindowsFormsWindow.ClientSize.Height);

				WindowsFormsWindow.MinimumSize = windowSize;
			}
		}

		public override void OnClosed(EventArgs e)
		{
			WindowsFormsWindow.RequestClose();
		}

		public override void Show()
		{
			if (mainWindowsFormsWindow != WindowsFormsWindow
				&& childSystemWindow.AlwaysOnTopOfMain)
			{
				WindowsFormsWindow.Show(mainWindowsFormsWindow);
			}
			else
			{
				WindowsFormsWindow.Show();
			}
		}

		public override void ShowModal()
		{
			WindowsFormsWindow.ShowDialog();
		}

		public override void Run()
		{
			Show();
			Application.Run(WindowsFormsWindow);
		}
	}
}


text:
const exec = require('child_process').exec;

jest.setTimeout(20000)

// https://www.facebook.com/zuck
const url = `https://raw.githubusercontent.com/gustawdaniel/facebook-nologin-scraper/organization/tests/pages/fb-log-zuck.html`;

it('Zuck Profile should be collected from command line', async () => {
    const runCommand = `node bin/facebook-nologin-scraper.js ${url}`;
    const myShellScript = exec(runCommand);

    await new Promise((resolve, reject) => {
        myShellScript.stdout.on('data', (out: string) => {
            // console.log(out);
            const data = JSON.parse(out);
            expect(data.name).toBe('Mark Zuckerberg');
            resolve(data);
        });
        myShellScript.stderr.on('data', (error: string) => {
            console.error(error);
            expect(error).toBe(null);
            reject(error)
        });
    });
});


text:
package io.micrometer.core.instrument.binder.jetty;

import io.micrometer.core.instrument.MockClock;
import io.micrometer.core.instrument.simple.SimpleConfig;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.Request;
import org.eclipse.jetty.client.util.StringContentProvider;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.util.component.LifeCycle;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import java.util.concurrent.CountDownLatch;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;

class JettyConnectionMetricsTest {

    private SimpleMeterRegistry registry = new SimpleMeterRegistry(SimpleConfig.DEFAULT, new MockClock());

    private Server server = new Server(0);

    private ServerConnector connector = new ServerConnector(server);

    private CloseableHttpClient client = HttpClients.createDefault();

    void setup() throws Exception {
        connector.addBean(new JettyConnectionMetrics(registry));
        server.setConnectors(new Connector[] { connector });
        server.start();
    }

    @AfterEach
    void teardown() throws Exception {
        if (server.isRunning()) {
            server.stop();
        }
    }

    @Test
    void contributesServerConnectorMetrics() throws Exception {
        setup();
        HttpPost post = new HttpPost("http://localhost:" + connector.getLocalPort());
        post.setEntity(new StringEntity("123456"));

        try (CloseableHttpResponse ignored = client.execute(post)) {
            try (CloseableHttpResponse ignored2 = client.execute(post)) {
                assertThat(registry.get("jetty.connections.current").gauge().value()).isEqualTo(2.0);
                assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(2.0);
            }
        }

        CountDownLatch latch = new CountDownLatch(1);
        connector.addLifeCycleListener(new LifeCycle.Listener() {
            @Override
            public void lifeCycleStopped(LifeCycle event) {
                latch.countDown();
            }
        });
        // Convenient way to get Jetty to flush its connections, which is required to
        // update the sent/received bytes metrics
        server.stop();

        assertTrue(latch.await(10, SECONDS));
        assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(2.0);
        assertThat(registry.get("jetty.connections.request").tag("type", "server").timer().count()).isEqualTo(2);
        assertThat(registry.get("jetty.connections.bytes.in").summary().totalAmount()).isGreaterThan(1);
    }

    @Test
    void contributesClientConnectorMetrics() throws Exception {
        setup();
        HttpClient httpClient = new HttpClient();
        httpClient.setFollowRedirects(false);
        httpClient.addBean(new JettyConnectionMetrics(registry));

        CountDownLatch latch = new CountDownLatch(1);
        httpClient.addLifeCycleListener(new LifeCycle.Listener() {
            @Override
            public void lifeCycleStopped(LifeCycle event) {
                latch.countDown();
            }
        });

        httpClient.start();

        Request post = httpClient.POST("http://localhost:" + connector.getLocalPort());
        post.content(new StringContentProvider("123456"));
        post.send();
        httpClient.stop();

        assertTrue(latch.await(10, SECONDS));
        assertThat(registry.get("jetty.connections.max").gauge().value()).isEqualTo(1.0);
        assertThat(registry.get("jetty.connections.request").tag("type", "client").timer().count()).isEqualTo(1);
        assertThat(registry.get("jetty.connections.bytes.out").summary().totalAmount()).isGreaterThan(1);
    }

    @Test
    void passingConnectorAddsConnectorNameTag() {
        new JettyConnectionMetrics(registry, connector);

        assertThat(registry.get("jetty.connections.messages.in").counter().getId().getTag("connector.name"))
                .isEqualTo("unnamed");
    }

    @Test
    void namedConnectorsGetTaggedWithName() {
        connector.setName("super-fast-connector");
        new JettyConnectionMetrics(registry, connector);

        assertThat(registry.get("jetty.connections.messages.in").counter().getId().getTag("connector.name"))
                .isEqualTo("super-fast-connector");
    }

}


text:
package ru.job4j.start;

/**
* Интерфейс UserAction описывает основные действия меню(добавление, удаление, поиск и т.д.).
* @author Konstantin Kolganov (kkolganov.92@gmail.com)
* @since 25.09.2017
* @version 2.0
*/

public interface UserAction {
/**
* Интерфейс UserAction.
*/
/**
* Метод key.
* Возвращает уникальный ключ меню.
* @return Ключ.
*/
	String key();
/**
* Метод execute.
* Исполнение действия над заявками.
* @param tracker Tracker.
* @param input Input.
*/
	void execute(Tracker tracker, Input input);
/**
* Метод info.
* Отображение информации.
* @return Info.
*/
	String info();
}


text:
<?php

// File generated from our OpenAPI spec

namespace Stripe;

/**
 * Customers with certain payments enabled have a cash balance, representing funds
 * that were paid by the customer to a merchant, but have not yet been allocated to
 * a payment. Cash Balance Transactions represent when funds are moved into or out
 * of this balance. This includes funding by the customer, allocation to payments,
 * and refunds to the customer.
 *
 * @property string $id Unique identifier for the object.
 * @property string $object String representing the object's type. Objects of the same type share the same value.
 * @property \Stripe\StripeObject $applied_to_payment
 * @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
 * @property string $currency Three-letter ISO currency code, in lowercase. Must be a supported currency.
 * @property string|\Stripe\Customer $customer The customer whose available cash balance changed as a result of this transaction.
 * @property int $ending_balance The total available cash balance for the specified currency after this transaction was applied. Represented in the smallest currency unit.
 * @property \Stripe\StripeObject $funded
 * @property bool $livemode Has the value true if the object exists in live mode or the value false if the object exists in test mode.
 * @property int $net_amount The amount by which the cash balance changed, represented in the smallest currency unit. A positive value represents funds being added to the cash balance, a negative value represents funds being removed from the cash balance.
 * @property \Stripe\StripeObject $refunded_from_payment
 * @property string $type The type of the cash balance transaction. One of applied_to_payment, unapplied_from_payment, refunded_from_payment, funded, return_initiated, or return_canceled. New types may be added in future. See Customer Balance to learn more about these types.
 * @property \Stripe\StripeObject $unapplied_from_payment
 */
class CustomerCashBalanceTransaction extends ApiResource
{
    const OBJECT_NAME = 'customer_cash_balance_transaction';

    use ApiOperations\All;
    use ApiOperations\Retrieve;

    const TYPE_APPLIED_TO_PAYMENT = 'applied_to_payment';
    const TYPE_FUNDED = 'funded';
    const TYPE_REFUNDED_FROM_PAYMENT = 'refunded_from_payment';
    const TYPE_RETURN_CANCELED = 'return_canceled';
    const TYPE_RETURN_INITIATED = 'return_initiated';
    const TYPE_UNAPPLIED_FROM_PAYMENT = 'unapplied_from_payment';
}


text:
    <input type="checkbox" id="field_{{ $field->id }}_default_ticked" name="field_{{ $field->id }}_custom[default_ticked]" value="true" {{ isset($field->typeData()['default_ticked']) && $field->typeData()['default_ticked'] ? ' checked="checked"' : '' }}">
    id }}_default_ticked">Default ticked


text:
#pragma once

#include "il2cpp-config.h"

#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif

#include <stdint.h>

#include "mscorlib_System_Attribute542643598.h"

// System.ComponentModel.TypeConverterAttribute
struct TypeConverterAttribute_t252469870;
// System.String
struct String_t;

#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif

// System.ComponentModel.TypeConverterAttribute
struct  TypeConverterAttribute_t252469870  : public Attribute_t542643598
{
public:
	// System.String System.ComponentModel.TypeConverterAttribute::converter_type
	String_t* ___converter_type_1;

public:
	inline static int32_t get_offset_of_converter_type_1() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_t252469870, ___converter_type_1)); }
	inline String_t* get_converter_type_1() const { return ___converter_type_1; }
	inline String_t** get_address_of_converter_type_1() { return &___converter_type_1; }
	inline void set_converter_type_1(String_t* value)
	{
		___converter_type_1 = value;
		Il2CppCodeGenWriteBarrier(&___converter_type_1, value);
	}
};

struct TypeConverterAttribute_t252469870_StaticFields
{
public:
	// System.ComponentModel.TypeConverterAttribute System.ComponentModel.TypeConverterAttribute::Default
	TypeConverterAttribute_t252469870 * ___Default_0;

public:
	inline static int32_t get_offset_of_Default_0() { return static_cast<int32_t>(offsetof(TypeConverterAttribute_t252469870_StaticFields, ___Default_0)); }
	inline TypeConverterAttribute_t252469870 * get_Default_0() const { return ___Default_0; }
	inline TypeConverterAttribute_t252469870 ** get_address_of_Default_0() { return &___Default_0; }
	inline void set_Default_0(TypeConverterAttribute_t252469870 * value)
	{
		___Default_0 = value;
		Il2CppCodeGenWriteBarrier(&___Default_0, value);
	}
};

#ifdef __clang__
#pragma clang diagnostic pop
#endif


text:
<?php

class Edge_CatalogFilter_Block_Layer_Filter_Category extends Mage_Catalog_Block_Layer_Filter_Category
{
    public function __construct()
    {
        parent::__construct();
        $this->setTemplate('catalogfilter/filter.phtml');
    }

    protected function _getFilterType()
    {
        return Mage::getStoreConfig('catalog/layered_navigation/category_filter_type');
    }

    public function isDropdown()
    {
        return $this->_getFilterType() === Edge_CatalogFilter_Helper_Data::FILTER_TYPE_SINGLE;
    }

    public function isMultiple()
    {
        return $this->_getFilterType() === Edge_CatalogFilter_Helper_Data::FILTER_TYPE_MULTIPLE;
    }

    public function isUnset()
    {
        return !$this->getRequest()->getParam($this->_filter->getRequestVar());
    }
}


text:
#include <ztest.h>
#include <linker/linker-defs.h>
#include <syscall_handler.h>

static volatile int test_flag;

__ramfunc static void arm_ram_function(void)
{
	test_flag = 1;
}

void test_arm_ramfunc(void)
{
	int init_flag, post_flag;

	init_flag = test_flag;
	zassert_true(init_flag == 0, "Test flag not initialized to zero");

	/* Verify that the .ramfunc section is not empty, it is located
	 * inside SRAM, and that arm_ram_function(.) is located inside
	 * the .ramfunc section.
	 */
	zassert_true((uint32_t)&_ramfunc_ram_size != 0,
		".ramfunc linker section is empty");
	zassert_true(((uint32_t)&_ramfunc_ram_start >= (uint32_t)&_image_ram_start)
			&& ((uint32_t)&_ramfunc_ram_end < (uint32_t)&_image_ram_end),
			".ramfunc linker section not in RAM");
	zassert_true(
		(((uint32_t)&_ramfunc_ram_start) <= (uint32_t)arm_ram_function) &&
		(((uint32_t)&_ramfunc_ram_end) > (uint32_t)arm_ram_function),
		"arm_ram_function not loaded into .ramfunc");

	/* If we build with User Mode support, verify that the
	 * arm_ram_function(.) is user (read) accessible.
	 */
#if defined(CONFIG_USERSPACE)
	zassert_true(arch_buffer_validate((void *)&_ramfunc_ram_start,
			(size_t)&_ramfunc_ram_size, 0) == 0 /* Success */,
		".ramfunc section not user accessible");
#endif /* CONFIG_USERSPACE */

	/* Execute the function from SRAM. */
	arm_ram_function();

	/* Verify that the function is executed successfully. */
	post_flag = test_flag;
	zassert_true(post_flag == 1,
		"arm_ram_function() execution failed.");
}
/**
 * @}
 */


text:
import logging
import sys
import csv
import re
import StringIO
import operator
from datetime import datetime

from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import user_passes_test
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import HttpResponseRedirect, HttpResponseForbidden, Http404, HttpResponse
from django.shortcuts import render, get_object_or_404
from django.views.decorators.cache import cache_page
from django.utils import timezone

from dojo.filters import TemplateFindingFilter
from dojo.forms import NoteForm, TestForm, FindingForm, \
    DeleteTestForm, AddFindingForm, \
    ImportScanForm, ReImportScanForm, FindingBulkUpdateForm, JIRAFindingForm
from dojo.models import Finding, Test, Notes,\
    BurpRawRequestResponse, Endpoint, Stub_Finding, Finding_Template, JIRA_PKey, Cred_User,\
    Cred_Mapping, Dojo_User, Multi_Usage_Notes
from dojo.tools.factory import import_parser_factory
from dojo.utils import get_page_items, add_breadcrumb, get_cal_event, message, \
    process_notifications, get_system_setting, create_notification
from dojo.tasks import add_issue_task

logging.basicConfig(
    level=logging.DEBUG,
    format='[%(asctime)s] %(levelname)s [%(name)s:%(lineno)d] %(message)s',
    datefmt='%d/%b/%Y %H:%M:%S',
    filename=settings.DOJO_ROOT + '/../django_app.log',
)
logger = logging.getLogger(__name__)

@user_passes_test(lambda u: u.is_staff)
def view_test(request, tid):
    test = Test.objects.get(id=tid)
    notes = test.notes.all()
    person = request.user.username
    findings = Finding.objects.filter(test=test)
    stub_findings = Stub_Finding.objects.filter(test=test)
    cred_test = Cred_Mapping.objects.filter(test=test).select_related('cred_id').order_by('cred_id')
    creds = Cred_Mapping.objects.filter(engagement=test.engagement).select_related('cred_id').order_by('cred_id')

    if request.method == 'POST':
        form = NoteForm(request.POST)
        if form.is_valid():
            new_note = form.save(commit=False)
            new_note.author = request.user
            new_note.date = timezone.now()
            new_note.save()
            test.notes.add(new_note)
            form = NoteForm()
            url = request.build_absolute_uri(reverse("view_test", args=(test.id,)))
            title="Test: %s on %s" % (test.test_type.name, test.engagement.product.name)
            process_notifications(request, new_note, url, title)
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Note added successfully.',
                                 extra_tags='alert-success')
    else:
        form = NoteForm()

    fpage = get_page_items(request, findings, 25)
    sfpage = get_page_items(request, stub_findings, 25)
    show_re_upload = any(test.test_type.name in code for code in ImportScanForm.SCAN_TYPE_CHOICES)

    add_breadcrumb(parent=test, top_level=False, request=request)
    return render(request, 'dojo/view_test.html',
                  {'test': test,
                   'findings': fpage,
                   'stub_findings': sfpage,
                   'form': form,
                   'notes': notes,
                   'person': person,
                   'request': request,
                   'show_re_upload': show_re_upload,
                   'creds': creds,
                   'cred_test': cred_test
                   })

@user_passes_test(lambda u: u.is_staff)
def edit_test(request, tid):
    test = get_object_or_404(Test, pk=tid)
    form = TestForm(instance=test)
    if request.method == 'POST':
        form = TestForm(request.POST, instance=test)
        if form.is_valid():
            new_test = form.save()
            tags = request.POST.getlist('tags')
            t = ", ".join(tags)
            new_test.tags = t
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Test saved.',
                                 extra_tags='alert-success')

    form.initial['target_start'] = test.target_start.date()
    form.initial['target_end'] = test.target_end.date()
    form.initial['tags'] = [tag.name for tag in test.tags]

    add_breadcrumb(parent=test, title="Edit", top_level=False, request=request)
    return render(request, 'dojo/edit_test.html',
                  {'test': test,
                   'form': form,
                   })

@user_passes_test(lambda u: u.is_staff)
def delete_test(request, tid):
    test = get_object_or_404(Test, pk=tid)
    eng = test.engagement
    form = DeleteTestForm(instance=test)

    from django.contrib.admin.utils import NestedObjects
    from django.db import DEFAULT_DB_ALIAS

    collector = NestedObjects(using=DEFAULT_DB_ALIAS)
    collector.collect([test])
    rels = collector.nested()

    if request.method == 'POST':
        if 'id' in request.POST and str(test.id) == request.POST['id']:
            form = DeleteTestForm(request.POST, instance=test)
            if form.is_valid():
                del test.tags
                test.delete()
                messages.add_message(request,
                                     messages.SUCCESS,
                                     'Test and relationships removed.',
                                     extra_tags='alert-success')
                return HttpResponseRedirect(reverse('view_engagement', args=(eng.id,)))

    add_breadcrumb(parent=test, title="Delete", top_level=False, request=request)
    return render(request, 'dojo/delete_test.html',
                  {'test': test,
                   'form': form,
                   'rels': rels,
                   'deletable_objects': rels,
                   })

@user_passes_test(lambda u: u.is_staff)
def delete_test_note(request, tid, nid):
    note = Notes.objects.get(id=nid)
    test = Test.objects.get(id=tid)
    if note.author == request.user:
        test.notes.remove(note)
        note.delete()
        messages.add_message(request,
                             messages.SUCCESS,
                             'Note removed.',
                             extra_tags='alert-success')
        return view_test(request, tid)
    return HttpResponseForbidden()

@user_passes_test(lambda u: u.is_staff)
@cache_page(60 * 5)  # cache for 5 minutes
def test_calendar(request):
    if not 'lead' in request.GET or '0' in request.GET.getlist('lead'):
        tests = Test.objects.all()
    else:
        filters = []
        leads = request.GET.getlist('lead','')
        if '-1' in request.GET.getlist('lead'):
            leads.remove('-1')
            filters.append(Q(lead__isnull=True))
        filters.append(Q(lead__in=leads))
        tests = Test.objects.filter(reduce(operator.or_, filters))
    add_breadcrumb(title="Test Calendar", top_level=True, request=request)
    return render(request, 'dojo/calendar.html', {
        'caltype': 'tests',
        'leads': request.GET.getlist('lead', ''),
        'tests': tests,
        'users': Dojo_User.objects.all()})

@user_passes_test(lambda u: u.is_staff)
def test_ics(request, tid):
    test = get_object_or_404(Test, id=tid)
    start_date = datetime.combine(test.target_start, datetime.min.time())
    end_date = datetime.combine(test.target_end, datetime.max.time())
    uid = "dojo_test_%d_%d_%d" % (test.id, test.engagement.id, test.engagement.product.id)
    cal = get_cal_event(start_date,
                        end_date,
                        "Test: %s (%s)" % (test.test_type.name, test.engagement.product.name),
                        "Set aside for test %s, on product %s.  Additional detail can be found at %s" % (
                            test.test_type.name, test.engagement.product.name,
                            request.build_absolute_uri((reverse("view_test", args=(test.id,))))),
                        uid)
    output = cal.serialize()
    response = HttpResponse(content=output)
    response['Content-Type'] = 'text/calendar'
    response['Content-Disposition'] = 'attachment; filename=%s.ics' % test.test_type.name
    return response

@user_passes_test(lambda u: u.is_staff)
def add_findings(request, tid):
    test = Test.objects.get(id=tid)
    form_error = False
    enabled = False
    jform = None
    form = AddFindingForm(initial={'date': timezone.now().date()})

    if get_system_setting('enable_jira') and JIRA_PKey.objects.filter(product=test.engagement.product).count() != 0:
        enabled = JIRA_PKey.objects.get(product=test.engagement.product).push_all_issues
        jform = JIRAFindingForm(enabled=enabled, prefix='jiraform')
    else:
        jform = None

    if request.method == 'POST':
        form = AddFindingForm(request.POST)
        if form.is_valid():
            new_finding = form.save(commit=False)
            new_finding.test = test
            new_finding.reporter = request.user
            new_finding.numerical_severity = Finding.get_numerical_severity(
                new_finding.severity)
            if new_finding.false_p or new_finding.active is False:
                new_finding.mitigated = timezone.now()
                new_finding.mitigated_by = request.user
            create_template = new_finding.is_template
            # always false now since this will be deprecated soon in favor of new Finding_Template model
            new_finding.is_template = False
            new_finding.save()
            new_finding.endpoints = form.cleaned_data['endpoints']
            new_finding.save()
            if 'jiraform-push_to_jira' in request.POST:
                jform = JIRAFindingForm(request.POST, prefix='jiraform', enabled=enabled)
                if jform.is_valid():
                    add_issue_task.delay(new_finding, jform.cleaned_data.get('push_to_jira'))
                messages.add_message(request,
                                     messages.SUCCESS,
                                     'Finding added successfully.',
                                     extra_tags='alert-success')
            if create_template:
                templates = Finding_Template.objects.filter(title=new_finding.title)
                if len(templates) > 0:
                    messages.add_message(request,
                                         messages.ERROR,
                                         'A finding template was not created.  A template with this title already '
                                         'exists.',
                                         extra_tags='alert-danger')
                else:
                    template = Finding_Template(title=new_finding.title,
                                                cwe=new_finding.cwe,
                                                severity=new_finding.severity,
                                                description=new_finding.description,
                                                mitigation=new_finding.mitigation,
                                                impact=new_finding.impact,
                                                references=new_finding.references,
                                                numerical_severity=new_finding.numerical_severity)
                    template.save()
                    messages.add_message(request,
                                         messages.SUCCESS,
                                         'A finding template was also created.',
                                         extra_tags='alert-success')
            if '_Finished' in request.POST:
                return HttpResponseRedirect(reverse('view_test', args=(test.id,)))
            else:
                return HttpResponseRedirect(reverse('add_findings', args=(test.id,)))
        else:
            if 'endpoints' in form.cleaned_data:
                form.fields['endpoints'].queryset = form.cleaned_data['endpoints']
            else:
                form.fields['endpoints'].queryset = Endpoint.objects.none()
            form_error = True
            messages.add_message(request,
                                 messages.ERROR,
                                 'The form has errors, please correct them below.',
                                 extra_tags='alert-danger')
    add_breadcrumb(parent=test, title="Add Finding", top_level=False, request=request)
    return render(request, 'dojo/add_findings.html',
                  {'form': form,
                   'test': test,
                   'temp': False,
                   'tid': tid,
                   'form_error': form_error,
                   'jform': jform,
                   })

@user_passes_test(lambda u: u.is_staff)
def add_temp_finding(request, tid, fid):
    jform = None
    test = get_object_or_404(Test, id=tid)
    finding = get_object_or_404(Finding_Template, id=fid)
    findings = Finding_Template.objects.all()

    if request.method == 'POST':
        form = FindingForm(request.POST)
        if form.is_valid():
            new_finding = form.save(commit=False)
            new_finding.test = test
            new_finding.reporter = request.user
            new_finding.numerical_severity = Finding.get_numerical_severity(
                new_finding.severity)
            new_finding.date = datetime.today()
            if new_finding.false_p or new_finding.active is False:
                new_finding.mitigated = timezone.now()
                new_finding.mitigated_by = request.user

            create_template = new_finding.is_template
            # is template always False now in favor of new model Finding_Template
            # no further action needed here since this is already adding from template.
            new_finding.is_template = False
            new_finding.save()
            new_finding.endpoints = form.cleaned_data['endpoints']
            new_finding.save()
            if 'jiraform-push_to_jira' in request.POST:
                jform = JIRAFindingForm(request.POST, prefix='jiraform', enabled=True)
                add_issue_task.delay(new_finding, jform.cleaned_data.get('push_to_jira'))
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Finding from template added successfully.',
                                 extra_tags='alert-success')

            if create_template:
                templates = Finding_Template.objects.filter(title=new_finding.title)
                if len(templates) > 0:
                    messages.add_message(request,
                                         messages.ERROR,
                                         'A finding template was not created.  A template with this title already '
                                         'exists.',
                                         extra_tags='alert-danger')
                else:
                    template = Finding_Template(title=new_finding.title,
                                                cwe=new_finding.cwe,
                                                severity=new_finding.severity,
                                                description=new_finding.description,
                                                mitigation=new_finding.mitigation,
                                                impact=new_finding.impact,
                                                references=new_finding.references,
                                                numerical_severity=new_finding.numerical_severity)
                    template.save()
                    messages.add_message(request,
                                         messages.SUCCESS,
                                         'A finding template was also created.',
                                         extra_tags='alert-success')

            return HttpResponseRedirect(reverse('view_test', args=(test.id,)))
        else:
            messages.add_message(request,
                                 messages.ERROR,
                                 'The form has errors, please correct them below.',
                                 extra_tags='alert-danger')

    else:
        form = FindingForm(initial={'active': False,
                                    'date': timezone.now().date(),
                                    'verified': False,
                                    'false_p': False,
                                    'duplicate': False,
                                    'out_of_scope': False,
                                    'title': finding.title,
                                    'description': finding.description,
                                    'cwe': finding.cwe,
                                    'severity': finding.severity,
                                    'mitigation': finding.mitigation,
                                    'impact': finding.impact,
                                    'references': finding.references,
                                    'numerical_severity': finding.numerical_severity})
        if get_system_setting('enable_jira'):
            enabled = JIRA_PKey.objects.get(product=test.engagement.product).push_all_issues
            jform = JIRAFindingForm(enabled=enabled, prefix='jiraform')
        else:
            jform = None

    add_breadcrumb(parent=test, title="Add Finding", top_level=False, request=request)
    return render(request, 'dojo/add_findings.html',
                  {'form': form,
                   'jform': jform,
                   'findings': findings,
                   'temp': True,
                   'fid': finding.id,
                   'tid': test.id,
                   'test': test,
                   })

def search(request, tid):
    test = get_object_or_404(Test, id=tid)
    templates = Finding_Template.objects.all()
    templates = TemplateFindingFilter(request.GET, queryset=templates).qs
    paged_templates = get_page_items(request, templates, 25)
    title_words = [word
                   for finding in templates
                   for word in finding.title.split() if len(word) > 2]

    title_words = sorted(set(title_words))
    add_breadcrumb(parent=test, title="Add From Template", top_level=False, request=request)
    return render(request, 'dojo/templates.html',
                  {'templates': paged_templates,
                   'filtered': templates,
                   'title_words': title_words,
                   'tid': tid,
                   'add_from_template': True,
                   })

@user_passes_test(lambda u: u.is_staff)
def finding_bulk_update(request, tid):
    test = get_object_or_404(Test, id=tid)
    finding = test.finding_set.all()[0]
    form = FindingBulkUpdateForm(request.POST)
    if request.method == "POST":
        if form.is_valid():
            finding_to_update = request.POST.getlist('finding_to_update')
            finds = Finding.objects.filter(test=test, id__in=finding_to_update)
            finds.update(severity=form.cleaned_data['severity'],
                         active=form.cleaned_data['active'],
                         verified=form.cleaned_data['verified'],
                         false_p=form.cleaned_data['false_p'],
                         duplicate=form.cleaned_data['duplicate'],
                         out_of_scope=form.cleaned_data['out_of_scope'])
            messages.add_message(request,
                                 messages.SUCCESS,
                                 'Bulk edit of findings was successful.  Check to make sure it is what you intended.',
                                 extra_tags='alert-success')
        else:
            messages.add_message(request,
                                 messages.ERROR,
                                 'Unable to process bulk update. Required fields are invalid,  '
                                 'please update individually.',
                                 extra_tags='alert-danger')

    return HttpResponseRedirect(reverse('view_test', args=(test.id,)))

@user_passes_test(lambda u: u.is_staff)
def re_import_scan_results(request, tid):
    additional_message = "When re-uploading a scan, any findings not found in original scan will be updated as " \
                         "mitigated.  The process attempts to identify the differences, however manual verification " \
                         "is highly recommended."
    t = get_object_or_404(Test, id=tid)
    scan_type = t.test_type.name
    engagement = t.engagement
    form = ReImportScanForm()

    form.initial['tags'] = [tag.name for tag in t.tags]
    if request.method == "POST":
        form = ReImportScanForm(request.POST, request.FILES)
        if form.is_valid():
            scan_date = form.cleaned_data['scan_date']
            min_sev = form.cleaned_data['minimum_severity']
            file = request.FILES['file']
            scan_type = t.test_type.name
            active = form.cleaned_data['active']
            verified = form.cleaned_data['verified']
            tags = request.POST.getlist('tags')
            ts = ", ".join(tags)
            t.tags = ts
            try:
                parser = import_parser_factory(file, t)
            except ValueError:
                raise Http404()

            try:
                items = parser.items
                original_items = t.finding_set.all().values_list("id", flat=True)
                new_items = []
                mitigated_count = 0
                finding_count = 0
                finding_added_count = 0
                reactivated_count = 0
                for item in items:
                    sev = item.severity
                    if sev == 'Information' or sev == 'Informational':
                        sev = 'Info'

                    if Finding.SEVERITIES[sev] > Finding.SEVERITIES[min_sev]:
                        continue

                    if scan_type == 'Veracode Scan' or scan_type == 'Arachni Scan':
                        find = Finding.objects.filter(title=item.title,
                                                      test__id=t.id,
                                                      severity=sev,
                                                      numerical_severity=Finding.get_numerical_severity(sev),
                                                      description=item.description
                                                      )
                    else:
                        find = Finding.objects.filter(title=item.title,
                                                      test__id=t.id,
                                                      severity=sev,
                                                      numerical_severity=Finding.get_numerical_severity(sev),
                                                      )

                    if len(find) == 1:
                        find = find[0]
                        if find.mitigated:
                            # it was once fixed, but now back
                            find.mitigated = None
                            find.mitigated_by = None
                            find.active = True
                            find.verified = verified
                            find.save()
                            note = Notes(entry="Re-activated by %s re-upload." % scan_type,
                                         author=request.user)
                            note.save()
                            find.notes.add(note)
                            reactivated_count += 1
                        new_items.append(find.id)
                    else:
                        item.test = t
                        item.date = t.target_start
                        item.reporter = request.user
                        item.last_reviewed = timezone.now()
                        item.last_reviewed_by = request.user
                        item.verified = verified
                        item.active = active
                        item.save()
                        finding_added_count += 1
                        new_items.append(item.id)
                        find = item

                        if hasattr(item, 'unsaved_req_resp') and len(item.unsaved_req_resp) > 0:
                            for req_resp in item.unsaved_req_resp:
                                burp_rr = BurpRawRequestResponse(finding=find,
                                                                 burpRequestBase64=req_resp["req"],
                                                                 burpResponseBase64=req_resp["resp"],
                                                                 )
                                burp_rr.clean()
                                burp_rr.save()

                        if item.unsaved_request is not None and item.unsaved_response is not None:
                            burp_rr = BurpRawRequestResponse(finding=find,
                                                             burpRequestBase64=item.unsaved_request,
                                                             burpResponseBase64=item.unsaved_response,
                                                             )
                            burp_rr.clean()
                            burp_rr.save()
                    if find:
                        finding_count += 1
                        for endpoint in item.unsaved_endpoints:
                            ep, created = Endpoint.objects.get_or_create(protocol=endpoint.protocol,
                                                                         host=endpoint.host,
                                                                         path=endpoint.path,
                                                                         query=endpoint.query,
                                                                         fragment=endpoint.fragment,
                                                                         product=t.engagement.product)
                            find.endpoints.add(ep)

                        if item.unsaved_tags is not None:
                            find.tags = item.unsaved_tags

                # calculate the difference
                to_mitigate = set(original_items) - set(new_items)
                for finding_id in to_mitigate:
                    finding = Finding.objects.get(id=finding_id)
                    finding.mitigated = datetime.combine(scan_date, timezone.now().time())
                    finding.mitigated_by = request.user
                    finding.active = False
                    finding.save()
                    note = Notes(entry="Mitigated by %s re-upload." % scan_type,
                                 author=request.user)
                    note.save()
                    finding.notes.add(note)
                    mitigated_count += 1
                messages.add_message(request,
                                     messages.SUCCESS,
                                     '%s processed, a total of ' % scan_type + message(finding_count, 'finding',
                                                                                'processed'),
                                     extra_tags='alert-success')
                if finding_added_count > 0:
                    messages.add_message(request,
                                         messages.SUCCESS,
                                         'A total of ' + message(finding_added_count, 'finding',
                                                                 'added') + ', that are new to scan.',
                                         extra_tags='alert-success')
                if reactivated_count > 0:
                    messages.add_message(request,
                                         messages.SUCCESS,
                                         'A total of ' + message(reactivated_count, 'finding',
                                                                 'reactivated') + ', that are back in scan results.',
                                         extra_tags='alert-success')
                if mitigated_count > 0:
                    messages.add_message(request,
                                         messages.SUCCESS,
                                         'A total of ' + message(mitigated_count, 'finding',
                                                                 'mitigated') + '. Please manually verify each one.',
                                         extra_tags='alert-success')

                create_notification(event='results_added', title='Results added', finding_count=finding_count, test=t, engagement=engagement, url=request.build_absolute_uri(reverse('view_test', args=(t.id,))))

                return HttpResponseRedirect(reverse('view_test', args=(t.id,)))
            except SyntaxError:
                messages.add_message(request,
                                     messages.ERROR,
                                     'There appears to be an error in the XML report, please check and try again.',
                                     extra_tags='alert-danger')

    add_breadcrumb(parent=t, title="Re-upload a %s" % scan_type, top_level=False, request=request)
    return render(request,
                  'dojo/import_scan_results.html',
                  {'form': form,
                   'eid': engagement.id,
                   'additional_message': additional_message,
                   })

@user_passes_test(lambda u: u.is_staff)
def download_cvffv1_test(request, tid):
    test = get_object_or_404(Test, pk=tid)

    output = StringIO.StringIO()
    wr = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
    product_name=test.engagement.product.name
    if str(test.test_type) == 'Veracode Scan':
        headings = ["finding_id", "issue_id", "title", "cwe", "url", "severity", "description", "mitigation", "impact",
                    "line_number", "sourcefile", "sourcefilepath", "Function", "WSO2_resolution", "WSO2_offset", "WSO2_comment", "Use_Case" , "Vulnerability_Influence" , "Resolution", "Applicable_Product"]
        wr.writerow(headings)

        offsets = [0, 10, 20, 50, 100, 150]
        for finding in Finding.objects.filter(test_id=tid):
            data = [finding.id, finding.issue_id, finding.title, finding.cwe, finding.url, finding.severity,
                    finding.description, finding.mitigation, finding.impact, finding.line_number, finding.sourcefile,
                    finding.sourcefilepath, finding.function ]

            comment_found = 0

            if int(finding.cwe) == 117:
                data.append("Already Mitigated")
                data.append("0");
                data.append("CRLF prevention in HTTP headers is already handled in Tomcat level. "
                            "Therefore  it is not required to do additional validation in applications. "
                            "Please refer to CARBON-15811 (https://wso2.org/jira/browse/CARBON-15811) for details.")
                comment_found = 1

            if comment_found == 0:
                use_case_found = 0
                wso2_comment = ""
                wso2_resolution = ""
                wso2_use_case = ""
                wso2_vulnerability_influence = ""
                resolution = ""
                wso2_offset = 0
                wso2_comment_found = 0

                for offset in offsets:
                    pattern = re.compile('[0-9]*')
                    product_name= pattern.split(product_name)[0]
                    similarFindingsWithNotes = filter_similar_findings_for_veracode_items(offset, finding, product_name)

                    if similarFindingsWithNotes:
                        t = get_object_or_404(Test, pk=similarFindingsWithNotes[0].test_id)

                        for note in similarFindingsWithNotes[0].notes.all():
                            if note.entry.find("] ~ ") > -1:
                                if str(note.entry[1:note.entry.find("] ~ ")]).strip().replace(" ","") != "":
                                        if note.entry.find("] ~ : ") > -1:
                                            if use_case_found != 1:
                                                use_case_found = 1
                                                wso2_resolution = str(note.entry[1:note.entry.find("] ~ ")]).strip()
                                                if wso2_comment_found == 0:
                                                    wso2_offset = str(offset)
                                                wso2_use_case = note.entry[note.entry.find("] ~ : ") + 5 : note.entry.find(":- ")]
                                                wso2_vulnerability_influence = note.entry[note.entry.find(":- ")  + 3 : note.entry.find(" :: ")]
                                                resolution = note.entry[note.entry.find(" :: ") + 3 :]
                                                comment_found = 1
                                                wso2_product = t.engagement.product
                                                if wso2_comment_found == 1:
                                                    break
                                        elif note.entry.find("] ~ ") > -1:
                                            if wso2_comment_found != 1:
                                                wso2_resolution = str(note.entry[1:note.entry.find("] ~ ")]).strip()
                                                wso2_offset = str(offset)
                                                wso2_product = t.engagement.product
                                                wso2_comment = note.entry[note.entry.find("] ~ ") + 4:]
                                                comment_found = 1
                                                wso2_comment_found = 1
                                                if use_case_found == 1:
                                                    break
                        if use_case_found ==1 & wso2_comment_found ==1:
                            break
                if comment_found == 1:
                    data.append(wso2_resolution)
                    data.append(wso2_offset)
                    data.append(wso2_comment)
                    data.append(wso2_use_case)
                    data.append(wso2_vulnerability_influence)
                    data.append(resolution)
                    if wso2_product.id != test.engagement.product.id:
                        data.append(wso2_product)

            wr.writerow([unicode(c).encode('utf8') for c in data])

    elif str(test.test_type) == 'Qualys Scan (Webapp)' or str(test.test_type) == 'Qualys Scan (Single Scan)':
        headings = ["finding_id", "issue_id", "title", "severity", "impact", "url", "param", "payload","endpoint", "description", "mitigation",
                    "WSO2_resolution", "WSO2_comment", "Use_Case" , "Vulnerability_Influence" , "Resolution"]
        wr.writerow(headings)

        for finding in Finding.objects.filter(test_id=tid):
            endpoint = ""
            if finding.endpoints:
                if finding.endpoints.all():
                    endpoint = finding.endpoints.all()[0];

                if endpoint:
                    data = [finding.id, finding.issue_id, finding.title, finding.severity, finding.impact, str(endpoint) + "\r\n(" + finding.url + ")", finding.param,
                            finding.payload, endpoint, finding.description, finding.mitigation]
                else:
                    data = [finding.id, finding.issue_id, finding.title, finding.severity, finding.impact, str(endpoint) + "\r\n(" + finding.url + ")", finding.param,
                            finding.payload , "", finding.description, finding.mitigation]
                comment_found = 0

                if finding.param:
                    similarFindingsWithNotes = Finding.objects.filter(title=finding.title,
                                                                    param=finding.param,
                                                                    url=finding.url).exclude(notes=None).order_by('-id')
                elif endpoint:
                    similarFindingsWithNotes = Finding.objects.filter(title=finding.title,
                                                                      payload=finding.payload,
                                                                      url=finding.url).exclude(notes=None).order_by('-id')

                if similarFindingsWithNotes:
                    for note in similarFindingsWithNotes[0].notes.all():
                        if note.entry.find("] ~ ") > -1:
                            if note.entry.find("] ~ : ") > -1:
                                data.append(str(note.entry[1:note.entry.find("] ~ ")]).strip())
                                data.append("N/A")
                                data.append("")
                                data.append(note.entry[note.entry.find("] ~ : ") + 5 : note.entry.find(":- ")])
                                data.append(note.entry[note.entry.find(":- ")  + 3 : note.entry.find(" :: ")])
                                data.append(note.entry[note.entry.find(" :: ") + 3 :])
                                break
                            elif note.entry.find("] ~ ") > -1:
                                data.append(str(note.entry[1:note.entry.find("] ~ ")]).strip())
                                data.append("N/A")
                                data.append(note.entry[note.entry.find("] ~ ") + 4:])
                                break

            wr.writerow([unicode(c).encode('utf8') for c in data])

    response = HttpResponse(output.getvalue(), content_type='plain/text')
    response['Content-Disposition'] = 'attachment; filename=' + str(test.test_type).replace(' ','_') + "-" + tid + '.csv'

    return response

def filter_similar_findings_for_veracode_items(offset, finding, product_name):
    pattern = re.compile('[0-9]*')
    product_name= pattern.split(product_name)[0]
    if offset == 0:
        filter = Finding.objects.filter(title=finding.title, sourcefile=finding.sourcefile, function=finding.function, line_number=finding.line_number, test__engagement__product=finding.test.engagement.product)
        similarFindingsWithNotes = get_notes_for_similar_findings(filter,offset)
        if len(similarFindingsWithNotes) == 0 :
            filter = Finding.objects.filter(title=finding.title, sourcefile=finding.sourcefile, function=finding.function, line_number=finding.line_number, test__engagement__product__name__startswith=product_name)
            similarFindingsWithNotes = get_notes_for_similar_findings(filter,offset)
            if len(similarFindingsWithNotes) == 0 :
                Finding.objects.filter(title=finding.title, sourcefile=finding.sourcefile, function=finding.function, line_number=finding.line_number)
                similarFindingsWithNotes = get_notes_for_similar_findings(filter,offset)
    else:
        filter = Finding.objects.filter(title=finding.title, sourcefile=finding.sourcefile, function=finding.function, line_number=finding.line_number, test__engagement__product=finding.test.engagement.product)
        similarFindingsWithNotes = get_notes_for_similar_findings(filter,offset)
        if len(similarFindingsWithNotes) == 0 :
            filter = Finding.objects.filter( title=finding.title, sourcefile=finding.sourcefile, function=finding.function, test__engagement__product__name__startswith=product_name)
            similarFindingsWithNotes = get_notes_for_similar_findings(filter,offset)
            if len(similarFindingsWithNotes) == 0:
                filter = Finding.objects.filter( title=finding.title, sourcefile=finding.sourcefile, function=finding.function)
                similarFindingsWithNotes = get_notes_for_similar_findings(filter,offset)
    return similarFindingsWithNotes

def get_notes_for_similar_findings(filter,offset):
    if offset == 0:
        similarFindingsWithNotes = filter.exclude(notes=None).order_by('-id')
    else:
        similarFindingsWithNotes = filter.filter(line_number__gte=(int(finding.line_number) - offset), line_number__lte=(int(finding.line_number) + offset)).exclude(notes=None).order_by('-id')
    return similarFindingsWithNotes

def download_multi_usage_cvffv1_test(request, tid):
    test = get_object_or_404(Test, pk=tid)

    output = StringIO.StringIO()
    wr = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
    product_name=test.engagement.product.name

    if str(test.test_type) == 'Veracode Scan':
        headings = ["finding_id", "issue_id", "occurrence_number","WSO2_resolution", "Use_Case" , "Vulnerability_Influence" , "Resolution", "Applicable_Product"]
        wr.writerow(headings)

        offsets = [0, 10, 20, 50, 100, 150]
        for finding in Finding.objects.filter(test_id=tid):
            comment_found = 0
            if comment_found == 0:
                wso2_resolution = ""
                wso2_use_case = ""
                wso2_vulnerability_influence = ""
                resolution = ""
                multi_usage_comment_found = 0
                for offset in offsets:
                    pattern = re.compile('[0-9]*')
                    product_name = pattern.split(product_name)[0]
                    similarFindingsWithNotes = filter_similar_findings_for_veracode_items(offset, finding, product_name)
                    if similarFindingsWithNotes:
                        t = get_object_or_404(Test, pk=similarFindingsWithNotes[0].test_id)
                        for note in similarFindingsWithNotes[0].notes.all():
                            if str(note.entry[note.entry.find(": "):note.entry.find("] ~ : ")+20]) == ": [Multi Usage]":
                                if multi_usage_comment_found == 0:
                                    note_id=note.id
                                    multi_usage_notes=Multi_Usage_Notes.objects.filter(note_id=note_id)
                                    for multi_usage_note in multi_usage_notes:
                                        data = [finding.id, finding.issue_id ]
                                        if str(multi_usage_note.entry[1:multi_usage_note.entry.find("] ~ ")]).strip().replace(" ","") != "":
                                            if multi_usage_note.entry.find("] ~ : ") > -1:
                                                    wso2_resolution = str(multi_usage_note.entry[1:multi_usage_note.entry.find("] ~ ")]).strip()
                                                    occurrence_number = multi_usage_note.occurrence_number
                                                    wso2_use_case = multi_usage_note.entry[multi_usage_note.entry.find("] ~ : ") + 5 : multi_usage_note.entry.find(":- ")]
                                                    wso2_vulnerability_influence = multi_usage_note.entry[multi_usage_note.entry.find(":- ")  + 3 : multi_usage_note.entry.find(" :: ")]
                                                    resolution = multi_usage_note.entry[multi_usage_note.entry.find(" :: ") + 3 :]
                                                    multi_usage_comment_found = 1
                                                    wso2_product = t.engagement.product
                                        data.append(occurrence_number)
                                        data.append(wso2_resolution)
                                        data.append(wso2_use_case)
                                        data.append(wso2_vulnerability_influence)
                                        data.append(resolution)
                                        if wso2_product.id != test.engagement.product.id:
                                            data.append(wso2_product)

                                        wr.writerow([unicode(c).encode('utf8') for c in data])

    response = HttpResponse(output.getvalue(), content_type='plain/text')
    response['Content-Disposition'] = 'attachment; filename=' + str(test.test_type).replace(' ','_') + "-" + tid + '.csv'

    return response