text:
using System;
using System.IO;
using System.Reflection;
using FluentMigrator.Runner.Announcers;
using FluentMigrator.Runner.Initialization;

namespace linger.Tests
{
    public class MigrationHelper
    {
        private readonly string _databaseType;

        public MigrationHelper(string databaseType)
        {
            _databaseType = databaseType;
        }

        public virtual void Migrate(string connectionString, Assembly assembly = null)
        {
            if (_databaseType == "sqlite")
            {
                CopyInteropAssemblyByPlatform();
            }
            assembly = assembly ?? Assembly.GetExecutingAssembly();
            var announcer = new TextWriterAnnouncer(Console.Out) {ShowSql = true, ShowElapsedTime = false};
            var context = new RunnerContext(announcer)
            {
                Connection = connectionString,
                Database = _databaseType,
                Target = assembly.FullName,
                Profile = "linger",
            };
            var executor = new TaskExecutor(context);
            executor.Execute();
        }

        private const string SQLiteAssembly = "SQLite.Interop.dll";
        public static void CopyInteropAssemblyByPlatform()
        {
            var baseDir = WhereAmI();
            var destination = Path.Combine(baseDir, SQLiteAssembly);
            if (File.Exists(destination))
            {
                return;
            }
            var arch = Environment.Is64BitProcess ? "x64" : "x86";
            var path = Path.Combine(arch, SQLiteAssembly);
            var source = Path.Combine(baseDir, path);
            File.Copy(source, destination, true);
        }

        internal static string WhereAmI()
        {
            var dir = new Uri(Assembly.GetExecutingAssembly().CodeBase);
            var fi = new FileInfo(dir.AbsolutePath);
            return fi.Directory != null ? fi.Directory.FullName : null;
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>#DevTO Presents the 6th Annual International Women's Day Talks</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet">

    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" href="vendor/simple-line-icons/css/simple-line-icons.css">
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Muli" rel="stylesheet">

    <link href="css/flipclock.css" rel="stylesheet">

    <link rel="stylesheet" href="device-mockups/device-mockups.min.css">

    <link href="css/new-age.css" rel="stylesheet">

        #IWDTO
        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
          Menu

        </button>

              Tickets

              Speakers

              Sponsors

              Get Involved

                #IWDTO 6th Year in the 6ix!

              Monday March 2nd 2020, 5:30pm-9:30pm

              RBC WaterPark Place, 88 Queens Quay W, Toronto

                   A day we celebrate and set a stage for Women in Tech to gather, speak and cheer with their allies.

              Buy Tickets

                🎉 Stay tuned for the 6 speakers we are inviting this year! 🎉

Sixth year, seven amazing speakers, 500 attendees. Join us today!

              Buy Tickets

                  Join these amazing organizations that are sending their teams to join us for an evening of inspiration & celebration!

 2019 Presenting Sponsor

Booth Sponsors

 Community Supporters

Get Involved!

                Email nael@devto.ca to join us as a community supporter or send a team of 10 using our Company Night Out Ticket Package

The Company Night Out Ticket Package

              Your company can support this event by sending 10 employees to attend #IWDTO. For $700, the Company Night Out Ticket Package includes:

10 Tickets to send your team to the event

Recognition abov as a Community Supporter of IWDTO. (upload your logo here)

🙏🏻 🙏🏾 🙏🏿

                Last Year's Event

                 In 2019, we welcomed over 500 people to come together, celebrate, empower and inspire.

               2020 Sponsor Packages

                  So you heard about #IWDTO, and you're wondering why you should get involved?

                  #DevTO is a Toronto based organized founded in 2011 to produce events for the Toronto Tech community. In this time we have hosted over 100 events including meetups, conferences, documentary presentations and more. This year will be the 6th year we host this event as well.

 2,000+ guests over the past 4 years

 Last year we had 500 people attend with around 80% women in tech attendees

 You will be in good company with 20+ other amazing sponsors and community supporters

Company Night Out 10 Ticket Pack

 $700

 10 tickets for your team to attend

 logo on this site and at the event

                   Buy your tickets now

We

          new friends!

© #DevTO, #IWDTO 2020. All Rights Reserved.

            Code of Conduct

redpajama_set_name: RedPajamaGithub


text:
@interface UHMBox : NSObject

@property (strong, nonatomic) NSArray *sides;
@property (strong, nonatomic) NSArray *joints;
@property (strong, nonatomic) UHMProjectile *content;

@end


text:
#pragma once

#ifndef __AFXWIN_H__
	#error include 'stdafx.h' before including this file for PCH
#endif

#include "resource.h"		// main symbols

// CDataCreatorApp:
// See DataCreator.cpp for the implementation of this class
//

class CDataCreatorApp : public CWinApp
{
public:
	CDataCreatorApp();

	CString GetAppFolder()
	{
		return csAppFolder;
	}

// Overrides
	public:
	virtual BOOL InitInstance();

// Implementation

	DECLARE_MESSAGE_MAP()

private:
	CString						csAppFolder;
};

extern CDataCreatorApp theApp;


text:
require 'sidekiq/web'

Scumblr::Application.routes.draw do

  resources :flags

  get "user_saved_filters/create"
  get "user_saved_filters/destroy"
  get "saved_filters/new"
  get "saved_filters/destroy"

  resources :saved_filters do
    member do
      post :add
      post :remove
    end
  end

  resources :results do
    collection do
      post 'update_multiple'
      post 'bulk_add'
      post 'search' => 'results#index'
      get 'search' => 'results#index'
      get 'tags/:tag', to: 'results#index', as: :tag
      get 'dashboard'
      get 'workflow_autocomplete'

    end

    member do
      post 'change_status/:status_id'=>"results#update_status", as: 'update_status'
      post 'comment'  => 'results#comment', :as=> :comment
      post 'tag'  => 'results#tag'
      post 'flag'  => 'results#flag'
      post 'action/:result_flag_id/step/:stage_id'  => 'results#action', as: 'action'
      post 'assign'  => 'results#assign'
      post 'subscribe'  => 'results#subscribe'
      post 'unsubscribe'  => 'results#unsubscribe'
      delete 'tags/:tag_id', to: 'results#delete_tag', as: :delete_tag
      post :add_attachment
      delete 'attachment/:attachment_id', to: 'results#delete_attachment', as: :delete_attachment
      post 'generate_screenshot' => "results#generate_screenshot"
      post 'update_screenshot'
      get 'update_screenshot'
    end

  end

  devise_for :users
  resources :users do
    member do
      post 'toggle_admin'
    end
  end

  resources :tags, only: :index

  resources :searches do
    collection do
      get 'options', to: 'providers#options'
      get 'run', to: 'searches#run'
      get :events
    end

    member do
      get 'run', to: 'searches#run'
    end

    member do
      get 'options', to: 'providers#options'
    end
  end

  resources :statuses do
    member do
      post 'set_default'
    end
  end

  get 'status', to: 'status#status'

  root to: "results#index"

  admin_constraint = lambda do |request|
    request.env['warden'].authenticate? && request.env['warden'].user.admin?
  end

  constraints admin_constraint do
    mount Workflowable::Engine => "/workflowable", as: :workflowable
    mount Sidekiq::Web => '/sidekiq'
    get 'errors', :to => "event_groups#index"
    get 'about', to: 'status#about'
  end

end


text:
package org.jclouds.aliyun.ecs.compute.strategy;

import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import org.jclouds.aliyun.ecs.AliyunEcsApi;
import org.jclouds.compute.domain.Hardware;
import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.compute.reference.ComputeServiceConstants.Timeouts;
import org.jclouds.ecs.compute.strategy.EcsComputeServiceAdapter;
import org.jclouds.logging.Logger;

import com.google.common.base.Function;

@Singleton
public class AliyunEcsComputeServiceAdapter extends EcsComputeServiceAdapter {

	@Resource
	@Named(ComputeServiceConstants.COMPUTE_LOGGER)
	protected Logger logger = Logger.NULL;

	@Inject
	protected AliyunEcsComputeServiceAdapter(AliyunEcsApi api,
			Function<Hardware, String> sizeToRam, Timeouts timeouts) {
		super(api, sizeToRam, timeouts);

	}

}


text:
package org.apache.ignite.internal.processors.cache.consistency.persistence;

import org.apache.ignite.internal.processors.cache.consistency.inmem.ImplicitTransactionalReadRepairTest;

/**
 *
 */
public class PdsImplicitTransactionalReadRepairTest extends ImplicitTransactionalReadRepairTest {
    /** {@inheritDoc} */
    @Override protected boolean persistenceEnabled() {
        return true;
    }
}


text:
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>

#include <cutils/log.h>
#include <cutils/atomic.h>

#include "codeflinger/CodeCache.h"

namespace android {

// ----------------------------------------------------------------------------

#if defined(__arm__)
#include <unistd.h>
#include <errno.h>
#endif

// ----------------------------------------------------------------------------

Assembly::Assembly(size_t size)
    : mCount(1), mSize(0)
{
    mBase = (uint32_t*)mspace_malloc(getMspace(), size);
    mSize = size;
    ensureMbaseExecutable();
}

Assembly::~Assembly()
{
    mspace_free(getMspace(), mBase);
}

void Assembly::incStrong(const void*) const
{
    android_atomic_inc(&mCount);
}

void Assembly::decStrong(const void*) const
{
    if (android_atomic_dec(&mCount) == 1) {
        delete this;
    }
}

ssize_t Assembly::size() const
{
    if (!mBase) return NO_MEMORY;
    return mSize;
}

uint32_t* Assembly::base() const
{
    return mBase;
}

ssize_t Assembly::resize(size_t newSize)
{
    mBase = (uint32_t*)mspace_realloc(getMspace(), mBase, newSize);
    mSize = newSize;
    ensureMbaseExecutable();
    return size();
}

mspace Assembly::getMspace()
{
    static mspace msp = create_contiguous_mspace(2 * 1024, 1024 * 1024, /*locked=*/ false);
    return msp;
}

void Assembly::ensureMbaseExecutable()
{
    long pagesize = sysconf(_SC_PAGESIZE);
    long pagemask = ~(pagesize - 1);  // assumes pagesize is a power of 2

    uint32_t* pageStart = (uint32_t*) (((uintptr_t) mBase) & pagemask);
    size_t adjustedLength = (mBase - pageStart) * sizeof(uint32_t) + mSize;

    if (mBase && mprotect(pageStart, adjustedLength, PROT_READ | PROT_WRITE | PROT_EXEC) != 0) {
        mspace_free(getMspace(), mBase);
        mBase = NULL;
    }
}

// ----------------------------------------------------------------------------

CodeCache::CodeCache(size_t size)
    : mCacheSize(size), mCacheInUse(0)
{
    pthread_mutex_init(&mLock, 0);
}

CodeCache::~CodeCache()
{
    pthread_mutex_destroy(&mLock);
}

sp<Assembly> CodeCache::lookup(const AssemblyKeyBase& keyBase) const
{
    pthread_mutex_lock(&mLock);
    sp<Assembly> r;
    ssize_t index = mCacheData.indexOfKey(key_t(keyBase));
    if (index >= 0) {
        const cache_entry_t& e = mCacheData.valueAt(index);
        e.when = mWhen++;
        r = e.entry;
    }
    pthread_mutex_unlock(&mLock);
    return r;
}

int CodeCache::cache(  const AssemblyKeyBase& keyBase,
                            const sp<Assembly>& assembly)
{
    pthread_mutex_lock(&mLock);

    const ssize_t assemblySize = assembly->size();
    while (mCacheInUse + assemblySize > mCacheSize) {
        // evict the LRU
        size_t lru = 0;
        size_t count = mCacheData.size();
        for (size_t i=0 ; i<count ; i++) {
            const cache_entry_t& e = mCacheData.valueAt(i);
            if (e.when < mCacheData.valueAt(lru).when) {
                lru = i;
            }
        }
        const cache_entry_t& e = mCacheData.valueAt(lru);
        mCacheInUse -= e.entry->size();
        mCacheData.removeItemsAt(lru);
    }

    ssize_t err = mCacheData.add(key_t(keyBase), cache_entry_t(assembly, mWhen));
    if (err >= 0) {
        mCacheInUse += assemblySize;
        mWhen++;
        // synchronize caches...
#if defined(__arm__)
        const long base = long(assembly->base());
        const long curr = base + long(assembly->size());
        err = cacheflush(base, curr, 0);
        LOGE_IF(err, "__ARM_NR_cacheflush error %s\n",
                strerror(errno));
#endif
    }

    pthread_mutex_unlock(&mLock);
    return err;
}

// ----------------------------------------------------------------------------

}; // namespace android


text:
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------

/*
 * Created on Sep 22, 2004
 */
package org.globus.cog.karajan.compiled.nodes;

import k.rt.ExecutionException;
import k.rt.KRunnable;
import k.thr.LWThread;

public class UnsynchronizedNode extends Sequential {

	@Override
	public void run(LWThread thr) {
		LWThread nt = thr.fork(new KRunnable() {
			@Override
			public void run(LWThread thr) {
				try {
	    			UnsynchronizedNode.super.run(thr);
	    		}
	    		catch (ExecutionException e) {
	    		}
			}
		});
		nt.start();
	}
}


text:
package org.contikios.cooja.dialogs;

import java.io.OutputStream;

public class MessageListText implements MessageList {

    public MessageListText() {
    }

    @Override
    public void addMessage(String string, int type) {
        System.out.println("Message:" + string);
    }

    @Override
    public MessageContainer[] getMessages() {
        // TODO Auto-generated method stub
        return new MessageContainer[0];
    }

    @Override
    public void clearMessages() {
        // TODO Auto-generated method stub
    }

    @Override
    public void addMessage(String string) {
        // TODO Auto-generated method stub
        addMessage(string, MessageList.NORMAL);
    }

    @Override
    public OutputStream getInputStream(int type) {
        // TODO Auto-generated method stub
        return System.out;
    }

}


text:
class Organization < ApplicationRecord
  resourcify :roles, dependent: :delete_all

  has_paper_trail

  has_many :conferences, dependent: :destroy

  after_create :create_roles

  validates :name,
            uniqueness: {
              case_sensitive: false
            },
            presence:   true

  mount_uploader :picture, PictureUploader, mount_on: :picture

  private

  def create_roles
    roles.where(name: 'organization_admin').first_or_create(description: 'For the administrators of an organization and its conferences')
  end
end


text:
using System.Threading.Tasks;
using PCLStorage;

namespace ToolbarBadgeSample.Services.Contracts
{
    public interface IDeviceService
    {
        IFolder CacheFolder { get; }
        Task<IFolder> GetCacheFolder();
        float Scale { get; }
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace OnLine.Pages.Popups.AdminPref {

    public partial class DocFormatManagement {

        /// <summary>
        /// form1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlForm form1;

        /// <summary>
        /// ScriptManager1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.ScriptManager ScriptManager1;

        /// <summary>
        /// UpdatePanel1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel UpdatePanel1;

        /// <summary>
        /// Panel_PO control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel Panel_PO;

        /// <summary>
        /// TextBox_PO_format_name control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox_PO_format_name;

        /// <summary>
        /// RequiredFieldValidator1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;

        /// <summary>
        /// TextBox_PO_TnC control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox_PO_TnC;

        /// <summary>
        /// Label_TNC_flag_PO control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label_TNC_flag_PO;

        /// <summary>
        /// Button_Update_PO control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button Button_Update_PO;

        /// <summary>
        /// Label_PO_update_stat control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label_PO_update_stat;

        /// <summary>
        /// UpdatePanel2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel UpdatePanel2;

        /// <summary>
        /// Panel_Invoice control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel Panel_Invoice;

        /// <summary>
        /// TextBox_INV_format_name control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox_INV_format_name;

        /// <summary>
        /// RequiredFieldValidator2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2;

        /// <summary>
        /// TextBox_INV_TnC control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox_INV_TnC;

        /// <summary>
        /// Label_TNC_flag_Inv control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label_TNC_flag_Inv;

        /// <summary>
        /// Panel_Inv_Tax control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel Panel_Inv_Tax;

        /// <summary>
        /// Label1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label1;

        /// <summary>
        /// TextBox_Inv_Tax_Comp_Name control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox_Inv_Tax_Comp_Name;

        /// <summary>
        /// Label2 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label2;

        /// <summary>
        /// TextBox_Inv_Tax_Comp_Value control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox_Inv_Tax_Comp_Value;

        /// <summary>
        /// Label_Inv_Tax_Comp_Ext_List control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label_Inv_Tax_Comp_Ext_List;

        /// <summary>
        /// UpdatePanel4 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel UpdatePanel4;

        /// <summary>
        /// GridView_Inv_Tax_Comp control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.GridView GridView_Inv_Tax_Comp;

        /// <summary>
        /// Button_Inv_Update control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button Button_Inv_Update;

        /// <summary>
        /// Label_Inv_Update_stat control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label_Inv_Update_stat;

        /// <summary>
        /// UpdatePanel3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.UpdatePanel UpdatePanel3;

        /// <summary>
        /// Panel_Sales_Order control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Panel Panel_Sales_Order;

        /// <summary>
        /// TextBox_SO_format_name control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox_SO_format_name;

        /// <summary>
        /// RequiredFieldValidator3 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator3;

        /// <summary>
        /// TextBox_SO_TnC control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox TextBox_SO_TnC;

        /// <summary>
        /// Label_TNC_flag_SO control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label_TNC_flag_SO;

        /// <summary>
        /// Button_SO_Update control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button Button_SO_Update;

        /// <summary>
        /// Label_SO_update_stat control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label Label_SO_update_stat;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Modelisator.Forms.View
{
    /// <summary>
    /// Logique d'interaction pour MenuTop_CouleursForm_View.xaml
    /// </summary>
    public partial class MenuTop_CouleursForm_View : UserControl
    {
        public MenuTop_CouleursForm_View()
        {
            InitializeComponent();
        }

        public ComboBox cmdBoxCouleurs
        {
            get { return m_cmdBoxCouleurs; }
            set { m_cmdBoxCouleurs = value; }
        }

        public Button btn_Import
        {
            get { return m_btn_Import; }
            set { m_btn_Import = value; }
        }

        public Button btn_Export
        {
            get { return m_btn_Export; }
            set { m_btn_Export = value; }
        }
        public Button btn_VueEnsemble
        {
            get { return m_btn_VueEnsemble; }
            set { m_btn_VueEnsemble = value; }
        }

    }
}


text:
<!doctype html>

    <title>Training Stories</title>

    <link href="css/jspsych-mobile.css" rel="stylesheet" type="text/css"></link>
    <link href="css/experiment.css" rel="stylesheet" type="text/css"></link>

    <meta name="viewport" content="width=device-width, initial-scale=1">


text:
{% comment %}
###############################################################################
# Browser Base
#
# Note: Override this base template to integrate rest of templates to site
# look and feel.
###############################################################################
{% endcomment %}

  <title>{% block title %}{% endblock %}</title>
{% block cloud_browser_template_head %}{% endblock %}
{% block extra_head %}{% endblock %}

{% block body %}
  {% block menu %}{% endblock %}

    {% block cloud_browser_breadcrumbs %}{% endblock %}

    {% block cloud_browser_content %}{% endblock %}

{% endblock %}


text:
/* eslint-disable react/prop-types */
import React from 'react';
import { Image, View, Text } from 'react-sketchapp';
import { css, withStyles } from '../withStyles';

const Profile = ({ user, styles }) => (
  <View {...css(styles.container)}>
    <Image source={user.profile_image_url} {...css(styles.avatar)} />
    <View {...css(styles.titleWrapper)}>
      <Text {...css(styles.title)}>{user.name}</Text>
      <Text {...css(styles.subtitle)}>{`@${user.screen_name}`}</Text>
    </View>
    <Text {...css(styles.body)}>{user.description}</Text>
    <Text {...css(styles.body)}>{user.location}</Text>
    <Text {...css(styles.body)}>{user.url}</Text>
  </View>
);

export default withStyles(({ colors, fonts, spacing }) => ({
  container: {
    backgroundColor: colors.Haus,
    padding: spacing,
    width: 260,
    marginRight: spacing,
  },
  avatar: {
    height: 220,
    resizeMode: 'contain',
    marginBottom: spacing * 2,
    borderRadius: 10,
  },
  titleWrapper: {
    marginBottom: spacing,
  },
  title: { ...fonts['Title 2'] },
  subtitle: { ...fonts['Title 3'] },
  body: { ...fonts.Body },
}))(Profile);


text:
% ChirpAlert.m
% Authors: Suzie, James, Thadd, Mary, Sooyan
% Date: 28 Jan 17
% Description: TODO

% ChirpAlert()
% Inputs:
% Outputs:
% Description
function [] = chirpAlert()
% Clear variables
  clear all
  clearvars -global
% Setup Global
  setupGlobalVars();
% Setup Audio
  setupAudio();
% Setup ML stuff

% Buffer update

% Apply filter

% Detection

% Interpret results

% Produce outputs to user
end

% setupGlobalvars()
% Inputs: None
% Outputs: None
% Description: This function setups up the various global variables that will
% be used throught the program
function [] = setupGlobalVars()
  setGlobalParams();
  % Create a buffer for the audio
  global BUFFER_SIZE;
  audioBuffer = zeros(1,BUFFER_SIZE);
  % Counter for number of chirps
  global numChirps;
  numChirps = 0;
  % Counter for number of abnormalities
  global numAbnormal;
  numAbnormal = 0;
end

% setupGlobalparams()
% Inputs: None
% Outputs: None
% Description: Used to set parameters for the rest of the program
function [] = setGlobalParams()
  % Amount of time present in the bufer
  global BUFFER_TIME;
  BUFFER_TIME = 1; % Guess value, need to change
  % The audio sampling rate
  global SAMPLE_RATE;
  SAMPLE_RATE = 44100; % 44.1 kHz since that is standard sampling rate
  % How many data points are in our buffer (floored for integer number)
  global BUFFER_SIZE;
  BUFFER_SIZE = floor(SAMPLE_RATE / BUFFER_TIME);
  % Filename to get audio from
  global FILE_NAME;
  FILE_NAME = 'anthem.wav';
  % Lowest frequency of bandpass filter
  global FILTER_LOW;
  FILTER_LOW = 1000; % Lowest possible freq by bird
  % Highest frequency of bandpass filter
  global FILTER_HIGH;
  FILTER_HIGH = 8000; % Highest possible freq by bird
end

% setupAudio()
% Inputs:
% Outputs:
% Description: Initializes how we keep track of our place in the audio file
function [] = setupAudio()
  % The number of samples we have taken, used to iterate through the .WAV file
  global numSampled
  numSampled = 1;
end

% setupFilter()
% Inputs:
% Outputs:
% Description
function [] = setupFilter()
  % Initialize the buffer
  global bandpassFilter = zeros(1, BUFFER_SIZE);
  % Fill out bandpass filter
end

% setupML()
% Inputs:
% Outputs:
% Description
function [] = setupML()

end

% updateBuffer()
% Inputs: None
% Outputs: None
% Description: Shifts the contents of the buffer and then adds in the next
% sample to the front of the buffer
function [] = updateBuffer()
  % global variables to use
  global FILE_NAME;
  global numSampled;
  global BUFFER_SIZE;
  global audioBuffer;
  % Get the next sample
  [sample, fs] = audioread(FILE_NAME, [numSampled, numSampled]);
  % shift all previous samples
  audioBuffer(2 : BUFFER_SIZE);
  audioBuffer(1 : BUFFER_SIZE - 1);
  % add in new value
  audiobuffer(1:2,1) = sample;
  % increment our place in the audio file
  numSampled = numSampled + 1;
end

% applyFilter()
% Inputs:
% Outputs:
% Description
function [] = applyFilter()

end

% detection()
% Inputs:
% Outputs:
% Description:
function [] = detection()

end

% interpretresults()
% Inputs:
% Outputs:
% Description:
function [] = interpretResults()

end

% outputUserresults()
% Inputs:
% Outputs:
% Description:
function [] = outputUserResults()

end


text:
package net.vrallev.android.ecc;

import com.github.dazoe.android.Ed25519;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import djb.Curve25519;

/**
 * @author Ralf Wondratschek
 */
@SuppressWarnings("UnusedDeclaration")
public class Ecc25519Helper {

    protected static final MessageDigest MESSAGE_DIGEST_SHA_256;

    static {
        try {
            MESSAGE_DIGEST_SHA_256 = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            // ignore, won't happen
            throw new IllegalStateException(e);
        }
    }

    private final KeyHolder mKeyHolder;

    public Ecc25519Helper() {
        this((KeyHolder) null);
    }

    public Ecc25519Helper(byte[] privateKey) {
        this(new KeyHolder(privateKey));
    }

    public Ecc25519Helper(KeyHolder keyHolder) {
        mKeyHolder = keyHolder;
    }

    /*
     * Diffie Hellman
     */

    public byte[] diffieHellman() {
        return diffieHellman(mKeyHolder.getPrivateKey(), mKeyHolder.getPublicKeyDiffieHellman());
    }

    public byte[] diffieHellman(byte[] privateKey, byte[] publicKey) {
        byte[] sharedSecret = new byte[32];
        Curve25519.curve(sharedSecret, privateKey, publicKey);

        // see documentation of curve function above
        MESSAGE_DIGEST_SHA_256.reset();
        return MESSAGE_DIGEST_SHA_256.digest(sharedSecret);
    }

    /*
     * Signature
     */

    public byte[] sign(byte[] message) {
        return signWithoutClamp(message, mKeyHolder.getPrivateKey());
    }

    public byte[] sign(byte[] message, byte[] privateKey) {
        privateKey = Arrays.copyOf(privateKey, privateKey.length);
        Curve25519.clamp(privateKey);
        return signWithoutClamp(message, privateKey);
    }

    protected byte[] signWithoutClamp(byte[] message, byte[] privateKey) {
        try {
            return Ed25519.Sign(message, privateKey);

        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    /*
     * Signature verification
     */

    public boolean isValidSignature(byte[] message, byte[] signature) {
        return isValidSignature(message, signature, mKeyHolder.getPublicKeySignature());
    }

    public boolean isValidSignature(byte[] message, byte[] signature, byte[] publicKey) {
        try {
            return 0 == Ed25519.Verify(message, signature, publicKey);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

    /*
     * Getter
     */

    public KeyHolder getKeyHolder() {
        return mKeyHolder;
    }
}


text:
namespace Google.Analytics.Admin.V1Alpha.Snippets
{
    // [START analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_async]
    using Google.Analytics.Admin.V1Alpha;
    using System.Threading.Tasks;

    public sealed partial class GeneratedAnalyticsAdminServiceClientSnippets
    {
        /// <summary>Snippet for DeleteMeasurementProtocolSecretAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public async Task DeleteMeasurementProtocolSecretRequestObjectAsync()
        {
            // Create client
            AnalyticsAdminServiceClient analyticsAdminServiceClient = await AnalyticsAdminServiceClient.CreateAsync();
            // Initialize request argument(s)
            DeleteMeasurementProtocolSecretRequest request = new DeleteMeasurementProtocolSecretRequest
            {
                MeasurementProtocolSecretName = MeasurementProtocolSecretName.FromPropertyDataStreamMeasurementProtocolSecret("[PROPERTY]", "[DATA_STREAM]", "[MEASUREMENT_PROTOCOL_SECRET]"),
            };
            // Make the request
            await analyticsAdminServiceClient.DeleteMeasurementProtocolSecretAsync(request);
        }
    }
    // [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_DeleteMeasurementProtocolSecret_async]
}


text:
import fileinput
import shutil
import subprocess
import os
import uuid

#build_ref=str(uuid.uuid4)
#os.mkdir(build_ref)
#os.chdir(build_ref)

c_names=[]

def build():
    global all
    ### duplicate function file
    shutil.copy2( f_name, f_build )

    #apply changes
    for line in fileinput.input( f_build, inplace=True ):
        print line.replace(C_placeholder, C),

    for line in fileinput.input( f_build, inplace=True ):
        print line.replace(Q_placeholder, Q),

    for line in fileinput.input( f_build, inplace=True ):
        print line.replace(R_placeholder, R),

    for line in fileinput.input( f_build, inplace=True ):
        print line.replace(r_placeholder, r),

    for line in fileinput.input( f_build, inplace=True ):
        print line.replace(img_d_placeholder, img_d),

    for line in fileinput.input( f_build, inplace=True ):
        print line.replace(D_placeholder, D),
    #ADD MORE

    ### duplicate mpi file
    shutil.copy2( mpi_name, mpi_build )

    #apply changes
    for line in fileinput.input( mpi_build, inplace=True ):
        print line.replace(mpi_f_placeholder, f_build),

    #compile new mpic++
    local_odeint="/home/alberto.anzellotti/odeint/odeint-v2-master/include"
    p = subprocess.Popen('mpic++ '+mpi_build+" -o "+mpi_c+" -std=c++11 -I "+local_odeint, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for line in p.stdout.readlines():
        print line

    #see exceptions
    retval = p.wait()
    print retval

##### GENERAL VALUES

f_name="doTheMath.cpp" #name of the virgin function script
mpi_name="MPIbasejump.cpp" #name of the virgin mpi launcher file

C_placeholder="@C@"
Q_placeholder="@Q@"
R_placeholder="@R@"
r_placeholder="@r@"
img_d_placeholder="@img_d@"
D_placeholder="@D@"

mpi_f_placeholder="@function@"

##### Build 1 :: ...description...
f_build="f1.cpp"
mpi_build="mpi1.cpp"

mpi_c="mpi1.o"
c_names.append(mpi_c)

R="0.01"
r="30"
C="0.01"
Q="30"
img_d="1.0"
D="40"

build()

##### Build 2 ...

##### WRITE OUT BASH LAUNCHER
NODES=4
PPN=2

launcher = open("launcher.sh" , "w+")
launcher.close()
launcher = open("launcher.sh" , "a")
launcher.write("""
#!/bin/sh \n
#PBS -V \n
#PBS -N mag_pendulum_job \n
#PBS -l nodes="""+str(NODES)+""":ppn="""+str(PPN)+""" \n
#PBS -l alberto.anzellotti=10:00:00 \n
#PBS -m bea \n
#PBS -M alberto.anzellotti@science.unitn.it \n
cd $PBS_O_WORKDIR \n
""")
for step in c_names:
	launcher.write("/usr/local/bin/mpirun -np "+str(NODES*PPN)+" /home/alberto.anzellotti/"+step+"\n")
	launcher.write("python collector.py \n")

launcher.close()


text:
import unittest
from unittest.mock import patch
from tempfile import TemporaryDirectory
from time import time

from isurlshortenercache.unshorten_cache import UnshortenCache

def simple_unshorten(url):
    return url

def simple_now():
    return 100

class TestUnshortenCache(unittest.TestCase):
    def setUp(self):
        self.tempfolder = TemporaryDirectory()
        database_path = '{}/{}'.format(self.tempfolder.name, 'test.sqlite3')
        self.unshorten_cache = UnshortenCache(database_path)

    def tearDown(self):
        self.tempfolder.cleanup()

    @patch('isurlshortener.unshortener.Unshortener.unshorten_url', side_effect=simple_unshorten)
    @patch('isurlshortenercache.unshorten_cache.UnshortenCache._now', side_effect=simple_now)
    def test_valid_already_unshortened_url(self, mock_shorten_url, mock_now):
        samples = {'https://www.google.com/abc': {'requested_url': 'https://www.google.com/abc',
                                                  'unshortened_url': [(simple_unshorten('https://www.google.com/abc'),
                                                                       simple_now())]}}

        for sample, expected in samples.items():
            self.assertEqual(expected, self.unshorten_cache.unshorten(sample))

    @patch('isurlshortener.unshortener.Unshortener.unshorten_url', side_effect=simple_unshorten)
    @patch('isurlshortenercache.unshorten_cache.UnshortenCache._now', side_effect=[100, 101])
    def test_simple_caching_url(self, mock_shorten_url, mock_now):
        samples = {'https://www.google.com/abc': {'requested_url': 'https://www.google.com/abc',
                                                  'unshortened_url': [(simple_unshorten('https://www.google.com/abc'),
                                                                       100),
                                                                      (simple_unshorten('https://www.google.com/abc'),
                                                                       101)]}}

        for sample, expected in samples.items():
            self.unshorten_cache.unshorten(sample)
            self.assertDictEqual(expected, self.unshorten_cache.unshorten(sample))

    @patch('isurlshortener.unshortener.Unshortener.unshorten_url', side_effect=simple_unshorten)
    @patch('isurlshortenercache.unshorten_cache.UnshortenCache._now', side_effect=[100])
    def test_simple_caching_url_without_rerequest(self, mock_shorten_url, mock_now):
        samples = {'https://www.google.com/abc': {'requested_url': 'https://www.google.com/abc',
                                                  'unshortened_url': [(simple_unshorten('https://www.google.com/abc'),
                                                                       100)]}}

        for sample, expected in samples.items():
            self.unshorten_cache.unshorten(sample, False)
            self.assertDictEqual(expected, self.unshorten_cache.unshorten(sample, False))

    def test_request_url_from_empty_cache(self):
        url = 'https://www.google.com/abc'
        expected = {'requested_url': 'https://www.google.com/abc', 'unshortened_url': []}
        self.assertDictEqual(expected, self.unshorten_cache.query_cache(url))

    @patch('isurlshortener.unshortener.Unshortener.unshorten_url', side_effect=simple_unshorten)
    @patch('isurlshortenercache.unshorten_cache.UnshortenCache._now', side_effect=[100])
    def test_simple_caching_url_without_rerequest(self, mock_shorten_url, mock_now):
        samples = {'https://www.google.com/abc': {'requested_url': 'https://www.google.com/abc',
                                                  'unshortened_url': [(simple_unshorten('https://www.google.com/abc'),
                                                                       100)]}}

        for sample, expected in samples.items():
            self.unshorten_cache.unshorten(sample, False)
            self.assertDictEqual(expected, self.unshorten_cache.query_cache(sample))

    @patch('isurlshortener.unshortener.Unshortener.unshorten_url', side_effect=simple_unshorten)
    @patch('isurlshortenercache.unshorten_cache.UnshortenCache._now', side_effect=[100])
    def test_delete_url(self, mock_shorten_url, mock_now):
        sample = 'https://www.google.com/abc'

        self.unshorten_cache.unshorten(sample)
        from_cache = self.unshorten_cache.query_cache(sample)
        self.assertEqual(1, len(from_cache['unshortened_url']))

        self.unshorten_cache.delete_from_cache(sample)
        from_cache = self.unshorten_cache.query_cache(sample)
        self.assertEqual(0, len(from_cache['unshortened_url']))

    def test_dump_empty_database(self):
        expected = []
        self.assertEqual(expected, self.unshorten_cache.dump())

    @patch('isurlshortener.unshortener.Unshortener.unshorten_url', side_effect=simple_unshorten)
    @patch('isurlshortenercache.unshorten_cache.UnshortenCache._now', side_effect=[100])
    def test_dump_non_database(self, mock_shorten_url, mock_now):
        url = 'https://www.google.com/abc'
        expected = [{'requested_url': url, 'unshortened_url': [(url, 100)]}]
        self.unshorten_cache.unshorten(url)

        self.assertEqual(expected, self.unshorten_cache.dump())

    def test_check_now_helper(self):
        now = int(time())
        self.assertTrue(now <= UnshortenCache._now() <= now + 1)

    def test_protocol_exception(self):
        unshorten_result = self.unshorten_cache.unshorten('ftp://ftp.kernel.org/abc/')
        self.assertIn('error', unshorten_result)
        self.assertEqual('Protocol exception', unshorten_result['error'])


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.gam3r.partyrocker" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".spotifyAuth"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name=".demo"
            android:label="@string/app_name"
            android:noHistory="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.spotify.sdk.android.authentication.LoginActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <activity
            android:name=".ChangePreference"
            android:label="@string/title_activity_change_preference" >
        </activity>
    </application>

</manifest>


text:
if(!Signavio){ var Signavio = {} };
if (!Signavio.Core) { Signavio.Core = {} };
Signavio.Core.Version = "${webui-version}";

Signavio.Config.EXPLORER_PATH           = '/${webui-webapp-context}/explorer';
Signavio.Config.EDITOR_PATH                     = '/${webui-webapp-context}/editor';
Signavio.Config.BACKEND_PATH            = '/${webui-webapp-context}/p';
Signavio.Config.LIBS_PATH                       = '/${webui-webapp-context}/libs';

Signavio.Config.DIAGRAMS_IMAGE_PATH = Signavio.Config.EXPLORER_PATH + "/src/img"
Signavio.Config.STENCILSET_EXTENSION_PATH = Signavio.Config.EDITOR_PATH + "/stencilsets/extensions/";
Signavio.Config.PATH                            = Signavio.Config.EXPLORER_PATH + '/src/javascript';
Signavio.Config.PLUGIN_PATH             = Signavio.Config.EXPLORER_PATH + '/src/javascript/plugins';
Signavio.Config.EDITOR_HANDLER_URI      = Signavio.Config.BACKEND_PATH + "/editor";
Signavio.Config.STENCILSET_URI          = Signavio.Config.BACKEND_PATH + "/editor_stencilset";
Signavio.Config.PLUGIN_CONFIG           = Signavio.Config.BACKEND_PATH + "/explorer_plugins";
Signavio.Config.USE_CACHE                       = false;
Signavio.Config.REMOVE_ON_DELETE        = true;
Signavio.Config.HIDE_NOTIFICATION       = true;


text:
namespace Studio {
    public interface IShell {}
}


text:
/*
 *This program simulates the movement of inert particles using Lennard-Jones potential.
 *Force is calculated from the potential.  Position and velocity are updated using the Verlet
 * Algorithm (with Euler algorithm initialization).
 */

#include <cmath>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include "KernelSourceReader.h"
#ifdef __APPLE__
#include <OpenCL/cl.h>
#else
#include <CL/cl.h>
#endif

using namespace std;

/*const char *saxpy_kernel =
"__kernel \n"
"void saxpy_kernel(float alpha, \n"
" __global float *A, \n"
" __global float *B, \n"
" __global float *C \n"
")"
"{ \n"
" //Get the index of the work-item \n"
" int index = get_global_id(0); \n"
" C[index] = alpha* A[index] + B[index]; \n"
"} \n";*/

//IF YOU'RE GOING TO USE DYNAMIC BOUNDARIES YOU MUST USE A float INSTEAD OF AN INT

//Calculates force on each particle based on the present position of all particles
//Cutoff distance of 4.5 units.
void calcForceMatrices(int totalParticles, float* xForce,
	float* yForce, float* positionX, float* positionY,
	int particlesType1, float* potentialEnergyArray, int upperBoundary,
	int rightBoundary, cl_mem& positionXBuffer, cl_mem& positionYBuffer,
	cl_mem& forceBufferX, cl_mem& forceBufferY, cl_mem& potentialEnergyBuffer,
	cl_command_queue& command_queue, cl_kernel& forceKernel);

//Helper method for determining force based on the type (masses) of
//the particles interacting
//char particleComboType(int particlesType1, int i, int j);

//Recalculates the acceleration of each particle based on the force
//currently applied to it.
void recalcAcceleration(float* accelerationX, float* accelerationY,
		float* xForce, float* yForce, int totalParticles,
		int numParticlesType1);

//Determines shortest X distance between particles (since we're using
//periodic boundary condition)
float determineXVector(float positionX1, float positionX2,
	int rightBoundary);

//Determines shortest Y distance between particles (since we're using
//periodic boundary condition)
float determineYVector(float positionY1, float positionY2,
		int upperBoundary);

//Function that performs the Euler algorithm on all particles in the set
void performEulerOperation(int totalParticles, float* xForce,
	float* yForce, float* positionX, float* positionY,
	int particlesType1, float* potentialEnergyArray, float& kineticEnergy,
	int upperBoundary, int rightBoundary, float* oldPositionX,
	float* oldPositionY, float* accelerationX, float* accelerationY,
	float* velocityX, float* velocityY, float currentTime,
	float timestep, ofstream& positionFile, cl_mem& positionBuffer, cl_mem& velocityBuffer,
	cl_mem& accelerationBuffer, cl_mem& futurePositionBuffer, cl_mem& positionXBuffer, cl_mem& positionYBuffer,
	cl_mem& forceBufferX, cl_mem& forceBufferY, cl_mem& potentialEnergyBuffer, cl_command_queue& command_queue, cl_kernel& eulerKernel, cl_kernel& forceKernel);

//Function that performs the Verlet algorithm on all particles in the set
void performVerletOperation(int totalParticles, float* xForce,
	float* yForce, float* positionX, float* positionY,
	int particlesType1, float* potentialEnergyArray, float& kineticEnergy,
	int upperBoundary, int rightBoundary, float* oldPositionX,
	float* oldPositionY, float* accelerationX, float* accelerationY,
	float* velocityX, float* velocityY, float currentTime,
	float timestep, ofstream& positionFile, cl_mem& positionBuffer, cl_mem& oldPositionBuffer,
	cl_mem& velocityBuffer, cl_mem& accelerationBuffer, cl_mem& displacementBuffer,
	cl_mem& futurePositionBuffer, cl_mem& positionXBuffer, cl_mem& positionYBuffer,
	cl_mem& forceBufferX, cl_mem& forceBufferY, cl_mem& potentialEnergyBuffer, cl_command_queue& command_queue, cl_kernel& eulerKernel, cl_kernel& forceKernel);

//Translates particles that have exited the simulation area back into the
//Simulation region
void applyPeriodicBoundary(float &positionX, float &positionY,
		float &oldPositionX, float &oldPositionY, int rightBoundary,
		int upperBoundary);

void createHistogram(float binSize, int totalParticles, int particlesType1,
		float* positionX, float* positionY, int upperBoundary,
		int rightBoundary);

//The main function to execute the simulation
int main()
{
	/*CONSTANTS FOR REFERENCE THESE ARE HARDCODED*/
//constants 0.5(sigma1 + sigma2)
//float sigma1to1 = 1; //in units of sigma
//float sigma2to2 = 1.4; //in units of sigma
//float sigma1to2 = 1.2; // in units of sigma
//float epsilon = 1;// in units of epsilon
//float massParticle1 = 1; //in units of massParticle1
//float massParticle2 = 2; //in units of massParticle1

//Create data files
	ofstream positionFile;
	ofstream energyFile;
	positionFile.open("position.txt");
	energyFile.open("energy.txt");

	float timestep = 0.001f; //Can be arbitrarily small
	float maxTime = 0.5f; //Can be arbitrarily long or short
	float binSize = 0.1f;

	int numParticlesType1 = 512;
	int numParticlesType2 = 512;
	int totalParticles = numParticlesType1 + numParticlesType2;

	float potentialEnergy;
	float kineticEnergy;

//THIS MUST BE MODIFIED IF YOU USE MORE PARTICLES
	int rightBoundary = 40;
	int upperBoundary = 40;

//Particle information arrays
	float *potentialEnergyArray = new float[totalParticles];
	float *positionX = new float[totalParticles];
	float *positionY = new float[totalParticles];
	float *velocityX = new float[totalParticles];
	float *velocityY = new float[totalParticles];
	float *accelerationX = new float[totalParticles];
	float *accelerationY = new float[totalParticles];
	float *oldPositionX = new float[totalParticles];
	float *oldPositionY = new float[totalParticles];
	float *xForce = new float[totalParticles*totalParticles];
	float *yForce = new float[totalParticles*totalParticles];

	/*<<<<<<<<<<<<<<<<<<<BEGIN OPENCL STUFF>>>>>>>>>>>>>>>>>*/

	// Get platform and device information
	cl_platform_id* platforms = NULL;
	cl_uint num_platforms;

	//Set up the Platform
	cl_int clStatus = clGetPlatformIDs(0, NULL, &num_platforms);
	platforms = (cl_platform_id *)
	malloc(sizeof(cl_platform_id)*num_platforms);
	clStatus = clGetPlatformIDs(num_platforms, platforms, NULL);

	//Get the devices list and choose the device you want to run on
	cl_device_id *device_list = NULL;
	cl_uint num_devices;
	clStatus = clGetDeviceIDs(platforms[0], CL_DEVICE_TYPE_GPU, 0,
		NULL, &num_devices);
	device_list = (cl_device_id *)
	malloc(sizeof(cl_device_id)*num_devices);
	clStatus = clGetDeviceIDs(platforms[0],
	CL_DEVICE_TYPE_GPU, num_devices, device_list, NULL);

	// Create one OpenCL context for each device in the platform
	cl_context context;
	context = clCreateContext(NULL, num_devices, device_list,
		NULL, NULL, &clStatus);

	// Create a command queue
	cl_command_queue command_queue = clCreateCommandQueue(
		context, device_list[0], 0, &clStatus);

	//Create program from source
	cl_program programEuler = createProgram(context, device_list[0], "Euler.cl");
	cl_program programVerlet = createProgram(context, device_list[0], "Verlet.cl");
	cl_program programForce = createProgram(context, device_list[0], "ForceMatrix.cl");

	//Create the OpenCL kernel
	cl_kernel eulerKernel = clCreateKernel(programEuler, "euler_kernel", &clStatus);
	cl_kernel verletKernel = clCreateKernel(programVerlet, "verlet_kernel", &clStatus);
	cl_kernel forceKernel = clCreateKernel(programForce, "calc_force", &clStatus);

	//Create memory buffers on the device for each array
	cl_mem positionBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem velocityBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem accelerationBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem oldPositionBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem displacementBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem futurePositionBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem potentialEnergyBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem positionXBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem positionYBuffer = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem forceBufferX = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);
	cl_mem forceBufferY = clCreateBuffer(context, CL_MEM_READ_WRITE, sizeof(float)*totalParticles, NULL, &clStatus);

	/*<<<<<<<<<<<<<<<<<<<END OPENCL STUFF>>>>>>>>>>>>>>>>>>>>>>>>>*/

//Initialize to small initial velocity
//Increase velocity by constant factor until reach target temperature.

//THIS MUST BE MODIFIED IF YOU USE MORE PARTICLES
	int part = 0;
	for (int i = 0; i < 32; i++)
	{
		for (int j = 0; j < 32; j++)
		{
			positionX[part] = (float)i;
			positionY[part] = (float)j;

			if (part < totalParticles / 4)
			{
				velocityX[part] = 0.01f;
				velocityY[part] = 0;
			}
			else if (part < totalParticles / 2)
			{
				velocityX[part] = -0.01f;
				velocityY[part] = 0;
			}
			else if (part < (totalParticles / 2 + totalParticles / 4))
			{
				velocityX[part] = 0;
				velocityY[part] = 0.01f;
			}
			else
			{
				velocityX[part] = 0;
				velocityY[part] = -0.01f;
			}
			part++;
		}
	}

	//Randomizing initial velocity direction
	srand((unsigned) time(NULL));
	float holderX;
	float holderY;
	int locationY;
	int locationX;
	for (int i = 0; i < totalParticles; i++)
	{
		//Select two random particles in array
		locationX = rand() % totalParticles;
		locationY = rand() % totalParticles;
		//Swap velocity
		holderX = velocityX[i];
		holderY = velocityY[i];
		velocityX[i] = velocityX[locationX];
		velocityY[i] = velocityY[locationY];
		velocityX[locationX] = holderX;
		velocityY[locationY] = holderY;

		//Select single random particle in array
		locationX = rand() % totalParticles;
		//Swap position
		holderX = positionX[i];
		holderY = positionY[i];
		positionX[i] = positionX[locationX];
		positionY[i] = positionY[locationX];
		positionX[locationX] = holderX;
		positionY[locationX] = holderY;
	}

//Setting up force matrices
	/*float **forceBetweenX;
	float **forceBetweenY;
	forceBetweenX = new float*[totalParticles];
	forceBetweenY = new float*[totalParticles];
	for (int i = 0; i < totalParticles; i++)
	{
		forceBetweenX[i] = new float[i + 1];
		forceBetweenY[i] = new float[i + 1];
	}*/

//Start of simulation - setting initial time to zero
	float currentTime = 0;

//Perform initial Euler operation to set things in motion
	positionFile << "* " << currentTime << endl;

	performEulerOperation(totalParticles, xForce,
		yForce, positionX, positionY,
		numParticlesType1, potentialEnergyArray, kineticEnergy,
		upperBoundary, rightBoundary, oldPositionX,
		oldPositionY, accelerationX, accelerationY,
		velocityX, velocityY, currentTime,
		timestep, positionFile, positionBuffer, velocityBuffer,
		accelerationBuffer, futurePositionBuffer, positionXBuffer, positionYBuffer,
		forceBufferX, forceBufferY, potentialEnergyBuffer, command_queue,
		eulerKernel, forceKernel);

	//performsaxby(timestep, positionX, velocityX, accelerationX, command_queue, kernel, positionBuffer, velocityBuffer, accelerationBuffer);

	potentialEnergy = 0;
	for (int i = 0; i < totalParticles; i++)
	{
		potentialEnergy += potentialEnergyArray[i];
	}

	energyFile << currentTime << " " << kineticEnergy + potentialEnergy << " "
			<< kineticEnergy << " " << potentialEnergy << endl;

	//Main loop - performing Verlet operations for the remainder of the simulation
	for (currentTime = timestep; currentTime < maxTime; currentTime += timestep)
	{
		positionFile << "* " << currentTime << endl;
		performVerletOperation(totalParticles, xForce,
			yForce, positionX, positionY,
			numParticlesType1, potentialEnergyArray, kineticEnergy,
			upperBoundary, rightBoundary, oldPositionX,
			oldPositionY, accelerationX, accelerationY,
			velocityX, velocityY, currentTime,
			timestep, positionFile, positionBuffer, oldPositionBuffer,
			velocityBuffer, accelerationBuffer, displacementBuffer,
			futurePositionBuffer, positionXBuffer, positionYBuffer,
			forceBufferX, forceBufferY, potentialEnergyBuffer,
			command_queue, verletKernel, forceKernel);

		potentialEnergy = 0;
		for (int i = 0; i < totalParticles; i++)
		{
			potentialEnergy += potentialEnergyArray[i];
		}

		energyFile << currentTime << " " << kineticEnergy + potentialEnergy
				<< " " << kineticEnergy << " " << potentialEnergy << endl;
	}

	createHistogram(binSize, totalParticles, numParticlesType1, positionX,
			positionY, upperBoundary, rightBoundary);

	//Deleting arrays
	delete positionX;
	delete positionY;
	delete velocityX;
	delete velocityY;
	delete accelerationX;
	delete accelerationY;
	delete oldPositionX;
	delete oldPositionY;
	delete xForce;
	delete yForce;
	delete potentialEnergyArray;
	/*for (int i = 0; i < totalParticles; i++)
	{
		delete[] forceBetweenY[i];
		delete[] forceBetweenX[i];
	}
	delete[] forceBetweenY;
	delete[] forceBetweenX;*/

	clStatus = clReleaseKernel(eulerKernel);
	clStatus = clReleaseProgram(programEuler);
	clStatus = clReleaseKernel(verletKernel);
	clStatus = clReleaseProgram(programVerlet);
	clStatus = clReleaseKernel(forceKernel);
	clStatus = clReleaseProgram(programForce);
	clStatus = clReleaseMemObject(positionBuffer);
	clStatus = clReleaseMemObject(oldPositionBuffer);
	clStatus = clReleaseMemObject(velocityBuffer);
	clStatus = clReleaseMemObject(accelerationBuffer);
	clStatus = clReleaseMemObject(displacementBuffer);
	clStatus = clReleaseMemObject(futurePositionBuffer);
	clStatus = clReleaseCommandQueue(command_queue);
	clStatus = clReleaseContext(context);
	free(platforms);
	free(device_list);

	positionFile.close();
	energyFile.close();
}
//End of main function

void calcForceMatrices(int totalParticles, float* xForce,
		float* yForce, float* positionX, float* positionY,
		int particlesType1, float* potentialEnergyArray, int upperBoundary,
		int rightBoundary, cl_mem& positionXBuffer, cl_mem& positionYBuffer,
		cl_mem& forceBufferX, cl_mem& forceBufferY, cl_mem& potentialEnergyBuffer,
		cl_command_queue& command_queue, cl_kernel& forceKernel)
{

	//Enqueue data
	clEnqueueWriteBuffer(command_queue, positionXBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionX, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, positionYBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionY, 0, NULL, NULL);

	//Set arguments for kernel
	clSetKernelArg(forceKernel, 0, sizeof(cl_mem), (void *)&positionXBuffer);
	clSetKernelArg(forceKernel, 1, sizeof(cl_mem), (void *)&positionYBuffer);
	clSetKernelArg(forceKernel, 2, sizeof(cl_mem), (void *)&xForce);
	clSetKernelArg(forceKernel, 3, sizeof(cl_mem), (void *)&yForce);
	clSetKernelArg(forceKernel, 4, sizeof(cl_mem), (void *)&potentialEnergyBuffer);
	clSetKernelArg(forceKernel, 5, sizeof(int), (void *)&rightBoundary);
	clSetKernelArg(forceKernel, 6, sizeof(int), (void *)&upperBoundary);
	clSetKernelArg(forceKernel, 7, sizeof(int), (void *)&totalParticles);
	clSetKernelArg(forceKernel, 8, sizeof(int), (void *)&particlesType1);

	size_t global_size = totalParticles;
	size_t local_size = 64;
	clEnqueueNDRangeKernel(command_queue, forceKernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL);

	//Read data back
	clEnqueueReadBuffer(command_queue, potentialEnergyBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, potentialEnergyArray, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, forceBufferX, CL_TRUE, 0, sizeof(float)*totalParticles, xForce, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, forceBufferY, CL_TRUE, 0, sizeof(float)*totalParticles, yForce, 0, NULL, NULL);

	clFlush(command_queue);
	clFinish(command_queue);

	/*float xvector;
	float yvector;
	potentialEnergy = 0;
	float pythagorean;
	for (int i = 0; i < totalParticles; i++)
	{
		for (int j = 0; j < i; j++)
		{
			xvector = determineXVector(positionX[i], positionX[j],
					rightBoundary);
			yvector = determineYVector(positionY[i], positionY[j],
					upperBoundary);
			pythagorean = ((yvector * yvector) + (xvector * xvector));

			if (sqrt(pythagorean) > 4.5)
			{
				forceBetweenX[i][j] = 0;
				forceBetweenY[i][j] = 0;
			}
			else
			{
				char pType = particleComboType(particlesType1, i, j);

				float sigma;
				if (pType == 1)
				{
					sigma = 1;
				}
				else if (pType == 2)
				{
					sigma = 1.4f;
				}
				else
				{
					sigma = 1.2f;
				}

				forceBetweenX[i][j] = ((24 * xvector * pow(sigma, 6))
					/ (pow(pythagorean, 4)))
					* ((2 * pow(sigma, 6) / (pow(pythagorean, 3))) - 1);
				forceBetweenY[i][j] = ((24 * yvector * pow(sigma, 6))
					/ (pow(pythagorean, 4)))
					* ((2 * pow(sigma, 6) / (pow(pythagorean, 3))) - 1);
				potentialEnergy += 4
					* (pow(((sigma * sigma) / pythagorean), 6)
					- pow(((sigma * sigma) / pythagorean), 3));
			}
		}
	}*/
}

/*char particleComboType(int particlesType1, int i, int j)
{
	if (i < particlesType1 && j < particlesType1)
	{
		return 1;
	}
	else if (i >= particlesType1 && j >= particlesType1)
	{
		return 2;
	}
	else
	{
		return 12;
	}
}*/

void recalcAcceleration(float* accelerationX, float* accelerationY,
		float* xForce, float* yForce, int totalParticles,
		int numParticlesType1)
{
	float sumForceX;
	float sumForceY;
	int location;
	for (int i = 0; i < totalParticles; i++)
	{
		sumForceX = 0;
		sumForceY = 0;
		for (int j = 0; j < totalParticles; j++)
		{
			if (i != j)
			{
				location = i*totalParticles + j;
				sumForceX += xForce[location];
				sumForceY += yForce[location];
			}
			/*if (j > i)
			{
				sumForceX += -1 * xForce[j][i];
				sumForceY += -1 * yForce[j][i];
			}
			else if (j < i)
			{
				sumForceX += xForce[i][j];
				sumForceY += yForce[i][j];
			}
			//Does nothing for the case j == i*/
		}
		accelerationX[i] = sumForceX;
		accelerationY[i] = sumForceY;
	}

	//Because type two particles are twice as heavy
	for (int i = numParticlesType1; i < totalParticles; i++)
	{
		accelerationX[i] = accelerationX[i] / 2;
		accelerationY[i] = accelerationY[i] / 2;
	}
}

//Determines if a given particle should be compared to a ghost particle in the X direction
float determineXVector(float positionX1, float positionX2, int rightBoundary)
{
	//This can be simplified
	//Changed || to &&
	if ((positionX1 >= 4.5) && (positionX1 <= rightBoundary - 4.5))
	{
		return (positionX1 - positionX2);
	}
	else if (positionX1 < 4.5
			&& positionX2 < (rightBoundary - (4.5 - positionX1)))
	{
		return (positionX1 - positionX2);
	}
	else if ((positionX1 > rightBoundary - 4.5)
			&& (positionX2 > (4.5 - (rightBoundary - positionX1))))
	{
		return (positionX1 - positionX2);
	}
	else if (positionX1 < 4.5
			&& positionX2 > (rightBoundary - (4.5 - positionX1)))
	{
		return (positionX1 - (positionX2 - rightBoundary));
	}
	else
	{
		return (positionX1 - (positionX2 + rightBoundary));
	}
}

//This function determines if a given particle should be compared to a ghost particle in the Y direction
float determineYVector(float positionY1, float positionY2, int upperBoundary)
{
	//This can be simplified
	//Changed || to &&
	if ((positionY1 >= 4.5) && (positionY1 <= upperBoundary - 4.5))
	{
		return (positionY1 - positionY2);
	}
	else if (positionY1 < 4.5
			&& positionY2 < (upperBoundary - (4.5 - positionY1)))
	{
		return (positionY1 - positionY2);
	}
	else if ((positionY1 > upperBoundary - 4.5)
			&& (positionY2 > (4.5 - (upperBoundary - positionY1))))
	{
		return (positionY1 - positionY2);
	}
	else if (positionY1 < 4.5
			&& positionY2 > (upperBoundary - (4.5 - positionY1)))
	{
		return (positionY1 - (positionY2 - upperBoundary));
	}
	else
	{
		return (positionY1 - (positionY2 + upperBoundary));
	}
}

void performEulerOperation(int totalParticles, float* xForce,
		float* yForce, float* positionX, float* positionY,
		int particlesType1, float* potentialEnergyArray, float& kineticEnergy,
		int upperBoundary, int rightBoundary, float* oldPositionX,
		float* oldPositionY, float* accelerationX, float* accelerationY,
		float* velocityX, float* velocityY, float currentTime,
		float timestep, ofstream& positionFile, cl_mem& positionBuffer, cl_mem& velocityBuffer,
		cl_mem& accelerationBuffer, cl_mem& futurePositionBuffer, cl_mem& positionXBuffer, cl_mem& positionYBuffer,
		cl_mem& forceBufferX, cl_mem& forceBufferY, cl_mem& potentialEnergyBuffer, cl_command_queue& command_queue,
		cl_kernel& eulerKernel, cl_kernel& forceKernel)
{
//Calculate individual forces
	calcForceMatrices(totalParticles, xForce,
		yForce, positionX, positionY,
		particlesType1, potentialEnergyArray, upperBoundary,
		rightBoundary, positionXBuffer, positionYBuffer,
		forceBufferX, forceBufferY, potentialEnergyBuffer,
		command_queue, forceKernel);

//Sum specific forces, divide by mass to get acceleration
	recalcAcceleration(accelerationX, accelerationY, xForce,
			yForce, totalParticles, particlesType1);

	kineticEnergy = 0;

	//Start with the X direction

	//Enqueue data
	clEnqueueWriteBuffer(command_queue, positionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionX, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, velocityBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, velocityX, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, accelerationBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, accelerationX, 0, NULL, NULL);

	//Set arguments for kernel
	clSetKernelArg(eulerKernel, 0, sizeof(float), (void *)&timestep);
	clSetKernelArg(eulerKernel, 1, sizeof(cl_mem), (void *)&positionBuffer);
	clSetKernelArg(eulerKernel, 2, sizeof(cl_mem), (void *)&velocityBuffer);
	clSetKernelArg(eulerKernel, 3, sizeof(cl_mem), (void *)&accelerationBuffer);
	clSetKernelArg(eulerKernel, 4, sizeof(cl_mem), (void *)&futurePositionBuffer);

	size_t global_size = totalParticles;
	size_t local_size = 64;
	clEnqueueNDRangeKernel(command_queue, eulerKernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL);

	//Read data back
	clEnqueueReadBuffer(command_queue, futurePositionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionX, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, positionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, oldPositionX, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, velocityBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, velocityX, 0, NULL, NULL);

	clFlush(command_queue);
	clFinish(command_queue);

	//Now for the Y direction

	//Enqueue data
	clEnqueueWriteBuffer(command_queue, positionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionY, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, velocityBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, velocityY, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, accelerationBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, accelerationY, 0, NULL, NULL);

	//Set arguments for kernel
	clSetKernelArg(eulerKernel, 0, sizeof(float), (void *)&timestep);
	clSetKernelArg(eulerKernel, 1, sizeof(cl_mem), (void *)&positionBuffer);
	clSetKernelArg(eulerKernel, 2, sizeof(cl_mem), (void *)&velocityBuffer);
	clSetKernelArg(eulerKernel, 3, sizeof(cl_mem), (void *)&accelerationBuffer);
	clSetKernelArg(eulerKernel, 4, sizeof(cl_mem), (void *)&futurePositionBuffer);

	clEnqueueNDRangeKernel(command_queue, eulerKernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL);

	//Read data back
	clEnqueueReadBuffer(command_queue, futurePositionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionY, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, positionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, oldPositionY, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, velocityBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, velocityY, 0, NULL, NULL);

	clFlush(command_queue);
	clFinish(command_queue);

	/*for (int i = 0; i < totalParticles; i++)
	{
		cout << i << " " << positionX[i] << " " << oldPositionX[i] << " " << velocityX[i] << endl;
		cout << i << " " << positionY[i] << " " << oldPositionY[i] << " " << velocityY[i] << endl;
	}*/

	for (int i = 0; i < totalParticles; i++)
	{
		/*oldPositionX[i] = positionX[i];
		oldPositionY[i] = positionY[i];

		//Euler method
		positionX[i] += (velocityX[i] * timestep);
		positionY[i] += (velocityY[i] * timestep);

		velocityX[i] += (accelerationX[i] * timestep);
		velocityY[i] += (accelerationY[i] * timestep);*/

		if (i < particlesType1)
			kineticEnergy += 0.5f
					* ((velocityX[i] * velocityX[i])
							+ (velocityY[i] * velocityY[i]));
		else
			kineticEnergy += ((velocityX[i] * velocityX[i])
					+ (velocityY[i] * velocityY[i]));

		applyPeriodicBoundary(positionX[i], positionY[i], oldPositionX[i],
				oldPositionY[i], rightBoundary, upperBoundary);
		positionFile << positionX[i] << " " << positionY[i]
				<< " 0 0 0 0 0 0 0 0 0 0" << '\n';
	}
}

void performVerletOperation(int totalParticles, float* xForce,
		float* yForce, float* positionX, float* positionY,
		int particlesType1, float* potentialEnergyArray, float& kineticEnergy,
		int upperBoundary, int rightBoundary, float* oldPositionX,
		float* oldPositionY, float* accelerationX, float* accelerationY,
		float* velocityX, float* velocityY, float currentTime,
		float timestep, ofstream& positionFile, cl_mem& positionBuffer, cl_mem& oldPositionBuffer,
		cl_mem& velocityBuffer, cl_mem& accelerationBuffer, cl_mem& displacementBuffer,
		cl_mem& futurePositionBuffer, cl_mem& positionXBuffer, cl_mem& positionYBuffer,
		cl_mem& forceBufferX, cl_mem& forceBufferY, cl_mem& potentialEnergyBuffer,
		cl_command_queue& command_queue, cl_kernel& verletKernel, cl_kernel& forceKernel)
{
	//Calculate individual forces
	calcForceMatrices(totalParticles, xForce,
		yForce, positionX, positionY,
		particlesType1, potentialEnergyArray, upperBoundary,
		rightBoundary, positionXBuffer, positionYBuffer,
		forceBufferX, forceBufferY, potentialEnergyBuffer,
		command_queue, forceKernel);

//Sum specific forces, divide by mass to get acceleration
	recalcAcceleration(accelerationX, accelerationY, xForce,
			yForce, totalParticles, particlesType1);

	kineticEnergy = 0;

	//Start with X direction

	//Write information to CL buffers
	/*clEnqueueWriteBuffer(command_queue, positionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionX, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, oldPositionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, oldPositionX, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, accelerationBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, accelerationX, 0, NULL, NULL);

	//Set arguments for kernel
	clSetKernelArg(kernel, 0, sizeof(float), (void *) &timestep);
	clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *) &positionBuffer);
	clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *) &oldPositionBuffer);
	clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *) &velocityBuffer);
	clSetKernelArg(kernel, 4, sizeof(cl_mem), (void *) &accelerationBuffer);
	clSetKernelArg(kernel, 5, sizeof(cl_mem), (void *) &displacementBuffer);
	clSetKernelArg(kernel, 6, sizeof(cl_mem), (void *) &futurePositionBuffer);

	//Execute the Kernel
	size_t global_size = totalParticles;
	size_t local_size = 64;
	clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL);

	//read data back into arrays
	//future position becomes current position, current position becomes old position

	cout << positionX[1] << endl;

	clEnqueueReadBuffer(command_queue, positionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, oldPositionX, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, futurePositionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionX, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, velocityBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, velocityX, 0, NULL, NULL);

	cout << positionX[1] << endl;

	clFlush(command_queue);
	clFinish(command_queue);

	//Now do for the Y direction*/

	//Write information to CL buffers
	/*clEnqueueWriteBuffer(command_queue, positionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionY, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, oldPositionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, oldPositionY, 0, NULL, NULL);
	clEnqueueWriteBuffer(command_queue, accelerationBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, accelerationY, 0, NULL, NULL);

	//Set arguments for kernel
	clSetKernelArg(kernel, 0, sizeof(float), (void *)& timestep);
	clSetKernelArg(kernel, 1, sizeof(cl_mem), (void *)& positionBuffer);
	clSetKernelArg(kernel, 2, sizeof(cl_mem), (void *)& oldPositionBuffer);
	clSetKernelArg(kernel, 3, sizeof(cl_mem), (void *)& velocityBuffer);
	clSetKernelArg(kernel, 4, sizeof(cl_mem), (void *)& accelerationBuffer);
	clSetKernelArg(kernel, 5, sizeof(cl_mem), (void *)& displacementBuffer);
	clSetKernelArg(kernel, 6, sizeof(cl_mem), (void *)& futurePositionBuffer);

	//Execute the Kernel
	clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_size, &local_size, 0, NULL, NULL);

	//read data back into arrays
	clEnqueueReadBuffer(command_queue, positionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, oldPositionY, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, futurePositionBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, positionY, 0, NULL, NULL);
	clEnqueueReadBuffer(command_queue, velocityBuffer, CL_TRUE, 0, sizeof(float)*totalParticles, velocityY, 0, NULL, NULL);

	clFlush(command_queue);
	clFinish(command_queue);*/

	/*for (int i = 0; i < totalParticles; i++)
	{
		cout << i << " " << positionX[i] << " " << oldPositionX[i] << " " << velocityX[i] << endl;
		cout << i << " " << positionY[i] << " " << oldPositionY[i] << " " << velocityY[i] << endl;
	}*/

	float currentDisplacement;
	float currentPosition;
	float futureDisplacement;
	for (int i = 0; i < totalParticles; i++)
	{
		//Leapfrog Verlet method - unstable
		/*velocityX[i] = velocityX[i] + accelerationX[i]*timestep;
		 positionX[i] = positionX[i] + timestep*velocityX[i];
		 velocityY[i] = velocityY[i] + accelerationY[i]*timestep;
		 positionY[i] = positionY[i] + timestep*velocityY[i];*/

		// Vector Verlet Method
		currentDisplacement = positionX[i] - oldPositionX[i];
		futureDisplacement = currentDisplacement
				+ (timestep * timestep * accelerationX[i]);
		currentPosition = positionX[i];
		positionX[i] = positionX[i] + futureDisplacement;
		velocityX[i] = (positionX[i] - oldPositionX[i]) / (2 * timestep);
		oldPositionX[i] = currentPosition;

		currentDisplacement = positionY[i] - oldPositionY[i];
		futureDisplacement = currentDisplacement
				+ (timestep * timestep * accelerationY[i]);
		currentPosition = positionY[i];
		positionY[i] = positionY[i] + futureDisplacement;
		velocityY[i] = (positionY[i] - oldPositionY[i]) / (2 * timestep);
		oldPositionY[i] = currentPosition;

		//Verlet method
		/*currentPosition = positionX[i];
		 positionX[i] = 2*(currentPosition) - oldPositionX[i] + (timestep*timestep*accelerationX[i]);
		 velocityX[i] = (positionX[i] - oldPositionX[i])/(2*timestep);
		 oldPositionX[i] = currentPosition;

		 currentPosition = positionY[i];
		 positionY[i] = 2*(currentPosition) - oldPositionY[i] + (timestep*timestep*accelerationY[i]);
		 velocityY[i] = (positionY[i] - oldPositionY[i])/(2*timestep);
		 oldPositionY[i] = currentPosition;*/

		if (i < particlesType1)
			kineticEnergy += 0.5f
					* ((velocityX[i] * velocityX[i])
							+ (velocityY[i] * velocityY[i]));
		else
			kineticEnergy += ((velocityX[i] * velocityX[i])
					+ (velocityY[i] * velocityY[i]));

		//cout << kineticEnergy << endl;

		applyPeriodicBoundary(positionX[i], positionY[i], oldPositionX[i],
				oldPositionY[i], rightBoundary, upperBoundary);
		positionFile << positionX[i] << " " << positionY[i]
				<< " 0 0 0 0 0 0 0 0 0 0" << '\n';
	}
}

void applyPeriodicBoundary(float &positionX, float &positionY,
		float &oldPositionX, float &oldPositionY, int rightBoundary,
		int upperBoundary)
{
	while (positionX > rightBoundary)
	{
		positionX -= rightBoundary;
		oldPositionX -= rightBoundary;
	}
	while (positionX < 0)
	{
		positionX += rightBoundary;
		oldPositionX += rightBoundary;
	}
	while (positionY > upperBoundary)
	{
		positionY -= upperBoundary;
		oldPositionY -= upperBoundary;
	}
	while (positionY < 0)
	{
		positionY += upperBoundary;
		oldPositionY += upperBoundary;
	}
}

void createHistogram(float binSize, int totalParticles, int particlesType1,
		float* positionX, float* positionY, int upperBoundary,
		int rightBoundary)
{
	int maxSize = (int) (sqrt(
			((float)(rightBoundary * rightBoundary + upperBoundary * upperBoundary)))
			/ (binSize));
	float* type1and1Histogram = new float[maxSize];
	float* type2and2Histogram = new float[maxSize];
	float* type2and1Histogram = new float[maxSize];
	for (int i = 0; i < maxSize; i++)
	{
		type1and1Histogram[i] = 0;
		type2and1Histogram[i] = 0;
		type2and2Histogram[i] = 0;
	}

	float xVector;
	float yVector;
	float distance;
	int binNumber;

	for (int i = 0; i < totalParticles; i++)
	{
		for (int j = i + 1; j < totalParticles; j++)
		{
			xVector = determineXVector(positionX[i], positionX[j],
					rightBoundary);
			yVector = determineYVector(positionY[i], positionY[j],
					upperBoundary);
			distance = sqrt(xVector * xVector + yVector * yVector);
			binNumber = (int) (distance / binSize);

			if (i < particlesType1 && j < particlesType1)
			{
				type1and1Histogram[binNumber] += 1;
			}
			else if (i >= particlesType1 && j >= particlesType1)
			{
				type2and2Histogram[binNumber] += 1;
			}
			else
			{
				type2and1Histogram[binNumber] += 1;
			}
		}
	}

	// NEED TO DEFINE FOR EACH PARTICLE
	float density = ((float) totalParticles)
			/ (rightBoundary * upperBoundary);
	float area;

	for (int i = 0; i < maxSize; i++)
	{
		area = 3.1415926535897932384626433832795f
				* (((i + 1) * binSize) * ((i + 1) * binSize)
						- (i * binSize) * (i * binSize));
		type1and1Histogram[i] *= (1 / area);
		type2and1Histogram[i] *= (1 / area);
		type2and2Histogram[i] *= (1 / area);
	}

	ofstream histoFile;
	histoFile.open("histoFile.txt");
	for (int i = 0; i < maxSize; i++)
	{
		histoFile << i << " " << type1and1Histogram[i] << " "
				<< type2and1Histogram[i] << " " << type2and2Histogram[i]
				<< endl;
	}
	histoFile.close();

	delete type1and1Histogram;
	delete type2and1Histogram;
	delete type2and2Histogram;
}