text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MatrixCalculations
{
	public class MatrixMath
    {
		/// <summary>
		/// The matrix calculations are done on
		/// </summary>
        private Matrix m = null;

		/// <summary>
		/// Matrixsize n  (Matrix is of size n x n)
		/// </summary>
        private int m_size = 0;

		/// <summary>
		/// Minimum column value
		/// </summary>
        private int m_minColID = -1;

		/// <summary>
		/// Minimum row value
		/// </summary>
        private int m_minRowID = -1;

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="p_size"></param>
		/// <param name="p_costs"></param>
        public MatrixMath(int p_size, List<int> p_costs)
        {
            m = new Matrix(p_size, p_costs);
            m_size = p_size;
        }

        /// <summary>
        /// Calculate a valid, optimal assignment for the matrix
        /// Source: http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
        /// </summary>
        /// <returns>Optimal assignment (indexed by rowID)</returns>
        public List<int> Calculate()
        {
            m.PrintMatrix("(0) Original Matrix");

            SubMinFromRows();
            m.PrintMatrix("(1) After substracting row minimums");

            FindAndStarZeroes();
            m.PrintMatrix("(2) After finding/staring zeroes");

            while (!CoverColumnsAndFindAssignment())
            {
                m.PrintMatrix("(3) After covering zeroes");

                while (!PrimeNoncoveredZero())
                {
                    m.PrintMatrix("(4) After priming zeroes");

                    SubstractSmallestValue();
                    m.PrintMatrix("(6) After substracting smallest value");
                }
                m.PrintMatrix("(4) After priming zeroes");

                AugmentPath();
                m.PrintMatrix("(5) After augmenting path");
            }

            m.PrintMatrix("(7) Final Matrix");

            return m.GetOptimalAssignmentByRow();
        }

        /// <summary>
        /// Substract the minimum value of each row from each element of the row
        /// </summary>
        private void SubMinFromRows()
        {
            // Iterate over rows to find minimum element
            for (int rowID = 0; rowID < m_size; rowID++)
            {
                int rowMinimum = m[rowID, 0].Value;
                for (int colID = 0; colID < m_size; colID++)
                {
                    if (m[rowID, colID].Value < rowMinimum)
                    {
                        rowMinimum = m[rowID, colID].Value;
                    }
                }
                for (int colID = 0; colID < m_size; colID++)
                {
                    m[rowID, colID].Value -= rowMinimum;
                }
            }
        }

        /// <summary>
        /// Find Zero in matrix. If there is no starred zero in it's row or column, star it. Repeat for each element
        /// </summary>
        private void FindAndStarZeroes()
        {
            int rowID = 0;
            int colID = 0;

            // Iterate over rows and colums to find (and star) zeroes
            while (true)
            {
                m.FindUncoveredZero(ref rowID, ref colID);

                if (rowID == -1) break;

                m[rowID, colID].IsStar = true;
                m.CoverRow(rowID);
                m.CoverColumn(colID);
            }

            // Remove cover from matrix again
            m.Uncover();
        }

        /// <summary>
        /// Cover all columns containing starred zeroes.
        /// If all Columns are covered, complete assignment was found
        /// </summary>
        /// <returns>TRUE is assignment was found</returns>
        private bool CoverColumnsAndFindAssignment()
        {
            // Iterate over rows and colums to find starred zeroes
            for (int rowID = 0; rowID < m_size; rowID++)
            {
                for (int colID = 0; colID < m_size; colID++)
                {
                    if (m[rowID, colID].IsStar)
                    {
                        m.CoverColumn(colID);
                    }
                }
            }

            // Count number of covered columns
            int columnCount = 0;
            for (int colID = 0; colID < m_size; colID++)
            {
                if (m.ColCovered(colID))
                {
                    columnCount++;
                }
            }

            // If all columns covered, assignment was found
            if (columnCount >= m_size)
            {
                return true;
            }

            return false;
        }

        /// <summary>
        /// Finds noncovered zero and primes it
        /// </summary>
        /// <returns>FALSE if no zero to prime</returns>
        private bool PrimeNoncoveredZero()
        {
            int rowID = -1;
            int colID = -1;

            while (true)
            {
                m.FindUncoveredZero(ref rowID, ref colID);
                if (rowID == -1)
                {
                    return false;
                }
                else
                {
                    m[rowID, colID].IsPrime = true;
                    if (m.IsStarInRow(rowID))
                    {
                        colID = m.FindStarInRow(rowID);
                        m.CoverRow(rowID);
                        m.CoverColumn(colID, false);
                    }
                    else
                    {
                        m_minRowID = rowID;
                        m_minColID = colID;
                        return true;
                    }
                }
            }
        }

        private void AugmentPath()
        {
            bool done = false;
            int rowID = -1;
            int colID = -1;

            List<int> rowPath = new List<int>();
            List<int> colPath = new List<int>();

            rowPath.Add(m_minRowID);
            colPath.Add(m_minColID);

            while (!done)
            {
                rowID = m.FindStarInColumn(colPath[colPath.Count - 1]);
                if (rowID > -1)
                {
                    rowPath.Add(rowID);
                    colPath.Add(colPath[colPath.Count - 1]);
                }
                else
                {
                    done = true;
                }

                if (!done)
                {
                    colID = m.FindPrimeInRow(rowPath[rowPath.Count - 1]);
                    rowPath.Add(rowPath[rowPath.Count - 1]);
                    colPath.Add(colID);
                }
            }

            m.AugmentPath(rowPath, colPath);
            m.Uncover();
            m.RemovePrimes();
        }

        /// <summary>
        /// Add smallest uncovered value to each element of covered rows,
        /// then substract it from each element in an uncovered column
        /// </summary>
        public void SubstractSmallestValue()
        {
            int minValue = m.FindSmallestUncoveredValue();

            for (int rowID = 0; rowID < m_size; rowID++)
            {
                for (int colID = 0; colID < m_size; colID++)
                {
                    if (m.RowCovered(rowID))
                    {
                        m[rowID, colID].Value += minValue;
                    }
                    if (!m.ColCovered(colID))
                    {
                        m[rowID, colID].Value -= minValue;
                    }
                }
            }
        }
    }
}


text:
package com.mulberry.athena.toolkit.collect;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;
import com.mulberry.athena.toolkit.base.Consumer;
import org.junit.Assert;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created with IntelliJ IDEA.
 *
 * @author zizhi.zhzzh
 *         Date: 4/23/14
 *         Time: 2:40 AM
 */
public class Collection3Tests {

    @Test
    public void reduce() {
        int ret = Collections3.reduce(ImmutableList.of(1l, 2l, 3l), 10, new Function<Integer, Function<Long, Integer>>() {
            public Function<Long, Integer> apply(final Integer memo) {
                return new Function<Long, Integer>() {
                    public Integer apply(Long el) {
                        return memo + el.intValue();
                    }
                };
            }
        });
        Assert.assertEquals(ret, 16);

        ret = Collections3.reduce(ImmutableList.of(1l, 2l, 3l), new Function<Integer, Function<Long, Integer>>() {
            public Function<Long, Integer> apply(final Integer memo) {
                return new Function<Long, Integer>() {
                    public Integer apply(Long el) {
                        int a = memo == null ? 0 : memo, b = el == null ? 0 : el.intValue();
                        return a + b;  //To change body of implemented methods use File | Settings | File Templates.
                    }
                };
            }
        });
        Assert.assertEquals(ret, 6);
    }

    @Test
    public void batchExecute() {
        final AtomicInteger count = new AtomicInteger();
        List<Integer> list = ImmutableList.of(1, 2, 3, 5, 6, 7, 8, 9);
        Collections3.batchExecute(list, 3, new Consumer<List<Integer>>() {
            public void accept(List<Integer> sum) {
                Assert.assertTrue(sum.size() <= 3);
                count.addAndGet(sum.size());
            }
        });
        Assert.assertEquals(count.get(), list.size());
    }

}

redpajama_set_name: RedPajamaGithub


text:
@echo off
setlocal ENABLEDELAYEDEXPANSION ENABLEEXTENSIONS
title Kipling Updater

:: Save arguments as variables
set arg1=%1
CALL :unquote arg1 %arg1%
set arg2=%2
CALL :unquote arg2 %arg2%
set arg3=%3
CALL :unquote arg3 %arg3%
set arg4=%4
CALL :unquote arg4 %arg4%
set arg5=%5
CALL :unquote arg5 %arg5%

set CURRENT_EXEC_PATH=%arg1%
set DOWNLOADED_FILE_PATH=%arg2%
set DOWNLOADED_APP_NAME=%arg3%
set REBOOT_SCRIPT_PATH=%arg4%
set DEBUG_FILE_DIRECTORY=%arg5%
echo "HERE"
if exist "%REBOOT_SCRIPT_PATH%\win_start_reboot.bat" (
	echo "It exists---"
) else (
	echo "It doesn't exist"
)
if "%CURRENT_EXEC_PATH%" == "" (
	echo "Overwriting CURRENT_EXEC_PATH"
	set CURRENT_EXEC_PATH="C:\Program Files (x86)\Kipling"
	:: set CURRENT_EXEC_PATH=J:\Users\Chris_2\temp Kipling Upgrading\current exe
	:: set CURRENT_EXEC_PATH="C:\Users\chris\temp Kipling Upgrading\current exe"
	echo "HEREB %CURRENT_EXEC_PATH%"
)
if "%DOWNLOADED_FILE_PATH%" == "" (
	echo "Overwriting DOWNLOADED_FILE_PATH"
	set DOWNLOADED_FILE_PATH=J:\Users\Chris_2\temp Kipling Upgrading\downloaded files
	set DOWNLOADED_FILE_PATH=C:\Users\chris\temp Kipling Upgrading\downloaded files
	echo "After Overwrite"
)
if "%DOWNLOADED_APP_NAME%" == "" (
	echo "Overwriting DOWNLOADED_APP_NAME"
	set DOWNLOADED_APP_NAME=Kipling.exe
)
if "%REBOOT_SCRIPT_PATH%" == "" (
	echo "Overwriting REBOOT_SCRIPT_PATH"
	set REBOOT_SCRIPT_PATH=J:\Users\Chris_2\Dropbox\Labjack\Kipling 3\Updater\Kipling Updater\Kipling Updater\bin\Release
	set REBOOT_SCRIPT_PATH=C:\Users\chris\Dropbox\Labjack\Kipling 3\Updater\Kipling Updater\Kipling Updater\bin\Release
	echo "After Overwrite"
)
if "%DEBUG_FILE_DIRECTORY%" == "" (
	echo "Overwriting DEBUG_FILE_DIRECTORY"
	set DEBUG_FILE_DIRECTORY=J:\Users\Chris_2\Dropbox\LabJack-Shared\Kipling Updater
	set DEBUG_FILE_DIRECTORY=C:\Users\chris\Dropbox\LabJack-Shared\Kipling Updater
	echo "After Overwrite"
)
echo "HEREC"

:: set DEBUG_FILE_DIRECTORY=J:\Users\Chris_2\temp Kipling Upgrading\downloaded files

:: Setup some required file paths
set WIN_UPDATE_SCRIPT=%REBOOT_SCRIPT_PATH%\win_update.bat
set WIN_UPDATE_EXE=%REBOOT_SCRIPT_PATH%\Kipling Updater.exe
set FILE_TO_CREATE=%DEBUG_FILE_DIRECTORY%\kiplingUpdate.tst
set FILE_TO_CREATE_SECONDARY=%DEBUG_FILE_DIRECTORY%\kiplingUpdateStart.tst
set FILE_TO_CONTINUE_UPGRADE=%DEBUG_FILE_DIRECTORY%\launchUpdate.tst
set DEBUG_FILE=%DEBUG_FILE_DIRECTORY%\Debug_win_reboot_bat.txt
set UPGRADER_DEBUG_FILE=%DEBUG_FILE_DIRECTORY%\Debug_Kipling_Upgrader_exe.txt

echo "Checking to Delete %FILE_TO_CREATE%"
if exist "%FILE_TO_CREATE%" (
	del "%FILE_TO_CREATE%"
)
echo "Checking to Delete %FILE_TO_CONTINUE_UPGRADE%"
if exist "%FILE_TO_CONTINUE_UPGRADE%" (
	del "%FILE_TO_CONTINUE_UPGRADE%"
)
echo "Checking to Delete %DEBUG_FILE%"
if exist "%DEBUG_FILE%" (
	del "%DEBUG_FILE%"
)
echo "Checking to Delete %UPGRADER_DEBUG_FILE%"
if exist "%UPGRADER_DEBUG_FILE%" (
	del "%UPGRADER_DEBUG_FILE%"
)
echo "Checking to Delete %FILE_TO_CREATE_SECONDARY%"
if exist "%FILE_TO_CREATE_SECONDARY%" (
	del "%FILE_TO_CREATE_SECONDARY%"
)

echo "CURRENT_EXEC_PATH: %CURRENT_EXEC_PATH%" >> "%DEBUG_FILE%"
echo "DOWNLOADED_FILE_PATH: %DOWNLOADED_FILE_PATH%" >> "%DEBUG_FILE%"
echo "DOWNLOADED_APP_NAME: %DOWNLOADED_APP_NAME%" >> "%DEBUG_FILE%"
echo "REBOOT_SCRIPT_PATH: %REBOOT_SCRIPT_PATH%" >> "%DEBUG_FILE%"
echo "DEBUG_FILE_DIRECTORY: %DEBUG_FILE_DIRECTORY%" >> "%DEBUG_FILE%"
echo "WIN_UPDATE_SCRIPT: %WIN_UPDATE_SCRIPT%" >> "%DEBUG_FILE%"
echo "WIN_UPDATE_EXE: %WIN_UPDATE_EXE%" >> "%DEBUG_FILE%"
echo "FILE_TO_CREATE: %FILE_TO_CREATE%" >> "%DEBUG_FILE%"
echo "FILE_TO_CREATE_SECONDARY: %FILE_TO_CREATE_SECONDARY%" >> "%DEBUG_FILE%"
echo "DEBUG_FILE: %DEBUG_FILE%" >> "%DEBUG_FILE%"
echo "**" >> "%DEBUG_FILE%"
echo "**" >> "%DEBUG_FILE%"

:: Define other variables
set PROGRAM_STATE=INIT
set HAS_ACCESS_TO_DIRECTORY=NO
set CHECK_FILE_ACCESS=YES
set /a "numTimeout = 0"
set /a "timeoutLength = 5"
set WAIT_FILE_NAME="%FILE_TO_CREATE%"
set WAIT_LOOP_NEXT=""
set WAIT_LOOP_FAIL=""
set WFKTQ_WAIT_LOOP_NEXT=""
set WFKTQ_WAIT_LOOP_FAIL=""

:: Make sure that the update script/exe exists.
echo "Checking for .bat" >> "%DEBUG_FILE%"
if exist "%WIN_UPDATE_SCRIPT%" (
	echo "Update Script exists" >> "%DEBUG_FILE%"
) else (
	echo "Update Script doesn't exist" >> "%DEBUG_FILE%"
)
echo "Checking for exe" >> "%DEBUG_FILE%"
if exist "%WIN_UPDATE_EXE%" (
	echo "Update Exe exists" >> "%DEBUG_FILE%"
) else (
	set PROGRAM_STATE=MISSING_UPGRADE_SCRIPT
	echo "Update Exe doesn't exist, halting upgrade: %WIN_UPDATE_EXE%" >> "%DEBUG_FILE%"
	timeout /t 1 /nobreak > NUL
	echo ABORT UPGRADE >> "%DEBUG_FILE%"
	timeout /t 1 /nobreak > NUL
)

echo "Finished Initialization Procedures" >> "%DEBUG_FILE%"
timeout /t 1 /nobreak > NUL

goto changeStateAndJump
echo "BAD BAD BAD" >> "%DEBUG_FILE%"

:: ------------- Define random subroutines
:unquote
	set %1=%~2
	goto :eof

:: ------------- Begin terminate program code ----------------------------------
echo "Defining terminateProgram" >> "%DEBUG_FILE%"
:terminateProgram
	if exist "%DOWNLOADED_FILE_PATH%\getadmin.vbs" (
		del "%DOWNLOADED_FILE_PATH%\getadmin.vbs"
	)
	if exist "%DOWNLOADED_FILE_PATH%\runUser.vbs" (
		del "%DOWNLOADED_FILE_PATH%\runUser.vbs"
	)
	if exist "%FILE_TO_CONTINUE_UPGRADE%" (
		del "%FILE_TO_CONTINUE_UPGRADE%"
	)
	if exist "%FILE_TO_CREATE%" (
		del "%FILE_TO_CREATE%"
	)
	if exist "%FILE_TO_CREATE_SECONDARY%" (
		del "%FILE_TO_CREATE_SECONDARY%"
	)
	echo "Terminating Program"
	echo "Terminating Program" >> "%DEBUG_FILE%"
	set PROGRAM_STATE=TERMINATE_PROGRAM
	pause
	exit /B
:: ------------- End terminate program code ------------------------------------

:: ------------- Begin main state machine --------------------------------------
:changeStateAndJump
	if "%CHECK_FILE_ACCESS%" == "YES" (
		goto checkForPermissions
	)
	echo "Current Program State: %PROGRAM_STATE%"
	echo "Current Program State: %PROGRAM_STATE%" >> "%DEBUG_FILE%"
	if "%PROGRAM_STATE%" == "INIT" (
		:: "INIT" is basically just a dead state that starts the state machine
		:: After "INIT" we go to "SWITCH_ON_ACCESS"
		echo "Program State: INIT" >> "%DEBUG_FILE%"
		set PROGRAM_STATE=SWITCH_ON_ACCESS
		goto changeStateAndJump

	) else if "%PROGRAM_STATE%" == "SWITCH_ON_ACCESS" (
		:: "SWITCH_ON_ACCESS" determines how to start the Kipling_Upgrader.exe
		:: After "SWITCH_ON_ACCESS" we go to "STARTED_UPDATE_SCRIPT"
		echo "Program State: SoA - Has Access? %HAS_ACCESS_TO_DIRECTORY%" >> "%DEBUG_FILE%"
		if "%HAS_ACCESS_TO_DIRECTORY%" == "YES" (
			goto updateWithCurrentPermissions
		) else (
			goto updateWithAdminPermissions
		)

	) else if "%PROGRAM_STATE%" == "STARTED_UPDATE_SCRIPT" (
		:: "STARTED_UPDATE_SCRIPT" enters a wait loop to wait for the script to start.
		:: It waits for a file to get created.
		:: If the file gets created, we go to "QUIT_KIPLING"
		:: If the file doesn't get created, we go to "ABORT_UPGRADE"
		echo "Program State: SUS" >> "%DEBUG_FILE%"
		set /a "numTimeout = 0"
		set /a "timeoutLength = 40"
		set WAIT_LOOP_NEXT=QUIT_KIPLING
		set WAIT_LOOP_FAIL=ABORT_UPGRADE
		set PROGRAM_STATE=WAIT_FOR_UPDATE_SCRIPT
		goto changeStateAndJump

	) else if "%PROGRAM_STATE%" == "QUIT_KIPLING" (
		:: "QUIT_KIPLING" enters a wait loop to wait for kipling to quit.
		:: It checks for nw.exe being executed in the tasklist, this isn't the best way to do this...
		:: If Kipling quits, we go to "WAIT_FOR_UPGRADE"
		:: If Kipling doesn't quit, we go to "ABORT_UPGRADE"
		echo "Program State: QK" >> "%DEBUG_FILE%"
		echo "QUIT KIPLING" >> "%DEBUG_FILE%"
		echo QUIT KIPLING
		set /a "numTimeout = 0"
		set /a "timeoutLength = 120"
		set WFKTQ_WAIT_LOOP_NEXT=START_UPGRADE
		set WFKTQ_WAIT_LOOP_FAIL=ABORT_UPGRADE
		set PROGRAM_STATE=WAIT_FOR_KIPLING_TO_QUIT
		goto changeStateAndJump

	) else if "%PROGRAM_STATE%" == "START_UPGRADE" (
		:: "START_UPGRADE" creates the "lock" file that indicates that K3 can be upgraded.
		:: The next state is "WAIT_FOR_UPGRADE"
		echo "Program State: SU" >> "%DEBUG_FILE%"
		set PROGRAM_STATE=WAIT_FOR_UPGRADE
		echo "Creating file: %FILE_TO_CONTINUE_UPGRADE%" >> "%DEBUG_FILE%"
		echo "Continue Upgrade" >> "%FILE_TO_CONTINUE_UPGRADE%"
		goto changeStateAndJump

	) else if "%PROGRAM_STATE%" == "WAIT_FOR_UPGRADE" (
		:: "WAIT_FOR_UPGRADE" enters a wait loop to wait for the upgrade process to happen.
		:: It checks for the file saved in the "FILE_TO_CREATE" variable to get created.
		:: If the file gets created, we go to "CHECK_UPGRADE"
		:: If the file doesn't get created, we go to "ABORT_UPGRADE"
		echo "Program State: WFU" >> "%DEBUG_FILE%"
		set /a "numTimeout = 0"
		set /a "timeoutLength = 120"
		set WAIT_LOOP_NEXT=CHECK_UPGRADE
		set WAIT_LOOP_FAIL=ABORT_UPGRADE
		set PROGRAM_STATE=WAIT_FOR_UPDATE_SCRIPT
		goto changeStateAndJump

	) else if "%PROGRAM_STATE%" == "CHECK_UPGRADE" (
		:: "CHECK_UPGRADE" enters a wait loop to make sure that Kipling.exe has been created.
		:: It checks to see if the file "Kipling.exe" exists in the proper directory.
		:: If the file gets created, we go to "LAUNCH_KIPLING"
		:: If the file doesn't get created, we go to "ABORT_UPGRADE"
		echo "Program State: WFU" >> "%DEBUG_FILE%"
		set /a "numTimeout = 0"
		set /a "timeoutLength = 120"
		set WAIT_LOOP_NEXT=LAUNCH_KIPLING
		set WAIT_LOOP_FAIL=ABORT_UPGRADE
		set PROGRAM_STATE=WAIT_FOR_KIPLING_UPGRADE
		goto changeStateAndJump

	) else if "%PROGRAM_STATE%" == "LAUNCH_KIPLING" (
		:: "LAUNCH_KIPLING" launches Kipling, hopefully by this point it has been upgraded.
		:: We set the state to "FINISHED" and start Kipling.
		echo "Program State: LK" >> "%DEBUG_FILE%"
		set PROGRAM_STATE=FINISHED
		if exist "%CURRENT_EXEC_PATH%\%DOWNLOADED_APP_NAME%" (
			echo "K3 exe exists" >> "%DEBUG_FILE%"
			echo "Starting Kipling: %CURRENT_EXEC_PATH%\%DOWNLOADED_APP_NAME%" >> "%DEBUG_FILE%"
			echo "start ""%CURRENT_EXEC_PATH%"" ""%CURRENT_EXEC_PATH%\%DOWNLOADED_APP_NAME%""" >> "%DEBUG_FILE%"
			cd /D "%CURRENT_EXEC_PATH%"
			start "%CURRENT_EXEC_PATH%" "%CURRENT_EXEC_PATH%\%DOWNLOADED_APP_NAME%"
		) else (
			echo "K3 exe doesn't exist" >> "%DEBUG_FILE%"
		)
		goto changeStateAndJump
	) else if "%PROGRAM_STATE%" == "WAIT_FOR_UPDATE_SCRIPT" (
		echo "Program State: WFUS: %numTimeout%" >> "%DEBUG_FILE%"
		goto waitForStartProgram
	) else if "%PROGRAM_STATE%" == "WAIT_FOR_KIPLING_TO_QUIT" (
		echo "Program State: WFKTQ: %numTimeout%" >> "%DEBUG_FILE%"
		goto waitForKiplingToQuit
	) else if "%PROGRAM_STATE%" == "WAIT_FOR_KIPLING_UPGRADE" (
		echo "Program State: WFSK: %numTimeout%" >> "%DEBUG_FILE%"
		goto waitForKiplingExe
	) else if "%PROGRAM_STATE%" == "ABORT_UPGRADE" (
		echo "Program State: AU" >> "%DEBUG_FILE%"
		echo "ABORT UPGRADE" >> "%DEBUG_FILE%"
		echo ABORT UPGRADE
		set PROGRAM_STATE=FINISHED
		goto changeStateAndJump
	) else if "%PROGRAM_STATE%" == "FINISHED" (
		echo "Program State: F" >> "%DEBUG_FILE%"
		goto terminateProgram
	) else if "%PROGRAM_STATE%" == "MISSING_UPGRADE_SCRIPT" (
		echo "Program State: MUS" >> "%DEBUG_FILE%"
		goto terminateProgram
	) else if "%PROGRAM_STATE%" == "TERMINATE_PROGRAM" (
		echo "Program State: TP" >> "%DEBUG_FILE%"
		goto terminateProgram
	) else (
		echo "Potentially bad state" >> "%DEBUG_FILE%"
		echo "Program State is: %PROGRAM_STATE%"
		goto terminateProgram
	)
	echo "End of changeStateAndJump BAD"
:: ------------- End main state machine ----------------------------------------

:: ------------- Begin checking for write access -------------------------------
:checkForPermissions
	set CHECK_FILE_ACCESS=NO
	echo "Checking to see if admin is required" >> "%DEBUG_FILE%"
	echo "DIR: %CURRENT_EXEC_PATH%\.writable" >> "%DEBUG_FILE%"
	set HAS_ACCESS_TO_DIRECTORY=NO
	copy /Y NUL "%CURRENT_EXEC_PATH%\.writable" > NUL 2>&1 && set WRITEOK=1
	IF DEFINED WRITEOK (
		if exist "%CURRENT_EXEC_PATH%\.writable" (
		   set HAS_ACCESS_TO_DIRECTORY=YES
		   del "%CURRENT_EXEC_PATH%\.writable"
		   echo "File exists and copy worked" >> "%DEBUG_FILE%"
		   goto changeStateAndJump
		) else (
			echo "File Does Not Exist..." >> "%DEBUG_FILE%"
			goto changeStateAndJump
		)
	) else (
		echo "File Copy Reported Fail" >> "%DEBUG_FILE%"
		goto changeStateAndJump
	)
:: ------------- End checking for write access ---------------------------------

:: ------------- Begin Launch win_update.bat with admin permissions ------------
:updateWithAdminPermissions
	echo "in updateWithAdminPermissions" >> "%DEBUG_FILE%"

:getAdminPermissions
	echo "in getAdminPermissions" >> "%DEBUG_FILE%"
	REM  --> Check for permissions
	>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

	REM --> If error flag set, we do not have admin.
	if '%errorlevel%' NEQ '0' (
	echo "Requesting administrative privileges..." >> "%DEBUG_FILE%"
	goto UACPrompt
	) else ( goto gotAdmin )

:UACPrompt
	echo "in UACPrompt" >> "%DEBUG_FILE%"
	echo Set UAC = CreateObject^("Shell.Application"^) > "%DOWNLOADED_FILE_PATH%\getadmin.vbs"
	set ADMIN_SCRIPT_CMD= """%CURRENT_EXEC_PATH%"" ""%DOWNLOADED_FILE_PATH%"" ""%DOWNLOADED_APP_NAME%"" ""%REBOOT_SCRIPT_PATH%"" ""%FILE_TO_CREATE%"" ""%FILE_TO_CREATE_SECONDARY%"" ""%FILE_TO_CONTINUE_UPGRADE%"" ""%UPGRADER_DEBUG_FILE%"""
	:: ""%arg1%"" ""%arg2%"" ""%arg3%"" ""%arg4%"" ""%FILE_TO_CREATE%""
	echo "ADMIN SCRIPT: %ADMIN_SCRIPT_CMD%" >> "%DEBUG_FILE%"
	:: Commands to update the Kipling Updater .exe
	echo UAC.ShellExecute "%WIN_UPDATE_EXE%", %ADMIN_SCRIPT_CMD%, "", "runas", 0 >> "%DOWNLOADED_FILE_PATH%\getadmin.vbs"

	:: Commands to execute the update script
	:: echo UAC.ShellExecute "cmd.exe", "/c start /min \"%REBOOT_SCRIPT_PATH%\" \"%WIN_UPDATE_SCRIPT%\" def \"%DOWNLOADED_APP_NAME%\" klm opq", "", "runas", 0 >> "%DOWNLOADED_FILE_PATH%\getadmin.vbs"
	:: echo UAC.ShellExecute "cmd.exe", "/c start /min %~s0 %params%", "", "runas", 1 >> "%DOWNLOADED_FILE_PATH%\getadmin.vbs"
	:: echo UAC.ShellExecute "C:\Users\Rory\Desktop\kipling\update.exe","%params%", "", "runas", 1 >> "%DOWNLOADED_FILE_PATH%\getadmin.vbs"
	CSCRIPT "%DOWNLOADED_FILE_PATH%\getadmin.vbs"
	del "%DOWNLOADED_FILE_PATH%\getadmin.vbs"
	set PROGRAM_STATE=STARTED_UPDATE_SCRIPT
	goto changeStateAndJump

:gotAdmin
	echo "in gotAdmin" >> "%DEBUG_FILE%"
	goto updateWithCurrentPermissions
:: ------------- End Launch win_update.bat with admin permissions --------------

:: ------------- Begin Launch win_update.bat with current permissions ----------
:updateWithCurrentPermissionsA
	goto updateWithCurrentPermissions
:updateWithCurrentPermissions
	echo "in updateWithCurrentPermissions" >> "%DEBUG_FILE%"
	:: start /min %WIN_UPDATE_SCRIPT% %arg1% %arg2% %arg3% %arg4%

	:: Dim WinScriptHost
	echo set WIN_SCRIPT_HOST=CreateObject^("WScript.Shell"^) > "%DOWNLOADED_FILE_PATH%\runUser.vbs"
	:: echo WIN_SCRIPT_HOST.ShellExecute "cmd.exe", "/c start /min %WIN_UPDATE_SCRIPT% %arg1% %arg2% %arg3% %arg4%", 0  >> "%DOWNLOADED_FILE_PATH%\runUser.vbs"

	:: Commands to update the Kipling Updater .exe
	echo WIN_SCRIPT_HOST.Run """%WIN_UPDATE_EXE%"" ""%CURRENT_EXEC_PATH%"" ""%DOWNLOADED_FILE_PATH%"" ""%DOWNLOADED_APP_NAME%"" ""%REBOOT_SCRIPT_PATH%"" ""%FILE_TO_CREATE%"" ""%FILE_TO_CREATE_SECONDARY%"" ""%FILE_TO_CONTINUE_UPGRADE%"" ""%UPGRADER_DEBUG_FILE%""", 0 >> "%DOWNLOADED_FILE_PATH%\runUser.vbs"
	echo "Starting Program" >> "%DEBUG_FILE%"
	:: WORKING: start "%DOWNLOADED_FILE_PATH%" "%WIN_UPDATE_EXE%" "%CURRENT_EXEC_PATH%" "%DOWNLOADED_FILE_PATH%" "%DOWNLOADED_APP_NAME%" "%REBOOT_SCRIPT_PATH%" "%FILE_TO_CREATE%" "%UPGRADER_DEBUG_FILE%"
	:: NOT WORKING: start /B "%DOWNLOADED_FILE_PATH%" "%arg1%" "%arg2%" "%arg3%" "%arg4%" "%FILE_TO_CREATE%" "%UPGRADER_DEBUG_FILE%"

	:: Commands to execute the update script
	:: echo WIN_SCRIPT_HOST.Run """%WIN_UPDATE_SCRIPT%"" ""%arg1%"" ""%arg2%"" ""%arg3%"" ""%arg4%"" ""%FILE_TO_CREATE%""", 1  >> "%DOWNLOADED_FILE_PATH%\runUser.vbs"
	:: set WinScriptHost = Nothing
	CSCRIPT "%DOWNLOADED_FILE_PATH%\runUser.vbs"
	del "%DOWNLOADED_FILE_PATH%\runUser.vbs"
	set PROGRAM_STATE=STARTED_UPDATE_SCRIPT
	echo "Finished Executing Program" >> "%DEBUG_FILE%"
	goto changeStateAndJump

:: ------------- End Launch win_update.bat with current permissions ------------

:: ------------- Begin wait loop -----------------------------------------------
:waitForStartProgram
	echo "in waitForStartProgram" >> "%DEBUG_FILE%"
	if exist %WAIT_FILE_NAME% (
		del %WAIT_FILE_NAME%
		echo "Removing temp file: %WAIT_FILE_NAME%" >> "%DEBUG_FILE%"
		timeout /t 1 /nobreak > NUL
		set PROGRAM_STATE=%WAIT_LOOP_NEXT%
		goto changeStateAndJump
	) else if %numTimeout% leq %timeoutLength% (
		:: echo "Wait for updater timer: %numTimeout%"
		set /a "numTimeout = numTimeout + 1"
		timeout /t 1 /nobreak > NUL
		goto changeStateAndJump
	) else (
		echo "Aborting Program, didn't hear response from win_update.bat" >> "%DEBUG_FILE%"
		set PROGRAM_STATE=%WAIT_LOOP_FAIL%
		goto changeStateAndJump
	)
:: ------------- End wait loop -------------------------------------------------

:: ------------- Begin start wait loop -----------------------------------------------
:waitForKiplingExe
	echo "in waitForKiplingExe" >> "%DEBUG_FILE%"
	if exist "%CURRENT_EXEC_PATH%\%DOWNLOADED_APP_NAME%" (
		echo "Kipling Exe has been found: %numTimeout%" >> "%DEBUG_FILE%"
		set PROGRAM_STATE=%WAIT_LOOP_NEXT%
		goto changeStateAndJump
	) else if %numTimeout% leq %timeoutLength% (
		:: echo "Wait for updater timer: %numTimeout%"
		set /a "numTimeout = numTimeout + 1"
		timeout /t 1 /nobreak > NUL
		goto changeStateAndJump
	) else (
		echo "Aborting Program, ""%CURRENT_EXEC_PATH%\%DOWNLOADED_APP_NAME%"" wasn't ever created" >> "%DEBUG_FILE%"
		set PROGRAM_STATE=%WAIT_LOOP_FAIL%
		goto changeStateAndJump
	)
:: ------------- End start wait loop -------------------------------------------------

:: ------------- Begin wait-for-kipling-exit wait loop -----------------------------------------------

:waitForKiplingToQuit
	echo "in waitForKiplingToQuit" >> "%DEBUG_FILE%"
	set IS_KIPLING_RUNNING="YES"
	"%REBOOT_SCRIPT_PATH%\tasklist.exe" /nh /fi "imagename eq nw.exe" | find /i "nw.exe" >nul && (
		echo "Kipling is running" >> "%DEBUG_FILE%"
	) || (
		echo "Kipling is not running" >> "%DEBUG_FILE%"
		set IS_KIPLING_RUNNING="NO"
	)
	if %IS_KIPLING_RUNNING% == "NO" (
		echo "Kipling is not running: %numTimeout%" >> "%DEBUG_FILE%"
		echo "New Program State: %WFKTQ_WAIT_LOOP_NEXT%" >> "%DEBUG_FILE%"
		set PROGRAM_STATE=%WFKTQ_WAIT_LOOP_NEXT%
		goto changeStateAndJump
	) else if %numTimeout% leq %timeoutLength% (
		:: echo "Wait for updater timer: %numTimeout%"
		set /a "numTimeout = numTimeout + 1"
		timeout /t 1 /nobreak > NUL
		goto changeStateAndJump
	) else (
		echo "Aborting Program, Kipling is still running" >> "%DEBUG_FILE%"
		set PROGRAM_STATE=%WFKTQ_WAIT_LOOP_FAIL%
		goto changeStateAndJump
	)
:: ------------- End wait-for-kipling-exit wait loop -------------------------------------------------

:: ------------- Begin Re-Open Kipling with current permissions ----------

:: start "%CURRENT_EXEC_PATH%" "%CURRENT_EXEC_PATH%\%DOWNLOADED_APP_NAME%"
::
:: "start "J:\Users\Chris_2\temp Kipling Upgrading\current exe" "J:\Users\Chris_2\temp Kipling Upgrading\current exe\Kipling.exe""

:: ------------- Begin Re-Open Kipling with current permissions ----------


text:
package com.sfsu.investickation.fragments;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.appcompat.BuildConfig;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sfsu.controllers.DatabaseDataController;
import com.sfsu.db.ActivitiesDao;
import com.sfsu.entities.Account;
import com.sfsu.entities.Activities;
import com.sfsu.entities.Observation;
import com.sfsu.investickation.R;
import com.sfsu.investickation.UserActivityMasterActivity;
import com.sfsu.network.bus.BusProvider;
import com.sfsu.network.events.ActivityEvent;
import com.sfsu.network.events.ObservationEvent;
import com.sfsu.network.handler.ApiRequestHandler;
import com.sfsu.utils.AppUtils;
import com.squareup.otto.Subscribe;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Displays the details of a specific {@link Activities}. Allows {@link Account} to see all the observations
 * that belongs to this specific activity.
 */
public class ActivityDetailFragment extends Fragment implements View.OnClickListener {

    private static String KEY_ARGS = "activity_object";
    public final String TAG = "~!@#ActivityDet";
    @Bind(R.id.textview_activity_details_activity_name)
    TextView txtView_name;
    @Bind(R.id.textview_activity_details_observation_count)
    TextView txtView_observationCount;
    @Bind(R.id.textview_activity_details_date)
    TextView txtView_date;
    @Bind(R.id.textview_activity_details_total_people)
    TextView txtView_totalPeople;
    @Bind(R.id.textview_activity_details_total_pets)
    TextView txtView_totalPets;
    @Bind(R.id.textview_activity_details_time)
    TextView txtView_time;
    @Bind(R.id.button_activity_details_view_all_observation)
    Button button_viewObservations;
    @Bind(R.id.imageview_activity_details_static_map)
    ImageView imageView_staticMap;
    @Bind(R.id.icon_activity_details_view_map)
    ImageView icon_openMap;
    private IActivityDetailsCallBacks mListener;
    private Context mContext;
    private Bundle mArgs;
    private Activities mActivity;
    private SharedPreferences activityPref;
    private SharedPreferences.Editor editor;
    private Gson gson;

    private DatabaseDataController dbController;
    private List<Observation> mObservationList;

    public ActivityDetailFragment() {
        // Required empty public constructor
    }

    /**
     * Method to create {@link ActivityDetailFragment} instance.
     *
     * @param key
     * @param mActivity
     * @return
     */
    public static ActivityDetailFragment newInstance(Activities mActivity) {
        ActivityDetailFragment fragment = new ActivityDetailFragment();
        Bundle args = new Bundle();
        args.putParcelable(KEY_ARGS, mActivity);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_activity_details, container, false);
        ButterKnife.bind(this, rootView);

        if (getArguments() != null) {
            mArgs = getArguments();
        }
        gson = new Gson();
        activityPref = mContext.getSharedPreferences(UserActivityMasterActivity.PREF_ACTIVITY_DATA, Context.MODE_PRIVATE);
        dbController = new DatabaseDataController(mContext, ActivitiesDao.getInstance());

        button_viewObservations.setOnClickListener(this);
        icon_openMap.setOnClickListener(this);

        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (IActivityDetailsCallBacks) activity;
            mContext = activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement IActivityDetailsCallBacks interface");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // save the Currently running object in SharedPref to retrieve it later using editor.
        editor = activityPref.edit();
        String activityJson = gson.toJson(mActivity);
        editor.putString(UserActivityMasterActivity.EDITOR_ONGOING_ACTIVITY, activityJson);
        editor.apply();

        BusProvider.bus().unregister(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        getActivity().setTitle(R.string.title_fragment_activity_detail);

        BusProvider.bus().register(this);

        // depending on the mArgs, populate view based on the Activity restored.
        if (mArgs != null) {
            // if mArgs not null, retrieve the Activities object.
            if (mArgs.getParcelable(KEY_ARGS) != null) {
                mActivity = mArgs.getParcelable(KEY_ARGS);
            }
        } else {
            // get data from SharedPref
            String activityJson = activityPref.getString(UserActivityMasterActivity.EDITOR_ONGOING_ACTIVITY, "no-data");
            mActivity = gson.fromJson(activityJson, Activities.class);
        }

        if (mActivity != null) {
            populateView();
        }

        if (mActivity.getId() != null) {
            // since we have the activityId, get all Observations for this Activity and display it on Maps as well as view it in List.
            BusProvider.bus().post(new ObservationEvent.OnLoadingInitialized("", mActivity.getId(), ApiRequestHandler.ACT_OBSERVATIONS));
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        dbController.closeConnection();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * Helper method to populate View in ActivityDetailFragment.
     */
    private void populateView() {
        try {
            // once the object is collected, display it in the respective controls.
            String activityName = mActivity.getActivityName() + " @ " + mActivity.getLocation_area();
            txtView_name.setText(activityName);

            String observationCount = mActivity.getNum_of_ticks() + " Obs.";
            txtView_observationCount.setText(observationCount);
            String[] dateAndTime = AppUtils.getDateAndTimeSeparate(mActivity.getTimestamp());
            txtView_date.setText(dateAndTime[0]);
            txtView_time.setText(dateAndTime[1]);
            String people = mActivity.getNum_of_people() + " people";
            txtView_totalPeople.setText(people);
            String pets = mActivity.getNum_of_pets() + " pets";
            txtView_totalPets.setText(pets);
            String image_url = mActivity.getImage_url();
            // imageFile
            File imgFile = new File(mActivity.getImage_url());

            // depending on the image url, display the activity image
            if (image_url == null || image_url.equals("")) {
                imageView_staticMap.setImageResource(R.mipmap.placeholder_activity);
            } else {
                if (AppUtils.isConnectedOnline(mContext)) {
                    if (mActivity.getImage_url().startsWith("http")) {
                        Picasso.with(mContext).load(mActivity.getImage_url()).into(imageView_staticMap);
                    } else {
                        if (imgFile.exists()) {
                            Bitmap tickBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                            imageView_staticMap.setImageBitmap(tickBitmap);
                        }
                    }
                } else {
                    if (imgFile.exists()) {
                        Bitmap tickBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                        imageView_staticMap.setImageBitmap(tickBitmap);
                    }
                }
            }
        } catch (Exception e) {

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // delete the SharedPref data
        activityPref.edit().remove(UserActivityMasterActivity.PREF_ACTIVITY_DATA).apply();

        // free up all the resources.
        mActivity = null;
        mContext = null;
        gson = null;
        dbController = null;
        mObservationList = null;
    }

    /**
     * Subscribes to the event of success loading of {@link com.sfsu.entities.Observation} related to this Activity.
     *
     * @param onLoaded
     */
    @Subscribe
    public void onObservationsLoadSuccess(ObservationEvent.OnListLoaded onLoaded) {
        try {
            mObservationList = onLoaded.getResponseList();
            // only if the observations can be retrieved for current Activity, open the List of Observation.
            if (mObservationList == null || mObservationList.size() <= 0) {
                button_viewObservations.setEnabled(false);
                button_viewObservations.setText(R.string.actDet_noObservationRecorded);
            }
        } catch (Exception e) {

        }
    }

    /**
     * Subscribes to the event of failure in deletion of {@link Activities}.
     *
     * @param onLoadingError
     */
    @Subscribe
    public void onDeleteActivityFailure(ActivityEvent.OnLoadingError onLoadingError) {
        Toast.makeText(mContext, onLoadingError.getErrorMessage(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_activity_details_view_all_observation:
                mListener.onViewAllObservationsClicked(mActivity.getId());
                break;
            case R.id.icon_activity_details_view_map:
                try {
                    ArrayList<Observation> mObservationArrayList = new ArrayList<Observation>(mObservationList);
                    mListener.onOpenActivitiesMapClicked(mObservationArrayList);
                } catch (Exception e) {
                    if (BuildConfig.DEBUG)
                        Log.e(TAG, "onClick: ", e);
                }
                break;
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_activity_detail, menu);
        final MenuItem item = menu.findItem(R.id.action_delete);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_delete:
                deleteActivity();
                return true;
        }
        return false;
    }

    /**
     * Delete the {@link Activities} from Local Storage or Cloud Server depending on where its stored.
     */
    private void deleteActivity() {
        if (mActivity.isOnCloud()) {
            AlertDialog.Builder deleteActivityDialog = new AlertDialog.Builder(mContext);
            String deleteTitle = "Delete '" + mActivity.getActivityName() + "' Activity?";
            deleteActivityDialog.setTitle(deleteTitle);
            deleteActivityDialog.setMessage(R.string.alertDialog_delete_activity_warning);
            deleteActivityDialog.setIcon(R.mipmap.ic_delete_black_24dp);

            deleteActivityDialog.setPositiveButton(R.string.alertDialog_YES, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    BusProvider.bus().post(new ActivityEvent.OnLoadingInitialized(mActivity.getId(), ApiRequestHandler.DELETE));
                }
            });

            deleteActivityDialog.setNegativeButton(R.string.alertDialog_NO, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do nothing
                }
            });
            deleteActivityDialog.show();
        } else {
            dbController.delete(mActivity.getId());
            // open ActivityListFragment after deleting the Observation
            getActivity().getSupportFragmentManager().popBackStack();
        }
    }

    /**
     * Subscribes to the event of successful deletion of {@link Activities} from the server
     *
     * @param onLoaded
     */
    @Subscribe
    public void onActivityDeleteSuccess(ActivityEvent.OnLoadedCount onLoaded) {
        if (onLoaded.getResponse().getCount() == 1) {
            Toast.makeText(mContext, "Activity deleted", Toast.LENGTH_LONG).show();
            // open ActivityListFragment after the current Activity is successfully deleted.
            getActivity().getSupportFragmentManager().popBackStack();
        }
    }

    /**
     * Subscribes to the event of failure in deleting {@link Activities} from the server
     *
     * @param onLoadingError
     */
    @Subscribe
    public void onActivityDeleteFailure(ActivityEvent.OnLoadingError onLoadingError) {
        //Toast.makeText(mContext, onLoadingError.getErrorMessage(), Toast.LENGTH_LONG).show();
    }

    /**
     * Interface callback for handling onClick Listeners in {@link ActivityDetailFragment} Fragment.
     */
    public interface IActivityDetailsCallBacks {
        /**
         * Callback method to handle the click event when user clicks <tt>View Observation</tt> button in {@link
         * ActivityDetailFragment} fragment.
         */
        public void onViewAllObservationsClicked(String activityId);

        /**
         * Callback method to handle the onclick event of the button in {@link ActivityDetailFragment} fragment to open up the {@link
         * ObservationMap} fragment.
         */
        public void onOpenActivitiesMapClicked(ArrayList<Observation> mObservationList);
    }

}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class PhonebookUsers extends Migration
{
    protected $primaryKey = 'name';
    public $incrementing = false;

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table)
        {
            $table->engine = 'InnoDB';

            $table->integer('id')->unsigned()->autoIncrement();
            $table->string('user_image');
            $table->string('name');
            $table->string('email', 191)->unique();
            $table->string('password', 191);
            $table->timestamp('updated_at');
            $table->timestamp('created_at');
            $table->rememberToken();
        });

    }

        // 2017_07_10_133259  THEN 2017_06_...changed to
        // 2017_05_26_120607 changed from

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('users');
    }
}


text:
package com.github.peejweej.androidsideloading.fragments.wifi;

import android.content.Context;
import android.net.wifi.p2p.WifiP2pDevice;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

import com.github.peejweej.androidsideloading.R;
import com.github.peejweej.androidsideloading.activities.WiFiDirectActivity;

/**
 * Array adapter for ListFragment that maintains WifiP2pDevice list.
 */
public class WiFiPeerListAdapter extends ArrayAdapter<WifiP2pDevice> {

    private List<WifiP2pDevice> items;

    /**
     * @param context
     * @param textViewResourceId
     * @param objects
     */
    public WiFiPeerListAdapter(Context context, int textViewResourceId,
                               List<WifiP2pDevice> objects) {
        super(context, textViewResourceId, objects);
        items = objects;

    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row_devices, null);
        }
        WifiP2pDevice device = items.get(position);
        if (device != null) {
            TextView top = (TextView) v.findViewById(R.id.device_name);
            TextView bottom = (TextView) v.findViewById(R.id.device_details);
            if (top != null) {
                top.setText(device.deviceName);
            }
            if (bottom != null) {
                bottom.setText(getDeviceStatus(device.status));
            }
        }

        return v;
    }

    public static String getDeviceStatus(int deviceStatus) {
        Log.d(WiFiDirectActivity.TAG, "Peer status :" + deviceStatus);
        switch (deviceStatus) {
            case WifiP2pDevice.AVAILABLE:
                return "Available";
            case WifiP2pDevice.INVITED:
                return "Invited";
            case WifiP2pDevice.CONNECTED:
                return "Connected";
            case WifiP2pDevice.FAILED:
                return "Failed";
            case WifiP2pDevice.UNAVAILABLE:
                return "Unavailable";
            default:
                return "Unknown";

        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Rem
 * Date: 08.09.2016
 * Time: 16:45
 */

namespace site\controllers;

use Yii;
use site\abstracts\ControllerAbstract;
use yii\web\BadRequestHttpException;
use yii\web\NotFoundHttpException;
use models\User;

class MailDeliveryController extends ControllerAbstract
{
    public function actionUnfollow($token)
    {
        // Try to find the user by mail delivery token
        if (($user = User::findOne(['mail_delivery_token' => base64_decode($token)])) === null) {
            throw new NotFoundHttpException($this->t('Incorrect token'));
        }

        // Login the user
        $user->setStoryAction(User::STORY_ACTION_LOGIN);
        Yii::$app->user->login($user, $user->getSessionTime());

        // Unfollow user from mail deliveries
        $user->mailDeliveryAllowed = false;
        $user->mailDeliveryToken = null;
        $user->setStoryAction(User::STORY_ACTION_MAIL_DELIVERY_UNFOLLOW);

        if (!$user->save()) {
            $this->setError($this->t('Can not unfollow from mail deliveries'));
        } else {
            $this->setFlash($this->t('You are unfollow from the mail deliveries'));
        }

        return $this->redirect(['/site/account/update']);
    }

    public function actionSubscribe()
    {
        // Check the request method
        if (!$this->isPost()) {
            throw new BadRequestHttpException($this->t('Bad request'));
        }
        // Check is user not subscribed
        if (Yii::$app->user->getIsSubscribed()) {
            throw new BadRequestHttpException($this->t('You are already subscribed to our newsletter'));
        }

        // Try to subscribe user to mail delivery
        if (Yii::$app->user->setIsSubscribed(true)) {
            $this->setSuccess($this->t('You are subscribed to our newsletter'));
        } else {
            $this->setError($this->t('Could not subscribe you to our newsletter'));
        }

        return $this->redirect(['/site/account/update']);
    }
}


text:
using System.Buffers;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;

namespace System.Net.Sockets
{
    // Provides the underlying stream of data for network access.
    public class NetworkStream : Stream
    {
        // Used by the class to hold the underlying socket the stream uses.
        private readonly Socket _streamSocket;

        // Whether the stream should dispose of the socket when the stream is disposed
        private readonly bool _ownsSocket;

        // Used by the class to indicate that the stream is m_Readable.
        private bool _readable;

        // Used by the class to indicate that the stream is writable.
        private bool _writeable;

        // Creates a new instance of the System.Net.Sockets.NetworkStream class for the specified System.Net.Sockets.Socket.
        public NetworkStream(Socket socket)
            : this(socket, FileAccess.ReadWrite, ownsSocket: false)
        {
        }

        public NetworkStream(Socket socket, bool ownsSocket)
            : this(socket, FileAccess.ReadWrite, ownsSocket)
        {
        }

        public NetworkStream(Socket socket, FileAccess access)
            : this(socket, access, ownsSocket: false)
        {
        }

        public NetworkStream(Socket socket, FileAccess access, bool ownsSocket)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
            {
#endif
                if (socket == null)
                {
                    throw new ArgumentNullException(nameof(socket));
                }
                if (!socket.Blocking)
                {
                    throw new IOException(SR.net_sockets_blocking);
                }
                if (!socket.Connected)
                {
                    throw new IOException(SR.net_notconnected);
                }
                if (socket.SocketType != SocketType.Stream)
                {
                    throw new IOException(SR.net_notstream);
                }

                _streamSocket = socket;
                _ownsSocket = ownsSocket;

                switch (access)
                {
                    case FileAccess.Read:
                        _readable = true;
                        break;
                    case FileAccess.Write:
                        _writeable = true;
                        break;
                    case FileAccess.ReadWrite:
                    default: // assume FileAccess.ReadWrite
                        _readable = true;
                        _writeable = true;
                        break;
                }
#if DEBUG
            }
#endif
        }

        // Socket - provides access to socket for stream closing
        protected Socket Socket => _streamSocket;

        // Used by the class to indicate that the stream is m_Readable.
        protected bool Readable
        {
            get { return _readable; }
            set { _readable = value; }
        }

        // Used by the class to indicate that the stream is writable.
        protected bool Writeable
        {
            get { return _writeable; }
            set { _writeable = value; }
        }

        // Indicates that data can be read from the stream.
        // We return the readability of this stream. This is a read only property.
        public override bool CanRead => _readable;

        // Indicates that the stream can seek a specific location
        // in the stream. This property always returns false.
        public override bool CanSeek => false;

        // Indicates that data can be written to the stream.
        public override bool CanWrite => _writeable;

        // Indicates whether we can timeout
        public override bool CanTimeout => true;

        // Set/Get ReadTimeout, note of a strange behavior, 0 timeout == infinite for sockets,
        // so we map this to -1, and if you set 0, we cannot support it
        public override int ReadTimeout
        {
            get
            {
#if DEBUG
                using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
                {
#endif
                    int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
                    if (timeout == 0)
                    {
                        return -1;
                    }
                    return timeout;
#if DEBUG
                }
#endif
            }
            set
            {
#if DEBUG
                using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
                {
#endif
                    if (value <= 0 && value != System.Threading.Timeout.Infinite)
                    {
                        throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero);
                    }
                    SetSocketTimeoutOption(SocketShutdown.Receive, value, false);
#if DEBUG
                }
#endif
            }
        }

        // Set/Get WriteTimeout, note of a strange behavior, 0 timeout == infinite for sockets,
        // so we map this to -1, and if you set 0, we cannot support it
        public override int WriteTimeout
        {
            get
            {
#if DEBUG
                using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
                {
#endif
                    int timeout = (int)_streamSocket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
                    if (timeout == 0)
                    {
                        return -1;
                    }
                    return timeout;
#if DEBUG
                }
#endif
            }
            set
            {
#if DEBUG
                using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
                {
#endif
                    if (value <= 0 && value != System.Threading.Timeout.Infinite)
                    {
                        throw new ArgumentOutOfRangeException(nameof(value), SR.net_io_timeout_use_gt_zero);
                    }
                    SetSocketTimeoutOption(SocketShutdown.Send, value, false);
#if DEBUG
                }
#endif
            }
        }

        // Indicates data is available on the stream to be read.
        // This property checks to see if at least one byte of data is currently available
        public virtual bool DataAvailable
        {
            get
            {
#if DEBUG
                using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
                {
#endif
                    if (_cleanedUp)
                    {
                        throw new ObjectDisposedException(this.GetType().FullName);
                    }

                    // Ask the socket how many bytes are available. If it's
                    // not zero, return true.
                    return _streamSocket.Available != 0;
#if DEBUG
                }
#endif
            }
        }

        // The length of data available on the stream. Always throws NotSupportedException.
        public override long Length
        {
            get
            {
                throw new NotSupportedException(SR.net_noseek);
            }
        }

        // Gets or sets the position in the stream. Always throws NotSupportedException.
        public override long Position
        {
            get
            {
                throw new NotSupportedException(SR.net_noseek);
            }

            set
            {
                throw new NotSupportedException(SR.net_noseek);
            }
        }

        // Seeks a specific position in the stream. This method is not supported by the
        // NetworkStream class.
        public override long Seek(long offset, SeekOrigin origin)
        {
            throw new NotSupportedException(SR.net_noseek);
        }

        // Read - provide core Read functionality.
        //
        // Provide core read functionality. All we do is call through to the
        // socket Receive functionality.
        //
        // Input:
        //
        //     Buffer  - Buffer to read into.
        //     Offset  - Offset into the buffer where we're to read.
        //     Count   - Number of bytes to read.
        //
        // Returns:
        //
        //     Number of bytes we read, or 0 if the socket is closed.
        public override int Read(byte[] buffer, int offset, int size)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
            {
#endif
                bool canRead = CanRead;  // Prevent race with Dispose.
                if (_cleanedUp)
                {
                    throw new ObjectDisposedException(this.GetType().FullName);
                }
                if (!canRead)
                {
                    throw new InvalidOperationException(SR.net_writeonlystream);
                }

                // Validate input parameters.
                if (buffer == null)
                {
                    throw new ArgumentNullException(nameof(buffer));
                }
                if (offset < 0 || offset > buffer.Length)
                {
                    throw new ArgumentOutOfRangeException(nameof(offset));
                }
                if (size < 0 || size > buffer.Length - offset)
                {
                    throw new ArgumentOutOfRangeException(nameof(size));
                }

                try
                {
                    return _streamSocket.Receive(buffer, offset, size, 0);
                }
                catch (Exception exception) when (!(exception is OutOfMemoryException))
                {
                    // Some sort of error occurred on the socket call,
                    // set the SocketException as InnerException and throw.
                    throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
                }
#if DEBUG
            }
#endif
        }

        // Write - provide core Write functionality.
        //
        // Provide core write functionality. All we do is call through to the
        // socket Send method..
        //
        // Input:
        //
        //     Buffer  - Buffer to write from.
        //     Offset  - Offset into the buffer from where we'll start writing.
        //     Count   - Number of bytes to write.
        //
        // Returns:
        //
        //     Number of bytes written. We'll throw an exception if we
        //     can't write everything. It's brutal, but there's no other
        //     way to indicate an error.
        public override void Write(byte[] buffer, int offset, int size)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
            {
#endif
                bool canWrite = CanWrite; // Prevent race with Dispose.
                if (_cleanedUp)
                {
                    throw new ObjectDisposedException(this.GetType().FullName);
                }
                if (!canWrite)
                {
                    throw new InvalidOperationException(SR.net_readonlystream);
                }

                // Validate input parameters.
                if (buffer == null)
                {
                    throw new ArgumentNullException(nameof(buffer));
                }
                if (offset < 0 || offset > buffer.Length)
                {
                    throw new ArgumentOutOfRangeException(nameof(offset));
                }
                if (size < 0 || size > buffer.Length - offset)
                {
                    throw new ArgumentOutOfRangeException(nameof(size));
                }

                try
                {
                    // Since the socket is in blocking mode this will always complete
                    // after ALL the requested number of bytes was transferred.
                    _streamSocket.Send(buffer, offset, size, SocketFlags.None);
                }
                catch (Exception exception) when (!(exception is OutOfMemoryException))
                {
                    // Some sort of error occurred on the socket call,
                    // set the SocketException as InnerException and throw.
                    throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
                }
#if DEBUG
            }
#endif
        }

        private int _closeTimeout = Socket.DefaultCloseTimeout; // -1 = respect linger options

        public void Close(int timeout)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Sync))
            {
#endif
                if (timeout < -1)
                {
                    throw new ArgumentOutOfRangeException(nameof(timeout));
                }
                _closeTimeout = timeout;
                Dispose();
#if DEBUG
            }
#endif
        }
        private volatile bool _cleanedUp = false;
        protected override void Dispose(bool disposing)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
            {
#endif
                // Mark this as disposed before changing anything else.
                bool cleanedUp = _cleanedUp;
                _cleanedUp = true;
                if (!cleanedUp && disposing)
                {
                    // The only resource we need to free is the network stream, since this
                    // is based on the client socket, closing the stream will cause us
                    // to flush the data to the network, close the stream and (in the
                    // NetoworkStream code) close the socket as well.
                    _readable = false;
                    _writeable = false;
                    if (_ownsSocket)
                    {
                        // If we own the Socket (false by default), close it
                        // ignoring possible exceptions (eg: the user told us
                        // that we own the Socket but it closed at some point of time,
                        // here we would get an ObjectDisposedException)
                        _streamSocket.InternalShutdown(SocketShutdown.Both);
                        _streamSocket.Close(_closeTimeout);
                    }
                }
#if DEBUG
            }
#endif
            base.Dispose(disposing);
        }

        ~NetworkStream()
        {
#if DEBUG
            DebugThreadTracking.SetThreadSource(ThreadKinds.Finalization);
#endif
            Dispose(false);
        }

        // BeginRead - provide async read functionality.
        //
        // This method provides async read functionality. All we do is
        // call through to the underlying socket async read.
        //
        // Input:
        //
        //     buffer  - Buffer to read into.
        //     offset  - Offset into the buffer where we're to read.
        //     size   - Number of bytes to read.
        //
        // Returns:
        //
        //     An IASyncResult, representing the read.
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
            {
#endif
                bool canRead = CanRead; // Prevent race with Dispose.
                if (_cleanedUp)
                {
                    throw new ObjectDisposedException(this.GetType().FullName);
                }
                if (!canRead)
                {
                    throw new InvalidOperationException(SR.net_writeonlystream);
                }

                // Validate input parameters.
                if (buffer == null)
                {
                    throw new ArgumentNullException(nameof(buffer));
                }
                if (offset < 0 || offset > buffer.Length)
                {
                    throw new ArgumentOutOfRangeException(nameof(offset));
                }
                if (size < 0 || size > buffer.Length - offset)
                {
                    throw new ArgumentOutOfRangeException(nameof(size));
                }

                try
                {
                    return _streamSocket.BeginReceive(
                            buffer,
                            offset,
                            size,
                            SocketFlags.None,
                            callback,
                            state);
                }
                catch (Exception exception) when (!(exception is OutOfMemoryException))
                {
                    // Some sort of error occurred on the socket call,
                    // set the SocketException as InnerException and throw.
                    throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
                }
#if DEBUG
            }
#endif
        }

        // EndRead - handle the end of an async read.
        //
        // This method is called when an async read is completed. All we
        // do is call through to the core socket EndReceive functionality.
        //
        // Returns:
        //
        //     The number of bytes read. May throw an exception.
        public override int EndRead(IAsyncResult asyncResult)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
            {
#endif
                if (_cleanedUp)
                {
                    throw new ObjectDisposedException(this.GetType().FullName);
                }

                // Validate input parameters.
                if (asyncResult == null)
                {
                    throw new ArgumentNullException(nameof(asyncResult));
                }

                try
                {
                    return _streamSocket.EndReceive(asyncResult);
                }
                catch (Exception exception) when (!(exception is OutOfMemoryException))
                {
                    // Some sort of error occurred on the socket call,
                    // set the SocketException as InnerException and throw.
                    throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
                }
#if DEBUG
            }
#endif
        }

        // BeginWrite - provide async write functionality.
        //
        // This method provides async write functionality. All we do is
        // call through to the underlying socket async send.
        //
        // Input:
        //
        //     buffer  - Buffer to write into.
        //     offset  - Offset into the buffer where we're to write.
        //     size   - Number of bytes to written.
        //
        // Returns:
        //
        //     An IASyncResult, representing the write.
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, Object state)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User | ThreadKinds.Async))
            {
#endif
                bool canWrite = CanWrite; // Prevent race with Dispose.
                if (_cleanedUp)
                {
                    throw new ObjectDisposedException(this.GetType().FullName);
                }
                if (!canWrite)
                {
                    throw new InvalidOperationException(SR.net_readonlystream);
                }

                // Validate input parameters.
                if (buffer == null)
                {
                    throw new ArgumentNullException(nameof(buffer));
                }
                if (offset < 0 || offset > buffer.Length)
                {
                    throw new ArgumentOutOfRangeException(nameof(offset));
                }
                if (size < 0 || size > buffer.Length - offset)
                {
                    throw new ArgumentOutOfRangeException(nameof(size));
                }

                try
                {
                    // Call BeginSend on the Socket.
                    return _streamSocket.BeginSend(
                            buffer,
                            offset,
                            size,
                            SocketFlags.None,
                            callback,
                            state);
                }
                catch (Exception exception) when (!(exception is OutOfMemoryException))
                {
                    // Some sort of error occurred on the socket call,
                    // set the SocketException as InnerException and throw.
                    throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
                }
#if DEBUG
            }
#endif
        }

        // Handle the end of an asynchronous write.
        // This method is called when an async write is completed. All we
        // do is call through to the core socket EndSend functionality.
        // Returns:  The number of bytes read. May throw an exception.
        public override void EndWrite(IAsyncResult asyncResult)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
            {
#endif
                if (_cleanedUp)
                {
                    throw new ObjectDisposedException(this.GetType().FullName);
                }

                // Validate input parameters.
                if (asyncResult == null)
                {
                    throw new ArgumentNullException(nameof(asyncResult));
                }

                try
                {
                    _streamSocket.EndSend(asyncResult);
                }
                catch (Exception exception) when (!(exception is OutOfMemoryException))
                {
                    // Some sort of error occurred on the socket call,
                    // set the SocketException as InnerException and throw.
                    throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
                }
#if DEBUG
            }
#endif
        }

        // ReadAsync - provide async read functionality.
        //
        // This method provides async read functionality. All we do is
        // call through to the Begin/EndRead methods.
        //
        // Input:
        //
        //     buffer            - Buffer to read into.
        //     offset            - Offset into the buffer where we're to read.
        //     size              - Number of bytes to read.
        //     cancellationToken - Token used to request cancellation of the operation
        //
        // Returns:
        //
        //     A Task<int> representing the read.
        public override Task<int> ReadAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken)
        {
            bool canRead = CanRead; // Prevent race with Dispose.
            if (_cleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (!canRead)
            {
                throw new InvalidOperationException(SR.net_writeonlystream);
            }

            // Validate input parameters.
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(offset));
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException(nameof(size));
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled<int>(cancellationToken);
            }

            try
            {
                return _streamSocket.ReceiveAsync(
                    new ArraySegment<byte>(buffer, offset, size),
                    SocketFlags.None,
                    fromNetworkStream: true);
            }
            catch (Exception exception) when (!(exception is OutOfMemoryException))
            {
                // Some sort of error occurred on the socket call,
                // set the SocketException as InnerException and throw.
                throw new IOException(SR.Format(SR.net_io_readfailure, exception.Message), exception);
            }
        }

        // WriteAsync - provide async write functionality.
        //
        // This method provides async write functionality. All we do is
        // call through to the Begin/EndWrite methods.
        //
        // Input:
        //
        //     buffer  - Buffer to write into.
        //     offset  - Offset into the buffer where we're to write.
        //     size    - Number of bytes to write.
        //     cancellationToken - Token used to request cancellation of the operation
        //
        // Returns:
        //
        //     A Task representing the write.
        public override Task WriteAsync(byte[] buffer, int offset, int size, CancellationToken cancellationToken)
        {
            bool canWrite = CanWrite; // Prevent race with Dispose.
            if (_cleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (!canWrite)
            {
                throw new InvalidOperationException(SR.net_readonlystream);
            }

            // Validate input parameters.
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(offset));
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException(nameof(size));
            }

            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled(cancellationToken);
            }

            try
            {
                return _streamSocket.SendAsync(
                    new ArraySegment<byte>(buffer, offset, size),
                    SocketFlags.None,
                    fromNetworkStream: true);
            }
            catch (Exception exception) when (!(exception is OutOfMemoryException))
            {
                // Some sort of error occurred on the socket call,
                // set the SocketException as InnerException and throw.
                throw new IOException(SR.Format(SR.net_io_writefailure, exception.Message), exception);
            }
        }

        public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
        {
            // Validate arguments as would the base CopyToAsync
            StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);

            // And bail early if cancellation has already been requested
            if (cancellationToken.IsCancellationRequested)
            {
                return Task.FromCanceled(cancellationToken);
            }

            // Do the copy.  We get a copy buffer from the shared pool, and we pass both it and the
            // socket into the copy as part of the event args so as to avoid additional fields in
            // the async method's state machine.
            return CopyToAsyncCore(
                destination,
                new AwaitableSocketAsyncEventArgs(_streamSocket, ArrayPool<byte>.Shared.Rent(bufferSize)),
                cancellationToken);
        }

        private static async Task CopyToAsyncCore(Stream destination, AwaitableSocketAsyncEventArgs ea, CancellationToken cancellationToken)
        {
            try
            {
                while (true)
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    int bytesRead = await ea.ReceiveAsync();
                    if (bytesRead == 0)
                    {
                        break;
                    }

                    await destination.WriteAsync(ea.Buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false);
                }
            }
            finally
            {
                ArrayPool<byte>.Shared.Return(ea.Buffer, clearArray: true);
                ea.Dispose();
            }
        }

        // Flushes data from the stream.  This is meaningless for us, so it does nothing.
        public override void Flush()
        {
        }

        public override Task FlushAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        // Sets the length of the stream. Always throws NotSupportedException
        public override void SetLength(long value)
        {
            throw new NotSupportedException(SR.net_noseek);
        }

        private int _currentReadTimeout = -1;
        private int _currentWriteTimeout = -1;
        internal void SetSocketTimeoutOption(SocketShutdown mode, int timeout, bool silent)
        {
            if (NetEventSource.IsEnabled) NetEventSource.Enter(this, mode, timeout, silent);

            if (timeout < 0)
            {
                timeout = 0; // -1 becomes 0 for the winsock stack
            }

            if (mode == SocketShutdown.Send || mode == SocketShutdown.Both)
            {
                if (timeout != _currentWriteTimeout)
                {
                    _streamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, timeout, silent);
                    _currentWriteTimeout = timeout;
                }
            }

            if (mode == SocketShutdown.Receive || mode == SocketShutdown.Both)
            {
                if (timeout != _currentReadTimeout)
                {
                    _streamSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, timeout, silent);
                    _currentReadTimeout = timeout;
                }
            }
        }

        /// <summary>A SocketAsyncEventArgs that can be awaited to get the result of an operation.</summary>
        internal sealed class AwaitableSocketAsyncEventArgs : SocketAsyncEventArgs, ICriticalNotifyCompletion
        {
            /// <summary>Sentinel object used to indicate that the operation has completed prior to OnCompleted being called.</summary>
            private static readonly Action s_completedSentinel = () => { };
            /// <summary>
            /// null if the operation has not completed, <see cref="s_completedSentinel"/> if it has, and another object
            /// if OnCompleted was called before the operation could complete, in which case it's the delegate to invoke
            /// when the operation does complete.
            /// </summary>
            private Action _continuation;

            /// <summary>Initializes the event args.</summary>
            /// <param name="socket">The associated socket.</param>
            /// <param name="buffer">The buffer to use for all operations.</param>
            public AwaitableSocketAsyncEventArgs(Socket socket, byte[] buffer)
            {
                Debug.Assert(socket != null);
                Debug.Assert(buffer != null && buffer.Length > 0);

                // Store the socket into the base's UserToken.  This avoids the need for an extra field, at the expense
                // of an object=>Socket cast when we need to access it, which is only once per operation.
                UserToken = socket;

                // Store the buffer for use by all operations with this instance.
                SetBuffer(buffer, 0, buffer.Length);

                // Hook up the completed event.
                Completed += delegate
                {
                    // When the operation completes, see if OnCompleted was already called to hook up a continuation.
                    // If it was, invoke the continuation.
                    Action c = _continuation;
                    if (c != null)
                    {
                        c();
                    }
                    else
                    {
                        // We may be racing with OnCompleted, so check with synchronization, trying to swap in our
                        // completion sentinel.  If we lose the race and OnCompleted did hook up a continuation,
                        // invoke it.  Otherwise, there's nothing more to be done.
                        Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null)?.Invoke();
                    }
                };
            }

            /// <summary>Initiates a receive operation on the associated socket.</summary>
            /// <returns>This instance.</returns>
            public AwaitableSocketAsyncEventArgs ReceiveAsync()
            {
                if (!Socket.ReceiveAsync(this))
                {
                    _continuation = s_completedSentinel;
                }
                return this;
            }

            /// <summary>Gets this instance.</summary>
            public AwaitableSocketAsyncEventArgs GetAwaiter() => this;

            /// <summary>Gets whether the operation has already completed.</summary>
            /// <remarks>
            /// This is not a generically usable IsCompleted operation that suggests the whole operation has completed.
            /// Rather, it's specifically used as part of the await pattern, and is only usable to determine whether the
            /// operation has completed by the time the instance is awaited.
            /// </remarks>
            public bool IsCompleted => _continuation != null;

            /// <summary>Same as <see cref="OnCompleted(Action)"/> </summary>
            public void UnsafeOnCompleted(Action continuation) => OnCompleted(continuation);

            /// <summary>Queues the provided continuation to be executed once the operation has completed.</summary>
            public void OnCompleted(Action continuation)
            {
                if (ReferenceEquals(_continuation, s_completedSentinel) ||
                    ReferenceEquals(Interlocked.CompareExchange(ref _continuation, continuation, null), s_completedSentinel))
                {
                    Task.Run(continuation);
                }
            }

            /// <summary>Gets the result of the completion operation.</summary>
            /// <returns>Number of bytes transferred.</returns>
            /// <remarks>
            /// Unlike Task's awaiter's GetResult, this does not block until the operation completes: it must only
            /// be used once the operation has completed.  This is handled implicitly by await.
            /// </remarks>
            public int GetResult()
            {
                _continuation = null;
                if (SocketError != SocketError.Success)
                {
                    ThrowIOSocketException();
                }
                return BytesTransferred;
            }

            /// <summary>Gets the associated socket.</summary>
            internal Socket Socket => (Socket)UserToken; // stored in the base's UserToken to avoid an extra field in the object

            /// <summary>Throws an IOException wrapping a SocketException using the current <see cref="SocketError"/>.</summary>
            [MethodImpl(MethodImplOptions.NoInlining)]
            private void ThrowIOSocketException()
            {
                var se = new SocketException((int)SocketError);
                throw new IOException(SR.Format(SR.net_io_readfailure, se.Message), se);
            }
        }
    }
}


text:
__copyright__ = "Copyright 2014, University of Florida"
__license__ = "BSD 3-Clause"

######################################################
#
#
#  Cancel.py module
#       This module looks for 'CANCELED', 'CANCELLED'
#       or other variations and blanks out the form
#       before sending to REDCap.
#
#
######################################################

from form import Form
import re

def run_rules(data):
    """Mandatory function which runs the rules pertaining
        to this module

    """
    form = Form(data)
    for event in form.events():
        for field in event.fields():
            field_value = field.value
            if not field_value:
                continue
            else:
                is_cancelled = False
                is_cancelled = process_field_cancelled_value(field_value)
                if is_cancelled is True:
                    # clear the field value
                    field.clear_value()
                else:
                    continue
    return form

def process_field_cancelled_value(value):
    """This method processes the value in field. It checks
        for the value 'CANCELED' or 'CANCELLED' in the
        <value> tag under the parent <field> tag.
    """
    value = value.strip().lower()
    cancel_match = re.findall(r'cancel[led$]*', value, re.I)
    if not cancel_match:
        return False
    else:
        return True


text:
/*
Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
*/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

 //without counting length, but this get TLE?

 class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if (head == null || head.next == null || n == 0) {
             return head;
        }
        ListNode fast = head;
        ListNode slow = head;
        ListNode newHead;
        for (int i = 0; i < n; i++) {
            if (fast.next == null) {
                fast = head;
            } else {
                fast = fast.next;
            }
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        fast.next = head; //make a "circle"
        newHead = slow.next; //new head since i<n,
        slow.next = null;//tail becomes null
        return newHead;
    }
}

//with counting length and no dummy head

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null)
            return null;
        int size = 1; // since we are already at head node
        ListNode fast=head;
        ListNode slow = head;

        while(fast.next!=null){
            size++;
            fast = fast.next;
        }

        for(int i=size-k%size;i>1;i--) // i>1 because we need to put slow.next at the start.
            slow = slow.next;

        fast.next = head;
        head = slow.next;
        slow.next = null;

        return head;
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package viewer;

import fotos.*;
import verzameling.IFotoVerzameling;
import verzameling.VerzamelingLijst;
import java.net.URL;
import java.util.Comparator;
import java.util.ResourceBundle;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;

/**
 *
 * @author tijmen
 */
public class FotoFrameController implements Initializable {

    @FXML private Button btInlezen;
    @FXML private Button btNieuweFoto;
    @FXML private Button btSortHoogte;
    @FXML private Button btSortBreedte;
    @FXML private Button btSortNaam;
    @FXML private ListView<Foto> lvFotos;
    @FXML private TextField tfSelectedNaam;
    @FXML private TextField tfSelectedHoogte;
    @FXML private TextField tfSelectedBreedte;
    @FXML private TextField tfInputNaam;
    @FXML private TextField tfInputHoogte;
    @FXML private TextField tfInputBreedte;

    private IFotoVerzameling fotos;
    private Comparator<Foto> currentComparator;

    private final ChangeListener<String> integerOnly =
            (observable, oldValue, newValue) -> {
                if (newValue != null && !newValue.equals("") && !newValue.matches("\\d{1,5}"))
                    ((StringProperty) observable).setValue(oldValue);
            };

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        this.fotos = new VerzamelingLijst();
        lvFotos.setItems(fotos.getReadOnlyList());
        lvFotos.getSelectionModel().selectedItemProperty()
                .addListener(this::selectedFotoChanged);

        // Hoogte/Breedte fields should only accept integers
        tfInputHoogte.textProperty().addListener(integerOnly);
        tfInputBreedte.textProperty().addListener(integerOnly);
        //this.handleButtonInlezen(null);
    }

    @FXML private void handleButtonInlezen(ActionEvent event) {
        fotos.add(new Foto(100,50,"zebra2"));
        fotos.add(new Foto(100,505,"paard"));
        fotos.add(new Foto(1000,50,"beer"));
        fotos.add(new Foto(10,50,"stinkdier"));
        fotos.add(new Foto(200,50,"foto5"));
        fotos.add(new Foto(100,150,"foto6"));
        fotos.add(new Foto(100,250,"foto7"));
        fotos.add(new Foto(100,650,"foto8"));
        fotos.add(new Foto(1100,50,"foto9"));
        fotos.add(new Foto(1800,50,"foto10"));
        fotos.add(new Foto(100,50,"foto11"));
        fotos.add(new Foto(100,50,"foto12"));
        fotos.add(new Foto(100,50,"foto13"));
        fotos.add(new Foto(100,50,"foto14"));
        fotos.add(new Foto(100,50,"foto15"));
        fotos.add(new Foto(100,50,"foto16"));
        fotos.add(new Foto(100,50,"foto17"));
        fotos.add(new Foto(100,50,"foto18"));
        fotos.add(new Foto(100,50,"foto19"));
        fotos.add(new Foto(100,50,"foto20"));
        fotos.add(new Foto(100,50,"foto21"));
        fotos.add(new Foto(100,50,"foto22"));
        fotos.add(new Foto(100,50,"foto23"));
        fotos.add(new Foto(100,50,"foto24"));
        fotos.add(new Foto(100,50,"foto25"));
        fotos.add(new Foto(100,50,"foto26"));
        fotos.add(new Foto(100,50,"foto27"));
        fotos.add(new Foto(100,50,"foto28"));
        //TODO
    }

    @FXML private void handleButtonSortNaam(ActionEvent e) {
        this.currentComparator = new NaamComparator();
        this.sortFotos();
    }

    @FXML private void handleButtonSortHoogte(ActionEvent e) {
        this.currentComparator = new HoogteComparator();
        this.sortFotos();
    }

    @FXML private void handleButtonSortBreedte(ActionEvent e) {
        this.currentComparator = new BreedteComparator();
        this.sortFotos();
    }

    @FXML private void handleButtonNieuweFoto(ActionEvent e) {
        String name = tfInputNaam.getText();
        String height = tfInputHoogte.getText();
        String width = tfInputBreedte.getText();

        int iH = 0;
        int iB = 0;

        String errorStr = "De volgende fouten hebben zich voorgedaan:\n";
        boolean error = false;
        if (name.equals("")) {
            error = true;
            errorStr += "- De naam is leeg!\n";
        }
        if (width.equals("") || !this.checkInt(width)) {
            error = true;
            errorStr += "- De breedte moet een getal zijn!\n";
        } else {
            iB = Integer.parseInt(width);
        }

        if (height.equals("") || !this.checkInt(height)) {
            error = true;
            errorStr += "- De hoogte moet een getal zijn!\n";
        } else {
            iH = Integer.parseInt(height);
        }

        // Ga door als alle waarden int zijn
        if (error != true) {
            fotos.add(new Foto(iB, iH, name));
            this.sortFotos();
            tfInputNaam.clear();
            tfInputHoogte.clear();
            tfInputBreedte.clear();

            Alert pop;
            pop = new Alert(Alert.AlertType.INFORMATION); pop.setTitle("Gelukt");

            pop.setHeaderText(null);
            pop.setContentText("Gelukt! Foto " + name + " met afmetingen " + width + "x" + height + "px (bxh) is toegevoegd!");
            pop.showAndWait();

        }
        // indien er fouten zijn, geef aan welke fouten
        else {
            Alert pop;
            pop = new Alert(Alert.AlertType.INFORMATION); pop.setTitle("Oeps!");

            pop.setHeaderText(null);
            pop.setContentText(errorStr);
            pop.showAndWait();
        }
    }

    private void selectedFotoChanged(ObservableValue<? extends Foto> ov, Foto oldFoto, Foto newFoto) {
        if (newFoto != null) {
            tfSelectedNaam.setText("Naam: " + newFoto.getNaam());
            tfSelectedHoogte.setText("Hoogte: " + newFoto.getHoogte().toString());
            tfSelectedBreedte.setText("Breedte: " + newFoto.getBreedte().toString());
        }
    }

    private boolean checkInt(String str)
    {
        try{
            int num = Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private void sortFotos()
    {
        this.fotos.sort(this.currentComparator);
    }
}