text:
package com.balysv.material.drawable.menu;

import android.os.Bundle;
import android.view.animation.Interpolator;

import static com.balysv.material.drawable.menu.MaterialMenuDrawable.IconState;
import static com.balysv.material.drawable.menu.MaterialMenuDrawable.IconState.BURGER;

/**
 * Base class for ActionBar implementations of {@link com.balysv.material.drawable.menu.MaterialMenuDrawable}
 *
 * @see MaterialMenuIcon
 */
public abstract class MaterialMenuBase implements MaterialMenu {

    private static final String STATE_KEY = "material_menu_icon_state";

    protected IconState currentState = IconState.BURGER;

    public final void setState(IconState state) {
        currentState = state;
        getDrawable().setIconState(state);
    }

    public final void animateState(IconState state) {
        currentState = state;
        getDrawable().animateIconState(state, false);
    }

    public final void animatePressedState(IconState state) {
        currentState = state;
        getDrawable().animateIconState(state, true);
    }

    public final void setColor(int color) {
        getDrawable().setColor(color);
    }

    public final void setTransformationDuration(int duration) {
        getDrawable().setTransformationDuration(duration);
    }

    public final void setPressedDuration(int duration) {
        getDrawable().setPressedDuration(duration);
    }

    public final void setInterpolator(Interpolator interpolator) {
        getDrawable().setInterpolator(interpolator);
    }

    public abstract MaterialMenuDrawable getDrawable();

    /**
     * Overwrites behaviour of pressed state circle animation even when using {@link #animatePressedState(IconState)}
     *
     * @param neverDrawTouch true to never draw pressed state circle animation
     */
    public final void setNeverDrawTouch(boolean neverDrawTouch) {
        getDrawable().setNeverDrawTouch(neverDrawTouch);
    }

    /**
     * Call from {@link android.app.Activity#onSaveInstanceState(android.os.Bundle)} to store current icon state
     *
     * @param outState outState
     */
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(STATE_KEY, currentState.name());
    }

    /**
     * Call from {@link android.app.Activity#onPostCreate(android.os.Bundle)} to restore icon state
     *
     * @param state state
     */
    public void syncState(Bundle state) {
        if (state != null) {
            String iconStateName = state.getString(STATE_KEY, BURGER.name());
            setState(IconState.valueOf(iconStateName));
        }
    }
}


text:
using BudgetAnalyser.Engine.Statement;
using BudgetAnalyser.Engine.Statement.Data;
using Xunit;
using Xunit.Abstractions;

namespace MapperGeneration
{
    public class StatementMapperGenerator : MapperGenerator
    {
        private const string NameSpace = "BudgetAnalyser.Engine.Statement.Data";
        public StatementMapperGenerator(ITestOutputHelper output) : base(output)
        {
        }

        [Fact]
        public void GenerateStatementModelToDto()
        {
            Act<TransactionSetDto, StatementModel>(NameSpace);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.daemon.woman.index;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;

import com.daemon.woman.utils.Logs;
import com.daemon.woman.utils.WoManConfig;

public class DaemonWoMan {

	private final static String WOMAN_FILE_PATH = WoManConfig.getWoManFilePath();

	private RandomAccessFile accessFile;
	private FileChannel aFileChannel;
	private FileLock aFileLock;

	private static class ManHolder {
		private static DaemonWoMan aDaemonMan = new DaemonWoMan();
	}

	private DaemonWoMan() {
		try {
			File aFile = new File(WOMAN_FILE_PATH);
			if (aFile == null || !aFile.exists() || !aFile.isFile()) {
				aFile.getParentFile().mkdirs();
				aFile.createNewFile();
			}
			accessFile = new RandomAccessFile(aFile, "rw");
			aFileChannel = accessFile.getChannel();
		} catch (IOException e) {
			Logs.error("init woman failure" + e.getMessage());
		}
	}

	public static DaemonWoMan getInstance() {
		return ManHolder.aDaemonMan;
	}

	public boolean isLock() {
		boolean isLock;
		try {
			aFileLock = aFileChannel.tryLock();
			isLock = !(aFileLock != null && aFileLock.isValid());
		} catch (Exception e) {
			isLock = true;
		}
		return isLock;
	}
}


text:
module Mongoid #:nodoc:
  # Include this module to get automatic versioning of root level documents.
  # This will add a version field to the +Document+ and a has_many association
  # with all the versions contained in it.
  module Versioning
    extend ActiveSupport::Concern
    included do
      field :version, :type => Integer, :default => 1
      embeds_many :versions, :class_name => self.name
      set_callback :save, :before, :revise
    end

    # Create a new version of the +Document+. This will load the previous
    # document from the database and set it as the next version before saving
    # the current document. It then increments the version number.
    def revise
      last_version = self.class.first(:conditions => { :_id => id, :version => version })
      if last_version
        self.versions << last_version.clone
        self.version = version + 1
        @modifications["versions"] = [ nil, @attributes["versions"] ] if @modifications
      end
    end
  end
end


text:
require 'rails_helper'

RSpec.describe Group, type: :model do
end


text:
<?php $this->section('main'); ?>

Step 3.

Please enter the publishing details of your installation. Note that none of these details are recorded externally, they simply provide global values for use within the system.

<?php echo $form->open()->build(); ?>
<?php echo $form->input('step')->build(); ?>

<?php echo $form->label('organisation', 'Organisation')->build(); ?>
<?php echo $form->error('organisation', 'b')->build(); echo $form->input('organisation')->attribute('class', 'span-4')->build(); ?>

<?php echo $form->label('domain', 'Domain Name')->build(); ?>
<?php echo $form->error('domain', 'b')->build(); echo $form->input('domain')->attribute('class', 'span-4')->build(); ?>

<?php echo $form->label('email', 'Contact Email')->build(); ?>
<?php echo $form->error('email', 'b')->build(); echo $form->input('email')->attribute('class', 'span-4')->build(); ?>

<?php echo $form->label('version', 'Install Version')->build(); ?>
<?php echo $form->error('version', 'b')->build(); echo $form->input('version')->attribute('class', 'span-2')->build(); ?>

<?php echo $form->label('timezone', 'Hosted Timezone')->build(); ?>
<?php echo $form->error('timezone', 'b')->build(); echo $form->input('timezone')->attribute('class', 'span-4')->build(); ?>

<?php echo $form->submit('Continue')->attribute('class', 'button')->attribute('title', 'Next Step')->build(); ?>

<?php echo $form->close()->build(); ?>
<?php $this->section(); ?>


text:
set(proj PythonQt)

set(${proj}_DEPENDENCIES "")

ExternalProject_Include_Dependencies(${proj}
  PROJECT_VAR proj
  DEPENDS_VAR ${proj}_DEPENDENCIES
  EP_ARGS_VAR ${proj}_EXTERNAL_PROJECT_ARGS
  USE_SYSTEM_VAR ${CMAKE_PROJECT_NAME}_USE_SYSTEM_${proj}
  )

if(${CMAKE_PROJECT_NAME}_USE_SYSTEM_${proj})
  message(FATAL_ERROR "Enabling ${CMAKE_PROJECT_NAME}_USE_SYSTEM_${proj} is not supported !")
endif()

# Sanity checks
if(DEFINED PYTHONQT_INSTALL_DIR AND NOT EXISTS ${PYTHONQT_INSTALL_DIR})
  message(FATAL_ERROR "PYTHONQT_INSTALL_DIR variable is defined but corresponds to non-existing directory")
endif()

if(NOT DEFINED PYTHONQT_INSTALL_DIR)

  set(ep_PythonQt_args)

  # Should PythonQt use VTK
  if(CTK_LIB_Scripting/Python/Core_PYTHONQT_USE_VTK)
    list(APPEND proj_DEPENDENCIES VTK)
  endif()

  # Enable Qt libraries PythonQt wrapping if required
  if (CTK_QT_VERSION VERSION_GREATER "4")
    message(FATAL_ERROR "To build CTK with Qt >= 5 and wrapping enabled, you "
                        "are currently required to provide your own PythonQt "
                        "by re-configuring CTK with option "
                        "-DPYTHONQT_INSTALL_DIR:PATH=/path/to/PythonQt-30-install")
    list(APPEND ep_PythonQt_args
      -DPythonQt_QT_VERSION:STRING=${CTK_QT_VERSION}
      )
    set(qtlibs Core Gui Widgets Network OpenGL PrintSupport Sql Svg UiTools WebKit WebKitWidgets Xml)
  else()
    list(APPEND ep_PythonQt_args
      -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}
      )
    set(qtlibs core gui network opengl sql svg uitools webkit xml)
  endif()
  foreach(qtlib All ${qtlibs})
    string(TOUPPER ${qtlib} qtlib_uppercase)
    list(APPEND ep_PythonQt_args -DPythonQt_Wrap_Qt${qtlib}:BOOL=${CTK_LIB_Scripting/Python/Core_PYTHONQT_WRAP_QT${qtlib_uppercase}})
  endforeach()

  # Force wrap option to ON if WRAP_QTALL was set to ON
  if(${CTK_LIB_Scripting/Python/Core_PYTHONQT_WRAP_QTALL})
    foreach(qtlib ${qtlibs})
      string(TOUPPER ${qtlib} qtlib_uppercase)
      set(CTK_LIB_Scripting/Python/Core_PYTHONQT_WRAP_QT${qtlib_uppercase} ON CACHE BOOL "Enable Scripting/Python/Core Library PYTHONQT_WRAP_QT${qtlib_uppercase} option" FORCE)
    endforeach()
  endif()

  # Python is required
  find_package(PythonLibs)
  if(NOT PYTHONLIBS_FOUND)
    message(FATAL_ERROR "error: Python is required to build ${PROJECT_NAME}")
  endif()

  set(revision_tag e1f1c77d9675c3c5fb1cba19d2a32ace483eda2c)
  if(${proj}_REVISION_TAG)
    set(revision_tag ${${proj}_REVISION_TAG})
  endif()

  set(location_args )
  if(${proj}_URL)
    set(location_args URL ${${proj}_URL})
  elseif(${proj}_GIT_REPOSITORY)
    set(location_args GIT_REPOSITORY ${${proj}_GIT_REPOSITORY}
                      GIT_TAG ${revision_tag})
  else()
    set(location_args GIT_REPOSITORY "${git_protocol}://github.com/commontk/PythonQt.git"
                      GIT_TAG ${revision_tag})
  endif()

  ExternalProject_Add(${proj}
    ${${proj}_EXTERNAL_PROJECT_ARGS}
    SOURCE_DIR ${CMAKE_BINARY_DIR}/${proj}
    BINARY_DIR ${proj}-build
    PREFIX ${proj}${ep_suffix}
    ${location_args}
    BUILD_COMMAND ""
    CMAKE_CACHE_ARGS
      ${ep_common_cache_args}
      -DQT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}
      -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR}
      -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2}
      -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY}
      ${ep_PythonQt_args}
    DEPENDS
      ${${proj}_DEPENDENCIES}
    )
  set(PYTHONQT_INSTALL_DIR ${ep_install_dir})

else()
  ExternalProject_Add_Empty(${proj} DEPENDS ${${proj}_DEPENDENCIES})
endif()

set(PythonQt_DIR ${PYTHONQT_INSTALL_DIR})

mark_as_superbuild(
  VARS
    PYTHONQT_INSTALL_DIR:PATH
    PYTHON_EXECUTABLE:FILEPATH # FindPythonInterp expects PYTHON_EXECUTABLE variable to be defined
    PYTHON_INCLUDE_DIR:PATH # FindPythonQt expects PYTHON_INCLUDE_DIR variable to be defined
    PYTHON_INCLUDE_DIR2:PATH
    PYTHON_LIBRARY:FILEPATH # FindPythonQt expects PYTHON_LIBRARY variable to be defined
  LABELS "FIND_PACKAGE_VARS"
  )
mark_as_superbuild(
  VARS PythonQt_DIR:PATH
  LABELS "FIND_PACKAGE"
  )


text:
<title>X86 transactional memory intrinsics - Using the GNU Compiler Collection (GCC)</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using the GNU Compiler Collection (GCC)">
<meta name="generator" content="makeinfo 4.11">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Target-Builtins.html#Target-Builtins" title="Target Builtins">
<link rel="prev" href="X86-Built_002din-Functions.html#X86-Built_002din-Functions" title="X86 Built-in Functions">
<link rel="next" href="MIPS-DSP-Built_002din-Functions.html#MIPS-DSP-Built_002din-Functions" title="MIPS DSP Built-in Functions">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: MIPS DSP Built-in Functions,
Previous: X86 Built-in Functions,
Up: Target Builtins

6.56.8 X86 transaction memory intrinsics

Hardware transactional memory intrinsics for i386. These allow to use
memory transactions with RTM (Restricted Transactional Memory).
For using HLE (Hardware Lock Elision) see x86 specific memory model extensions for transactional memory instead.
This support is enabled with the <samp>-mrtm</samp> option.

A memory transaction commits all changes to memory in an atomic way,
as visible to other threads. If the transaction fails it is rolled back
and all side effects discarded.

Generally there is no guarantee that a memory transaction ever suceeds
and suitable fallback code always needs to be supplied.

— RTM Function: unsigned _xbegin ()<var></var>

Start a RTM (Restricted Transactional Memory) transaction.
Returns _XBEGIN_STARTED when the transaction
started successfully (note this is not 0, so the constant has to be
explicitely tested). When the transaction aborts all side effects
are undone and an abort code is returned. There is no guarantee
any transaction ever succeeds, so there always needs to be a valid
tested fallback path.

     #include <immintrin.h>

     if ((status = _xbegin ()) == _XBEGIN_STARTED) {
         ... transaction code...
         _xend ();
     } else {
         ... non transactional fallback path...
     }

Valid abort status bits (when the value is not _XBEGIN_STARTED) are:

_XABORT_EXPLICIT
Transaction explicitely aborted with _xabort. The parameter passed
to _xabort is available with _XABORT_CODE(status)

_XABORT_RETRY
Transaction retry is possible.

_XABORT_CONFLICT
Transaction abort due to a memory conflict with another thread

_XABORT_CAPACITY
Transaction abort due to the transaction using too much memory

_XABORT_DEBUG
Transaction abort due to a debug trap

_XABORT_NESTED
Transaction abort in a inner nested transaction

— RTM Function: void _xend ()<var></var>

Commit the current transaction. When no transaction is active this will
fault. All memory side effects of the transactions will become visible
to other threads in an atomic matter.

— RTM Function: int _xtest ()<var></var>

Return a value not zero when a transaction is currently active, otherwise 0.

— RTM Function: void _xabort (<var>status</var>)<var></var>

Abort the current transaction. When no transaction is active this is a no-op.
status must be a 8bit constant, that is included in the status code returned
by _xbegin


text:
//
// timer.cpp
// ~~~~~~~~~
//
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//

#include <iostream>
#include <boost/asio.hpp>

void print(const boost::system::error_code& /*e*/)
{
  std::cout << "Hello, world!" << std::endl;
}

int main()
{
  boost::asio::io_context io;

  boost::asio::steady_timer t(io, boost::asio::chrono::seconds(5));
  t.async_wait(&print);

  io.run();

  return 0;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="hello">Hello World, Click Me!</string>
	<string name="app_name">Nester.Deploy.Droid</string>
</resources>


text:
<!DOCTYPE html>

    <meta name="description" content="Equihash mining pool for Bitcoin Gold crypto coin. Bitcoin is under threat to be dominated by few very influential organisations. This is pool to mine BTG comunity induced fork at your home computer using conventional GPU." />
    <meta name="keywords" content="BTG ,Bitcoin, GPU, Mining, Crypto, Currency, Bitcoin Gold, Fork, AMD, Nvidia, Claymore, Democratic, ASIC Resistant, Equihash, Algorithm"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="author" content="">

    <title>Bitcoin Gold (BTG) - Equihash Mining Pool</title>
    <meta name="msvalidate.01" content="C654B3617D2F90FF2A7F0A2B23122E33" />

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/freelancer.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
    <link href="https://fonts.googleapis.com/css?family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation Menu
                </button>
                BTG Mine

                        About

                        Community

                        Bitcoin Gold Mining Pool

                        Fast - Safe - Dependable

About

In the beginning Bitcoin network transactions where secured by individual hobbyist miners. With the introduction of ASIC hardware security, functionality has been disproportionately concentrated into a handful of corporations making it less secure.

Bitcoin Gold blockchain database is going to be secured with Equihash algorithm that is ASIC resistant. Being able to mine bitcoin with conventional GPU hardware ensures Bitcoin Gold network security functions are well distributed across the world.

                         Join our miner community channels

Be first to mine:

Early miners are likely to have significant gains from low network difficulty advantages.

Subscribe for further announcements

Launch dates:

Bitcoin Gold coin is being launched between October 25 and early days of November.

                        Copyright © BTGMine.org 2017


text:
import React, { Component } from 'react';
import { hot } from 'react-hot-loader';
import { lazyInject } from 'ioc';
import { Router } from './../Router';
import { State } from '../State';

const log = require('debug')('router:components:Switch');

export interface SwitchProps {
    state: State
}

@hot(module)
export class Switch extends Component<SwitchProps> {
    static displayName                        = 'Switch';
    static defaultProps: Partial<SwitchProps> = {};

    @lazyInject('router') router: Router;

    public componentDidMount(): void {
    }

    render() {
        const { children, state, ...props } = this.props;
        let element, match;

        React.Children.forEach(children, child => {
            if ( match == null && React.isValidElement(child) ) {
                element = child;
                if ( child.props[ 'name' ] === state.name ) {
                    match = true;
                }
            }
        });

        return element ? React.cloneElement(element, { match, state }) : null;
    }
}


text:
package com.adobe.acs.commons.ccvar.impl;

import com.adobe.acs.commons.ccvar.ContentVariableProvider;
import com.adobe.acs.commons.ccvar.PropertyAggregatorService;
import org.apache.sling.api.SlingHttpServletRequest;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

@Component(service = PropertyAggregatorService.class,
        immediate = true,
        configurationPolicy = ConfigurationPolicy.REQUIRE)
public class PropertyAggregatorServiceImpl implements PropertyAggregatorService {

    private static final Logger LOG = LoggerFactory.getLogger(PropertyAggregatorServiceImpl.class);

    @Reference(policyOption = ReferencePolicyOption.GREEDY, cardinality = ReferenceCardinality.MULTIPLE)
    private List<ContentVariableProvider> variableProviders;

    @Override
    public Map<String, Object> getProperties(final SlingHttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();

        for (ContentVariableProvider variableProvider : variableProviders) {
            int sizeBefore = map.size();
            if (variableProvider.accepts(request)) {
                variableProvider.addProperties(map, request);
            } else {
                LOG.debug(variableProvider.getClass().getName() + " does not accept request for request at {}.", request.getPathInfo());
            }
            if (map.size() == sizeBefore) {
                LOG.debug(variableProvider.getClass().getName() + " either did not add any properties or replaced existing ones.");
            }
        }

        return map;
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.Build.Engine.Incrementals
{
    public class PostProcessorInfo : ProcessorInfoBase
    {
        public string ContextInfoFile { get; set; }

        public override bool Equals(object obj)
        {
            var another = obj as PostProcessorInfo;
            if (another == null)
            {
                return false;
            }

            return Name == another.Name && IncrementalContextHash == another.IncrementalContextHash;
        }

        public override int GetHashCode()
        {
            return Name?.GetHashCode() ?? 0;
        }
    }
}


text:
<?php

namespace Sendmail\Model;

use Zend\InputFilter\Factory as InputFactory;     // <-- Add this import
use Zend\InputFilter\InputFilter;                 // <-- Add this import
use Zend\InputFilter\InputFilterAwareInterface;   // <-- Add this import
use Zend\InputFilter\InputFilterInterface;        // <-- Add this import
use Zend\View\Model\ViewModel;
use Sendmail\Model\Plugin\SendMailHelper;

class Sendmail extends \Base\Model\BaseModel implements InputFilterAwareInterface {

    const RESORT_ROOM = 1;
    const EVENT_ROOM = 2;
    const CRUISE_CABIN = 3;
    const CANCELED = 0;
    const OPEN_BALANCE = 1;
    const CLOSED_BALANCE = 2;

    protected $inputFilter;

    public function setInputFilter(InputFilterInterface $inputFilter) {
        throw new \Exception("Not used");
    }

    public function getInputFilter() {
        if (!$this->inputFilter) {
            $inputFilter = new InputFilter();
            $factory = new InputFactory();

            $inputFilter->add($factory->createInput(array(
                        'name' => 'name',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'StripTags'),
                            array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'encoding' => 'UTF-8',
                                    'min' => 3,
                                    'max' => 50,
                                ),
                            ),
                        ),
            )));

            $inputFilter->add($factory->createInput(array(
                        'name' => 'header',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'encoding' => 'UTF-8',
                                    'min' => 6,
                                ),
                            ),
                        ),
            )));

            $inputFilter->add($factory->createInput(array(
                        'name' => 'footer',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'encoding' => 'UTF-8',
                                    'min' => 6,
                                ),
                            ),
                        ),
            )));

            $inputFilter->add($factory->createInput(array(
                        'name' => 'message',
                        'required' => true,
                        'filters' => array(
                            array('name' => 'StringTrim'),
                        ),
                        'validators' => array(
                            array(
                                'name' => 'StringLength',
                                'options' => array(
                                    'encoding' => 'UTF-8',
                                    'min' => 6,
                                ),
                            ),
                        ),
            )));

            $this->inputFilter = $inputFilter;
        }

        return $this->inputFilter;
    }

    protected function isValidName($object) {
        if ($this->checkItem(array('name' => $object->getData()->getName()))) {
            $object->get('name')->setMessages(array('Sendmail with this name already exists'));
            return false;
        }
        return true;
    }

    public function isValidModel($object) {
        return $this->isValidName($object);
    }

    public function isValidModelOnEdit($object) {
        if ($this->checkItem(array(
                    'id' => $object->getData()->getId(),
                    'name' => $object->getData()->getName()))
        ) {
            return true;
        }
        return $this->isValidName($object);
    }

    public function getContent($id) {
        $sendmailHelper = new Plugin\SendMailHelper($this->_serviceManager);
        $where = array(
            'id' => $id,
        );
        $data = array();
        $content = $sendmailHelper->getContent($where, $data);
        return $content;
    }

    public function save($object) {

        if ($object->getAction()) {
            $item = $this->getItemBy(array('action' => $object->getAction()), true);
            if (isset($item)) {
                $item->setAction(0);
                parent::save($item);
            }
        }
        parent::save($object);
    }

    public function update($object) {
        if ($object->getAction()) {
            $item = $this->getItemBy(array('action' => $object->getAction()), true);
            if (isset($item)) {
                if ($object->getId() != $item->getId()) {
                    $item->setAction(0);
                    parent::save($item);
                }
            }
        }
        parent::save($object);
    }

    public function getSendmailCollection($page = false) {

        return parent::getCollection($page);
    }

    public function sendMailOnEdit($to, array $data) {
        $sendmailHelper = new SendMailHelper($this->_serviceManager);
        $where = array(
            'action' => SendMailHelper::RESERVATION,
        );
        $emailData = array(
            'title' => 'Reservation',
            'data' => $data,
        );
        $isSend = $sendmailHelper->sendEmail(SendMailHelper::FROM, $to, $emailData['title'], $emailData, $where);
        return $isSend;
    }

    protected function _getItemName($reservationId, $type) {

        $em = $this->getEntityManager();

        switch ($type) {
            case self::RESORT_ROOM:
                $item = $em->getRepository('\Base\Entity\ReservationResortRoom')->findOneBy(array('reservation' => $reservationId));
                $name = !is_null($item) ? $item->getRoom() : null;
                break;
            case self::EVENT_ROOM:
                $item = $em->getRepository('\Base\Entity\ReservationEventRoom')->findOneBy(array('reservation' => $reservationId));
                $name = !is_null($item) ? $item->getEventRoom() : null;

                break;
            case self::CRUISE_CABIN:
                $item = $em->getRepository('\Base\Entity\ReservationCruiseCabin')->findOneBy(array('reservation' => $reservationId));
                $name = !is_null($item) ? $item->getCabin() : null;
                break;
        }

        return $name;
    }

    public function getTravellers($reservationId) {

        $em = $this->getEntityManager();

        $travellers = array();

        $collection = $em->getRepository('\Base\Entity\ReservationTravellers')->findBy(array('reservation' => $reservationId));

        //   d($collection[0]->getTraveller());

        return $collection[0]->getTraveller();
    }

    public function sendMailOnReservation($to, array $data, $subject, array $params = null) {
        // d($to);

        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();

        $viewModel->setTemplate("template/templates/reservation1.phtml");

        if ($data) {

            if ($data['reservation']->getAffiliateId() != ""):
                $viewModel->setTemplate("template/templates/reservation_reseller.phtml");
            endif;

            $viewModel->setVariable('data', $data);

            if ($data['reservation']->getAffiliateId()) {

                $affliate = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Affiliates')->findOneBy(array('id' => $data['reservation']->getAffiliateId()));
                $affliatename = $affliate->getName();
                //  d($affliatename);
                $viewModel->setVariable('affliatename', $affliatename);
            }

            $invoice = $this->getEntityManager()->getRepository('\Base\Entity\Avp\OrderInvoices')->findBy(array('orderId' => $data['reservation']->getId()));
            // d($invoice[0]);
	if($invoice){
            $viewModel->setVariable('invoice', $invoice[0]);
	}

            $itemname = $this->_getItemName($data['reservation']->getId(), $data['reservation']->getType());

            $type = $data['reservation']->getType();
            $viewModel->setVariable('itemname', $itemname);

            $traveller = $this->getTravellers($data['reservation']->getId());
            $viewModel->setVariable('clientdetail', $traveller);
            // d($traveller);

            if ($type == 2) {
                if ($itemname->getRoomId()->getResortId()) {
                    $resort = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Resorts')->findOneBy(array('id' => $itemname->getRoomId()->getResortId()));
                    $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $resort->getCountryId()));
                    //  d($itemname);
                    $eventName = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Events')->findOneBy(array('id' => $itemname->getEventId()));
                    //d( $itemname);
                    $inventorydetails = $this->getEntityManager()->getRepository('\Base\Entity\InventoryEvent')->findOneBy(array('eventId' => $itemname->getEventId(), 'roomId' => $itemname->getId(), 'resortId' => $resort->getId()));
                    //   d($inventoryevent);
                    if ($country) {
                        $viewModel->setVariable('country', $country->getCountryName());
                    } else {
                        $viewModel->setVariable('country', 'N/A');
                    }
                    $viewModel->setVariable('resorts', $resort);
                    $viewModel->setVariable('eventname', $eventName->getTitle());
                    $viewModel->setVariable('inventorydetails', $inventorydetails);

                    //d($country);
                    //    $country=$this->_getItemName($data['reservation']->getId(),$data['reservation']->getType());
                }
            }

            if ($type == 1) {
                if ($itemname->getResortId()) {
                    $resort = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Resorts')->findOneBy(array('id' => $itemname->getResortId()));
                    $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $resort->getCountryId()));

                    $inventorydetails = $this->getEntityManager()->getRepository('\Base\Entity\InventoryHotels')->findOneBy(array('resortId' => $resort->getId(), 'roomId' => $itemname->getId()));

                    if ($country) {
                        $viewModel->setVariable('country', $country->getCountryName());
                    } else {
                        $viewModel->setVariable('country', 'N/A');
                    }
                    $viewModel->setVariable('resorts', $resort);
                    $viewModel->setVariable('inventorydetails', $inventorydetails);

                    //d($country);
                    //    $country=$this->_getItemName($data['reservation']->getId(),$data['reservation']->getType());
                }
            }

            if ($type == 3) {
                $cruise = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Cruises')->findOneBy(array('id' => $itemname->getCruiseId()));
                $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $cruise->getCountryId()));

                $inventorydetails = $this->getEntityManager()->getRepository('\Base\Entity\InventoryCruise')->findOneBy(array('cruiseId' => $cruise->getId(), 'suiteId' => $itemname->getId()));
                $viewModel->setVariable('inventorydetails', $inventorydetails);

                if ($country) {
                    $viewModel->setVariable('country', $country->getCountryName());
                } else {
                    $viewModel->setVariable('country', "N/A");
                }
                $viewModel->setVariable('cruise', $cruise);
            }
        }

        $html = $viewRender->render($viewModel);
        // echo $html;die;
        $sendmail = $this->getItemBy(array('action' => SendMailHelper::RESERVATION), true);
        $viewModel->data = $data;

        // d($data);
        if ($params) {
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }
        if ($sendmail) {
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);
//echo $html;
        //echo "<pre>";
        //print_r($html);
      //  die;

        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

    public function sendMail($to, array $data, $subject, $template, $action, array $params = null) {
        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate($template);
        $sendmail = $this->getItemBy(array('action' => $action), true);
        $viewModel->data = $data;
        if ($params) {
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }

        if ($sendmail) {
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);
        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

    public function sendMailOnLead($to, $subject, $message, $cc=NULL) {
        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("lead-template");
        //  $sendmail = $this->getItemBy(array('action'=> SendMailHelper::Reservation), true);
        // d($cc);
        //     d($subject);
        $viewModel->data = $data;
        /*    if($params){
          foreach ($params as $key => $value) {
          $viewModel->__set($key, $value);
          }
          } */
        /*  if($sendmail){
          $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
          $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
          $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
          } */
        $html = $viewRender->render($viewModel);

        // d($html);
        $from = SendMailHelper::FROM;
        //    $to="test@mailinator.com ";
        return Plugin\SendMail::sendMail($from, $to, $subject, $message, $cc);
    }

    public function sendMailToClient($to, $subject, $message) {

        //d($to);

        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("lead-template");
        //  $sendmail = $this->getItemBy(array('action'=> SendMailHelper::Reservation), true);
        // d($cc);
        //     d($subject);
        //$viewModel->data = $data;
        /*    if($params){
          foreach ($params as $key => $value) {
          $viewModel->__set($key, $value);
          }
          } */
        /*  if($sendmail){
          $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
          $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
          $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
          } */
        $html = $viewRender->render($viewModel);

        // d($html);
        $from = SendMailHelper::FROM;
        //    $to="test@mailinator.com ";
        return Plugin\SendMail::sendMail($from, $to, $subject, $message);
    }

    public function sendReceiptToClient($to, $subject, $receipt) {

        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("template/templates/receipt.phtml");
        $viewModel->setVariable('receipt', $receipt);

        $html = $viewRender->render($viewModel);
        //d($html);
        //echo "<pre>";        print_r($html);

        $from = SendMailHelper::FROM;
        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

    public function sendMailOnDue($to, $subject, array $params = null) {
        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate('template/templates/reservation1.phtml');
        $sendmail = $this->getItemBy(array('action' => $action), true);
        $viewModel->data = $data;
        if ($params) {
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }
        if ($sendmail) {
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);
        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);

        //return Plugin\SendMail::sendMail($from, $to, $subject, $message,$cc);
    }

    public function getPaymentdues($reservationId) {
        //   d('here');
        $em = $this->getEntityManager();

        $paymentDue = array();

        $datebefore7days = date('Y-m-d', strtotime('7 days'));
        $datetoday = date('Y-m-d');

        $dateafter7days = date('Y-m-d', strtotime('-7 days'));

        $qb = $em->createQueryBuilder();
        $qb->select('c')->from('\Base\Entity\ReservationPaymentDue', 'c')
                ->where('c.reservation= :reservation')
                ->setParameter('reservation', $reservationId)
                ->andWhere('c.dueDate BETWEEN :id AND :endid')
                ->setParameter('id', $dateafter7days)
                ->setParameter('endid', $datebefore7days)
                ->andWhere('c.status=0');

        $query = $qb->getQuery();
        $results = $query->getResult();

//       d($results);
        return $results;
    }

    public function sendMailOnReminder($to, $id, $subject, array $params = null) {
        // d($to);

        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("template/templates/paymentdue.phtml");
        $data['reservation'] = $this->getEntityManager()->getRepository('\Base\Entity\Reservation')->findOneBy(array('id' => $id));

        $paymentdue = $this->getPaymentdues($id);
        $viewModel->setVariable('paymentdue', $paymentdue[0]);
        // d($paymentdue);

        if ($data) {
            $viewModel->setVariable('data', $data);
            if ($data['reservation']->getAffiliateId()) {

                $affliate = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Affiliates')->findOneBy(array('id' => $data['reservation']->getAffiliateId()));
                $affliatename = $affliate->getName();
                //d($affliatename);
                $viewModel->setVariable('affliatename', $affliatename);
            }

            $invoice = $this->getEntityManager()->getRepository('\Base\Entity\Avp\OrderInvoices')->findBy(array('orderId' => $data['reservation']->getId()));
            $viewModel->setVariable('invoice', $invoice[0]);

            $itemname = $this->_getItemName($data['reservation']->getId(), $data['reservation']->getType());

            $type = $data['reservation']->getType();
            $viewModel->setVariable('itemname', $itemname);

            $traveller = $this->getTravellers($data['reservation']->getId());
            $viewModel->setVariable('clientdetail', $traveller);

            if ($type == 2) {
                if($itemname){
                if ($itemname->getRoomId()->getResortId()) {
                    $resort = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Resorts')->findOneBy(array('id' => $itemname->getRoomId()->getResortId()));
                    $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $resort->getCountryId()));

                    if ($country) {
                        $viewModel->setVariable('country', $country->getCountryName());
                    } else {
                        $viewModel->setVariable('country', 'N/A');
                    }
                    $viewModel->setVariable('resorts', $resort);
                    //d($country);
                    //    $country=$this->_getItemName($data['reservation']->getId(),$data['reservation']->getType());
                }
                }
            }

            if ($type == 1) {
                if($itemname){
                if ($itemname->getResortId()) {
                    $resort = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Resorts')->findOneBy(array('id' => $itemname->getResortId()));
                    $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $resort->getCountryId()));
                    if ($country) {
                        $viewModel->setVariable('country', $country->getCountryName());
                    } else {
                        $viewModel->setVariable('country', 'N/A');
                    }
                    $viewModel->setVariable('resorts', $resort);
                    //d($country);
                    //    $country=$this->_getItemName($data['reservation']->getId(),$data['reservation']->getType());
                }
                }
            }

            if ($type == 3) {
                $cruise = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Cruises')->findOneBy(array('id' => $itemname->getCruiseId()));
                $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $cruise->getCountryId()));
                if ($country) {
                    $viewModel->setVariable('country', $country->getCountryName());
                } else {
                    $viewModel->setVariable('country', "N/A");
                }
                $viewModel->setVariable('cruise', $cruise);
            }
        }
        $html = $viewRender->render($viewModel);
        $sendmail = $this->getItemBy(array('action' => SendMailHelper::RESERVATION), true);
        $viewModel->data = $data;

        // d($data);
        if ($params) {
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }
        if ($sendmail) {
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);

        //d($html);
        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

    public function sendMailOnInvoice($to, array $data, $subject) {
        //d($data[0]);

        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("template/templates/sendinvoice.phtml");

        if ($data) {
            $viewModel->setVariable('collection', $data);
        }

        $html = $viewRender->render($viewModel);
        $sendmail = $this->getItemBy(array('action' => SendMailHelper::RESERVATION), true);
        $viewModel->data = $data;

        //  d($data);

        if ($sendmail) {
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);
        // echo '<pre>'; print_r($html);
        //d($html);
        //  $to="anup007@mailinator.com";
        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

    public function sendMailOnQuote($to, $clientname, array $data = null, array $params = null, $messagebody = null, $subject) {

        // d($params);
        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("template/templates/sendquote.phtml");

        if ($data) {
            $viewModel->setVariable('collection', $data);
        }
        $viewModel->setVariable('clientName', $clientname);
        $viewModel->setVariable('bodymessage', $messagebody);
        if ($params) {
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }

        $html = $viewRender->render($viewModel);
        $sendmail = $this->getItemBy(array('action' => SendMailHelper::RESERVATION), true);
        $viewModel->data = $data;

        if ($sendmail) {
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);
        //  echo "<pre>";        print_r($html)    ;
        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

    public function sendMailOnReservationPending($to, array $data, $subject, array $params = null) {
        // d($to);

        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("template/templates/reservationpending.phtml");
        if ($data) {
            $viewModel->setVariable('data', $data);

            if ($data['reservation']->getAffiliateId()) {

                $affliate = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Affiliates')->findOneBy(array('id' => $data['reservation']->getAffiliateId()));
                $affliatename = $affliate->getName();
                //  d($affliatename);
                $viewModel->setVariable('affliatename', $affliatename);
            }

            $invoice = $this->getEntityManager()->getRepository('\Base\Entity\Avp\OrderInvoices')->findBy(array('orderId' => $data['reservation']->getId()));
            // d($invoice[0]);

            $viewModel->setVariable('invoice', $invoice[0]);

            $itemname = $this->_getItemName($data['reservation']->getId(), $data['reservation']->getType());

            $type = $data['reservation']->getType();
            $viewModel->setVariable('itemname', $itemname);

            $traveller = $this->getTravellers($data['reservation']->getId());

            $viewModel->setVariable('clientdetail', $traveller);
            // d($traveller);

            if ($type == 2) {
                if ($itemname->getRoomId()->getResortId()) {
                    $resort = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Resorts')->findOneBy(array('id' => $itemname->getRoomId()->getResortId()));
                    $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $resort->getCountryId()));

                    if ($country) {
                        $viewModel->setVariable('country', $country->getCountryName());
                    } else {
                        $viewModel->setVariable('country', 'N/A');
                    }
                    $viewModel->setVariable('resorts', $resort);
                    //d($country);
                    //    $country=$this->_getItemName($data['reservation']->getId(),$data['reservation']->getType());
                }
            }

            if ($type == 1) {
                if ($itemname->getResortId()) {
                    $resort = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Resorts')->findOneBy(array('id' => $itemname->getResortId()));
                    $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $resort->getCountryId()));
                    if ($country) {
                        $viewModel->setVariable('country', $country->getCountryName());
                    } else {
                        $viewModel->setVariable('country', 'N/A');
                    }
                    $viewModel->setVariable('resorts', $resort);
                    //d($country);
                    //    $country=$this->_getItemName($data['reservation']->getId(),$data['reservation']->getType());
                }
            }

            if ($type == 3) {
                $cruise = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Cruises')->findOneBy(array('id' => $itemname->getCruiseId()));
                $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $cruise->getCountryId()));
                if ($country) {
                    $viewModel->setVariable('country', $country->getCountryName());
                } else {
                    $viewModel->setVariable('country', "N/A");
                }
                $viewModel->setVariable('cruise', $cruise);
            }
        }

        $html = $viewRender->render($viewModel);
        // echo $html;die;
        $sendmail = $this->getItemBy(array('action' => SendMailHelper::RESERVATION), true);
        $viewModel->data = $data;

        // d($data);
        if ($params) {
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }
        if ($sendmail) {
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);

        //d($html);
        // echo "<pre>";
        //print_r($html); die;
        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

     public function sendMailOnQuoteReservation($to, array $data, $subject, array $params = null) {
        // d($to);

        $viewRender = $this->_serviceManager->get("ViewRenderer");
        $viewModel = new ViewModel();
        $viewModel->setTemplate("template/templates/quotereservation.phtml");
        if ($data) {
            $viewModel->setVariable('data', $data);

            if ($data['reservation']->getAffiliateId()) {

                $affliate = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Affiliates')->findOneBy(array('id' => $data['reservation']->getAffiliateId()));
                $affliatename = $affliate->getName();
                //  d($affliatename);
                $viewModel->setVariable('affliatename', $affliatename);
            }

            $invoice = $this->getEntityManager()->getRepository('\Base\Entity\Avp\OrderInvoices')->findBy(array('orderId' => $data['reservation']->getId()));
            // d($invoice[0]);

            $viewModel->setVariable('invoice', $invoice[0]);

            $itemname = $this->_getItemName($data['reservation']->getId(), $data['reservation']->getType());

            $type = $data['reservation']->getType();
            $viewModel->setVariable('itemname', $itemname);

            $traveller = $this->getTravellers($data['reservation']->getId());
            $viewModel->setVariable('clientdetail', $traveller);
            // d($traveller);

            if ($type == 2) {
                if ($itemname->getRoomId()->getResortId()) {
                    $resort = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Resorts')->findOneBy(array('id' => $itemname->getRoomId()->getResortId()));
                    $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $resort->getCountryId()));
                    //  d($itemname);
                    $eventName = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Events')->findOneBy(array('id' => $itemname->getEventId()));
                    //d( $itemname);
                    $inventorydetails = $this->getEntityManager()->getRepository('\Base\Entity\InventoryEvent')->findOneBy(array('eventId' => $itemname->getEventId(), 'roomId' => $itemname->getId(), 'resortId' => $resort->getId()));
                    //   d($inventoryevent);
                    if ($country) {
                        $viewModel->setVariable('country', $country->getCountryName());
                    } else {
                        $viewModel->setVariable('country', 'N/A');
                    }
                    $viewModel->setVariable('resorts', $resort);
                    $viewModel->setVariable('eventname', $eventName->getTitle());
                    $viewModel->setVariable('inventorydetails', $inventorydetails);

                    //d($country);
                    //    $country=$this->_getItemName($data['reservation']->getId(),$data['reservation']->getType());
                }
            }

            if ($type == 1) {
                if ($itemname->getResortId()) {
                    $resort = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Resorts')->findOneBy(array('id' => $itemname->getResortId()));
                    $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $resort->getCountryId()));

                    $inventorydetails = $this->getEntityManager()->getRepository('\Base\Entity\InventoryHotels')->findOneBy(array('resortId' => $resort->getId(), 'roomId' => $itemname->getId()));

                    if ($country) {
                        $viewModel->setVariable('country', $country->getCountryName());
                    } else {
                        $viewModel->setVariable('country', 'N/A');
                    }
                    $viewModel->setVariable('resorts', $resort);
                    $viewModel->setVariable('inventorydetails', $inventorydetails);

                    //d($country);
                    //    $country=$this->_getItemName($data['reservation']->getId(),$data['reservation']->getType());
                }
            }

            if ($type == 3) {
                $cruise = $this->getEntityManager()->getRepository('\Base\Entity\Avp\Cruises')->findOneBy(array('id' => $itemname->getCruiseId()));
                $country = $this->getEntityManager()->getRepository('Base\Entity\Countries')->findOneBy(array('id' => $cruise->getCountryId()));

                $inventorydetails = $this->getEntityManager()->getRepository('\Base\Entity\InventoryCruise')->findOneBy(array('cruiseId' => $cruise->getId(), 'suiteId' => $itemname->getId()));
                $viewModel->setVariable('inventorydetails', $inventorydetails);

                if ($country) {
                    $viewModel->setVariable('country', $country->getCountryName());
                } else {
                    $viewModel->setVariable('country', "N/A");
                }
                $viewModel->setVariable('cruise', $cruise);
            }
        }

        $html = $viewRender->render($viewModel);
        // echo $html;die;
        $sendmail = $this->getItemBy(array('action' => SendMailHelper::RESERVATION), true);
        $viewModel->data = $data;

        // d($data);
        if ($params) {
            foreach ($params as $key => $value) {
                $viewModel->__set($key, $value);
            }
        }
        if ($sendmail) {
            $viewModel->header = htmlspecialchars_decode($sendmail->getHeader());
            $viewModel->footer = htmlspecialchars_decode($sendmail->getFooter());
            $viewModel->message = htmlspecialchars_decode($sendmail->getMessage());
        }
        $html = $viewRender->render($viewModel);

      //  echo "<pre>";
        //print_r($html);
        //die;

        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);
    }

public function sendMailOnExclusiveTemplate($to, $subject) {

        $html = "Hello,<br><br> New Template Exclusively has been added for you. Please Sign in http://reseller.mytravelcenter.net to have experience of new theme.<br><br> Thanks and Regards.<br>";
        $from = SendMailHelper::FROM;

        return Plugin\SendMail::sendMail($from, $to, $subject, $html);

        //return Plugin\SendMail::sendMail($from, $to, $subject, $message,$cc);
    }

}


text:
import subprocess
import os
import re
import sys
import urlparse

class SiteCloner():
    def __init__(self, clone_dir="web_clones/"):
        self.clone_dir = clone_dir

    def fixForms(self, html, method="POST", action="index"):
        html = re.sub("<\s*form[^>]+>", "<form method=\"%s\" action=\"%s\">" % (method, action), html)
        return html

    def writeConfig(self, tdir, url):
        of = open("%sCONFIG" % tdir, "w")
        url = urlparse.urlparse(url)
        vhost = url.hostname.split('.')[0]
        of.write("VHOST=%s\n" % vhost)
        of.write("LOGFILE=%s.log\n" % vhost)
        of.write("REDIRECTURL=error\n")
        of.close()

    def cloneUrl(self, url):
        # break URL apart into component parts
        url_details = urlparse.urlparse(url)
        path = os.path.split(url_details.path)[0]
        hostname = url_details.scheme + "_" + url_details.hostname

        ## make dir if needed
        if not os.path.isdir(self.clone_dir):
            os.makedirs(self.clone_dir)

        try:
            # check if we have wget
            if os.path.isfile("/usr/local/bin/wget") or os.path.isfile("/usr/bin/wget") or os.path.isfile("/usr/local/wget"):
                #use WGET to clone the index and supporting files
                subprocess.Popen('cd %s;timeout -s KILL 60 wget --no-check-certificate -e robots=off -O INDEX -c "%s";' % (self.clone_dir, url), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).wait()
                subprocess.Popen('cd %s;timeout -s KILL 60 wget --no-check-certificate -e robots=off -c -p -k -nH -P %s "%s";' % (self.clone_dir, hostname, url), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True).wait()

                # fix the <form> tag in INDEX to work with SPF
                html = ""
                with open ("%sINDEX" % self.clone_dir, "r") as myfile:
                    html=myfile.read()
                myfile.close()
                # correct/fix any forms
                html = self.fixForms(html)
                # write the file back out
                of = open("%sINDEX" % self.clone_dir, "w")
                of.write(html)
                of.close()

                # move INDEX to proper directory
                os.rename("%sINDEX" % self.clone_dir, "%s%s/%s/INDEX" % (self.clone_dir, hostname, path))

                # create a proper CONFIG file
                self.writeConfig("%s%s%s/" % (self.clone_dir, hostname, path), url)

                return "%s%s%s/" % (self.clone_dir, hostname, path)

            else:
                print "WGET WAS NOT FOUND"
        except TypeError as e:
           print e
        except NameError as e:
           print e
        except:
           print sys.exc_info()[0]

        return None

if __name__ == "__main__":
    s = SiteCloner()
    print s.cloneUrl("http://www.safelogin.co")
    #print s.cloneUrl("https://204.131.222.4/+CSCOE+/logon.html?fcadbadd=1")


text:
import render from './render'

let websocket = null
let timeout = 50
let timeout_token = null
let current_room = null
export var current_room_messages = null
export var metadata = {}
export var state = ""
export var room_list = []
let rooms = {}

let next_request_id = 0
let promises = {}

let insert_history = room => messages => {
    if(current_room !== room) {
        return
    }
    let existing = {}
    for(let msg of current_room_messages) {
        existing[msg.id] = msg
    }
    for(let msg of messages) {
        let old = existing[msg.id]
        if(old) {
            for(var k of Object.keys(msg)) {
                old[k] = msg[k]
            }
        } else {
            current_room_messages.push(msg)
        }
    }
    current_room_messages.sort(function(a, b) {
        return b.id - a.id
    })
}

function open() {
    state = "Connected. Authenticating..."
    render()
    if(timeout_token) {
        clearTimeout(timeout_token)
        timeout_token = null
    }
    if(current_room) {
        call('enter_room', current_room)
        let room = current_room
        call('get_history', room).then(insert_history(room))
    }
}

function close(e) {
    if(timeout_token) {
        clearTimeout(timeout_token);
    } else {
        timeout *= 2
        if(timeout > 300000) {
            timeout = 300000;
        }
    }
    state = ("Broken. Reconnecting in " +
             (timeout/1000).toFixed(0) + " sec...")
    render()
    timeout_token = setTimeout(timeout, reconnect)
    console.error("Websocket closed", e)
}

function reconnect() {
    if(timeout_token) {
        clearTimeout(timeout_token);
        timeout_token = null;
    }
    if(websocket) {
        websocket.onclose = null
        try {
            websocket.close()
        } catch(e) {}
        state = "Reconnecting..."
    } else {
        state = "Connecting..."
    }
    websocket = new WebSocket("ws://" + location.host + "/")
    websocket.onopen = open
    websocket.onclose = close
    websocket.onmessage = message
}

function update_rooms(data) {
    for(let k of Object.keys(data)) {
        let nroom = data[k];
        let r
        if(k in rooms) {
            r = rooms[k]
            if(!r.last_message_counter ||
                    r.last_message_counter < nroom.last_message_counter)
            {
                r.last_message_counter = nroom.last_message_counter
            }
            if(!r.last_seen_counter ||
                    r.last_seen_counter < nroom.last_seen_counter)
            {
                r.last_seen_counter = nroom.last_seen_counter
            }
        } else {
            r = nroom
            r.name = k
            rooms[k] = r
            room_list.push(r)
        }
        r.unseen = (r.last_message_counter || 0) -
                   (r.last_seen_counter || 0)
    }
    room_list.sort(function(a, b) {
        return a.name.localeCompare(b.name)
    })
}

function message(ev) {
    var data = JSON.parse(ev.data)

    // Not doing this on connect to be sure not to reconnect too fast
    // when connection doesn't actually work
    timeout = 50

    switch(data[0]) {
        case 'hello':
            metadata = data[2]
            state = "Connected."
            break;
        case 'message':
            console.debug("Message", data)
            if(data[1].topic === 'muc.' + current_room) {
                // TODO(tailhook) deduplicate
                current_room_messages.unshift(data[2])
            }
            break;
        case 'result': {
            let rid = data[1].request_id
            let prom = promises[rid]
            delete promises[rid]
            prom.resolve(data[2])
            break;
        }
        case 'error': {
            let rid = data[1].request_id
            if(rid) {
                let prom = promises[rid]
                delete promises[rid]
                prom.reject(data[2])
            }
            break;
        }
        case 'lattice':
            console.debug("Lattice", data)
            switch(data[1].namespace) {
                case 'muc':
                    update_rooms(data[2]);
                    break;
                default:
                    console.error("Lattice", data)
                    break;
            }
            break;
        default:
            console.error("Skipping message", data)
    }
    render()
}

function call(method, ...args) {
    next_request_id += 1
    var prom = new Promise(function(resolve, reject) {
        promises[next_request_id] = {
            resolve: resolve,
            reject: reject,
        }
    })
    websocket.send(JSON.stringify(
        ['muc.' + method, {'request_id': next_request_id}, args, {}]))
    return prom
}

export function start() {
    if(websocket) {
        return
    }
    reconnect()
}

export function stop() {
    websocket.close();
    if(timeout_token) {
        clearTimeout(timeout_token);
        timeout_token = null;
    }
    state = "Stopped."
}

export function enter_room(route) {
    let { params: {roomName}} = route;
    if(websocket.readyState === WebSocket.OPEN) {
        if(current_room) {
            call('switch_room', current_room, roomName)
        } else {
            call('enter_room', roomName)
        }
    }
    current_room = roomName
    current_room_messages = []
    call('get_history', roomName).then(insert_history(roomName))
}

export function leave_room(route) {
    call('leave_room', current_room)
    current_room = null
    current_room_messages = null
}

export function send_message(text) {
    call('message', current_room, text)
}


text:
import Ember from 'ember';
import config from './config/environment';

var Router = Ember.Router.extend({
  location: config.locationType
});

export default Router.map(function() {
  this.resource("index", {path: "/"});
  this.route("redirector");

  this.route("login");
  this.route("user", {path: "/user/:user_id"}, function() {
    this.route("activity");
    this.route("proposals");
  });

  this.route("auth", function() {
    this.route("setup", {path: "/:provider/setup/:token"});
    this.route("oauth_login", {path: "/:provider/login"});
    this.route("manual", {path: "/do/:username/:auth_key"});
  });

  this.route("users", {}, function() {
    this.route("index");
    this.route("forgot-password");
    this.route("reset-password");
    this.route("new");
    this.route("login");
  });
  this.resource("words", {path: "/words/:lang"}, function() {
    this.route("new");
    this.route("random");
  });
  this.resource("posts");
  this.resource("post", {path: "/post/:post_id"});
  this.resource("proposals", function() {
  });
  this.resource("proposal", {path: "/proposal/:proposal_id"}, function() {
    this.route("new-word");
    this.route("new-meaning");
    this.route("meaning-change");
  });
  this.route("project", {path: "/project/:project_id"}, function() {
    this.route("random");
    this.route("propose", {path: "/propose/:meaning_id"});
  });
  this.route("info", function() {
    this.route("goals");
    this.route("faqs");
    this.route("guidelines");
    this.route("get-started");
    this.route("legal");
  });

  this.route('legacy-word', {path: "/word/:seq"});

  this.route("quizzes");
  this.route("quiz", {path: "/quiz/:id"});

  this.resource("seq", {path: "/:lang/:seq"}, function() {
    this.route("wordset", {path: "/"}, function() {
      this.route("proposals");
    });
  });

  this.route('not-found', { path: '/*path' });

});


text:
'use strict';
console.log('index..................');

if(module.hot){
    module.hot.accept();
}


text:
package integration.mindbody;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy;
import org.jvnet.jaxb2_commons.lang.HashCode;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBToStringStrategy;
import org.jvnet.jaxb2_commons.lang.ToString;
import org.jvnet.jaxb2_commons.lang.ToStringStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;

/**
 *
Java class for ClientIndexValue complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ClientIndexValue">
 *   <complexContent>
 *     <extension base="{http://clients.mindbodyonline.com/api/0_5}MBObject">
 *       <sequence>
 *         <element name="Action" type="{http://clients.mindbodyonline.com/api/0_5}ActionCode" minOccurs="0"/>
 *         <element name="ID" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
 *         <element name="Name" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ClientIndexValue", propOrder = {
    "action",
    "id",
    "name"
})
@Entity(name = "ClientIndexValue")
@Table(name = "CLIENT_INDEX_VALUE")
@Inheritance(strategy = InheritanceType.JOINED)
public class ClientIndexValue
    extends MBObject
    implements Serializable, Equals, HashCode, ToString
{

    private final static long serialVersionUID = 1L;
    @XmlElement(name = "Action")
    protected ActionCode action;
    @XmlElement(name = "ID", nillable = true)
    protected Integer id;
    @XmlElement(name = "Name")
    protected String name;

    /**
     * Gets the value of the action property.
     *
     * @return
     *     possible object is
     *     {@link ActionCode }
     *
     */
    @Basic
    @Column(name = "ACTION_", length = 255)
    @Enumerated(EnumType.STRING)
    public ActionCode getAction() {
        return action;
    }

    /**
     * Sets the value of the action property.
     *
     * @param value
     *     allowed object is
     *     {@link ActionCode }
     *
     */
    public void setAction(ActionCode value) {
        this.action = value;
    }

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link Integer }
     *
     */
    @Id
    @Column(name = "ID", scale = 0)
    public Integer getID() {
        return id;
    }

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link Integer }
     *
     */
    public void setID(Integer value) {
        this.id = value;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    @Basic
    @Column(name = "NAME_", length = 255)
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

    public int hashCode(ObjectLocator locator, HashCodeStrategy strategy) {
        int currentHashCode = super.hashCode(locator, strategy);
        {
            ActionCode theAction;
            theAction = this.getAction();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "action", theAction), currentHashCode, theAction);
        }
        {
            Integer theID;
            theID = this.getID();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "id", theID), currentHashCode, theID);
        }
        {
            String theName;
            theName = this.getName();
            currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "name", theName), currentHashCode, theName);
        }
        return currentHashCode;
    }

    public int hashCode() {
        final HashCodeStrategy strategy = JAXBHashCodeStrategy.INSTANCE;
        return this.hashCode(null, strategy);
    }

    public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy strategy) {
        if (!(object instanceof ClientIndexValue)) {
            return false;
        }
        if (this == object) {
            return true;
        }
        if (!super.equals(thisLocator, thatLocator, object, strategy)) {
            return false;
        }
        final ClientIndexValue that = ((ClientIndexValue) object);
        {
            ActionCode lhsAction;
            lhsAction = this.getAction();
            ActionCode rhsAction;
            rhsAction = that.getAction();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "action", lhsAction), LocatorUtils.property(thatLocator, "action", rhsAction), lhsAction, rhsAction)) {
                return false;
            }
        }
        {
            Integer lhsID;
            lhsID = this.getID();
            Integer rhsID;
            rhsID = that.getID();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "id", lhsID), LocatorUtils.property(thatLocator, "id", rhsID), lhsID, rhsID)) {
                return false;
            }
        }
        {
            String lhsName;
            lhsName = this.getName();
            String rhsName;
            rhsName = that.getName();
            if (!strategy.equals(LocatorUtils.property(thisLocator, "name", lhsName), LocatorUtils.property(thatLocator, "name", rhsName), lhsName, rhsName)) {
                return false;
            }
        }
        return true;
    }

    public boolean equals(Object object) {
        final EqualsStrategy strategy = JAXBEqualsStrategy.INSTANCE;
        return equals(null, null, object, strategy);
    }

    public String toString() {
        final ToStringStrategy strategy = JAXBToStringStrategy.INSTANCE;
        final StringBuilder buffer = new StringBuilder();
        append(null, buffer, strategy);
        return buffer.toString();
    }

    public StringBuilder append(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
        strategy.appendStart(locator, this, buffer);
        appendFields(locator, buffer, strategy);
        strategy.appendEnd(locator, this, buffer);
        return buffer;
    }

    public StringBuilder appendFields(ObjectLocator locator, StringBuilder buffer, ToStringStrategy strategy) {
        super.appendFields(locator, buffer, strategy);
        {
            ActionCode theAction;
            theAction = this.getAction();
            strategy.appendField(locator, this, "action", buffer, theAction);
        }
        {
            Integer theID;
            theID = this.getID();
            strategy.appendField(locator, this, "id", buffer, theID);
        }
        {
            String theName;
            theName = this.getName();
            strategy.appendField(locator, this, "name", buffer, theName);
        }
        return buffer;
    }

}


text:
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.

using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using System;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI;
using Windows.UI.Popups;
using Windows.UI.Xaml;

namespace ArcGISRuntime.UWP.Samples.FeatureLayerQuery
{
    public partial class FeatureLayerQuery
    {
        // Create reference to service of US States
        private string _statesUrl = "http://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/2";

        // Create globally available feature table for easy referencing
        private ServiceFeatureTable _featureTable;

        // Create globally available feature layer for easy referencing
        private FeatureLayer _featureLayer;

        public FeatureLayerQuery()
        {
            InitializeComponent();

            // Create the UI, setup the control references and execute initialization
            Initialize();
        }

        private void Initialize()
        {
            // Create new Map with basemap
            Map myMap = new Map(Basemap.CreateTopographic());

            // Create and set initial map location
            MapPoint initialLocation = new MapPoint(
                -11000000, 5000000, SpatialReferences.WebMercator);
            myMap.InitialViewpoint = new Viewpoint(initialLocation, 100000000);

            // Create feature table using a url
            _featureTable = new ServiceFeatureTable(new Uri(_statesUrl));

            // Create feature layer using this feature table
            _featureLayer = new FeatureLayer(_featureTable);

            // Set the Opacity of the Feature Layer
            _featureLayer.Opacity = 0.6;

            // Create a new renderer for the States Feature Layer
            SimpleLineSymbol lineSymbol = new SimpleLineSymbol(
                SimpleLineSymbolStyle.Solid, Colors.Black, 1);
            SimpleFillSymbol fillSymbol = new SimpleFillSymbol(
                SimpleFillSymbolStyle.Solid, Colors.Yellow, lineSymbol);

            // Set States feature layer renderer
            _featureLayer.Renderer = new SimpleRenderer(fillSymbol);

            // Add feature layer to the map
            myMap.OperationalLayers.Add(_featureLayer);

            // Assign the map to the MapView
            myMapView.Map = myMap;
        }

        private async void OnQueryClicked(object sender, RoutedEventArgs e)
        {
            // Remove any previous feature selections that may have been made
            _featureLayer.ClearSelection();

            // Begin query process
            await QueryStateFeature(queryEntry.Text);
        }

        private async Task QueryStateFeature(string stateName)
        {
            try
            {
                // Create a query parameters that will be used to Query the feature table
                QueryParameters queryParams = new QueryParameters();

                // Construct and assign the where clause that will be used to query the feature table
                queryParams.WhereClause = "upper(STATE_NAME) LIKE '%" + (stateName.ToUpper()) + "%'";

                // Query the feature table
                FeatureQueryResult queryResult = await _featureTable.QueryFeaturesAsync(queryParams);

                // Cast the QueryResult to a List so the results can be interrogated
                var features = queryResult.ToList();

                if (features.Any())
                {
                    // Get the first feature returned in the Query result
                    Feature feature = features[0];

                    // Add the returned feature to the collection of currently selected features
                    _featureLayer.SelectFeature(feature);

                    // Zoom to the extent of the newly selected feature
                    await myMapView.SetViewpointGeometryAsync(feature.Geometry.Extent);
                }
                else
                {
                    var message = new MessageDialog("State Not Found!", "Add a valid state name.");
                    await message.ShowAsync();
                }
            }
            catch (Exception ex)
            {
                var message = new MessageDialog("Sample error: " + ex.ToString(), "An error occurred");
                await message.ShowAsync();
            }
        }
    }
}


text:
<!DOCTYPE HTML>

<title>Uses of Class com.brettonw.bedrock.bag.SortType (Bag 1.6.8 API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2021-12-14">
<meta name="description" content="use: package: com.brettonw.bedrock.bag, enum: SortType">
<meta name="generator" content="javadoc/ClassUseWriter">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../../script-dir/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Uses of Class
com.brettonw.bedrock.bag.SortType

Packages that use SortType

Package
Description

com.brettonw.bedrock.bag

Provides text-based storage of objects and un-formatted data in a simple, hierarchical key/value
 store.

Uses of SortType in com.brettonw.bedrock.bag

Fields in com.brettonw.bedrock.bag declared as SortType

Modifier and Type
Field
Description

static SortType
SortKey.DEFAULT_TYPE

Methods in com.brettonw.bedrock.bag that return SortType

Modifier and Type
Method
Description

SortType
SortKey.getType()

static SortType
SortType.valueOf(String name)

Returns the enum constant of this type with the specified name.

static SortType[]
SortType.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods in com.brettonw.bedrock.bag with parameters of type SortType

Modifier and Type
Method
Description

SortKey
SortKey.setType(SortType type)

Constructors in com.brettonw.bedrock.bag with parameters of type SortType

Constructor
Description

SortKey(String key,
SortType type,
SortOrder order)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Copyright © 2021. All rights reserved.


text:
"""
Bot which runs python framework scripts as (sub-)bot.

It provides a WikiUserInterface (WUI) with Lua support for bot operators.

This script needs external libraries (see imports and comments there)
in order to run properly. Most of them can be checked-out at:
    https://gerrit.wikimedia.org/r/#/admin/projects/?filter=pywikibot
(some code might get compiled on-the-fly, so a GNU compiler along
with library header files is needed too)

Syntax example:

    python pwb.py script_wui -dir:.
        Default operating mode.
"""
#
# (C) Dr. Trigon, 2012-2014
# (C) Pywikibot team, 2014-2017
#
# Distributed under the terms of the MIT license.
#
#  @package script_wui
#  @brief   Script WikiUserInterface (WUI) Bot
#
#  @copyright Dr. Trigon, 2012
#
#  @section FRAMEWORK
#
#  Python wikipedia bot framework, DrTrigonBot.
#  @see https://www.mediawiki.org/wiki/Pywikibot
#  @see https://de.wikipedia.org/wiki/Benutzer:DrTrigonBot
#
#  @section LICENSE
#
#  Distributed under the terms of the MIT license.
#  @see https://de.wikipedia.org/wiki/MIT-Lizenz
#
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
#  @todo Simulationen werden ausgeführt und das Resultat mit eindeutiger
#        Id (rev-id) auf Ausgabeseite geschrieben, damit kann der Befehl
#        (durch Angabe der Sim-Id) ausgeführt werden -> crontab (!)
#        [ shell (rev-id) -> output mit shell rev-id ]
#        [ shell rev-id (eindeutige job/task-config bzw. script) -> crontab ]
#  @todo Bei jeder Botbearbeitung wird der Name des Auftraggebers vermerkt
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
#  Writing code in Wikipedia:
#
#  # patches to keep code running
#  builtin_raw_input = __builtin__.raw_input
#  # overwrite 'raw_input' to run bot non-blocking and simulation mode
#  __builtin__.raw_input = lambda: 'n'
#
#  # backup sys.argv; depreciated: if possible manipulate pywikibot.config
#    instead
#  sys_argv = copy.deepcopy( sys.argv )
#
#  ...
# --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
#
from __future__ import absolute_import, unicode_literals

import datetime
import gc
import logging
import re
import sys
import threading
import traceback

from io import StringIO

# https://labix.org/lunatic-python is bit-rotting, and there are maintained
# versions on github:
# https://github.com/bastibe/lunatic-python.git
# https://github.com/AlereDevices/lunatic-python.git
import lua

# The crontab package is https://github.com/josiahcarlson/parse-crontab
# version 0.20 installs a package called 'tests' which conflicts with our
# test suite. The patch to fix this has been merged, but is not released.
# TODO: Use https://github.com/jayvdb/parse-crontab until it is fixed.
import crontab

import pywikibot
# pywikibot.botirc depends on https://pypi.python.org/pypi/irc
import pywikibot.botirc

from pywikibot.tools.formatter import color_format

if sys.version_info[0] > 2:
    import _thread as thread
else:
    import thread  # noqa: H237 (module does not exist in Python 3)

try:
    import resource
except ImportError:
    resource = None

bot_config = {
    'BotName': "{username}",

    'ConfCSSshell': u'User:{username}/script_wui-shell.css',
    'ConfCSScrontab': u'User:{username}/script_wui-crontab.css',
    'ConfCSSoutput': u'User:{username}/Simulation',

    'CRONMaxDelay': 5 * 60.0,       # check all ~5 minutes

    # forbidden parameters
    # (at the moment none, but consider e.g. '-always' or allow it with
    # '-simulate' only!)
}

__simulate = True
__sys_argv = []

class ScriptWUIBot(pywikibot.botirc.IRCBot):

    """WikiUserInterface bot."""

    def __init__(self, *arg):
        """Constructor."""
        pywikibot.output(color_format(
            '{lightgreen}* Initialization of bot{default}'))

        pywikibot.botirc.IRCBot.__init__(self, *arg)

        # init environment with minimal changes (try to do as less as possible)
        # - Lua -
        pywikibot.output(u'** Redirecting Lua print in order to catch it')
        lua.execute('__print = print')
        lua.execute('print = python.globals().pywikibot.output')
        # It may be useful in debugging to install the 'print' builtin
        # as the 'print' function in lua. To do this:
        # lua.execute('print = python.builtins().print')

        # init constants
        templ = pywikibot.Page(self.site, bot_config['ConfCSSshell'])
        cron = pywikibot.Page(self.site, bot_config['ConfCSScrontab'])

        self.templ = templ.title()
        self.cron = cron.title()
        self.refs = {self.templ: templ,
                     self.cron: cron,
                     }
        pywikibot.output(u'** Pre-loading all relevant page contents')
        for item in self.refs:
            # First check if page is protected, reject any data if not
            parts = self.refs[item].title().lower().rsplit('.')
            if len(parts) == 1 or parts[1] not in ['.css', '.js']:
                raise ValueError('%s config %s = %s is not a secure page; '
                                 'it should be a css or js userpage which are '
                                 'automatically semi-protected.'
                                 % (self.__class__.__name__, item,
                                    self.refs[item]))
            try:
                self.refs[item].get(force=True)   # load all page contents
            except pywikibot.NoPage:
                pywikibot.error("The configuation page %s doesn't exists"
                                % self.refs[item].title(asLink=True))
                raise
        # init background timer
        pywikibot.output(u'** Starting crontab background timer thread')
        self.on_timer()

    def on_pubmsg(self, c, e):
        match = self.re_edit.match(e.arguments()[0])
        if not match:
            return
        user = match.group('user').decode(self.site.encoding())
        if user == bot_config['BotName']:
            return
        # test actual page against (template incl.) list
        page = match.group('page').decode(self.site.encoding())
        if page in self.refs:
            pywikibot.output(u"RELOAD: %s" % page)
            self.refs[page].get(force=True)   # re-load (refresh) page content
        if page == self.templ:
            pywikibot.output(u"SHELL: %s" % page)
            self.do_check(page)

    def on_timer(self):
        self.t = threading.Timer(bot_config['CRONMaxDelay'], self.on_timer)
        self.t.start()

        self.do_check_CronJobs()

    def do_check_CronJobs(self):
        # check cron/date (changes of self.refs are tracked (and reload) in
        # on_pubmsg)
        page = self.refs[self.templ]
        ctab = self.refs[self.cron].get()
        # extract 'rev' and 'timestmp' from 'crontab' page text ...

        # hacky/ugly/cheap; already better done in trunk dtbext
        for line in ctab.splitlines():
            (rev, timestmp) = [item.strip() for item in line[1:].split(',')]

            # [min] [hour] [day of month] [month] [day of week]
            # (date supported only, thus [min] and [hour] dropped)
            entry = crontab.CronTab(timestmp)
            # find the delay from current minute
            # (does not return 0.0 - but next)
            now = datetime.datetime.now().replace(second=0, microsecond=0)
            delay = entry.next(
                now - datetime.timedelta(microseconds=1))

            if (delay <= bot_config['CRONMaxDelay']):
                pywikibot.output('CRONTAB: %s / %s / %s' %
                                 (page, rev, timestmp))
                self.do_check(page.title(), int(rev))

    def do_check(self, page_title, rev=None, params=None):
        # Create two threads as follows
        # (simple 'thread' for more sophisticated code use 'threading')
        try:
            thread.start_new_thread(main_script, (self.refs[page_title], rev,
                                                  params))
        except Exception:
            # (done according to subster in trunk and submit in
            # rewrite/.../data/api.py)
            # TODO: is this error handling here needed at all??!?

            # secure traceback print (from api.py submit)
            pywikibot.exception(tb=True)
            pywikibot.warning(u"Unable to start thread")

            wiki_logger(traceback.format_exc(), self.refs[page_title], rev)

# Define a function for the thread

# pylint: disable=unused-argument
def main_script(page, rev=None, params=NotImplemented):
    """Main thread."""
    # http://opensourcehacker.com/2011/02/23/temporarily-capturing-python-logging-output-to-a-string-buffer/

    # safety; default mode is safe (no writing)
    pywikibot.config.simulate = True

    pywikibot.output(u'--- ' * 20)

    buffer = StringIO()
    rootLogger = logging.getLogger()

    logHandler = logging.StreamHandler(buffer)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    logHandler.setFormatter(formatter)
    rootLogger.addHandler(logHandler)

    sys.stdout = buffer
    sys.stderr = buffer

    # all output to logging and stdout/stderr is catched BUT NOT lua output (!)
    if rev is None:
        code = page.get()               # shell; "on demand"
    else:
        code = page.getOldVersion(rev)  # crontab; scheduled
    try:
        exec(code)
    except Exception:
        # (done according to subster in trunk and submit in
        # rewrite/.../data/api.py)

        # secure traceback print (from api.py submit)
        pywikibot.exception(tb=True)

    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__

    # Remove our handler
    rootLogger.removeHandler(logHandler)

    logHandler.flush()
    buffer.flush()

    pywikibot.output(u'--- ' * 20)

    # safety; restore settings
    pywikibot.config.simulate = __simulate
    sys.argv = __sys_argv
    if resource:
        pywikibot.output(
            u'environment: garbage; %s / memory; %s / members; %s' % (
                gc.collect(),
                resource.getrusage(resource.RUSAGE_SELF).ru_maxrss *
                resource.getpagesize(),
                len(dir())))
    else:
        pywikibot.output(
            u'environment: garbage; %s / members; %s' % (
                gc.collect(), len(dir())))
    # 'len(dir())' is equivalent to 'len(inspect.getmembers(__main__))'

    # append result to output page
    if rev is None:
        wiki_logger(buffer.getvalue(), page, rev)

def wiki_logger(buffer, page, rev=None):
    """Log to wiki."""
    # FIXME: what is this??
    # (might be a problem here for TS and SGE, output string has another
    # encoding)
    if False:
        buffer = buffer.decode(pywikibot.config.console_encoding)
    buffer = re.sub(r'\03\{(.*?)\}(.*?)\03\{default\}', r'\g<2>', buffer)
    if rev is None:
        rev = page.latestRevision()
        link = page.permalink(oldid=rev)
    # append to page
    outpage = pywikibot.Page(pywikibot.Site(), bot_config['ConfCSSoutput'])
    text = outpage.get()
    outpage.put(
        text + ('\n== Simulation vom %s mit [%s code:%s] =='
                '\n<pre>\n%s</pre>\n\n')
        % (pywikibot.Timestamp.now().isoformat(' '), link, rev, buffer))
#        summary=pywikibot.translate(self.site.lang, bot_config['msg']))

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    global __simulate, __sys_argv

    unknown_args = pywikibot.handle_args(args)
    if unknown_args:
        pywikibot.bot.suggest_help(unknown_parameters=unknown_args)
        return False

    __simulate = pywikibot.config.simulate
    __sys_argv = sys.argv

    site = pywikibot.Site()
    site.login()
    chan = '#' + site.code + '.' + site.family.name

    bot_user_name = pywikibot.config.usernames[pywikibot.config.family][
        pywikibot.config.mylang]
    for key, value in bot_config.items():
        if hasattr(value, 'format'):
            bot_config[key] = value.format(username=bot_user_name)

    bot = ScriptWUIBot(site, chan, site.user() + "_WUI", "irc.wikimedia.org")
    try:
        bot.start()
    except BaseException:
        bot.t.cancel()
        raise

if __name__ == "__main__":
    main()