text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.redisenterprise.implementation;

import com.azure.core.annotation.ExpectedResponses;
import com.azure.core.annotation.Get;
import com.azure.core.annotation.HeaderParam;
import com.azure.core.annotation.Headers;
import com.azure.core.annotation.Host;
import com.azure.core.annotation.HostParam;
import com.azure.core.annotation.PathParam;
import com.azure.core.annotation.QueryParam;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceInterface;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.annotation.UnexpectedResponseExceptionType;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.RestProxy;
import com.azure.core.management.exception.ManagementException;
import com.azure.core.util.Context;
import com.azure.core.util.FluxUtil;
import com.azure.resourcemanager.redisenterprise.fluent.OperationsStatusClient;
import com.azure.resourcemanager.redisenterprise.fluent.models.OperationStatusInner;
import reactor.core.publisher.Mono;

/** An instance of this class provides access to all the operations defined in OperationsStatusClient. */
public final class OperationsStatusClientImpl implements OperationsStatusClient {
    /** The proxy service used to perform REST calls. */
    private final OperationsStatusService service;

    /** The service client containing this operation class. */
    private final RedisEnterpriseManagementClientImpl client;

    /**
     * Initializes an instance of OperationsStatusClientImpl.
     *
     * @param client the instance of the service client containing this operation class.
     */
    OperationsStatusClientImpl(RedisEnterpriseManagementClientImpl client) {
        this.service =
            RestProxy.create(OperationsStatusService.class, client.getHttpPipeline(), client.getSerializerAdapter());
        this.client = client;
    }

    /**
     * The interface defining all the services for RedisEnterpriseManagementClientOperationsStatus to be used by the
     * proxy service to perform REST calls.
     */
    @Host("{$host}")
    @ServiceInterface(name = "RedisEnterpriseManag")
    private interface OperationsStatusService {
        @Headers({"Content-Type: application/json"})
        @Get(
            "/subscriptions/{subscriptionId}/providers/Microsoft.Cache/locations/{location}/operationsStatus"
                + "/{operationId}")
        @ExpectedResponses({200})
        @UnexpectedResponseExceptionType(ManagementException.class)
        Mono<Response<OperationStatusInner>> get(
            @HostParam("$host") String endpoint,
            @PathParam("location") String location,
            @PathParam("operationId") String operationId,
            @QueryParam("api-version") String apiVersion,
            @PathParam("subscriptionId") String subscriptionId,
            @HeaderParam("Accept") String accept,
            Context context);
    }

    /**
     * Gets the status of operation.
     *
     * @param location The region the operation is in.
     * @param operationId The operation's unique identifier.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the status of operation along with {@link Response} on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<OperationStatusInner>> getWithResponseAsync(String location, String operationId) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (location == null) {
            return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null."));
        }
        if (operationId == null) {
            return Mono.error(new IllegalArgumentException("Parameter operationId is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        return FluxUtil
            .withContext(
                context ->
                    service
                        .get(
                            this.client.getEndpoint(),
                            location,
                            operationId,
                            this.client.getApiVersion(),
                            this.client.getSubscriptionId(),
                            accept,
                            context))
            .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly()));
    }

    /**
     * Gets the status of operation.
     *
     * @param location The region the operation is in.
     * @param operationId The operation's unique identifier.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the status of operation along with {@link Response} on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<Response<OperationStatusInner>> getWithResponseAsync(
        String location, String operationId, Context context) {
        if (this.client.getEndpoint() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getEndpoint() is required and cannot be null."));
        }
        if (location == null) {
            return Mono.error(new IllegalArgumentException("Parameter location is required and cannot be null."));
        }
        if (operationId == null) {
            return Mono.error(new IllegalArgumentException("Parameter operationId is required and cannot be null."));
        }
        if (this.client.getSubscriptionId() == null) {
            return Mono
                .error(
                    new IllegalArgumentException(
                        "Parameter this.client.getSubscriptionId() is required and cannot be null."));
        }
        final String accept = "application/json";
        context = this.client.mergeContext(context);
        return service
            .get(
                this.client.getEndpoint(),
                location,
                operationId,
                this.client.getApiVersion(),
                this.client.getSubscriptionId(),
                accept,
                context);
    }

    /**
     * Gets the status of operation.
     *
     * @param location The region the operation is in.
     * @param operationId The operation's unique identifier.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the status of operation on successful completion of {@link Mono}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    private Mono<OperationStatusInner> getAsync(String location, String operationId) {
        return getWithResponseAsync(location, operationId)
            .flatMap(
                (Response<OperationStatusInner> res) -> {
                    if (res.getValue() != null) {
                        return Mono.just(res.getValue());
                    } else {
                        return Mono.empty();
                    }
                });
    }

    /**
     * Gets the status of operation.
     *
     * @param location The region the operation is in.
     * @param operationId The operation's unique identifier.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the status of operation.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public OperationStatusInner get(String location, String operationId) {
        return getAsync(location, operationId).block();
    }

    /**
     * Gets the status of operation.
     *
     * @param location The region the operation is in.
     * @param operationId The operation's unique identifier.
     * @param context The context to associate with this operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation.
     * @throws ManagementException thrown if the request is rejected by server.
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
     * @return the status of operation along with {@link Response}.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<OperationStatusInner> getWithResponse(String location, String operationId, Context context) {
        return getWithResponseAsync(location, operationId, context).block();
    }
}


text: SELECT 0 as Zero FROM table

redpajama_set_name: RedPajamaGithub


text:
package com.jme3.gde.shadernodedefinition.wizard;

import com.jme3.gde.core.assets.ProjectAssetManager;
import java.awt.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.event.ChangeListener;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ProjectUtils;
import org.netbeans.api.project.SourceGroup;
import org.netbeans.api.project.Sources;
import org.netbeans.api.templates.TemplateRegistration;
import org.netbeans.api.templates.TemplateRegistrations;
import org.netbeans.spi.project.ui.templates.support.Templates;
import org.openide.WizardDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.loaders.DataFolder;
import org.openide.loaders.DataObject;
import org.openide.util.NbBundle.Messages;

// TODO define position attribute
@TemplateRegistrations({
    @TemplateRegistration(folder = "Material", content = "../SNDefTemplate.j3sn", displayName = "Shader Node Definition", iconBase = "com/jme3/gde/core/editor/icons/node.png", description = "./sNDef.html", scriptEngine = "freemarker"),
    @TemplateRegistration(folder = "Material", content = "../ShaderNodeSource", scriptEngine = "freemarker")
})
@Messages("SNDefWizardIterator_displayName=Shader Node Definition")
@SuppressWarnings({"unchecked", "rawtypes"})
public final class SNDefWizardIterator implements WizardDescriptor.InstantiatingIterator<WizardDescriptor> {

    private int index;

    private WizardDescriptor wizard;
    private List<WizardDescriptor.Panel<WizardDescriptor>> panels;

    private List<WizardDescriptor.Panel<WizardDescriptor>> getPanels() {
        if (panels == null) {
            panels = new ArrayList<>();
            // Change to default new file panel and add our panel at bottom
            Project p = Templates.getProject(wizard);
            SourceGroup[] groups = ProjectUtils.getSources(p).getSourceGroups(Sources.TYPE_GENERIC);

            // SimpleTargetChooser is the default new file panel,
            // Add our panel at the bottom
            WizardDescriptor.Panel<WizardDescriptor> advNewFilePanel = Templates.buildSimpleTargetChooser(p, groups).create();
            panels.add(advNewFilePanel);
            panels.add(new SNDefWizardPanel1());
            panels.add(new SNDefWizardPanel2("Inputs"));
            panels.add(new SNDefWizardPanel2("Outputs"));
            String[] steps = createSteps();
            for (int i = 0; i < panels.size(); i++) {
                Component c = panels.get(i).getComponent();
                if (steps[i] == null) {
                    // Default step name to component name of panel. Mainly
                    // useful for getting the name of the target chooser to
                    // appear in the list of steps.
                    steps[i] = c.getName();
                }
                if (c instanceof JComponent) { // assume Swing components
                    JComponent jc = (JComponent) c;
                    jc.putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, i);
                    jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, steps);
                    jc.putClientProperty(WizardDescriptor.PROP_AUTO_WIZARD_STYLE, true);
                    jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DISPLAYED, true);
                    jc.putClientProperty(WizardDescriptor.PROP_CONTENT_NUMBERED, true);
                }
            }
        }
        return panels;
    }

    @Override
    public Set<?> instantiate() throws IOException {

        FileObject createdFile = null;

        // Read Title from wizard
        // String HtmlTitle = (String) wizard.getProperty(SNDefWizardPanel1.TITLE);
        // FreeMarker Template will get its variables from HashMap.
        // HashMap key is the variable name.
        SNDefVisualPanel1 panel1 = ((SNDefWizardPanel1) panels.get(1)).getComponent();
        SNDefVisualPanel2 panel2 = ((SNDefWizardPanel2) panels.get(2)).getComponent();
        SNDefVisualPanel2 panel3 = ((SNDefWizardPanel2) panels.get(3)).getComponent();

        Map args = new HashMap();
        args.put("defName", panel1.getDefName());
        args.put("defType", panel1.getDefType());
        args.put("description", panel1.getDefDescription());
        args.put("inputParams", panel2.getData());
        args.put("outputParams", panel3.getData());

        //Get the template and convert it:
        FileObject tplSnd = Templates.getTemplate(wizard);
        FileObject tplShd = tplSnd.getParent().getChildren()[0];

        DataObject templateSnd = DataObject.find(tplSnd);
        DataObject templateShd = DataObject.find(tplShd);

        //Get the package:
        FileObject dir = Templates.getTargetFolder(wizard);
        DataFolder df = DataFolder.findFolder(dir);

        ProjectAssetManager assetManager = new ProjectAssetManager(Templates.getProject(wizard), "assets");

        //Get the class:
        String targetName = Templates.getTargetName(wizard);
        String shaderName = targetName;
        String ext = ".frag";
        if (panel1.getDefType().equals("Vertex")) {
            ext = ".vert";
        }
        args.put("ext", ext);
        args.put("glslVersions", panel1.getGlslVersions());

        args.put("shaderSnippet", assetManager.getRelativeAssetPath(dir.getPath() + "/" + shaderName));

        //Define the template from the above,
        //passing the package, the file name, and the map of strings to the template:
        // DataObject dobj = templateSnd.createFromTemplate(df, targetName, args);
        for (String ver : panel1.getGlslVersions()) {
            templateShd.createFromTemplate(df, shaderName + ver + ext, args);
        }

        DataObject dobj = templateSnd.createFromTemplate(df, targetName, args);
        //Obtain a FileObject:
        createdFile = dobj.getPrimaryFile();

        // Return the created file.
        return Collections.singleton(createdFile);
    }

    @Override
    public void initialize(WizardDescriptor wizard) {
        this.wizard = wizard;
    }

    @Override
    public void uninitialize(WizardDescriptor wizard) {
        panels = null;
    }

    @Override
    public WizardDescriptor.Panel<WizardDescriptor> current() {
        return getPanels().get(index);
    }

    @Override
    public String name() {
        return index + 1 + ". from " + getPanels().size();
    }

    @Override
    public boolean hasNext() {
        return index < getPanels().size() - 1;
    }

    @Override
    public boolean hasPrevious() {
        return index > 0;
    }

    @Override
    public void nextPanel() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        index++;
    }

    @Override
    public void previousPanel() {
        if (!hasPrevious()) {
            throw new NoSuchElementException();
        }
        index--;
    }

    // If nothing unusual changes in the middle of the wizard, simply:
    @Override
    public void addChangeListener(ChangeListener l) {
    }

    @Override
    public void removeChangeListener(ChangeListener l) {
    }
    // If something changes dynamically (besides moving between panels), e.g.
    // the number of panels changes in response to user input, then use
    // ChangeSupport to implement add/removeChangeListener and call fireChange
    // when needed

    // You could safely ignore this method. Is is here to keep steps which were
    // there before this wizard was instantiated. It should be better handled
    // by NetBeans Wizard API itself rather than needed to be implemented by a
    // client code.
    private String[] createSteps() {
        String[] beforeSteps = (String[]) wizard.getProperty(WizardDescriptor.PROP_CONTENT_DATA);
        assert beforeSteps != null : "This wizard may only be used embedded in the template wizard";
        String[] res = new String[(beforeSteps.length - 1) + panels.size()];
        for (int i = 0; i < res.length; i++) {
            if (i < (beforeSteps.length - 1)) {
                res[i] = beforeSteps[i];
            } else {
                res[i] = panels.get(i - beforeSteps.length + 1).getComponent().getName();
            }
        }
        return res;
    }

}


text:
package com.example.hashtagmediaplayer;

import java.io.File;

import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try
        {
        	//File dir = Environment.getExternalStorageDirectory();
        	//File lMp3 = new File(dir, "Downloads/test.mp3");
	        //Uri lUri = Uri.fromFile(lMp3);
        	//Uri lUri = Uri.parse("file:///sdcard/Downloads/test.mp3");
        	//System.out.println("URI: " + lUri);

	        MediaPlayer lPlayer = new MediaPlayer();
	        lPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
	        //lPlayer.setDataSource(getApplicationContext(), lUri);
	        lPlayer.setDataSource("http://wowimg.zamimg.com/hearthhead/sounds/VO_EX1_323_Play_01.mp3");
	        //lPlayer.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Downloads/test.mp3");
	        lPlayer.prepare();
	        lPlayer.start();
        }
        catch( Exception ex )
        {
        	ex.printStackTrace();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
import os
from setuptools import setup, find_packages
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))

import xadmin_extras as xae

setup(
    name='django-xadmin-extras',
    version=xae.__version__,
    url='https://github.com/jneight/django-xadmin-extras',
    description="Extensions for django-xadmin",
    author=xae.__author__,
    author_email=xae.__email__,
    packages=find_packages(exclude=['tests', 'tests.*',]),
    include_package_data=True,
    license=xae.__license__,
    test_suite="tests",
    zip_safe=False,
)


text:
<?php
namespace Sudoux\MortgageBundle\Command;

use Doctrine\ORM\EntityManager;
use Sudoux\Cms\SiteBundle\Entity\BatchJob;
use Sudoux\Cms\SiteBundle\Entity\BatchJobLog;
use Sudoux\MortgageBundle\Entity\LoanApplication;
use Sudoux\MortgageBundle\Entity\LoanMilestone;

use Sudoux\MortgageBundle\Entity\LoanMilestoneGroup;

use Sudoux\MortgageBundle\DependencyInjection\LosUtil;

use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Sudoux\Cms\SiteBundle\Entity\Site;

/**
 * Class LoanCommand
 * @package Sudoux\MortgageBundle\Command
 * @author Dan Alvare
 */
class LoanCommand extends ContainerAwareCommand
{
    /**
     * @var EntityManager
     */
	protected $em;

    /**
     * @var
     */
	protected $twig;

    /**
     * @var
     */
	protected $logger;

    /**
     * @var OutputInterface
     */
	protected $output;

    /**
     * @var LoanApplication
     */
	protected $loan;

    /**
     * @var LosUtil
     */
	protected $loanUtil;

	/**
	 * @var
	 */
	protected $verbose;

	/**
	 * @var
	 */
	protected $batchJob;

	protected $batchCommand = false;

    protected function configure()
    {
        $this
            ->setName('sudoux:mortgage:loan')
            ->setDescription('Loan Utility')
            ->addArgument('function', InputArgument::REQUIRED)
            ->addOption('loan_id',
            	null,
				InputOption::VALUE_OPTIONAL,
				'The loan ID to process'
			)
			->addOption('document_id',
				null,
				InputOption::VALUE_OPTIONAL,
				'The document ID to process.'
			)
			->addOption('start_date',
				null,
				InputOption::VALUE_OPTIONAL,
				'The start date for bulk processing.'
			)
			->addOption('site_id',
				null,
				InputOption::VALUE_OPTIONAL,
				'The site id for processing.'
			)
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
    	ini_set('memory_limit', -1);
    	set_time_limit(0);

        //$output->writeln('Timezone: ' . date_default_timezone_get());

    	$availableFunctions = array(
    		'upsert_loan_to_los',
    		'upsert_loan_from_los',
    		'delete_loan',
    		'add_document',
    		'update_loans',
    		'delete_loans',
    		'cron',
    		'add_loan_prospects',
    		'upsert_milestones',
			'add_queued_docs'
    	);

    	$function = $input->getArgument('function');

    	if(!in_array($function, $availableFunctions)) {
    		throw new \Exception("Function does not exist");
    	}

    	$this->em = $this->getContainer()->get('doctrine')->getEntityManager();
    	$this->logger = $this->getContainer()->get('logger');
		$this->output = $output;

    	$loanId = $input->getOption('loan_id');
    	if(isset($loanId)) {
			$this->loan = $this->em->getRepository('SudouxMortgageBundle:LoanApplication')->find($loanId);
			if(!isset($this->loan)) {
				throw new \Exception('Loan not found');
			}
    	}

		$this->loanUtil = $this->getContainer()->get('sudoux_mortgage.los_util');

		$batchFunctions = array('update_loans', 'delete_loans', 'cron');
		if(in_array($function, $batchFunctions)) {
			$this->batchCommand = true;
			$this->batchJob = new BatchJob();
			$this->batchJob->setName('Loan Command: ' . $function);
			$this->em->persist($this->batchJob);
			$this->em->flush($this->batchJob);
		}

    	switch($function) {
    		case 'upsert_loan_to_los':
		    	$this->loanUtil->upsertLoanToLos($this->loan);
    			break;
    		case 'upsert_loan_from_los':
		    	$this->loanUtil->upsertLoanFromLos($this->loan);
    			break;
    		case 'delete_loan':
    			$this->loanUtil->deleteLoan($this->loan);
    			break;
    		case 'add_document':
    			$documentId = $input->getOption('document_id');
    			if(!isset($documentId)) {
    				throw new \Exception("add_document method requires the --document_id option");
    			}

				$document = $this->em->getRepository('SudouxMortgageBundle:LoanDocument')->find($documentId);
    			if(!isset($document)) {
    				throw new \Exception("Document not found.");
    			}

    			$response = $this->loanUtil->addDocument($this->loan, $document);
				if($response['success']) {
					$this->output->writeln($response['message']);
				} else {
					$this->output->writeln(sprintf('Adding document %s failed: %s', $document->getId(), $response['message']));
				}

    			break;
    		case 'update_loans':
    			$startDateOption = $input->getOption('start_date');
    			if(!isset($startDateOption)) {
    				throw new \Exception("Start Date must be set");
    			}

    			$startDate = new \DateTime($startDateOption);
                //$startDate->modify('-1 day');
    			//$startDate->setTimezone(new \DateTimeZone("UTC"));

    			$this->processLoans($startDate, 'update');
    			break;
    		case 'delete_loans':
    			$startDateOption = $input->getOption('start_date');
    			if(!isset($startDateOption)) {
    				throw new \Exception("Start Date must be set");
    			}

    			$startDate = new \DateTime($startDateOption);
                //$startDate->modify('-1 day');
    			//$startDate->setTimezone(new \DateTimeZone("UTC"));

    			$this->processLoans('delete', $startDate);
    			break;
    		case 'add_loan_prospects':
    			$this->loanUtil->addProspects($this->loan);
    			break;
			case 'add_queued_docs':

				$startDateOption = $input->getOption('start_date');
				if(!isset($startDateOption)) {
					throw new \Exception("Option --start_date must be set");
				}

				$startDate = new \DateTime($startDateOption);
				//$startDate->modify('-1 day');
				//$startDate->setTimezone(new \DateTimeZone("UTC"));

				$this->processLoans('add_docs', $startDate);
				break;
			case 'upsert_milestones':
				$siteId = $input->getOption('site_id');
				if(!isset($siteId)) {
					throw new \Exception("Option --site_id must be set");
				}

				$site = $this->em->getRepository('SudouxCmsSiteBundle:Site')->find($siteId);

				if(isset($site)) {
					$this->upsertMilestones($site);
				} else {
					throw new \Exception("Site not found with ID: " . $siteId);
				}

				break;
    		case 'cron':

    			$this->processLoans('cron');

    			break;
    	}

		if($this->batchCommand) {
			$completed = new \DateTime();
			$this->batchJob->setCompleted($completed);
			$this->batchJob->setStatus(1);
			$this->em->persist($this->batchJob);
			$this->em->flush($this->batchJob);
		}
    }

    /**
     *
     * @param stringe $mode
     * @param \DateTime $startDate
     * @throws \Exception
     * @throws Exception
     */
    protected function processLoans($mode, \DateTime $startDate = null)
    {
    	$modes = array('update', 'delete', 'cron', 'add_docs');

    	if(!in_array($mode, $modes)) {
    		throw new \Exception("Mode does not exist");
    	}

    	$maxrows = true;
    	$limit = 100;
    	$lastId = 0;

    	while($maxrows) {
	    	try {
	    		$dql = 'SELECT s FROM Sudoux\Cms\SiteBundle\Entity\Site s JOIN s.settings st JOIN st.los l WHERE s.deleted=0 AND s.active=1 AND st.los IS NOT NULL AND l.active=1 AND s.id > :last_id ORDER BY s.id ASC ';
	    		$query = $this->em->createQuery($dql);
	    		$query->setMaxResults($limit);
	    		$query->setParameter('last_id', $lastId);
	    		$sites = $query->getResult();

	    		if(count($sites) > 0) {
		    		foreach($sites as $site) {

		    			$this->output->writeln(sprintf('Processing loans for %s ID:%s', $site->getName(), $site->getId()));
		    			$lastId = $site->getId();

	    				switch($mode) {
	    					case 'update':
					    		if(!isset($startDate)) {
					    			throw new \Exception(sprintf('You must set a start date. %s ID: %s', $site->getName(), $site->getId()));
					    		}
	    						$this->processLoanUpdates($site, $startDate);
	    						break;
	    					case 'delete':
					    		if(!isset($startDate)) {
					    			throw new \Exception(sprintf('You must set a start date. %s ID: %s', $site->getName(), $site->getId()));
					    		}
								$canDeleteLoans = true;
								$losConn = $site->getSettings()->getLos();
								if(isset($losConn)) {
									$canDeleteLoans = $losConn->getAllowLoanDeletions();
								}
								if($canDeleteLoans) {
									$this->processLoanDeletions($site, $startDate);
								}

	    						break;
							case 'add_docs':
								$processDocuments = $site->getSettings()->getMemberPortalDocumentsEnabled();
								if($processDocuments) {
									$this->processLoanDocuments($site);
								}

								break;
	    					case 'cron':

								$lastUpdated = new \DateTime();
								//$lastUpdated->setTimezone(new \DateTimeZone("UTC"));
					    		$losConnection = $site->getSettings()->getLos();
					    		$startDate = $losConnection->getLastUpdated();

					    		if(!isset($startDate)) {
					    			throw new \Exception(sprintf('No start date for %s ID: %s', $site->getName(), $site->getId()));
					    		}

					    		$this->output->writeln('updating milestones');
					    		$this->upsertMilestones($site);
					    		$this->output->writeln('done.');

	    						$this->processLoanUpdates($site, $startDate);
	    						$this->processLoanDeletions($site, $startDate);

								$processDocuments = $site->getSettings()->getMemberPortalDocumentsEnabled();
								if($processDocuments) {
									$this->processLoanDocuments($site);
								}

	    						$losConnection->setLastUpdated($lastUpdated);
	    						$this->em->persist($losConnection);
	    						$this->em->flush($losConnection);

	    						break;
	    				}

		    		}
	    		} else {
	    			$maxrows = false;
	    		}

	    	} catch (\Exception $e) {
	    		$this->logger->crit("Processing Loan Updates Failed: " . $e->getMessage());
	    		throw $e;
	    	}
    	}

    	$this->output->writeln('Loan updates complete!');
    }

    /**
     *
     * @param Site $site
     * @param \DateTime $startDate
     */
    protected function processLoanUpdates(Site $site, \DateTime $startDate)
    {

    	$updatedLoans = $this->loanUtil->getLoans($site, $startDate);
    	$updatedLoanIds = array();
    	if(isset($updatedLoans['loans'])) {
	    	$updatedLoanIds = $updatedLoans['loans'];
    	}

    	if(count($updatedLoanIds) > 0) {
    		$i = 1;
    		foreach($updatedLoanIds as $losId) {

	    		$loan = $this->em->getRepository('SudouxMortgageBundle:LoanApplication')->findByLosIds($losId);
	    		if(isset($loan)) {

					try {
						$this->output->writeln(sprintf('processing loan #%s. LOS ID: %s', $loan->getId(), $losId));
						$this->loanUtil->upsertLoanFromLos($loan);
						$this->output->writeln(sprintf('updated loan: %s of %s loans processed - id: %s', $i, count($updatedLoanIds), $loan->getId()));
					} catch(\Exception $e) {

						$errorMessage = sprintf('updating loan #%s failed', $loan->getId()) . ' | ' . $e->getMessage();

						if($this->batchCommand) {
							$jobLog = new BatchJobLog();
							$jobLog->setStatus(2);
							$jobLog->setBatchJob($this->batchJob);
							$jobLog->setStackTrace($e->getTraceAsString());
							$jobLog->setMessage($errorMessage);
							$this->em->persist($jobLog);
							$this->em->flush($jobLog);
						}

						$this->output->writeln($errorMessage);
						$this->logger->crit($errorMessage);
					}
	    		} else {
	    			$losConn = $site->getSettings()->getLos();
	    			if(isset($losConn)) {
	    				$importLoans = $losConn->getImportLosLoans();
	    				if($importLoans) {
							try {
								$this->output->writeln(sprintf('processing loan with LOS #%s', $losId));
								$this->loanUtil->createLoanFromLos($site, $losId);
								$this->output->writeln(sprintf('created loan: %s of %s loans processed', $i, count($updatedLoanIds)));
							} catch(\Exception $e) {
								$errorMessage = sprintf('adding loan #%s failed', $losId) . $e->getMessage();
								$this->output->writeln($errorMessage);
								$this->logger->crit($errorMessage);

								if($this->batchCommand) {
									$jobLog = new BatchJobLog();
									$jobLog->setStatus(2);
									$jobLog->setBatchJob($this->batchJob);
									$jobLog->setStackTrace($e->getTraceAsString());
									$jobLog->setMessage($errorMessage);
									$this->em->persist($jobLog);
									$this->em->flush($jobLog);
								}
							}

	    				}
	    			}
	    		}
    			$i++;
    		}
			$this->output->writeln('Loan updates complete!');
    	} else {
    		$this->output->writeln("No loans to update.");
    	}
    }

    /**
     *
     * @param Site $site
     * @param \DateTime $startDate
     */
    protected function processLoanDeletions(Site $site, \DateTime $startDate)
    {
    	$deletedLoans = $this->loanUtil->getDeletedLoans($site, $startDate);

    	$deletedLoanIds = array();
    	if(isset($deletedLoans['loans'])) {
    		$deletedLoanIds = $deletedLoans['loans'];
    	}

    	if(count($deletedLoanIds) > 0) {
    		$loans = $this->em->getRepository('SudouxMortgageBundle:LoanApplication')->findByLosIds($deletedLoanIds); // @todo - process in transactions
    		$i = 1;
    		foreach($deletedLoanIds as $losId) {
	    		$loan = $this->em->getRepository('SudouxMortgageBundle:LoanApplication')->findByLosIds($losId);
	    		if(isset($loan)) {
	    			$loan->setDeleted(true);
	    			$this->em->persist($loan);
		    		$this->em->flush();
	    			$this->output->writeln(sprintf('deleting %s of %s loans - id: %s', $i, count($deletedLoanIds), $loan->getId()));
	    			$i++;
	    		}
    		}

    	} else {
    		$this->output->writeln("No loans to delete.");
    	}
    }

    /**
     *
     * @param Site $site
     */
    protected function processLoanDocuments(Site $site)
    {
    	$limit = 100;
    	$offset = 0;
    	$maxrows = true;

    	while($maxrows) {
	    	$docs = $this->em->getRepository('SudouxMortgageBundle:LoanDocument')->findBySiteNotSentToLos($site, $limit, $offset);
    		if(count($docs) > 0) {
    			foreach($docs as $document) {
    				$loan = $document->getLoan()->get(0);
    				if(isset($loan)) { // fixes some bad data from testing
		    			$response = $this->loanUtil->addDocument($loan, $document);

						if(empty($response['success'])) {
							if(empty($response['message'])) {
								$response['message'] = 'No Message';
							}
							print_r($response);
							$this->output->writeln($response['message']);
							$this->logger->crit($response['message']);

							if($this->batchCommand) {
								$message =
								$jobLog = new BatchJobLog();
								$jobLog->setStatus(2);
								$jobLog->setBatchJob($this->batchJob);
								$jobLog->setMessage($response['message']);
								$this->em->persist($jobLog);
								$this->em->flush($jobLog);
							}
						} else {
							$this->output->writeln(sprintf('added document - id: %s', $document->getId()));
						}
    				}
    			}
    			$offset += $limit;
    		} else {
    			$maxrows = false;
    		}
    	}
    }

    /**
     *
     * @param Site $site
     */
    protected function upsertMilestones(Site $site)
    {
		try {
			$losMilestoneGroups = $this->loanUtil->getAllMilestones($site);
			// deactivate all milestone groups first
			$milestoneGroups = $this->em->getRepository('SudouxMortgageBundle:LoanMilestoneGroup')->findAllBySite($site);
			foreach($milestoneGroups as $milestoneGroup) {
				$milestoneGroup->setActive(false);
				$this->em->persist($milestoneGroup);
			}

			$this->em->flush();

			if(array_key_exists('allMilestones', $losMilestoneGroups)) {
				foreach($losMilestoneGroups['allMilestones'] as $losMilestoneGroup) {
					$milestoneGroup = $this->em->getRepository('SudouxMortgageBundle:LoanMilestoneGroup')->findOneByLosId($site, $losMilestoneGroup['ID']);

					if(!isset($milestoneGroup)) {
						$milestoneGroup = new LoanMilestoneGroup();
					}

					$milestoneGroup->setName($losMilestoneGroup['name']);
					$milestoneGroup->setLosId($losMilestoneGroup['ID']);
					$milestoneGroup->setSite($site);
					$milestoneGroup->setActive(true);

					$i=0;
					foreach($losMilestoneGroup['milestones'] as $losMilestone) {
						$milestone = $this->em->getRepository('SudouxMortgageBundle:LoanMilestone')->findOneMilestoneByLosId($site, $losMilestone['ID'], $losMilestoneGroup['ID']);

						if(!isset($milestone)) {
							$milestone = new LoanMilestone();
							$milestoneGroup->addMilestone($milestone);
						}

						$milestone->setLosId($losMilestone['ID']);
						$milestone->setName($losMilestone['name']);
						$milestone->setWeight($i);
						$milestone->setActive(true);
						$milestone->setMilestoneGroup($milestoneGroup);
						$this->em->persist($milestone);
						$i++;
					}

					$this->em->persist($milestoneGroup);
				}

				$this->em->flush();
			}
		} catch(\Exception $e) {
			$this->output->writeln($e->getMessage());
			$this->logger->crit($e->getMessage());

			if($this->batchCommand) {
				$jobLog = new BatchJobLog();
				$jobLog->setStatus(2);
				$jobLog->setBatchJob($this->batchJob);
				$jobLog->setMessage($e->getMessage());
				$jobLog->setStackTrace($e->getTraceAsString());
				$this->em->persist($jobLog);
				$this->em->flush($jobLog);
			}
		}

    }
}


text:
package mail

import (
	"crypto/tls"
	"fmt"
	"io"
	"net"
	"net/smtp"
	"strings"
	"time"
)

// A Dialer is a dialer to an SMTP server.
type Dialer struct {
	// Host represents the host of the SMTP server.
	Host string
	// Port represents the port of the SMTP server.
	Port int
	// Username is the username to use to authenticate to the SMTP server.
	Username string
	// Password is the password to use to authenticate to the SMTP server.
	Password string
	// Auth represents the authentication mechanism used to authenticate to the
	// SMTP server.
	Auth smtp.Auth
	// SSL defines whether an SSL connection is used. It should be false in
	// most cases since the authentication mechanism should use the STARTTLS
	// extension instead.
	SSL bool
	// TLSConfig represents the TLS configuration used for the TLS (when the
	// STARTTLS extension is used) or SSL connection.
	TLSConfig *tls.Config
	// StartTLSPolicy represents the TLS security level required to
	// communicate with the SMTP server.
	//
	// This defaults to OpportunisticStartTLS for backwards compatibility,
	// but we recommend MandatoryStartTLS for all modern SMTP servers.
	//
	// This option has no effect if SSL is set to true.
	StartTLSPolicy StartTLSPolicy
	// LocalName is the hostname sent to the SMTP server with the HELO command.
	// By default, "localhost" is sent.
	LocalName string
	// Timeout to use for read/write operations. Defaults to 10 seconds, can
	// be set to 0 to disable timeouts.
	Timeout time.Duration
	// Whether we should retry mailing if the connection returned an error,
	// defaults to true.
	RetryFailure bool
}

// NewDialer returns a new SMTP Dialer. The given parameters are used to connect
// to the SMTP server.
func NewDialer(host string, port int, username, password string) *Dialer {
	return &Dialer{
		Host:         host,
		Port:         port,
		Username:     username,
		Password:     password,
		SSL:          port == 465,
		Timeout:      10 * time.Second,
		RetryFailure: true,
	}
}

// NewPlainDialer returns a new SMTP Dialer. The given parameters are used to
// connect to the SMTP server.
//
// Deprecated: Use NewDialer instead.
func NewPlainDialer(host string, port int, username, password string) *Dialer {
	return NewDialer(host, port, username, password)
}

// NetDialTimeout specifies the DialTimeout function to establish a connection
// to the SMTP server. This can be used to override dialing in the case that a
// proxy or other special behavior is needed.
var NetDialTimeout = net.DialTimeout

// Dial dials and authenticates to an SMTP server. The returned SendCloser
// should be closed when done using it.
func (d *Dialer) Dial() (SendCloser, error) {
	conn, err := NetDialTimeout("tcp", addr(d.Host, d.Port), d.Timeout)
	if err != nil {
		return nil, err
	}

	if d.SSL {
		conn = tlsClient(conn, d.tlsConfig())
	}

	c, err := smtpNewClient(conn, d.Host)
	if err != nil {
		return nil, err
	}

	if d.Timeout > 0 {
		conn.SetDeadline(time.Now().Add(d.Timeout))
	}

	if d.LocalName != "" {
		if err := c.Hello(d.LocalName); err != nil {
			return nil, err
		}
	}

	if !d.SSL && d.StartTLSPolicy != NoStartTLS {
		ok, _ := c.Extension("STARTTLS")
		if !ok && d.StartTLSPolicy == MandatoryStartTLS {
			err := StartTLSUnsupportedError{
				Policy: d.StartTLSPolicy}
			return nil, err
		}

		if ok {
			if err := c.StartTLS(d.tlsConfig()); err != nil {
				c.Close()
				return nil, err
			}
		}
	}

	if d.Auth == nil && d.Username != "" {
		if ok, auths := c.Extension("AUTH"); ok {
			if strings.Contains(auths, "CRAM-MD5") {
				d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password)
			} else if strings.Contains(auths, "LOGIN") &&
				!strings.Contains(auths, "PLAIN") {
				d.Auth = &loginAuth{
					username: d.Username,
					password: d.Password,
					host:     d.Host,
				}
			} else {
				d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host)
			}
		}
	}

	if d.Auth != nil {
		if err = c.Auth(d.Auth); err != nil {
			c.Close()
			return nil, err
		}
	}

	return &smtpSender{c, conn, d}, nil
}

func (d *Dialer) tlsConfig() *tls.Config {
	if d.TLSConfig == nil {
		return &tls.Config{ServerName: d.Host}
	}
	return d.TLSConfig
}

// StartTLSPolicy constants are valid values for Dialer.StartTLSPolicy.
type StartTLSPolicy int

const (
	// OpportunisticStartTLS means that SMTP transactions are encrypted if
	// STARTTLS is supported by the SMTP server. Otherwise, messages are
	// sent in the clear. This is the default setting.
	OpportunisticStartTLS StartTLSPolicy = iota
	// MandatoryStartTLS means that SMTP transactions must be encrypted.
	// SMTP transactions are aborted unless STARTTLS is supported by the
	// SMTP server.
	MandatoryStartTLS
	// NoStartTLS means encryption is disabled and messages are sent in the
	// clear.
	NoStartTLS = -1
)

func (policy *StartTLSPolicy) String() string {
	switch *policy {
	case OpportunisticStartTLS:
		return "OpportunisticStartTLS"
	case MandatoryStartTLS:
		return "MandatoryStartTLS"
	case NoStartTLS:
		return "NoStartTLS"
	default:
		return fmt.Sprintf("StartTLSPolicy:%v", *policy)
	}
}

// StartTLSUnsupportedError is returned by Dial when connecting to an SMTP
// server that does not support STARTTLS.
type StartTLSUnsupportedError struct {
	Policy StartTLSPolicy
}

func (e StartTLSUnsupportedError) Error() string {
	return "gomail: " + e.Policy.String() + " required, but " +
		"SMTP server does not support STARTTLS"
}

func addr(host string, port int) string {
	return fmt.Sprintf("%s:%d", host, port)
}

// DialAndSend opens a connection to the SMTP server, sends the given emails and
// closes the connection.
func (d *Dialer) DialAndSend(m ...*Message) error {
	s, err := d.Dial()
	if err != nil {
		return err
	}
	defer s.Close()

	return Send(s, m...)
}

type smtpSender struct {
	smtpClient
	conn net.Conn
	d    *Dialer
}

func (c *smtpSender) retryError(err error) bool {
	if !c.d.RetryFailure {
		return false
	}

	if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
		return true
	}

	return err == io.EOF
}

func (c *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
	if c.d.Timeout > 0 {
		c.conn.SetDeadline(time.Now().Add(c.d.Timeout))
	}

	if err := c.Mail(from); err != nil {
		if c.retryError(err) {
			// This is probably due to a timeout, so reconnect and try again.
			sc, derr := c.d.Dial()
			if derr == nil {
				if s, ok := sc.(*smtpSender); ok {
					*c = *s
					return c.Send(from, to, msg)
				}
			}
		}

		return err
	}

	for _, addr := range to {
		if err := c.Rcpt(addr); err != nil {
			return err
		}
	}

	w, err := c.Data()
	if err != nil {
		return err
	}

	if _, err = msg.WriteTo(w); err != nil {
		w.Close()
		return err
	}

	return w.Close()
}

func (c *smtpSender) Close() error {
	return c.Quit()
}

// Stubbed out for tests.
var (
	tlsClient     = tls.Client
	smtpNewClient = func(conn net.Conn, host string) (smtpClient, error) {
		return smtp.NewClient(conn, host)
	}
)

type smtpClient interface {
	Hello(string) error
	Extension(string) (bool, string)
	StartTLS(*tls.Config) error
	Auth(smtp.Auth) error
	Mail(string) error
	Rcpt(string) error
	Data() (io.WriteCloser, error)
	Quit() error
	Close() error
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Threading.Tasks;
using AH.DUtility;
using AH.ModuleController.HRSR;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using AH.ModuleController.UI.HR.Reports.Viewer;

namespace AH.ModuleController.UI.HR.Forms
{
    public partial class frmLeaveApproved : AH.Shared.UI.frmSmartFormStandard
    {
        HRSR.HRWSClient hmsSC = new HRSR.HRWSClient();
        public Boolean Chk;

        public string ApprovedByRprPrsn { set; get; }
        public string ApprovedByRprPrsnName { set; get; }
        public string ApprovedByHead { set; get; }
        public string ApprovedByHeadName { set; get; }
        public string ApprovedByHR { set; get; }
        public string ApprovedByHRName { set; get; }
        public string EmpId { set; get; }
        public string LeaveTypeId { set; get; }
        public string LeaveSerial { set; get; }
        public string Flag { set; get; }
        private short CallMode;

        public frmLeaveApproved()
        {
            InitializeComponent();
        }

        private void frmLeaveApprovedByHead_Load(object sender, EventArgs e)
        {
            cboCancelCauseRpt.DisplayMember = "Value";
            cboCancelCauseRpt.ValueMember = "Key";
            cboCancelCauseRpt.DataSource = new BindingSource(hmsSC.GetLvCanCause("D"), null);

            cboCancelCauseHead.DisplayMember = "Value";
            cboCancelCauseHead.ValueMember = "Key";
            cboCancelCauseHead.DataSource = new BindingSource(hmsSC.GetLvCanCause("D"), null);

            cboCancelCauseHR.DisplayMember = "Value";
            cboCancelCauseHR.ValueMember = "Key";
            cboCancelCauseHR.DataSource = new BindingSource(hmsSC.GetLvCanCause("D"), null);

            cboYear.DisplayMember = "Value";
            cboYear.ValueMember = "Key";
            cboYear.DataSource = new BindingSource(Utility.GetNumbers(2010, 2030), null);
            cboYear.Text = DateTime.Now.ToString("yyyy");

            cboLeaveType.DisplayMember = "Value";
            cboLeaveType.ValueMember = "Key";
            cboLeaveType.DataSource = new BindingSource(hmsSC.GetLeaveID(cboYear.SelectedValue.ToString()), null);

            cboLeaveCause.DisplayMember = "Value";
            cboLeaveCause.ValueMember = "Key";
            cboLeaveCause.DataSource = new BindingSource(Utility.GetLeaveCauses(), null);

            ModeSelector();
        }
        private void ModeSelector()
        {
            EmpLeaveRegister oEmp = new EmpLeaveRegister();
            oEmp = hmsSC.GetLeaveReg(EmpId, LeaveTypeId, LeaveSerial);
            if (EmpId == null)
            {
                return;
            }
            if (EmpId != null)
            {
                if (oEmp.ReptPrsnAppFlag == "0")
                {
                    pnlHead.Enabled = false;
                    pnlHR.Enabled = false;
                    CallMode = 1;
                    txtEmp.Text = EmpId;
                    cboLeaveType.SelectedValue = oEmp.LeaveType.TypeID;
                    cboYear.Text = oEmp.year;
                    cboLeaveCause.SelectedValue = oEmp.LeaveCauseFlag;
                    txtResponsibility.Text = oEmp.ResponsibilityHolderID;
                    txtStartDate.Text = oEmp.StartDate.ToString();
                    txtEndDate.Text = oEmp.EndDate.ToString();
                    txtAddress.Text = oEmp.AddrtessWhileOnLeave.ToString();
                    txtApprovedByRpt.Text = ApprovedByRprPrsn;
                    txtserial.Text = LeaveSerial;
                    txtResponsibilityHolderName.Text = oEmp.ResponsibilityHolderName;
                    txtEmpName.Text = oEmp.EmployeeMaster.Name;
                    txtApprvdByRptName.Text = ApprovedByRprPrsnName;
                    txtTotalDays.Text = oEmp.LeaveDays.ToString();
                    txtLeaveWithPay.Text = oEmp.WithPayDays.ToString();
                    txtLeaveWithoutpay.Text = oEmp.WithoutPayDays.ToString();
                }
                if (oEmp.DeptAppFlag == "0" && oEmp.ReptPrsnAppFlag == "1")
                {
                    pnlRptPrsn.Enabled = false;
                    pnlHR.Enabled = false;
                    CallMode = 2;
                    txtEmp.Text = EmpId;
                    cboLeaveType.SelectedValue = oEmp.LeaveType.TypeID;
                    cboYear.Text = oEmp.year;
                    cboLeaveCause.SelectedValue = oEmp.LeaveCauseFlag;
                    txtResponsibility.Text = oEmp.ResponsibilityHolderID;
                    txtStartDate.Text = oEmp.StartDate.ToString();
                    txtEndDate.Text = oEmp.EndDate.ToString();
                    txtAddress.Text = oEmp.AddrtessWhileOnLeave.ToString();
                    txtApprovedByHead.Text = ApprovedByHead;
                    txtserial.Text = LeaveSerial;
                    txtResponsibilityHolderName.Text = oEmp.ResponsibilityHolderName;
                    txtEmpName.Text = oEmp.EmployeeMaster.Name;
                    txtApprovedByRpt.Text = oEmp.ReportingPersonID.ToString();
                    txtApprvdByRptName.Text = oEmp.ReportingPersonName.ToString();
                    txtApprovedByHeadName.Text = ApprovedByHeadName;
                    txtTotalDays.Text = oEmp.LeaveDays.ToString();
                    txtLeaveWithPay.Text = oEmp.WithPayDays.ToString();
                    txtLeaveWithoutpay.Text = oEmp.WithoutPayDays.ToString();
                    if (Convert.ToInt16(oEmp.ReptPrsnAppFlag) == 1)
                    {
                        chkAppRptYes.Checked = true;
                        chkAppRptNo.Checked = false;
                        cboCancelCauseRpt.Enabled = false;
                        btnAddCancelCauseRpt.Enabled = false;
                        btnRefreshCancelCauseRptPrsn.Enabled = false;
                    }
                    else
                    {
                        chkAppRptYes.Checked = false;
                        chkAppRptNo.Checked = true;
                        cboCancelCauseRpt.Enabled = true;
                        btnAddCancelCauseRpt.Enabled = true;
                        btnRefreshCancelCauseRptPrsn.Enabled = true;
                    }
                }
                if (oEmp.ReptPrsnAppFlag == "1" && oEmp.DeptAppFlag == "1")
                {
                    pnlRptPrsn.Enabled = false;
                    pnlHead.Enabled = false;
                    txtStartDate.ReadOnly = true;
                    txtEndDate.ReadOnly = true;
                    txtResponsibilityHolderName.ReadOnly = true;
                    txtAddress.ReadOnly = true;
                    txtEmpName.ReadOnly = true;
                    CallMode = 3;
                    txtEmp.Text = EmpId;
                    cboLeaveType.SelectedValue = oEmp.LeaveType.TypeID;
                    cboYear.Text = oEmp.year;
                    cboLeaveCause.SelectedValue = oEmp.LeaveCauseFlag;
                    txtResponsibility.Text = oEmp.ResponsibilityHolderID;
                    txtStartDate.Text = oEmp.StartDate.ToString();
                    txtEndDate.Text = oEmp.EndDate.ToString();
                    txtAddress.Text = oEmp.AddrtessWhileOnLeave.ToString();
                    txtApprovedByRpt.Text = oEmp.ReportingPersonID.ToString();
                    txtApprvdByRptName.Text = oEmp.ReportingPersonName.ToString();
                    txtApprovedByHead.Text = oEmp.ApprovedByID.ToString();
                    txtApprovedByHeadName.Text = oEmp.ApprovedByName.ToString();
                    txtTotalDays.Text = oEmp.LeaveDays.ToString();
                    txtLeaveWithPay.Text = oEmp.WithPayDays.ToString();
                    txtLeaveWithoutpay.Text = oEmp.WithoutPayDays.ToString();

                    if (Convert.ToInt16(oEmp.ReptPrsnAppFlag) == 1)
                    {
                        chkAppRptYes.Checked = true;
                        chkAppRptNo.Checked = false;
                        cboCancelCauseRpt.Enabled = false;
                        btnAddCancelCauseRpt.Enabled = false;
                        btnRefreshCancelCauseRptPrsn.Enabled = false;
                    }
                    else
                    {
                        chkAppRptYes.Checked = false;
                        chkAppRptNo.Checked = true;
                        cboCancelCauseRpt.Enabled = true;
                        btnAddCancelCauseRpt.Enabled = true;
                        btnRefreshCancelCauseRptPrsn.Enabled = true;
                    }

                    if (Convert.ToInt16(oEmp.DeptAppFlag) == 1)
                    {
                        chkAppHeadYes.Checked = true;
                        chkAppHeadNo.Checked = false;
                        cboCancelCauseHead.Enabled = false;
                        btnAddCauseHD.Enabled = false;
                        btnRefreshCauseHD.Enabled = false;
                    }
                    else
                    {
                        chkAppHeadYes.Checked = false;
                        chkAppHeadNo.Checked = true;
                        cboCancelCauseHead.Enabled = true;
                        btnAddCauseHD.Enabled = true;
                        btnRefreshCauseHD.Enabled = true;
                    }

                    txtRemarksHead.Text = oEmp.Remarks.ToString();
                    cboCancelCauseHead.Text = oEmp.CancelCauseID;
                    cboCancelCauseRpt.Text = oEmp.CancelCauseRptPrsn;

                    txtApprovedByHR.Text = ApprovedByHR;
                    txtserial.Text = LeaveSerial;
                    txtResponsibilityHolderName.Text = oEmp.ResponsibilityHolderName;
                    txtEmpName.Text = oEmp.EmployeeMaster.Name;
                    txtApprovedByHRName.Text = ApprovedByHRName;
                }
            }
        }

        private void chkAppHead_Click(object sender, EventArgs e)
        {
            if (chkAppHeadYes.Checked == true)
            {
                chkAppHeadNo.Checked = false;
                lblCancelCauseHd.Enabled = false;
                cboCancelCauseHead.Enabled = false;
            }
            else
            {
                chkAppHeadNo.Checked = true;
                chkAppHeadYes.Checked = false;
                lblCancelCauseHd.Enabled = true;
                cboCancelCauseHead.Enabled = true;
            }
        }

        private EmpLeaveRegister UpdateLeaveRegister()
        {
            EmpLeaveRegister oEmpLeaveRegis = new EmpLeaveRegister();

            EmployeeMaster oEmpMas = new EmployeeMaster();
            EmployeeMaster oEmpMaster = new EmployeeMaster();
            oEmpMas = hmsSC.GetEmpMaster(txtEmp.Text);
            oEmpMaster = hmsSC.GetEmpMaster(Utility.UserId);

            if (txtEmp.Text == oEmpMas.EmpId)
            {
                txtTO.Text = oEmpMas.Email.ToString();
                txtFrom.Text = oEmpMaster.Email.ToString();

                if (CallMode == 1)
                {
                    oEmpLeaveRegis.Mode = "1";
                    oEmpMas.EmpId = txtEmp.Text;
                    oEmpLeaveRegis.EmployeeMaster = oEmpMas;
                    oEmpLeaveRegis.year = cboYear.SelectedValue.ToString();
                    oEmpLeaveRegis.Serial = txtserial.Text.ToString();
                    oEmpLeaveRegis.WithPayDays =Convert.ToDouble(txtLeaveWithPay.Text.ToString());
                    oEmpLeaveRegis.WithoutPayDays = Convert.ToDouble(txtLeaveWithoutpay.Text.ToString());

                    LeaveType oLvTp = new LeaveType();
                    oLvTp.TypeID = cboLeaveType.SelectedValue.ToString();
                    oEmpLeaveRegis.LeaveType = oLvTp;

                    if (txtStartDate.Text != "  /  /")
                    {
                        oEmpLeaveRegis.StartDate = DateTime.ParseExact(txtStartDate.Text, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));
                    }
                    else
                    {
                        oEmpLeaveRegis.StartDate = null;
                    }
                    if (txtEndDate.Text != "  /  /")
                    {
                        oEmpLeaveRegis.EndDate = DateTime.ParseExact(txtEndDate.Text, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));
                    }
                    else
                    {
                        oEmpLeaveRegis.EndDate = null;
                    }
                    oEmpLeaveRegis.LeaveCauseFlag = cboLeaveCause.SelectedValue.ToString();
                    oEmpLeaveRegis.AddrtessWhileOnLeave = txtAddress.Text;
                    oEmpLeaveRegis.ResponsibilityHolderID = txtResponsibility.Text.ToString();
                    oEmpLeaveRegis.ReportingPersonID = txtApprovedByRpt.Text.ToString();
                    if (chkAppRptYes.Checked == true)
                    {
                        oEmpLeaveRegis.ReptPrsnAppFlag = "1";
                        oEmpLeaveRegis.CancelCauseRptPrsn = "";
                    }
                    if (chkAppRptNo.Checked == true)
                    {
                        oEmpLeaveRegis.ReptPrsnAppFlag = "0";
                        oEmpLeaveRegis.CancelCauseRptPrsn = cboCancelCauseRpt.SelectedValue.ToString();
                    }
                    oEmpLeaveRegis.ApprovedByID = "";
                    oEmpLeaveRegis.DeptAppFlag = "0";
                    oEmpLeaveRegis.CancelCauseID = "";
                    oEmpLeaveRegis.Remarks = "";
                    oEmpLeaveRegis.ApprovedByHR = "";
                    oEmpLeaveRegis.HrAppFlag = "0";
                    oEmpLeaveRegis.NotificationFlag = "0";
                    oEmpLeaveRegis.CancelCauseIDHr = "";
                    oEmpLeaveRegis.RemarksHR = " ";
                }

                if (CallMode == 2)
                {
                    oEmpLeaveRegis.Mode = "2";
                    oEmpMas.EmpId = txtEmp.Text;
                    oEmpLeaveRegis.EmployeeMaster = oEmpMas;
                    oEmpLeaveRegis.year = cboYear.SelectedValue.ToString();
                    oEmpLeaveRegis.Serial = txtserial.Text.ToString();
                    oEmpLeaveRegis.WithPayDays = Convert.ToDouble(txtLeaveWithPay.Text.ToString());
                    oEmpLeaveRegis.WithoutPayDays = Convert.ToDouble(txtLeaveWithoutpay.Text.ToString());

                    LeaveType oLvTp = new LeaveType();
                    oLvTp.TypeID = cboLeaveType.SelectedValue.ToString();
                    oEmpLeaveRegis.LeaveType = oLvTp;

                    if (txtStartDate.Text != "  /  /")
                    {
                        oEmpLeaveRegis.StartDate = DateTime.ParseExact(txtStartDate.Text, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));
                    }
                    else
                    {
                        oEmpLeaveRegis.StartDate = null;
                    }
                    if (txtEndDate.Text != "  /  /")
                    {
                        oEmpLeaveRegis.EndDate = DateTime.ParseExact(txtEndDate.Text, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));
                    }
                    else
                    {
                        oEmpLeaveRegis.EndDate = null;
                    }
                    oEmpLeaveRegis.LeaveCauseFlag = cboLeaveCause.SelectedValue.ToString();
                    oEmpLeaveRegis.AddrtessWhileOnLeave = txtAddress.Text;
                    oEmpLeaveRegis.ResponsibilityHolderID = txtResponsibility.Text.ToString();
                    oEmpLeaveRegis.ReportingPersonID = txtRemarksRptPrsn.Text.ToString();
                    if (chkAppRptYes.Checked == true)
                    {
                        oEmpLeaveRegis.ReptPrsnAppFlag = "1";
                        oEmpLeaveRegis.CancelCauseRptPrsn = "";
                    }
                    if (chkAppRptYes.Checked == false)
                    {
                        oEmpLeaveRegis.DeptAppFlag = "0";
                        oEmpLeaveRegis.CancelCauseRptPrsn = cboCancelCauseRpt.SelectedValue.ToString();
                    }

                    oEmpLeaveRegis.ApprovedByID = txtApprovedByHead.Text.ToString();
                    if (chkAppHeadYes.Checked == true)
                    {
                        oEmpLeaveRegis.DeptAppFlag = "1";
                        oEmpLeaveRegis.CancelCauseID = "";
                    }
                    if (chkAppHeadYes.Checked == false)
                    {
                        oEmpLeaveRegis.DeptAppFlag = "0";
                        oEmpLeaveRegis.CancelCauseID = cboCancelCauseHead.SelectedValue.ToString();
                    }
                    oEmpLeaveRegis.Remarks = txtRemarksHead.Text.ToString();

                    oEmpLeaveRegis.ApprovedByHR = "";
                    oEmpLeaveRegis.HrAppFlag = "0";
                    oEmpLeaveRegis.NotificationFlag = "0";
                    oEmpLeaveRegis.CancelCauseIDHr = "";
                    oEmpLeaveRegis.RemarksHR = " ";
                }
                if (CallMode == 3)
                {
                    oEmpLeaveRegis.Mode = "3";
                    oEmpMas.EmpId = txtEmp.Text;
                    oEmpLeaveRegis.EmployeeMaster = oEmpMas;
                    oEmpLeaveRegis.year = cboYear.SelectedValue.ToString();
                    oEmpLeaveRegis.Serial = txtserial.Text.ToString();
                    oEmpLeaveRegis.WithPayDays = Convert.ToDouble(txtLeaveWithPay.Text.ToString());
                    oEmpLeaveRegis.WithoutPayDays = Convert.ToDouble(txtLeaveWithoutpay.Text.ToString());

                    LeaveType oLvTp = new LeaveType();
                    oLvTp.TypeID = cboLeaveType.SelectedValue.ToString();
                    oEmpLeaveRegis.LeaveType = oLvTp;

                    if (txtStartDate.Text != "  /  /")
                    {
                        oEmpLeaveRegis.StartDate = DateTime.ParseExact(txtStartDate.Text, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));
                    }
                    else
                    {
                        oEmpLeaveRegis.StartDate = null;
                    }
                    if (txtEndDate.Text != "  /  /")
                    {
                        oEmpLeaveRegis.EndDate = DateTime.ParseExact(txtEndDate.Text, "dd/MM/yyyy", new System.Globalization.CultureInfo("en-GB"));
                    }
                    else
                    {
                        oEmpLeaveRegis.EndDate = null;
                    }
                    oEmpLeaveRegis.LeaveCauseFlag = cboLeaveCause.SelectedValue.ToString();
                    oEmpLeaveRegis.AddrtessWhileOnLeave = txtAddress.Text;
                    oEmpLeaveRegis.ResponsibilityHolderID = txtResponsibility.Text.ToString();
                    oEmpLeaveRegis.ReportingPersonID = txtApprovedByRpt.Text.ToString();
                    oEmpLeaveRegis.ApprovedByID = txtApprovedByHead.Text.ToString();

                    if (chkAppRptYes.Checked == true)
                    {
                        oEmpLeaveRegis.ReptPrsnAppFlag = "1";
                        oEmpLeaveRegis.CancelCauseRptPrsn = "";
                    }
                    if (chkAppRptYes.Checked == false)
                    {
                        oEmpLeaveRegis.DeptAppFlag = "0";
                        oEmpLeaveRegis.CancelCauseRptPrsn = cboCancelCauseRpt.SelectedValue.ToString();
                    }

                    if (chkAppHeadYes.Checked == true)
                    {
                        oEmpLeaveRegis.DeptAppFlag = "1";
                        oEmpLeaveRegis.CancelCauseID = "0";
                    }
                    if (chkAppHeadYes.Checked == false)
                    {
                        oEmpLeaveRegis.DeptAppFlag = "0";
                        oEmpLeaveRegis.CancelCauseID = cboCancelCauseHead.SelectedValue.ToString();
                    }

                    oEmpLeaveRegis.Remarks = txtRemarksHead.Text.ToString();

                    oEmpLeaveRegis.ApprovedByHR = txtApprovedByHR.Text.ToString();
                    if (chkAppHRYes.Checked == true)
                    {
                        oEmpLeaveRegis.HrAppFlag = "1";
                        oEmpLeaveRegis.CancelCauseIDHr = "0";
                    }
                    else
                    {
                        oEmpLeaveRegis.HrAppFlag = "0";
                        oEmpLeaveRegis.CancelCauseIDHr = cboCancelCauseHR.SelectedValue.ToString();
                    }
                    oEmpLeaveRegis.NotificationFlag = "0";
                    oEmpLeaveRegis.RemarksHR = txtRemarksHR.Text.ToString();
                }
                oEmpLeaveRegis.LeaveDocPath = "C";
                oEmpLeaveRegis.MailTO = txtTO.Text.ToString();
                oEmpLeaveRegis.MailFrom = txtFrom.Text.ToString();

                EntryParameter ep = new EntryParameter();
                ep.CompanyID = Utility.CompanyID;
                ep.EntryBy = Utility.UserId;
                ep.UpdateBy = Utility.UserId;
                ep.LocationID = Utility.LocationID;
                ep.MachineID = Utility.MachineID;
                oEmpLeaveRegis.EntryParameter = ep;

            }
            else
            {
                MessageBox.Show("Invalid Employee ID", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            return oEmpLeaveRegis;

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            List<string> vf = new List<string>() { "cboYear", "txtEmpName", "cboLeaveType", "txtStartDate", "txtEndDate", "cboLeaveCause", "txtResponsibilityHolderName", "txtAddress" };
            Control control = Utility.ReqFieldValidator(this, vf);
            if (control != null)
            {
                MessageBox.Show(Utility.getFMS(control.Name) + Utility.Req, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                control.Focus();
                return;
            }

            if (CallMode == 1)
            {
                if (chkAppRptYes.Checked == false && chkAppRptNo.Checked == false)
                {
                    MessageBox.Show("Please Select Approval Type", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (chkAppRptNo.Checked == true)
                {
                    if (cboCancelCauseRpt.SelectedValue == "")
                    {
                        MessageBox.Show("Please Select a Cancel Cause", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        cboCancelCauseRpt.Focus();
                        return;
                    }
                }
            }

            if (CallMode == 2)
            {
                if (chkAppHeadYes.Checked == false && chkAppHeadNo.Checked==false)
                {
                    MessageBox.Show("Please Select Approval Type", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (chkAppHeadNo.Checked==true)
                {
                    if(cboCancelCauseHead.SelectedValue =="")
                    {
                        MessageBox.Show("Please Select a Cancel Cause", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        cboCancelCauseHead.Focus();
                        return;
                    }
                }
            }
            if (CallMode == 3)
            {
                if (chkAppHRYes.Checked == false && chkAppHRNo.Checked == false)
                {
                    MessageBox.Show("Please Select Approval Type", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (chkAppHRNo.Checked == true)
                {
                    if (cboCancelCauseHR.SelectedValue == "")
                    {
                        MessageBox.Show("Please Select a Cancel Cause", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        cboCancelCauseHR.Focus();
                        return;
                    }
                }
            }

            try
            {
                EmpLeaveRegister oEmpLeaveRegis = this.UpdateLeaveRegister();
                if ((Convert.ToDouble(txtLeaveWithPay.Text.ToString()) + Convert.ToDouble(txtLeaveWithoutpay.Text.ToString())) != Convert.ToDouble(txtTotalDays.Text.ToString()))
                {
                    MessageBox.Show("Please Correct Leave Days!!!", Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    short i = hmsSC.UpdateLeaveRegister(oEmpLeaveRegis);
                    if (i == 0)
                    {
                        MessageBox.Show(Utility.MistakeMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    else if (i > 0)
                    {
                        MessageBox.Show(Utility.UpdateMsg, Utility.MessageSuccessCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                        btnClose.PerformClick();
                    }

                }
            }

            catch (System.ServiceModel.CommunicationException commp)
            {
                MessageBox.Show(Utility.CommunicationErrorMsg, Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Utility.MessageCaptionMsg, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }
        private void chkAppHRYes_Click(object sender, EventArgs e)
        {
            if (chkAppHRYes.Checked == true)
            {
                chkAppHRNo.Enabled = false;
                lblCancelCauseHR.Enabled = false;
                cboCancelCauseHR.Enabled = false;
            }
            else
            {
                lblCancelCauseHR.Enabled = true;
                chkAppHRYes.Enabled = false;
                cboCancelCauseHR.Enabled = true;
                chkAppHRNo.Enabled = true;
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            EmpId= "";
        }
        private void btnAddCauseHD_Click(object sender, EventArgs e)
        {
            frmLeaveCancelCause oCancelCause = new frmLeaveCancelCause();
            oCancelCause.ShowDialog();
        }

        private void btnRefreshCauseHD_Click(object sender, EventArgs e)
        {
            cboCancelCauseHead.DisplayMember = "Value";
            cboCancelCauseHead.ValueMember = "Key";
            cboCancelCauseHead.DataSource = new BindingSource(hmsSC.GetLvCanCause("D"), null);
        }

        private void btnAddCauseHR_Click(object sender, EventArgs e)
        {
            frmLeaveCancelCause oCancelCause = new frmLeaveCancelCause();
            oCancelCause.ShowDialog();
        }

        private void btnRefreshCauseHR_Click(object sender, EventArgs e)
        {
            cboCancelCauseHR.DisplayMember = "Value";
            cboCancelCauseHR.ValueMember = "Key";
            cboCancelCauseHR.DataSource = new BindingSource(hmsSC.GetLvCanCause("D"), null);
        }

        private void chkAppHeadNo_Click(object sender, EventArgs e)
        {
            if (chkAppHeadNo.Checked == true)
            {
                chkAppHeadYes.Checked = false;
                lblCancelCauseHd.Enabled = true;
                cboCancelCauseHead.Enabled = true;
            }
        }

        private void chkAppHRNo_Click(object sender, EventArgs e)
        {
            if (chkAppHRNo.Checked == true)
            {
                chkAppHRYes.Checked = false;
                lblCancelCauseHR.Enabled = true;
                lblCancelCauseHR.Enabled = true;
            }
        }

        private void btnAddCancelCauseRpt_Click(object sender, EventArgs e)
        {
            frmLeaveCancelCause oCancelCause = new frmLeaveCancelCause();
            oCancelCause.ShowDialog();
        }
        private void btnRefreshCancelCauseRptPrsn_Click(object sender, EventArgs e)
        {
            cboCancelCauseRpt.DisplayMember = "Value";
            cboCancelCauseRpt.ValueMember = "Key";
            cboCancelCauseRpt.DataSource = new BindingSource(hmsSC.GetLvCanCause("D"), null);
        }

        private void chkAppRptYes_Click(object sender, EventArgs e)
        {
            if (chkAppRptYes.Checked == true)
            {
                chkAppRptNo.Checked = false;
                cboCancelCauseRpt.Enabled = false;
                lblCancelCauseRpt.Enabled = false;
            }
            else
            {
                chkAppRptNo.Checked = true;
                cboCancelCauseRpt.Enabled = true;
                lblCancelCauseRpt.Enabled = true;
            }
        }

        private void chkAppRptNo_Click(object sender, EventArgs e)
        {
            if (chkAppRptNo.Checked == true)
            {
                chkAppRptYes.Checked = false;
                cboCancelCauseRpt.Enabled = true;
                lblCancelCauseRpt.Enabled = true;
            }
            else
            {
                chkAppRptYes.Checked = true;
                cboCancelCauseRpt.Enabled = false;
                lblCancelCauseRpt.Enabled = false;
            }
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Silverlight.Testing;

namespace Mindbox.Expressions.Tests
{
	public partial class App : Application
	{

		public App()
		{
			this.Startup += this.Application_Startup;

			InitializeComponent();
		}

		private void Application_Startup(object sender, StartupEventArgs e)
		{
			this.RootVisual = UnitTestSystem.CreateTestPage();
		}
	}
}


text:
/***
* Inferno Engine v4 2015-2017
* Written by Tomasz "Rex Dex" Jonarski
*
* [# filter: pass #]
***/

#pragma once

#include "renderingFragmentHandler.h"
#include "renderingFragmentList.h"

namespace rendering
{
    namespace scene
    {

        ///---

        /// an abstraction of a rendering pass
        class IRendererPass : public base::NoCopy
        {
            RTTI_DECLARE_VIRTUAL_ROOT_CLASS(IRendererPass);

        public:
            IRendererPass(IRendererView& view, const base::StringID& name);
            virtual ~IRendererPass();

            //---

            /// get view
            FORCEINLINE const IRendererView& getView() const { return m_view; }

            /// get the given name (debug)
            FORCEINLINE const base::StringID& getName() const { return m_name; }

            /// get pass depth layer
            FORCEINLINE const DepthCompositionLayer getLayer() const { return m_layer; }

            /// get the camera index
            FORCEINLINE const Uint8 getCameraIndex() const { return m_cameraIndex; }

            //---

            /// prepare, called after all normal stuff was collected in a view so we have access to anything there
            /// typical usage: do something with collected data
            /// NOTE: we are NON const here since we are allowed to cache results, also we are allowed to spawn sub-views if required
            /// NOTE: the cmd is a "Prepare" command buffer that is being run BEFORE any draw lists are processed
            virtual void prepare(microp::MicroOpWriter& cmd);

            /// run pass in context of a given view
            /// NOTE: this is const as we may be running from threads
            virtual void run(microp::MicroOpWriter& cmd) const;

            //---

            /// set the depth composition layer
            void setDepthLayer(const DepthCompositionLayer layer);

            /// set the camera index
            void setCameraIndex(const Uint8 cameraIndex);

        private:
            const IRendererView& m_view;
            Uint8 m_cameraIndex;
            base::StringID m_name;
            DepthCompositionLayer m_layer;
        };

        ///---

        /// pass outputing data to render targets, this is a typical case
        /// NOTE: the difference between a "pass" and post process is that pass operates in principle on the stuff in the scene and post process on stuff on the screen
        class IRendererViewportPass : public IRendererPass
        {
            RTTI_DECLARE_VIRTUAL_CLASS(IRendererViewportPass, IRendererPass);

        public:
            IRendererViewportPass(IRendererView& view, const base::StringID& name);
            virtual ~IRendererViewportPass();

            /// set clear color for color target
            void setClearColor(const Uint32 target, const base::math::Vector4& color = base::math::Vector4(0,0,0,1));

            /// set clear value for depth target
            void setClearDepth(const Float value = 1.0f);

            /// set clear value for the stencil buffer
            void setClearStencil(const Uint8 value = 0);

            /// set the clear values for depth and stencil
            void setClearDepthStencil(const Float depthValue = 1.0f, const Uint8 stencilValue = 0);

            /// configure the static depth bias
            void setDepthBias(const Float constant, const Float slope, const Float clamp);

            /// set color target
            void setColorTarget(const Uint32 index, const IRendererPostProcessSurface* surf);

            /// set depth target
            void setDepthTarget(const IRendererPostProcessSurface* surf);

        protected:
            // clear values
            Float m_clearDepthValue;
            Uint8 m_clearStencilValue;
            base::math::Vector4 m_clearColorValue[MAX_COLOR_TARGETS];

            // depth bias values
            Float m_depthBiasConstant;
            Float m_depthBiasSlope;
            Float m_depthBiasClamp;
            Bool m_setupDepthBias;

            // clear flags
            Bool m_clearDepthFlag;
            Bool m_clearStencilFlag;
            Bool m_clearColorFlag[MAX_COLOR_TARGETS];

            // render targets
            const IRendererPostProcessSurface* m_color[MAX_COLOR_TARGETS];
            const IRendererPostProcessSurface* m_depth;

            //--

            void recordClears(microp::MicroOpWriter& cmd) const;
            void buildFrameBuffer(pipeline::FrameBuffer& outFrameBuffer) const;
        };

        ///---

        /// pass capable of rendering fragments using predefiend shader template
        /// NOTE: materials must support it
        class MaterialFragmentPass : public IRendererViewportPass
        {
            RTTI_DECLARE_VIRTUAL_CLASS(MaterialFragmentPass, IRendererViewportPass);

        public:
            MaterialFragmentPass(IRendererView& view, const base::StringID& name);
            virtual ~MaterialFragmentPass();

            /// add pass bit (fragments with given pass bit will be rendered by this pass)
            void includePassBit(const PassBit& bit);

            /// remove pass bit (fragments with given pass bit will be rendered by this pass)
            void excludePassBit(const PassBit& bit);

            /// set sorting method for the pass
            void setSortingMethod(const FragmentSortingMethod sortMethod);

            //--

            virtual void run(microp::MicroOpWriter& cmd) const override;

        protected:
            //base::SharedPtr<runtime::ShaderLibrary> m_shaderFile;
            base::CompileTimeCRC32 m_passSelectorName;
            base::InplaceArray<PassBit, 4> m_passBits;
            FragmentSortingMethod m_sortMethod;
        };

        ///---

    } // scene
} // rendering


text:
#region License

#endregion

#region Imports

using System;
using NUnit.Framework;
using System.Reflection;

#endregion

namespace Spring.Aop.Support
{
	/// <summary>
	/// Unit tests for the AttributeMatchMethodPointcut class.
	/// </summary>
	/// <author>Rick Evans</author>
    /// <author>Ronald Wildenberg</author>
	[TestFixture]
	public sealed class AttributeMatchMethodPointcutTests
	{
		[Test]
		public void InstantiationWithASunnyDayAttributeType()
		{
			new AttributeMatchMethodPointcut(typeof(SerializableAttribute));
		}

		[Test]
		public void InstantiationWithNonAttributeType()
		{
            Assert.Throws<ArgumentException>(() => new AttributeMatchMethodPointcut(GetType()));
		}

		[Test]
		public void AttributeSetterWithNonAttributeType()
		{
			AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
            Assert.Throws<ArgumentException>(() => cut.Attribute = GetType());
		}

		[Test]
		public void AttributeSetterWithNullType()
		{
			AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
			cut.Attribute = null; // must allow this (no Exception)...
		}

		[Test]
		public void AttributeSetterWithASunnyDayAttributeType()
		{
			AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
			cut.Attribute = typeof(SerializableAttribute); // must allow this too (no Exception)...
		}

		[Test]
		public void MatchesWithASunnyDayAttributeTypeAndNoInheritance()
		{
			AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
			cut.Attribute = typeof(MarkupAttribute);
			bool matches = cut.Matches(typeof(WithMarkup).GetMethod("Bing"), null);
			Assert.IsTrue(matches, "Method was decorated with the target attribute, so this must match.");
		}

		[Test]
		public void MatchesWithASunnyDayAttributeTypeAndInheritance()
		{
			AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
			cut.Attribute = typeof(MarkupAttribute);
			bool matches = cut.Matches(typeof(InheritedWithMarkup).GetMethod("Bing"), null);
			Assert.IsTrue(matches, "Inherited method was decorated with the target attribute, so this must match.");
		}

		[Test]
		public void MatchesWithAMethodThatDontMatchTheAttributeTypeAndNoInheritance()
		{
			AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
			cut.Attribute = typeof(MarkupAttribute);
			bool matches = cut.Matches(typeof(WithMarkup).GetMethod("RiloKiley"), null);
			Assert.IsFalse(matches, "Method was not decorated with the target attribute, so this must not match.");
		}

		[Test]
		public void MatchesWithAnInheritedMethodThatDontMatchTheAttributeTypeAndNoInheritance()
		{
			AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
			cut.Attribute = typeof(MarkupAttribute);
			bool matches = cut.Matches(typeof(InheritedWithMarkup).GetMethod("RiloKiley"), null);
			Assert.IsFalse(matches, "Inherited method was not decorated with the target attribute, so this must not match.");
		}

        /// <summary>
        /// Confirms that without interfaces checking, a method that is implemented from an interface, will not match.
        /// </summary>
        [Test]
        public void MatchesWithAnInterfaceMethodThatMatchesTheAttributeTypeAndNoCheckInterfaces()
        {
            AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
            cut.Attribute = typeof(MarkupAttribute);
            cut.CheckInterfaces = false;
            bool matches = cut.Matches(typeof(ImplementingClass).GetMethod("OtherTestMethod"), null);
            Assert.IsFalse(matches, "Implementing method was not decorated with the target attribute, so this must not match since CheckInterfaces is false.");
        }

        /// <summary>
        /// Confirms that with interface checking, a method that is implementing an interface method
        /// where the attribute is defined will match.
        /// </summary>
        [Test]
        public void MatchesWithAnInterfaceMethodThatMatchesTheAttributeTypeAndCheckInterfaces()
        {
            AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
            cut.Attribute = typeof(MarkupAttribute);
            cut.CheckInterfaces = true;
            bool matches = cut.Matches(typeof(ImplementingClass).GetMethod("OtherTestMethod"), null);
            Assert.IsTrue(matches, "Implementing method was not decorated with the target attribute, " +
                "but the method from the interface was, so this must match.");
        }

        /// <summary>
        /// Confirms that with interfaces checking, a method that is indirectly implementing an interface method
        /// where the attribute is defined will match.
        /// </summary>
        [Test]
        public void MatchesWithAnIndirectInterfaceMethodThatMatchesTheAttributeTypeAndCheckInterfaces()
        {
            AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
            cut.Attribute = typeof(MarkupAttribute);
            cut.CheckInterfaces = true;
            bool matches = cut.Matches(typeof(ImplementingClass).GetMethod("TestMethod", new Type[] { }), null);
            Assert.IsTrue(matches, "Implementing method was not decorated with the target attribute, but the" +
                " method from an indirectly implemented interface was, so this must match.");
        }

        /// <summary>
        /// Confirms that overloading methods do not match, whatever the attributes.
        /// </summary>
        [Test]
        public void MatchesWithAnOverloadedInterfaceMethod()
        {
            AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
            cut.Attribute = typeof(MarkupAttribute);
            cut.CheckInterfaces = true;
            bool matches = cut.Matches(typeof(ImplementingClass).GetMethod("TestMethod", new Type[] { typeof(string) }), null);
            Assert.IsFalse(matches, "Overloaded method from an implemented interface is not decorated with" +
                " the attribute, so should not match.");
        }

        /// <summary>
        /// Confirms that methods, defined in a subclass of a class that implements an interface that
        /// has methods that have been decorated with an attribute, match.
        /// </summary>
        [Test]
        public void MatchesWithAnIndirectInterfaceMethodFromSubclassThatMatchesTheAttributeTypeAndCheckInterfaces()
        {
            AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
            cut.Attribute = typeof(MarkupAttribute);
            cut.CheckInterfaces = true;
            bool matches = cut.Matches(typeof(InheritedImplementingClass).GetMethod("TestMethod", new Type[] { }), null);
            Assert.IsTrue(matches, "Implementing method from subclass was not decorated with the target attribute " +
                "but the method from an indirectly implemented interface was, so this must match.");
        }

        /// <summary>
        /// Confirms that methods, explicitly implemented in the derived classes will match
        /// </summary>
        [Test(Description="SPRNET-1314")]
        public void MatchesWhenExplicitlyImplemed()
        {
            AttributeMatchMethodPointcut cut = new AttributeMatchMethodPointcut();
            cut.Attribute = typeof(MarkupAttribute);
            cut.CheckInterfaces = true;

            // Only methods implemented expicitly are marked with attribute
            foreach (MethodInfo mi in typeof(ExplicitlyImplementingClass).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic))
            {
                if (mi.Name.IndexOf('.') == -1) continue;
                bool matches = cut.Matches(mi, null);
                Assert.IsTrue(matches, "Explicitly implemented method must match");
            }

        }

        #region Helper classes definitions

        [AttributeUsage(AttributeTargets.Method)]
		private sealed class MarkupAttribute : Attribute {}

		private class WithMarkup
		{
			[Markup]
			public void Bing() {}

			public void RiloKiley() {}
		}

		private sealed class InheritedWithMarkup : WithMarkup
		{
        }

        private interface SuperInterface
        {
            [Markup]
            void TestMethod();

            void TestMethod(string param);
        }

        private interface SubInterface : SuperInterface
        {
            [Markup]
            void OtherTestMethod();
        }

        private interface AnotherSuperInterface
        {
            [Markup]
            void TestMethod();
        }

        private class ImplementingClass : SubInterface
        {
            public void TestMethod() {}

            public void TestMethod(string param) {}

            public void OtherTestMethod() {}
        }

        private sealed class InheritedImplementingClass : ImplementingClass
        {
        }

        private class ExplicitlyImplementingClass : SuperInterface, AnotherSuperInterface
        {
            void AnotherSuperInterface.TestMethod() { }

            void SuperInterface.TestMethod() { }

            public void TestMethod(string param) {}
        }

        #endregion
    }
}


text:
package com.xthena.jl.manager;

import com.xthena.core.hibernate.HibernateEntityDao;
import com.xthena.jl.domain.JlPxjcjl;

import org.springframework.stereotype.Service;

@Service
public class JlPxjcjlManager extends HibernateEntityDao<JlPxjcjl> {
}


text:
#ifndef PHO_XML_PROFIEPARSER_H
#define PHO_XML_PROFILEPARSER_H

#include <Windows.h>
#include <string>
#include <unordered_map>

#ifndef __cplusplus
#error "Only Support C++"
#endif

namespace Force {
class ProfileStructure;
class ProfileManager {
public:
  enum PROFILE_TYPE{
    XML_CONFIGFILE=0,
    INI_CONFIGFILE,
    JSON_CONFIGFILE
  };
private:
  std::unordered_map<std::wstring,std::wstring> kv;
  int filetype;
  std::wstring configFile;
public:
  ProfileManager(std::wstring profile);
  ProfileManager();
  ~ProfileManager();
  bool BeginParse();
  bool ChooseProfileType(int type=XML_CONFIGFILE);
  int get(const wchar_t *key,int de);
  std::wstring get(const wchar_t *key,const wchar_t *value);
  bool set(const wchar_t *key,int value);
  bool set(const wchar_t *key,const wchar_t *value);
};

typedef ProfileManager ConfiguretionManager;
}

#endif


text:
local classic = require 'classic'
local optim = require 'optim'
local AsyncAgent = require 'async/AsyncAgent'
require 'modules/sharedRmsProp'

local A3CAgent,super = classic.class('A3CAgent', 'AsyncAgent')

local TINY_EPSILON = 1e-20

function A3CAgent:_init(opt, policyNet, targetNet, theta, targetTheta, atomic, sharedG)
  super._init(self, opt, policyNet, targetNet, theta, targetTheta, atomic, sharedG)

  log.info('creating A3CAgent')

  self.policyNet_ = policyNet:clone()

  self.theta_, self.dTheta_ = self.policyNet_:getParameters()
  self.dTheta_:zero()

  self.policyTarget = self.Tensor(self.m)
  self.vTarget = self.Tensor(1)
  self.targets = { self.vTarget, self.policyTarget }

  self.rewards = torch.Tensor(self.batchSize)
  self.actions = torch.ByteTensor(self.batchSize)
  self.states = torch.Tensor(0)
  self.beta = opt.entropyBeta

  self.env:training()

  classic.strict(self)
end

function A3CAgent:learn(steps, from)
  self.step = from or 0

  self.stateBuffer:clear()

  log.info('A3CAgent starting | steps=%d', steps)
  local reward, terminal, state = self:start()

  self.states:resize(self.batchSize, table.unpack(state:size():totable()))

  self.tic = torch.tic()
  repeat
    self.theta_:copy(self.theta)
    self.batchIdx = 0
    repeat
      self.batchIdx = self.batchIdx + 1
      self.states[self.batchIdx]:copy(state)

      local V, probability = table.unpack(self.policyNet_:forward(state))
      local action = torch.multinomial(probability, 1):squeeze()

      self.actions[self.batchIdx] = action

      reward, terminal, state = self:takeAction(action)
      self.rewards[self.batchIdx] = reward

      self:progress(steps)
    until terminal or self.batchIdx == self.batchSize

    self:accumulateGradients(terminal, state)

    if terminal then
      reward, terminal, state = self:start()
    end

    self:applyGradients(self.policyNet_, self.dTheta_, self.theta)
  until self.step >= steps

  log.info('A3CAgent ended learning steps=%d', steps)
end

function A3CAgent:accumulateGradients(terminal, state)
  local R = 0
  if not terminal then
    R = self.policyNet_:forward(state)[1]
  end

  for i=self.batchIdx,1,-1 do
    R = self.rewards[i] + self.gamma * R

    local action = self.actions[i]
    local V, probability = table.unpack(self.policyNet_:forward(self.states[i]))
    probability:add(TINY_EPSILON) -- could contain 0 -> log(0)= -inf -> theta = nans

    self.vTarget[1] = -0.5 * (R - V)

    -- ∇θ logp(s) = 1/p(a) for chosen a, 0 otherwise
    self.policyTarget:zero()
    -- f(s) ∇θ logp(s)
    self.policyTarget[action] = -(R - V) / probability[action] -- Negative target for gradient descent

    -- Calculate (negative of) gradient of entropy of policy (for gradient descent): -(-logp(s) - 1)
    local gradEntropy = torch.log(probability) + 1
    -- Add to target to improve exploration (prevent convergence to suboptimal deterministic policy)
    self.policyTarget:add(self.beta, gradEntropy)

    self.policyNet_:backward(self.states[i], self.targets)
  end
end

function A3CAgent:progress(steps)
  self.atomic:inc()
  self.step = self.step + 1
  if self.step % self.progFreq == 0 then
    local progressPercent = 100 * self.step / steps
    local speed = self.progFreq / torch.toc(self.tic)
    self.tic = torch.tic()
    log.info('A3CAgent | step=%d | %.02f%% | speed=%d/sec | η=%.8f',
      self.step, progressPercent, speed, self.optimParams.learningRate)
  end
end

return A3CAgent


text:
layout: post
status: publish
published: true
title: Read-only select elements in HTML
author:
  display_name: Jay
  login: jk3us
  email: jay@jayknight.com
  url: ''
author_login: jk3us
author_email: jay@jayknight.com
wordpress_id: 41
wordpress_url: http://jk3.us/2006/07/06/read-only-select-elements-in-html/
date: !binary |-
  MjAwNi0wNy0wNiAxNjoxMTo1NSArMDAwMA==
date_gmt: !binary |-
  MjAwNi0wNy0wNiAyMjoxMTo1NSArMDAwMA==
categories:
- General
tags:
- html
- programming
- web
comments:
- id: 83
  author: Anon
  author_email: nope@example.com
  author_url: ''
  date: !binary |-
    MjAwOC0xMS0yNCAxNzozNjowNiArMDAwMA==
  date_gmt: !binary |-
    MjAwOC0xMS0yNCAyMjozNjowNiArMDAwMA==
  content: ! 'You can first disable the select in the HTML code, then enable them
    with javascript.

    Then you add a handler to the onChange-event or something. This handler will set
    the selected index back to its original value (and also output an error message
    saying that you can''t change the values)

    You could also make it more obvious that it''s read only by using CSS and give
    the elements a more grey look'
- id: 84
  author: josh
  author_email: a@b.cde
  author_url: ''
  date: !binary |-
    MjAwOC0xMS0yNCAxODo1NDo0NyArMDAwMA==
  date_gmt: !binary |-
    MjAwOC0xMS0yNCAyMzo1NDo0NyArMDAwMA==
  content: You could leave it disabled and duplicate it with a hidden field.
- id: 85
  author: igo
  author_email: shb@inbox.lv
  author_url: ''
  date: !binary |-
    MjAwOC0xMi0yOSAwODowMTo1MiArMDAwMA==
  date_gmt: !binary |-
    MjAwOC0xMi0yOSAxMzowMTo1MiArMDAwMA==
  content: ! 'josh++

    this approch is very useful in lots of situations. for example - read only checkboxes
    (if checkbox is marked readonly you can still check/uncheck it - value of control
    IS read only, but UI state not :D ).'
- id: 86
  author: Code Pug
  author_email: nickcecilyandeli@yahoo.com
  author_url: http://www.codepug.com
  date: !binary |-
    MjAwOS0wOS0zMCAwMDowNjoxMSArMDAwMA==
  date_gmt: !binary |-
    MjAwOS0wOS0zMCAwNTowNjoxMSArMDAwMA==
  content: ! 'I have created a JavaScript snippet that will allow you to make your
    HTML select controls read-only simply by giving them an ID attribute and calling
    the script available on my site at http://www.codepug.com/readonlySelect.html

    Happy coding!

    --X

    .'
- id: 243
  author: MightyPork
  author_email: ondra@ondrovo.com
  author_url: http://www.ondrovo.com
  date: !binary |-
    MjAxMi0wMy0yOSAxMjoxODo1NyArMDAwMA==
  date_gmt: !binary |-
    MjAxMi0wMy0yOSAxNzoxODo1NyArMDAwMA==
  content: What about hiding the Select behind a transparent div?
- id: 244
  author: MightyPork
  author_email: ondra@ondrovo.com
  author_url: http://www.ondrovo.com
  date: !binary |-
    MjAxMi0wMy0yOSAxMjoyMDoyMCArMDAwMA==
  date_gmt: !binary |-
    MjAxMi0wMy0yOSAxNzoyMDoyMCArMDAwMA==
  content: ! "First post didn't show the code successful, I hope this will work better:\n
\n

\n
    \   <select.../>\n
"
---

In HTML 4, form elements can be defined as "readonly" so that the user can't modify the value. However, you'll notice that select controls (the drop-down lists) do not support the readonly attribute, just input and textarea controls. Can anyone out there please explain the rational behind this? It seems perfectly reasonable to have a readonly select box, especially if it is put into that state by a script.

I think my workaround will consist of making them disabled so they cannot be editted, and enabling them via a script right before the form submits so that the values for those controls are submitted (disabled controls are not successful and are not "valid for submission").

If anyone can explain why selects can't be made readonly, or give me a better solution for simulating readonly-ness, please share.