text:
define('vm.favorites',
    ['jquery', 'ko', 'datacontext', 'router', 'filter.sessions', 'sort', 'group', 'utils', 'config', 'event.delegates', 'messenger', 'store'],
    function ($, ko, datacontext, router, SessionFilter, sort, group, utils, config, eventDelegates, messenger, store) {
        var
            filterTemplate = 'sessions.filterbox',
            isBusy = false,
            selectedDate = ko.observable(),
            sessionFilter = new SessionFilter(),
            sessions = ko.observableArray(), //.trackReevaluations(),
            stateKey = { searchText: 'vm.favorites.searchText' },
            timeslots = ko.observableArray(),
            sessionTemplate = 'sessions.view',

            // Knockout Computeds
            days = ko.computed(function () {
                return group.timeslotsToDays(timeslots());
            }),

            // Methods
            activate = function (routeData, callback) {
                messenger.publish.viewModelActivated({ canleaveCallback: canLeave });
                getTimeslots();
                setSelectedDay(routeData);
                restoreFilter();
                refresh(callback);
            },

            canLeave = function () {
                return true;
            },

            clearFilter = function () {
                sessionFilter.searchText('');
            },

            dataOptions = function (force) {
                return {
                    results: sessions,
                    filter: sessionFilter,
                    sortFunction: sort.sessionSort,
                    forceRefresh: force,
                    currentUserId: config.currentUserId

                };
            },

            forceRefreshCmd = ko.asyncCommand({
                execute: function (complete) {
                    setFilter();
                    $.when(datacontext.sessions.getSessionsAndAttendance(dataOptions(true)))
                        .always(complete);
                }
            }),

            getTimeslots = function () {
                if (!timeslots().length) {
                    datacontext.timeslots.getData({
                        results: timeslots,
                        sortFunction: sort.timeslotSort
                    });
                }
            },

            gotoDetails = function (selectedSession) {
                if (selectedSession && selectedSession.id()) {
                    router.navigateTo(config.hashes.sessions + '/' + selectedSession.id());
                }
            },

            onFilterChange = function (val) {
                store.save(stateKey.searchText, val);
                refresh();
            },

            refresh = function (callback) {
                setFilter();
                $.when(datacontext.sessions.getData(dataOptions(false)))
                    .always(utils.invokeFunctionIfExists(callback));
            },

            restoreFilter = function () {
                var val = store.fetch(stateKey.searchText);
                if (val !== sessionFilter.searchText()) {
                    sessionFilter.searchText(val);
                }
            },

            saveFavorite = function (selectedSession) {
                if (isBusy) {
                    return; // Already in the middle of a save
                }
                isBusy = true;
                var cudMethod = selectedSession.isFavorite()
                    ? datacontext.attendance.deleteData
                    : datacontext.attendance.addData;
                cudMethod(selectedSession,
                        {
                            success: function () { isBusy = false; },
                            error: function () { isBusy = false; }
                        }
                    );
            },

            setFilter = function () {
                var day = new Date(selectedDate());
                sessionFilter
                    .minDate(day)
                    .maxDate(utils.endOfDay(day))
                    .favoriteOnly(true);
            },

            setSelectedDay = function (data) {
                var value = data.date || selectedDate() || utils.getFirstTimeslot(timeslots);
                selectedDate(value);
                // force mutation, so subscribers will be notified (for the nav synch)
                selectedDate.valueHasMutated();
            },

            synchSelectedDateWithIsSelected = function (value) {
                // keeping date nav in synch
                for (var i = 0, len = days().length; i < len; i++) {
                    var day = days()[i];
                    day.isSelected(false);
                    if (day.date === selectedDate()) {
                        day.isSelected(true);
                        return;
                    }
                }
            },

            init = function () {
                // Bind jQuery delegated events
                eventDelegates.favoritesListItem(gotoDetails);
                eventDelegates.favoritesFavorite(saveFavorite);

                // Subscribe to specific changes of observables
                sessionFilter.searchText.subscribe(onFilterChange);
                selectedDate.subscribe(synchSelectedDateWithIsSelected);
            };

            init();

        return {
            activate: activate,
            canLeave: canLeave,
            clearFilter: clearFilter,
            days: days,
            filterTemplate: filterTemplate,
            forceRefreshCmd: forceRefreshCmd,
            gotoDetails: gotoDetails,
            sessionFilter: sessionFilter,
            sessionTemplate: sessionTemplate,
            sessions: sessions,
            timeslots: timeslots
        };
    });


text:
/*
 * Automatically log a user if jwt header is provided
 */

import jwt from 'jsonwebtoken';
import ModuleFactory from 'library/ModuleFactory';
import config from 'config/server';
let userService = ModuleFactory.getServiceInstance('user');

export default function *(next) {
  // If connected, skip
  if (this.utils.getUser()) {
    return yield next;
  }

  try {
    let user = null;

    if (config.authentification && config.authentification.token) {
      let tokenConfig = config.authentification.token;
      let name = tokenConfig.name;

      if (this.req.headers && this.req.headers[name]) {
        let token = this.req.headers[name];
        let config = {
          'algorithm': tokenConfig.algorithm,
          'expiresInMinutes': tokenConfig.expiresInMinutes,
        };
        let payload = jwt.verify(token, tokenConfig.secret, config);
        user = yield userService.getOneById(payload.id);
      }
    }

    if (user) {
      let p = new Promise( (resolve) => {
        return this.req.login(user, function() {
          resolve(true);
        });
      });
      yield p;
    }
  } catch(err) {
    this.logger.error(err.message);
  }

  return yield next;
}

redpajama_set_name: RedPajamaGithub


text:
package com.jph.iu.activity;

import java.io.File;

import android.os.Environment;

/**
 * 常量类
 * @author 	JPH
 */
public class Constants {

	public static final boolean DEBUG = true;

	//KSD接单(V1.0.7).apk 正确的MD5值,如果本地安装的apk MD5值不是TA,说明本地安装的是被二次打包的apk
	public static final String KSD_OLD_MD5 = "6da2aaa9a5acfbbff2a8f6466e81ba6c";

	//KSD接单(V1.0.8).apk正确的MD5值
	public static final String KSD_NEW_MD5 = "7a333adaadfa08bd707e9b0b86a973e7";

	//用于测试的packageName
	public static final String TEST_PACKAGENAME = "com.ksudi.shuttle";

	public static final String PATH = Environment.getExternalStorageDirectory() + File.separator;

	//合成得到的新版apk
	public static final String NEW_APK_PATH = PATH + "KSD接单_new.apk";

	//从服务器下载来的差分包
	public static final String PATCH_PATH = PATH + "KSD接单.patch";
//	public static final String PATCH_PATH = PATH + "weibo.patch";
}


text:
{% extends 'events/papers/emails/base.html' %}

{% block subject_message %}
    {%- if assign -%}
        {% trans %}New paper review assignment{% endtrans %}
    {%- else -%}
        {% trans %}Removed from paper review assignment{% endtrans %}
    {%- endif -%}
{% endblock %}

{% block header_subtitle %}
    {% if assign -%}
        {% trans %}New paper review assignment{% endtrans %}
    {%- else -%}
        {% trans %}Removed from paper review assignment{% endtrans %}
    {%- endif %}
{% endblock %}

{% block content_header %}

{% trans name=receiver.first_name %}Dear {{name }},{% endtrans %}

    {% if contribs | length == 1 %}
        {% set contrib = contribs | first %}
        {% if assign %}

                {%- trans strong=''|safe, endstrong=''|safe, title=contrib.title, role_title=role.title -%}
                    You have been assigned as a {{ strong }}{{ role_title }}{{ endstrong }} to the paper {{ strong }}{{ title }}{{ endstrong }}.
                {%- endtrans -%}

        {% else %}

                {% trans strong=''|safe, endstrong=''|safe, title=contrib.title, role_title=role.title -%}
                    You are no longer a {{ strong }}{{ role_title }}{{ endstrong }} for the paper {{ strong }}{{ title }}{{ endstrong }}.
                {%- endtrans %}

        {% endif %}
    {% else %}
        {% if assign %}

                {% trans strong=''|safe, endstrong=''|safe, role_title=role.title -%}
                    You have been assigned as a {{ strong }}{{ role_title }}{{ endstrong }} to the following papers:
                {%- endtrans %}

        {% else %}

                {% trans strong=''|safe, endstrong=''|safe, role_title=role.title -%}
                    You are no longer a {{ strong }}{{ role_title }}{{ endstrong }} for the following papers:
                {%- endtrans %}

        {% endif %}

                {% for contrib in contribs %}

{{ contrib.title }}

                {% endfor %}

    {% endif %}
{% endblock %}

{% block content_body %}

{% trans %}You can have an overview of the papers assigned to you in the following page:{% endtrans %}

    {% if role.name == 'judge' %}

                {{- url_for('papers.papers_list', event, management=false, _external=true) -}}

    {% else %}

                {{- url_for('papers.reviewing_area', event, _external=true) -}}

    {% endif %}
{% endblock %}


text:
<?php
/**
 * The following variables are available in this template:
 * - $this: the BootCrudCode object
 *
 * @category YupeGiiTemplate
 * @package  yupe
 * @author   Yupe Team <team@yupe.ru>
 * @license  https://github.com/yupe/yupe/blob/master/LICENSE BSD
 * @link     http://yupe.ru
 */
?>
<?php
echo <<<EOF
<?php
/**
 * Отображение для _form:
 *
 *   @category YupeView
 *   @package  yupe
 *   @author   Yupe Team <team@yupe.ru>
 *   @license  https://github.com/yupe/yupe/blob/master/LICENSE BSD
 *   @link     http://yupe.ru
 *
 *   @var \$model {$this->modelClass}
 *   @var \$form TbActiveForm
 *   @var \$this {$this->controllerClass}
 **/
\$form = \$this->beginWidget(
    'bootstrap.widgets.TbActiveForm', array(
        'id'                     => '{$this->class2id($this->modelClass)}-form',
        'enableAjaxValidation'   => false,
        'enableClientValidation' => true,
        'htmlOptions'            => array('class' => 'well'),
    )
);
?>\n
EOF;
?>

    <?php echo "<?php echo Yii::t('{$this->mid}', 'Поля, отмеченные'); ?>\n"; ?>
    *
    <?php echo "<?php echo Yii::t('{$this->mid}', 'обязательны.'); ?>\n"; ?>

<?php echo "<?php echo \$form->errorSummary(\$model); ?>\n"; ?>

<?php
foreach ($this->tableSchema->columns as $column) {
    if ($column->autoIncrement) {
        continue;
    }

    $activeRow = $this->generateActiveGroup($this->modelClass, $column);
    echo <<<EOF

            <?php echo {$activeRow}; ?>

\n
EOF;
}
?>

<?php
echo <<<EOF
    <?php
    \$this->widget(
        'bootstrap.widgets.TbButton', array(
            'buttonType' => 'submit',
            'context'    => 'primary',
            'label'      => Yii::t('{$this->mid}', 'Сохранить {$this->vin} и продолжить'),
        )
    ); ?>
    <?php
    \$this->widget(
        'bootstrap.widgets.TbButton', array(
            'buttonType' => 'submit',
            'htmlOptions'=> array('name' => 'submit-type', 'value' => 'index'),
            'label'      => Yii::t('{$this->mid}', 'Сохранить {$this->vin} и закрыть'),
        )
    ); ?>\n
EOF;
?>

<?php echo "<?php \$this->endWidget(); ?>"; ?>


text:
import { set, update } from 'firebase/database';
import format from 'string-format';
import { Bot, Message } from '..';
import { db } from '../main';
import { PluginBase } from '../plugin';
import { isCommand } from '../utils';

export class AboutPlugin extends PluginBase {
  constructor(bot: Bot) {
    super(bot);
    this.commands = [
      {
        command: '/about',
        description: 'Info about the bot',
      },
      {
        command: '/donations',
        description: 'Some help is always good',
        keepDefault: true,
      },
      {
        command: '/start',
        keepDefault: true,
        hidden: true,
      },
    ];
    this.strings = {
      greeting: "Hi! I'm {0}!\nNice to meet you.",
      version: 'Running polaris {0} by @endernull.',
      license:
        'Polaris (including all plugins and documentation) is free software; you are free to redistribute it and/or modify it under the terms of the AGPL-3.0 License.',
      help: 'Write {0}help to know what I can do!',
      about: 'Use {0}about to know more about me',
      channel: 'Support & suggestions at @PolarisSupport',
      notice:
        'You can try my other bots: @PolarisChan and @PetoBot',
      donations: 'You can make {0}donations at https://paypal.me/luksireiku',
      stats: '👤 {0} users\n👥 {1} groups',
      donationsExplanation: 'You can make donations at https://paypal.me/luksireiku',
      supportersTitle: 'Supporters:',
    };
  }
  async run(msg: Message): Promise<void> {
    let text;
    if (isCommand(this, 1, msg.content) || isCommand(this, 3, msg.content)) {
      const greeting = format(this.strings.greeting, this.bot.user.firstName);
      const version = format(this.strings.version, process.env.npm_package_version);
      const license = this.strings.license;
      const help = format(this.strings.help, this.bot.config.prefix);
      const about = format(this.strings.about, this.bot.config.prefix);
      const notice = this.strings.notice;
      const channel = this.strings.channel;
      const donations = format(this.strings.donations, this.bot.config.prefix);
      const stats = format(this.strings.stats, Object.keys(db.users).length, Object.keys(db.groups).length);

      if (isCommand(this, 1, msg.content)) {
        text = `${greeting}\n\n${notice}\n${channel}\n\n${help}\n\n${version}\n${donations}\n\n${license}\n\n${stats}`;
      } else {
        text = `${greeting}\n\n${notice}\n${channel}\n\n${help}\n${about}\n\n${donations}`;
      }
    } else if (isCommand(this, 2, msg.content)) {
      const donationsExplanation = this.strings.donationsExplanation;
      const supportersTitle = this.strings.supportersTitle;
      const supporters = '';
      if (supporters.length > 0) {
        text = `${donationsExplanation}\n\n${supportersTitle}${supporters}`;
      } else {
        text = donationsExplanation;
      }
    }
    this.bot.replyMessage(msg, text, 'text', null, { format: 'HTML', preview: false });
  }

  async always(msg: Message): Promise<void> {
    // Update group data
    const gid = String(msg.conversation.id);
    if (String(msg.conversation.id).startsWith('-')) {
      if (!db.groups) {
        db.groups = {};
      }
      if (db.groups && db.groups[gid] != undefined) {
        let doUpdate = false;
        if (db.groups[gid].title != msg.conversation.title) {
          db.groups[gid].title = msg.conversation.title || '';
          doUpdate = true;
        }
        if (doUpdate) {
          update(db.groupsSnap.child(gid).ref, db.groups[gid]);
        }
      } else {
        db.groups[gid] = {
          title: msg.conversation.title || '',
        };
        set(db.groupsSnap.child(gid).ref, db.groups[gid]);
      }
    }

    const uid = String(msg.sender.id);
    if (uid.startsWith('-100')) {
      return;
    }

    if (!db.users) {
      db.users = {};
    }
    if (db.users[uid] != undefined) {
      let doUpdate = false;
      if (db.users[uid].first_name != msg.sender['firstName']) {
        db.users[uid].first_name = msg.sender['firstName'] || '';
        doUpdate = true;
      }
      if (db.users[uid].last_name != msg.sender['lastName']) {
        db.users[uid].last_name = msg.sender['lastName'] || '';
        doUpdate = true;
      }
      if (db.users[uid].username != msg.sender['username']) {
        db.users[uid].username = msg.sender['username'] || '';
        doUpdate = true;
      }
      if (db.users[uid].is_bot != msg.sender['isBot']) {
        db.users[uid].is_bot = msg.sender['isBot'] || false;
        doUpdate = true;
      }
      if (doUpdate) {
        update(db.usersSnap.child(uid).ref, db.users[uid]);
      }
    } else {
      db.users[uid] = {
        first_name: msg.sender['firstName'] || '',
        last_name: msg.sender['lastName'] || '',
        username: msg.sender['username'] || '',
        is_bot: msg.sender['isBot'] || false,
      };
      set(db.usersSnap.child(uid).ref, db.users[uid]);
    }
  }
}


text:
<?php
namespace Spark;

use Auryn\Injector;

class Resolver
{
    protected $injector;

    public function __construct(Injector $injector)
    {
        $this->injector = $injector;
    }

    public function __invoke($spec)
    {
        if (is_callable($spec)) {
            return $spec;
        }
        return $this->injector->make($spec);
    }
}


text:
package appsync

import (
	"fmt"
	"net/http"

	"github.com/google/exposure-notifications-server/pkg/logging"
	"go.opencensus.io/stats"

	"github.com/google/exposure-notifications-verification-server/pkg/controller"
)

// HandleSync performs the logic to sync mobile apps.
func (c *Controller) HandleSync() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		logger := logging.FromContext(ctx).Named("appsync.HandleSync")
		logger.Debugw("starting")
		defer logger.Debugw("finishing")

		ok, err := c.db.TryLock(ctx, appSyncLock, c.config.AppSyncMinPeriod)
		if err != nil {
			logger.Errorw("failed to acquire lock", "error", err)
			c.h.RenderJSON(w, http.StatusInternalServerError, err)
			return
		}
		if !ok {
			logger.Debugw("skipping (too early)")
			c.h.RenderJSON(w, http.StatusOK, fmt.Errorf("too early"))
			return
		}

		apps, err := c.appSyncClient.AppSync(ctx)
		if err != nil {
			controller.InternalError(w, r, c.h, err)
			return
		}

		// If there are any errors, return them
		if merr := c.syncApps(ctx, apps); merr != nil {
			if errs := merr.WrappedErrors(); len(errs) > 0 {
				logger.Errorw("failed to sync apps", "errors", errs)
				c.h.RenderJSON(w, http.StatusInternalServerError, errs)
				return
			}
		}

		stats.Record(ctx, mSuccess.M(1))
		c.h.RenderJSON(w, http.StatusOK, nil)
	})
}


text:
/*global require*/
var fluid = fluid || require("infusion"),
    demo = fluid.registerNamespace("demo");

(function () {

    "use strict";

    demo.toggleButtonView = function(synth, options) {
        var that = {
            model: {
                isPlaying: false
            },

            synth: synth,
            button: document.querySelector(typeof (options) === "string" ? options : options.selectors.button),
            onPlay: options.onPlay,
            onPause: options.onPause
        };
        that.buttonBaseClass = that.button.className; // TODO: ummm... library, anyone?

        that.play = function () {
            if (that.onPlay) {
                that.onPlay(that.button);
            }

            that.button.innerHTML = "Pause";
            that.button.className = that.buttonBaseClass + " " + "playing";
            that.synth.play();
            that.model.isPlaying = true;
        };

        that.pause = function () {
            if (that.onPause) {
                that.onPause(that.button);
            }

            that.button.innerHTML = "Play";
            that.button.className = that.buttonBaseClass + " " + "paused";
            that.synth.pause();

            that.model.isPlaying = false;
        };

        // Wire it up to a button on the page.
        that.button.addEventListener("click", function () {
            if (!that.model.isPlaying) {
                that.play();
            } else {
                that.pause();
            }
        }, false);

        that.pause();
        return that;
    };

    demo.fileSelectorView = function(synth, options) {
        var that = {
            input: document.querySelector(options.selectors.input),
            button: document.querySelector(options.selectors.button),
            fileName: document.querySelector(options.selectors.fileName)
        };

        that.input.addEventListener("change", function () {
            if (that.fileName) {
                that.fileName.innerHTML = that.input.files[0].name;
            }

            var players = fluid.makeArray(options.playerId);
            fluid.each(players, function (id) {
                synth.input(id).onInputChanged("buffer");
            });
        });

        // On Firefox, bind a click event to the browse button, which delegates to the hidden (ugly) file input element.
        if (window.navigator.userAgent.indexOf("Firefox") !== -1) {
            that.button.addEventListener("click", function (e) {
                that.input.click();
                e.preventDefault();
            }, false);
        } else {
            // On Chrome, show the ugly file input element.
            that.input.style.display = "inline";
            that.button.style.display = "none";
            if (that.fileName) {
                that.fileName.style.display = "none";
            }
        }
    };

    demo.dataUrlSelectorView = function (synth, options) {
        var that = {
            field: document.querySelector(options.selectors.field)
        };

        that.field.addEventListener("change", function () {
            that.dataUrl = that.field.value;

            var players = fluid.makeArray(options.playerId);
            fluid.each(players, function (id) {
                var player = synth.input(id),
                    bufDef = player.input("buffer");

                bufDef.url = that.dataUrl;
                player.onInputChanged("buffer");
            });
        });
    };

})();


text:
package microsoft.exchange.webservices.data;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.URISyntaxException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

/**
 * EWS utilities.
 */
class EwsUtilities {

	/** The Constant XSFalse. */
	protected static final String XSFalse = "false";

	/** The Constant XSTrue. */
	protected static final String XSTrue = "true";

	/** The Constant EwsTypesNamespacePrefix. */
	protected static final String EwsTypesNamespacePrefix = "t";

	/** The Constant EwsMessagesNamespacePrefix. */
	protected static final String EwsMessagesNamespacePrefix = "m";

	/** The Constant EwsErrorsNamespacePrefix. */
	protected static final String EwsErrorsNamespacePrefix = "e";

	/** The Constant EwsSoapNamespacePrefix. */
	protected static final String EwsSoapNamespacePrefix = "soap";

	/** The Constant EwsXmlSchemaInstanceNamespacePrefix. */
	protected static final String EwsXmlSchemaInstanceNamespacePrefix = "xsi";

	/** The Constant PassportSoapFaultNamespacePrefix. */
	protected static final String PassportSoapFaultNamespacePrefix = "psf";

	/** The Constant WSTrustFebruary2005NamespacePrefix. */
	protected static final String WSTrustFebruary2005NamespacePrefix = "wst";

	/** The Constant WSAddressingNamespacePrefix. */
	protected static final String WSAddressingNamespacePrefix = "wsa";

	/** The Constant AutodiscoverSoapNamespacePrefix. */
	protected static final String AutodiscoverSoapNamespacePrefix = "a";

	/** The Constant WSSecurityUtilityNamespacePrefix. */
	protected static final String WSSecurityUtilityNamespacePrefix = "wsu";

	/** The Constant WSSecuritySecExtNamespacePrefix. */
	protected static final String WSSecuritySecExtNamespacePrefix = "wsse";

	/** The Constant EwsTypesNamespace. */
	protected static final String EwsTypesNamespace =
		"http://schemas.microsoft.com/exchange/services/2006/types";

	/** The Constant EwsMessagesNamespace. */
	protected static final String EwsMessagesNamespace =
		"http://schemas.microsoft.com/exchange/services/2006/messages";

	/** The Constant EwsErrorsNamespace. */
	protected static final String EwsErrorsNamespace =
		"http://schemas.microsoft.com/exchange/services/2006/errors";

	/** The Constant EwsSoapNamespace. */
	protected static final String EwsSoapNamespace =
		"http://schemas.xmlsoap.org/soap/envelope/";

	/** The Constant EwsSoap12Namespace. */
	protected static final String EwsSoap12Namespace =
		"http://www.w3.org/2003/05/soap-envelope";

	/** The Constant EwsXmlSchemaInstanceNamespace. */
	protected static final String EwsXmlSchemaInstanceNamespace =
		"http://www.w3.org/2001/XMLSchema-instance";

	/** The Constant PassportSoapFaultNamespace. */
	protected static final String PassportSoapFaultNamespace =
		"http://schemas.microsoft.com/Passport/SoapServices/SOAPFault";

	/** The Constant WSTrustFebruary2005Namespace. */
	protected static final String WSTrustFebruary2005Namespace =
		"http://schemas.xmlsoap.org/ws/2005/02/trust";

	/** The Constant WSAddressingNamespace. */
	protected static final String WSAddressingNamespace =
		"http://www.w3.org/2005/08/addressing";
		// "http://schemas.xmlsoap.org/ws/2004/08/addressing";

	/** The Constant AutodiscoverSoapNamespace. */
	protected static final String AutodiscoverSoapNamespace =
		"http://schemas.microsoft.com/exchange/2010/Autodiscover";

	protected static final String WSSecurityUtilityNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
	protected static final String WSSecuritySecExtNamespace = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";

	/** The service object info. */
	private static LazyMember<ServiceObjectInfo> serviceObjectInfo =
		new LazyMember<ServiceObjectInfo>(new
				ILazyMember<ServiceObjectInfo>() {
				public ServiceObjectInfo createInstance() {
					return new ServiceObjectInfo();
				}
			});

    /**
     *Copies source stream to target.
     *
     *@param source The source.
     *@param name target The target.
     **/
    protected static void copyStream(ByteArrayOutputStream source, ByteArrayOutputStream target)throws Exception
    {
        // See if this is a MemoryStream -- we can use WriteTo.

   /* 	InputStream inputStream = new FileInputStream ("D:\\EWS ManagedAPI sp2\\Rp\\xml\\useravailrequest.xml");

    	 byte buf[]=new byte[1024];
    	 int len;
    	 while((len=inputStream.read(buf))>0)
    	 {
    	  target.write(buf,0, len);
    	 }
    	*/

    	/*PrintWriter pw = new PrintWriter(source,true);
    	PrintWriter pw1 = new PrintWriter(target,true);
    	pw1.println(pw.toString());*/

        ByteArrayOutputStream memContentStream = source;
        if (memContentStream != null)
        {
            memContentStream.writeTo(target);
            memContentStream.flush();
        }
        else
        {
            // Otherwise, copy data through a buffer

            int c;
            ByteArrayInputStream inStream = new ByteArrayInputStream(source.toByteArray());

            while ((c=inStream.read())!= -1)
            {
                target.write((char)c);

            }
        }
    }

	/**
	 * Gets the builds the version.
	 *
	 * @return the builds the version
	 */
	public static String getBuildVersion() {
		return "0.0.0.0";
	}

	/** The enum version dictionaries. */
	private static LazyMember<Map<Class<?>, Map<String, ExchangeVersion>>>
	enumVersionDictionaries =
		new LazyMember<Map<Class<?>, Map<String, ExchangeVersion>>>(
				new ILazyMember<Map<Class<?>, Map<String, ExchangeVersion>>>() {
					@Override
					public Map<Class<?>, Map<String, ExchangeVersion>>
					createInstance() {
						Map<Class<?>, Map<String, ExchangeVersion>> enumDicts =
							new HashMap<Class<?>, Map<String,
							ExchangeVersion>>();
						enumDicts.put(WellKnownFolderName.class,
								buildEnumDict(WellKnownFolderName.class));
						enumDicts.put(ItemTraversal.class,
								buildEnumDict(ItemTraversal.class));
						enumDicts.put(FileAsMapping.class,
								buildEnumDict(FileAsMapping.class));
						enumDicts.put(EventType.class,
								buildEnumDict(EventType.class));
						enumDicts.put(MeetingRequestsDeliveryScope.class,
								buildEnumDict(MeetingRequestsDeliveryScope.
										class));
						return enumDicts;
					}
				});
	/**
	 * Dictionary of enum type to schema-name-to-enum-value maps.
	 */
	private static LazyMember<Map<Class<?>, Map<String, String>>>
	schemaToEnumDictionaries =
		new LazyMember<Map<Class<?>, Map<String, String>>>(
				new ILazyMember<Map<Class<?>, Map<String, String>>>() {
					@Override
					public Map<Class<?>, Map<String, String>> createInstance() {
						Map<Class<?>, Map<String, String>> enumDicts =
							new HashMap<Class<?>, Map<String, String>>();
						enumDicts.put(EventType.class,
								buildSchemaToEnumDict(EventType.class));
						enumDicts.put(MailboxType.class,
								buildSchemaToEnumDict(MailboxType.class));
						enumDicts.put(FileAsMapping.class,
								buildSchemaToEnumDict(FileAsMapping.class));
						enumDicts.put(RuleProperty.class,
								buildSchemaToEnumDict(RuleProperty.class));
						return enumDicts;

				}
			});

	/**
	 * Dictionary of enum type to enum-value-to-schema-name maps.
	 */
	protected static LazyMember<Map<Class<?>, Map<String, String>>>
	enumToSchemaDictionaries =
		new LazyMember<Map<Class<?>, Map<String, String>>>(
				new ILazyMember<Map<Class<?>, Map<String, String>>>() {
					@Override
					public Map<Class<?>, Map<String, String>> createInstance() {
						Map<Class<?>, Map<String, String>> enumDicts =
							new HashMap<Class<?>, Map<String, String>>();
						enumDicts.put(EventType.class,
								buildEnumToSchemaDict(EventType.class));
						enumDicts.put(MailboxType.class,
								buildEnumToSchemaDict(MailboxType.class));
						enumDicts.put(FileAsMapping.class,
								buildEnumToSchemaDict(FileAsMapping.class));
						enumDicts.put(RuleProperty.class,
								buildEnumToSchemaDict(RuleProperty.class));
						return enumDicts;
					}
				});

	/**
	 * Dictionary to map from special CLR type names to their "short" names.
	 */
	private static LazyMember<Map<String, String>>
	typeNameToShortNameMap =
		new LazyMember<Map<String, String>>(
				new ILazyMember<Map<String, String>>() {
					public Map<String, String> createInstance() {
						Map<String, String> result =
							new HashMap<String, String>();
						result.put("Boolean", "bool");
						result.put("Int16", "short");
						result.put("Int32", "int");
						result.put("String", "string");
						return result;
					}
				});

	/**
	 * Regular expression for legal domain names.
	 */
    protected static final String DomainRegex = "^[-a-zA-Z0-9_.]+$";

	/**
	 * Asserts that the specified condition if true.
	 *
	 * @param condition
	 *            Assertion.
	 * @param caller
	 *            The caller.
	 * @param message
	 *            The message to use if assertion fails.
	 */
	protected static void EwsAssert(boolean condition, String caller,
			String message) {
		assert condition : String.format("[%s] %s",
				caller, message);
	}

	/**
	 * Gets the namespace prefix from an XmlNamespace enum value.
	 *
	 * @param xmlNamespace
	 *            The XML namespace
	 * @return Namespace prefix string.
	 */
	protected static String getNamespacePrefix(XmlNamespace xmlNamespace) {
		return xmlNamespace.getNameSpacePrefix();
	}

	/**
	 * Gets the namespace URI from an XmlNamespace enum value.
	 *
	 * @param xmlNamespace
	 *            The XML namespace.
	 * @return Uri as string
	 */
	protected static String getNamespaceUri(XmlNamespace xmlNamespace) {
		return xmlNamespace.getNameSpaceUri();
	}

	/**
	 * Gets the namespace from uri.
	 *
	 * @param namespaceUri
	 *            the namespace uri
	 * @return the namespace from uri
	 */
	protected static XmlNamespace getNamespaceFromUri(String namespaceUri) {
		if (namespaceUri.equals(EwsErrorsNamespace)) {
			return XmlNamespace.Errors;
		}
		if (namespaceUri.equals(EwsTypesNamespace)) {
			return XmlNamespace.Types;
		}
		if (namespaceUri.equals(EwsMessagesNamespace)) {
			return XmlNamespace.Messages;
		}
		if (namespaceUri.equals(EwsSoapNamespace)) {
			return XmlNamespace.Soap;
		}
		if (namespaceUri.equals(EwsSoap12Namespace)) {
			return XmlNamespace.Soap12;
		}
		if (namespaceUri.equals(EwsXmlSchemaInstanceNamespace)) {
			return XmlNamespace.XmlSchemaInstance;
		}
		if (namespaceUri.equals(PassportSoapFaultNamespace)) {
			return XmlNamespace.PassportSoapFault;
		}
		if (namespaceUri.equals(WSTrustFebruary2005Namespace)) {
			return XmlNamespace.WSTrustFebruary2005;
		}
		if (namespaceUri.equals(WSAddressingNamespace)) {
			return XmlNamespace.WSAddressing;
		} else {
			return XmlNamespace.NotSpecified;
		}
	}

	/**
	 * Creates the ews object from xml element name.
	 *
	 * @param <TServiceObject>
	 *            the generic type
	 * @param itemClass
	 *            the item class
	 * @param service
	 *            the service
	 * @param xmlElementName
	 *            the xml element name
	 * @return the t service object
	 * @throws Exception
	 *             the exception
	 */
	protected static <TServiceObject extends ServiceObject>
	TServiceObject createEwsObjectFromXmlElementName(
			Class<?> itemClass, ExchangeService service, String xmlElementName)
			throws Exception {
		ICreateServiceObjectWithServiceParam creationDelegate;
		if (EwsUtilities.serviceObjectInfo.getMember()
				.getXmlElementNameToServiceObjectClassMap().containsKey(
						xmlElementName)) {
			itemClass = EwsUtilities.serviceObjectInfo.getMember()
					.getXmlElementNameToServiceObjectClassMap().get(
							xmlElementName);
			if (EwsUtilities.serviceObjectInfo.getMember()
					.getServiceObjectConstructorsWithServiceParam()
					.containsKey(itemClass)) {
				creationDelegate = EwsUtilities.serviceObjectInfo.getMember()
						.getServiceObjectConstructorsWithServiceParam().get(
								itemClass);
				return (TServiceObject)creationDelegate
						.createServiceObjectWithServiceParam(service);
			} else {
				throw new IllegalArgumentException(
						Strings.NoAppropriateConstructorForItemClass);
			}
		} else {
			return (TServiceObject)itemClass.newInstance();
		}
	}

	/**
	 * Creates the item from item class.
	 *
	 * @param itemAttachment
	 *            the item attachment
	 * @param itemClass
	 *            the item class
	 * @param isNew
	 *            the is new
	 * @return the item
	 * @throws Exception
	 *             the exception
	 */
	protected static Item createItemFromItemClass(
			ItemAttachment itemAttachment, Class itemClass, boolean isNew)
			throws Exception {
		ICreateServiceObjectWithAttachmentParam creationDelegate;
		if (EwsUtilities.serviceObjectInfo.getMember()
				.getServiceObjectConstructorsWithAttachmentParam().containsKey(
						itemClass)) {

			creationDelegate = EwsUtilities.serviceObjectInfo.getMember()
					.getServiceObjectConstructorsWithAttachmentParam().get(
							itemClass);
			return (Item)creationDelegate
					.createServiceObjectWithAttachmentParam(itemAttachment,
							isNew);
		} else {
			throw new IllegalArgumentException(
					Strings.NoAppropriateConstructorForItemClass);
		}
	}

	/**
	 * Creates the item from xml element name.
	 *
	 * @param itemAttachment
	 *            the item attachment
	 * @param xmlElementName
	 *            the xml element name
	 * @return the item
	 * @throws Exception
	 *             the exception
	 */
	protected static Item createItemFromXmlElementName(
			ItemAttachment itemAttachment, String xmlElementName)
			throws Exception {
		Class<?> itemClass;
		if (EwsUtilities.serviceObjectInfo.getMember()
				.getXmlElementNameToServiceObjectClassMap().containsKey(
						xmlElementName)) {
			itemClass = EwsUtilities.serviceObjectInfo.getMember()
					.getXmlElementNameToServiceObjectClassMap().get(
							xmlElementName);
			return createItemFromItemClass(itemAttachment, itemClass, false);
		} else {
			return null;
		}
	}

	/**
	 *
	 */
    protected static Class getItemTypeFromXmlElementName(String xmlElementName)
    {

       return  EwsUtilities.serviceObjectInfo.getMember().getXmlElementNameToServiceObjectClassMap().get(xmlElementName).getClass();

    }

	/**
	 * Finds the first item of type TItem (not a descendant type) in the
	 * specified collection.
	 *
	 * @param <TItem>
	 *            TItem is the type of the item to find.
	 * @param cls
	 *            the cls
	 * @param items
	 *            the items
	 * @return A TItem instance or null if no instance of TItem could be found.
	 */

	static <TItem extends Item> TItem findFirstItemOfType(Class<TItem> cls,
			Iterable<Item> items) {
		for (Item item : items) {
			// We're looking for an exact class match here.
			if (item.getClass().equals(cls)) {
				return (TItem)item;
			}
		}

		return null;
	}

	/**
	 * Write trace start element.
	 *
	 * @param writer
	 *            The writer to write the start element to.
	 * @param traceTag
	 *            The trace tag.
	 * @param includeVersion
	 *            If true, include build version attribute.
	 */
    private static void writeTraceStartElement(
    	XMLStreamWriter writer,
        String traceTag,
        boolean includeVersion) throws XMLStreamException {
        writer.writeStartElement("Trace");
        writer.writeAttribute("Tag", traceTag);
        writer.writeAttribute("Tid", Thread.currentThread().getId()+"");
        Date d = new Date();
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'Z'");
		df.setTimeZone(TimeZone.getTimeZone("UTC"));
		String formattedString = df.format(d);
        writer.writeAttribute("Time", formattedString);

        if (includeVersion) {
            writer.writeAttribute("Version", EwsUtilities.getBuildVersion());
        }
    }

	/**
	 *.
	 *
	 * @param entryKind
	 *            the entry kind
	 * @param logEntry
	 *            the log entry
	 * @return the string
	 * @throws javax.xml.stream.XMLStreamException
	 *             the xML stream exception
	 * @throws java.io.IOException
	 *             Signals that an I/O exception has occurred.
	 */
	protected static String formatLogMessage(String entryKind, String logEntry)
	throws XMLStreamException, IOException {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		XMLOutputFactory factory = XMLOutputFactory.newInstance();
		XMLStreamWriter writer = factory.createXMLStreamWriter(outStream);
		EwsUtilities.writeTraceStartElement(writer, entryKind,false);
		writer.writeCharacters(System.getProperty("line.separator"));
		writer.writeCharacters(logEntry);
		writer.writeCharacters(System.getProperty("line.separator"));
		writer.writeEndElement();
		writer.writeCharacters(System.getProperty("line.separator"));
		writer.flush();
		writer.close();
		outStream.flush();
		String formattedLogMessage = outStream.toString();
		formattedLogMessage = formattedLogMessage.replaceAll("'", "'");
		formattedLogMessage = formattedLogMessage.replaceAll(""", "\"");
		formattedLogMessage = formattedLogMessage.replaceAll(">", ">");
		formattedLogMessage = formattedLogMessage.replaceAll("<", "<");
		formattedLogMessage = formattedLogMessage.replaceAll("&", "&");
		outStream.close();
		return formattedLogMessage;
	}

	/**
	 * Format http response headers.
	 *
	 * @param response
	 *            the response
	 * @return the string
	 * @throws EWSHttpException
	 *             the eWS http exception
	 */
	protected static String formatHttpResponseHeaders(HttpWebRequest response)
	throws EWSHttpException {
		StringBuilder sb = new StringBuilder();
		sb.append(String.format("%d %s\n", response.getResponseCode(), response
				.getResponseContentType()));

		sb.append(EwsUtilities.formatHttpHeaders(response.
				getResponseHeaders()));
		sb.append("\n");
		return sb.toString();
	}

	/**
	 * Format request HTTP headers.
	 *
	 * @param request
	 *            The HTTP request.
	 */
	protected static String formatHttpRequestHeaders(HttpWebRequest request)
	throws URISyntaxException, EWSHttpException {
		StringBuilder sb = new StringBuilder();
		sb.append(
				String.format(
						"%s %s HTTP/%s\n",
						request.getRequestMethod().toUpperCase(),
						request.getUrl().toURI().getPath(),
						"1.1"));

		sb.append(EwsUtilities.formatHttpHeaders(request.getRequestProperty()));
		sb.append("\n");
		return sb.toString();
	}

	/**
	 * Formats HTTP headers.
	 *
	 * @param headers
	 *            The headers.
	 * @return Headers as a string
	 */
	private static String formatHttpHeaders(Map<String, String> headers)
	{
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> header : headers.entrySet()) {
			sb.append(String.format("%s : %s\n", header.getKey(), header.getValue()));
		}
		return sb.toString();
	}

	/**
	 * Format XML content in a MemoryStream for message.
	 *
	 * @param traceTypeStr
	 *            Kind of the entry.
	 * @param stream
	 *            The memory stream.
	 * @return XML log entry as a string.
	 */
	protected static String formatLogMessageWithXmlContent(String traceTypeStr,
			ByteArrayOutputStream stream) {
		try {
			return formatLogMessage(traceTypeStr, stream.toString());
		} catch (Exception e) {

			return stream.toString();
		}
	}

	/**
	 * Convert bool to XML Schema bool.
	 *
	 * @param value
	 *            Bool value.
	 * @return String representing bool value in XML Schema.
	 */
	protected static String boolToXSBool(Boolean value) {
		return value ? EwsUtilities.XSTrue : EwsUtilities.XSFalse;
	}

	/**
	 * Parses an enum value list.
	 *
	 * @param <T>
	 *            the generic type
	 * @param c
	 *            the c
	 * @param list
	 *            the list
	 * @param value
	 *            the value
	 * @param separators
	 *            the separators
	 */
	protected static <T extends Enum> void parseEnumValueList(Class<T> c,
			List<T> list, String value, char... separators) {
		EwsUtilities.EwsAssert(c.isEnum(), "EwsUtilities.ParseEnumValueList",
				"T is not an enum type.");

		StringBuffer regexp = new StringBuffer("");
		regexp.append("[");
		for (char s : separators) {
			regexp.append("[");
			regexp.append(Pattern.quote(s + ""));
			regexp.append("]");
		}
		regexp.append("]");

		String[] enumValues = value.split(regexp.toString());

		for (String enumValue : enumValues) {
			// list.add((T)Enum.parse(c, enumValue, false));
			for (Object o : c.getEnumConstants()) {
				if (o.toString().equals(enumValue)) {
					list.add((T) o);
				}
			}
		}
	}

	/**
	 * Converts an enum to a string, using the mapping dictionaries if
	 * appropriate.
	 *
	 * @param value
	 *            The enum value to be serialized
	 * @return String representation of enum to be used in the protocol
	 */
	protected static String serializeEnum(Object value) {
		Map<String, String> enumToStringDict;
		String strValue = value.toString();
		if (enumToSchemaDictionaries.getMember().
				containsKey(value.getClass())) {
			enumToStringDict = enumToSchemaDictionaries.getMember().get(
					value.getClass());
			Enum<?> e = (Enum<?>) value;
			if (enumToStringDict.containsKey(e.name())) {
				strValue = enumToStringDict.get(e.name());
			}
		}

		return strValue;
	}

	/**
	 * Parses the.
	 *
	 * @param <T>
	 *            the generic type
	 * @param cls
	 *            the cls
	 * @param value
	 *            the value
	 * @return the t
	 * @throws InstantiationException
	 *             the instantiation exception
	 * @throws IllegalAccessException
	 *             the illegal access exception
	 * @throws java.text.ParseException
	 *             the parse exception
	 */
	protected static <T> T parse(Class<T> cls, String value)
			throws InstantiationException, IllegalAccessException,
			ParseException {

		if (cls.isEnum()) {
			Map<String, String> stringToEnumDict;
			if (schemaToEnumDictionaries.getMember().containsKey(cls)) {
				stringToEnumDict = schemaToEnumDictionaries.getMember()
						.get(cls);
				if (stringToEnumDict.containsKey(value)) {
					String strEnumName = stringToEnumDict.get(value);
					for (Object o : cls.getEnumConstants()) {
						if (o.toString().equals(strEnumName)) {
							return (T) o;
						}
					}
					return null;
				} else {
					for (Object o : cls.getEnumConstants()) {
						if (o.toString().equals(value)) {
							return (T) o;
						}
					}
					return null;
				}
			} else {
				for (Object o : cls.getEnumConstants()) {
					if (o.toString().equals(value)) {
						return (T) o;
					}
				}
				return null;
			}
		} else if (cls.isInstance(Integer.valueOf(0)))
		// else if( cls.isInstance(new Integer(0)))
		{
			Object o = null;
			o = Integer.parseInt(value);
			return (T) o;
		} else if (cls.isInstance(new Date())) {
			Object o = null;
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
			return (T) df.parse(value);
		} else if (cls.isInstance(Boolean.valueOf(false)))
		// else if( cls.isInstance(new Boolean(false)))
		{
			Object o = null;
			o = Boolean.parseBoolean(value);
			return (T) o;
		}
		else if (cls.isInstance(new String())) {
			return (T) value;
		}
		else if (cls.isInstance(Double.valueOf(0.0)))
			{
				Object o = null;
				o = Double.parseDouble(value);
				return (T) o;
			}
		return null;
	}

	/**
	 * Builds the schema to enum mapping dictionary.
	 *
	 * @param <E>
	 *            Type of the enum.
	 * @param c
	 *            Class
	 * @return The mapping from enum to schema name
	 */
	private static <E extends Enum<E>> Map<String, String>
	buildSchemaToEnumDict(Class<E> c) {
		Map<String, String> dict = new HashMap<String, String>();

		Field[] fields = c.getDeclaredFields();
		for (Field f : fields) {
			if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
				EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
				String fieldName = f.getName();
				String schemaName = ewsEnum.schemaName();
				if (!schemaName.isEmpty()) {
					dict.put(schemaName, fieldName);
				}
			}
		}
		return dict;
	}

	/**
	 * Validate param collection.
	 *
	 * @param eventTypes
	 *            the event types
	 * @param paramName
	 *            the param name
	 * @throws Exception
	 *             the exception
	 */
	protected static void validateParamCollection(EventType[] eventTypes,
			String paramName) throws Exception {

		validateParam(eventTypes, paramName);

		int count = 0;

		for (Object event : eventTypes) {

			try {
				validateParam(event, String.format("collection[%d] , ", count));
			} catch (Exception e) {
				throw new IllegalArgumentException(String.format(
						"The element at position %d is invalid", count), e);
			}

			count++;
		}

		if (count == 0) {
			throw new IllegalArgumentException(String.format(
					Strings.CollectionIsEmpty, paramName));
		}
	}

	/**
	 * Convert DateTime to XML Schema date.
	 *
	 * @param date
	 *            the date
	 * @return String representation of DateTime.
	 */
	static String dateTimeToXSDate(Date date) {
		String format = "yyyy-MM-dd'Z'";
		DateFormat utcFormatter = new SimpleDateFormat(format);
		return utcFormatter.format(date);
	}

	/**
	 * Dates the DateTime into an XML schema date time.
	 *
	 * @param date
	 *            the date
	 * @return String representation of DateTime.
	 */
	protected static String dateTimeToXSDateTime(Date date) {
		String format = "yyyy-MM-dd'T'HH:mm:ss'Z'";
		DateFormat utcFormatter = new SimpleDateFormat(format);
		return utcFormatter.format(date);
	}

	/**
	 * Takes a System.TimeSpan structure and converts it into an xs:duration
	 * string as defined by the W3 Consortiums Recommendation
	 * "XML Schema Part 2: Datatypes Second Edition",
	 * http://www.w3.org/TR/xmlschema-2/#duration
	 *
	 * @param timeOffset
	 *            structure to convert
	 * @return xs:duration formatted string
	 */
	protected static String getTimeSpanToXSDuration(TimeSpan timeOffset) {

		/*
		 * SimpleDateFormat dateformatter = new SimpleDateFormat("dd:HH:mm:ss");
		 * return dateformatter.format(timeOffset.toString());
		 */
		// Optional '-' offset
		String offsetStr = (timeOffset.getTotalSeconds() < 0) ? "-" : "";

		// The TimeSpan structure does not have a Year or Month
		// property, therefore we wouldn't be able to return an xs:duration
		// string from a TimeSpan that included the nY or nM components.

		return String.format("%sP%sDT%sH%sM%sS", offsetStr, Math.abs(timeOffset
				.getDays()), Math.abs(timeOffset.getHours()), Math
				.abs(timeOffset.getMinutes()), Math
				.abs(timeOffset.getSeconds())
				+ "." + Math.abs(timeOffset.getMilliseconds()));
	}

	/**
	 * Takes an xs:duration string as defined by the W3 Consortiums
	 * Recommendation "XML Schema Part 2: Datatypes Second Edition",
	 * http://www.w3.org/TR/xmlschema-2/#duration, and converts it into a
	 * System.TimeSpan structure This method uses the following approximations:
	 * 1 year = 365 days 1 month = 30 days Additionally, it only allows for four
	 * decimal points of seconds precision.
	 *
	 * @param xsDuration
	 *            xs:duration string to convert
	 * @return System.TimeSpan structure
	 */
	protected static TimeSpan getXSDurationToTimeSpan(String xsDuration) {
		// TODO: Need to check whether this should be the equivalent or not
		Pattern timeSpanParser = Pattern.compile("-P");
		Matcher m = timeSpanParser.matcher(xsDuration);
		boolean negative = false;
		System.out.println(m.find());
		if (m.find())
			negative = true;
		System.out.println(m.group());

		// Year
		m = Pattern.compile("(\\d+)Y").matcher(xsDuration);
		System.out.println(m.find());
		int year = 0;
		if (m.find())
			year = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("Y")));

		// Month
		m = Pattern.compile("(\\d+)M").matcher(xsDuration);
		System.out.println(m.find());
		int month = 0;
		if (m.find())
			month = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("M")));

		// Day
		m = Pattern.compile("(\\d+)D").matcher(xsDuration);
		System.out.println(m.find());
		int day = 0;
		if (m.find())
			day = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("D")));

		// Hour
		m = Pattern.compile("(\\d+)H").matcher(xsDuration);
		System.out.println(m.find());
		int hour = 0;
		if (m.find())
			hour = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("H")));

		// Minute
		m = Pattern.compile("(\\d+)M").matcher(xsDuration);
		System.out.println(m.find());
		int minute = 0;
		if (m.find())
			minute = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("M")));

		// Seconds
		m = Pattern.compile("(\\d+).").matcher(xsDuration);
		System.out.println(m.find());
		int seconds = 0;
		if (m.find())
			seconds = Integer.parseInt(m.group().substring(0,
					m.group().indexOf(".")));

		int milliseconds = 0;
		m = Pattern.compile("(\\d+)S").matcher(xsDuration);
		System.out.println(m.find());
		if (m.find()) {
			// Only allowed 4 digits of precision
			if (m.group().length() > 5) {
				milliseconds = Integer.parseInt(m.group().substring(0, 4));
			} else
				seconds = Integer.parseInt(m.group().substring(0,
						m.group().indexOf("S")));
		}

		// Apply conversions of year and months to days.
		// Year = 365 days
		// Month = 30 days
		day = day + (year * 365) + (month * 30);
		// TimeSpan retval = new TimeSpan(day, hour, minute, seconds,
		// milliseconds);
		long retval = (((((((day * 24) + hour) * 60) + minute) * 60) +
				seconds) * 1000)+ milliseconds;
		if (negative) {
			retval = -retval;
		}
		return new TimeSpan(retval);

	}

	/**
	 * Takes an xs:duration string as defined by the W3 Consortiums
	 * Recommendation "XML Schema Part 2: Datatypes Second Edition",
	 * http://www.w3.org/TR/xmlschema-2/#duration, and converts it into a
	 * System.TimeSpan structure This method uses the following approximations:
	 * 1 year = 365 days 1 month = 30 days Additionally, it only allows for four
	 * decimal points of seconds precision.
	 *
	 * @param xsDuration
	 *            xs:duration string to convert
	 * @return System.TimeSpan structure
	 */
	protected static TimeSpan getXSDurationToTimeSpanValue(String xsDuration) {
		// TODO: Need to check whether this should be the equivalent or not
		Pattern timeSpanParser = Pattern.compile("-P");
		Matcher m = timeSpanParser.matcher(xsDuration);
		boolean negative = false;
		//System.out.println(m.find());
		if (m.find())
			negative = true;

		//System.out.println(m.find());
		// Year
		m = Pattern.compile("(\\d+)Y").matcher(xsDuration);
		//System.out.println(m.find());
		int year = 0;
		if (m.find())
			year = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("Y")));

		// Month
		m = Pattern.compile("(\\d+)M").matcher(xsDuration);
		//System.out.println(m.find());
		int month = 0;
		if (m.find())
			month = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("M")));

		// Day
		m = Pattern.compile("(\\d+)D").matcher(xsDuration);

		//System.out.println(m.find());

		long day = 0;
		if (m.find())
			day = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("D")));

		// Hour
		m = Pattern.compile("(\\d+)H").matcher(xsDuration);

		//System.out.println(m.find());

		int hour = 0;
		if (m.find())
			hour = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("H")));

		// Minute
		m = Pattern.compile("(\\d+)M").matcher(xsDuration);

		//System.out.println(m.find());

		int minute = 0;
		if (m.find())
			minute = Integer.parseInt(m.group().substring(0,
					m.group().indexOf("M")));

		// Seconds
		m = Pattern.compile("(\\d+).").matcher(xsDuration);

		//System.out.println(m.find());

		int seconds = 0;

//		if (m.find())
//			seconds = Integer.parseInt(m.group().substring(0,
//					m.group().indexOf(".")));

		int milliseconds = 0;
		m = Pattern.compile("(\\d+)S").matcher(xsDuration);

		//System.out.println(m.find());

		if (m.find()) {
			// Only allowed 4 digits of precision
			if (m.group().length() > 5) {
				milliseconds = Integer.parseInt(m.group().substring(0, 4));
			} else
				seconds = Integer.parseInt(m.group().substring(0,
						m.group().indexOf("S")));
		}

		// Apply conversions of year and months to days.
		// Year = 365 days
		// Month = 30 days
	//	day = day + (year * 365) + (month * 30);
		 //TimeSpan retval = new TimeSpan(day, hour, minute, seconds,
		// milliseconds);

		long retval = ((((((((day * 24) + hour) * 60) + minute) * 60) +
				seconds) * 1000)+ milliseconds);
//		long retval=1010010;
		if (negative) {
			retval = -retval;
		}
		return new TimeSpan(retval);

	}

	/**
	 * Time span to xs time.
	 *
	 * @param timeSpan
	 *				 the time span
	 * @return the string
	 */
	public static String timeSpanToXSTime(TimeSpan timeSpan) {
		DecimalFormat myFormatter = new DecimalFormat("00");
		return String.format("%s:%s:%s", myFormatter.format(timeSpan.getHours()), myFormatter.format(timeSpan
				.getMinutes()), myFormatter.format(timeSpan.getSeconds()));
	}

	/**
	 * Gets the printable name of a CLR type.
	 *
	 * @param type
	 *				The class.
	 * @return Printable name.
	 */
    public static String getPrintableTypeName(Class type) {
    	// Note: building array of generic parameters is
    	//done recursively. Each parameter could be any type.
    	Type[] genericArgs = type.getGenericInterfaces();
        if (genericArgs.length > 0) {
            // Convert generic type to printable form (e.g. List<Item>)
            String genericPrefix = type.getName().substring(0,
            		type.getName().indexOf('`'));
            StringBuilder nameBuilder = new StringBuilder(genericPrefix);

            //List<Type> genericList = new ArrayList<Type>();
            StringBuffer genericArgsStr = new StringBuffer();
            for (int i = 0; i < genericArgs.length; i++) {

            	if(!"".equals(genericArgsStr.toString())) {
            		genericArgsStr.append(",");
            	}
            	genericArgsStr.append(getPrintableTypeName(
            			genericArgs[i].getClass()));
			}
            nameBuilder.append("<");
            nameBuilder.append(genericArgsStr.toString());
            nameBuilder.append(">");
            return nameBuilder.toString();
        }
        else if (type.isArray()) {
            // Convert array type to printable form.
            String arrayPrefix = type.getName().substring(0,
            		type.getName().indexOf('['));
            StringBuilder nameBuilder =
            	new StringBuilder(EwsUtilities.
            			getSimplifiedTypeName(arrayPrefix));

            for (int rank = 0; rank < getDim(type); rank++) {
                nameBuilder.append("[]");
            }
            return nameBuilder.toString();
        }
        else {
            return EwsUtilities.getSimplifiedTypeName(type.getName());
        }
    }

    /**
	 * Gets the printable name of a CLR type.
	 *
	 * @param typeName
	 *				The type name.
	 * @return Printable name.
	 */
    private static String getSimplifiedTypeName(String typeName) {
        // If type has a shortname (e.g. int for Int32) map to the short name.
        return typeNameToShortNameMap.getMember().containsKey(typeName) ?
        		typeNameToShortNameMap.getMember().get(typeName) : typeName;
    }

	/**
	 * Gets the domain name from an email address.
	 *
	 * @param emailAddress
	 *            The email address.
	 * @return Domain name.
	 * @throws FormatException
	 *             the format exception
	 */
	protected static String domainFromEmailAddress(String emailAddress)
			throws FormatException {
		String[] emailAddressParts = emailAddress.split("@");

		if (emailAddressParts.length != 2
				|| (emailAddressParts[1] == null || emailAddressParts[1]
						.isEmpty())) {
			throw new FormatException(Strings.InvalidEmailAddress);
		}

		return emailAddressParts[1];
	}

    public static int getDim(Object array ) {
        int dim=0;
        Class c = array.getClass();
        while( c.isArray() ) {
          c = c.getComponentType();
          dim++;
        }
        return( dim );
      }

    /**
	 * Validates parameter (and allows null value).
	 *
	 * @param param
	 *            The param.
	 * @param paramName
	 *            Name of the param.
	 * @throws Exception
	 *             the exception
	 */
	protected static void validateParamAllowNull(Object param, String paramName)
			throws Exception {
		if (param instanceof ISelfValidate) {
			ISelfValidate selfValidate = (ISelfValidate) param;
			try {
				selfValidate.validate();
			} catch (ServiceValidationException e) {
				throw new Exception(String.format("%s %s",
						Strings.ValidationFailed, paramName), e);
			}
		}

		if (param instanceof ServiceObject) {
			ServiceObject ewsObject = (ServiceObject) param;
			if (ewsObject.isNew()) {
				throw new Exception(String.format("%s %s",
						Strings.ObjectDoesNotHaveId, paramName));
			}
		}
	}

	/**
	 * Validates parameter (null value not allowed).
	 *
	 * @param param
	 *            The param.
	 * @param paramName
	 *            Name of the param.
	 * @throws Exception
	 *             the exception
	 */
	protected static void validateParam(Object param, String paramName)
			throws Exception {
		boolean isValid = false;

		if (param != null && param instanceof String) {
			String strParam = (String) param;
			isValid = !strParam.isEmpty();
		} else {
			isValid = param != null;
		}

		if (!isValid) {
			throw new Exception(String.format("Argument %s not valid",
					paramName));
		}
		validateParamAllowNull(param, paramName);
	}

	/**
	 * Validates parameter collection.
	 *
	 * @param <T>
	 *            the generic type
	 * @param collection
	 *            The collection.
	 * @param paramName
	 *            Name of the param.
	 * @throws Exception
	 *             the exception
	 */
	protected static <T> void validateParamCollection(Iterator<T> collection,
			String paramName) throws Exception {

		validateParam(collection, paramName);

		int count = 0;

		while (collection.hasNext()) {
			T obj = collection.next();
			try {
				validateParam(obj, String.format("collection[%d],", count));
			} catch (Exception e) {
				throw new IllegalArgumentException(String.format(
						"The element at position %d is invalid", count), e);
			}

			count++;
		}

		if (count == 0) {
			throw new IllegalArgumentException(String.format(
					Strings.CollectionIsEmpty, paramName));
		}
	}

	/**
	 * Validates string parameter to be non-empty string (null value allowed).
	 * @param param The string parameter.
	 * @param paramName Name of the parameter.
	 * @throws ArgumentException
	 * @throws ServiceLocalException
	 */
	protected static void validateNonBlankStringParamAllowNull(String param,
			String paramName) throws ArgumentException, ServiceLocalException {
        if (param != null)
        {
            // Non-empty string has at least one character
        	//which is *not* a whitespace character
            if (param.length() == countMatchingChars(param,
            		new IPredicate<Character>() {
				@Override
				public boolean predicate(Character obj) {
					return Character.isWhitespace(obj);
				}
			}))
            {
                throw new ArgumentException(Strings.
                		ArgumentIsBlankString, paramName);
            }
        }
    }

	/**
	 * Validates string parameter to be
	 * non-empty string (null value not allowed).
	 * @param paramThe string parameter.
	 * @param paramName Name of the parameter.
	 * @throws ArgumentNullException
	 * @throws ArgumentException
	 * @throws ServiceLocalException
	 */
	protected static void validateNonBlankStringParam(String param,
			String paramName) throws ArgumentNullException, ArgumentException, ServiceLocalException {
         if (param == null)
         {
             throw new ArgumentNullException(paramName);
         }

         validateNonBlankStringParamAllowNull(param, paramName);
     }

    /**
	 * Validate enum version value.
	 *
	 * @param enumValue
	 *            the enum value
	 * @param requestVersion
	 *            the request version
	 * @throws ServiceVersionException
	 *             the service version exception
	 */
	protected static void validateEnumVersionValue(Enum<?> enumValue,
			ExchangeVersion requestVersion) throws ServiceVersionException {
		Map<String, ExchangeVersion> enumVersionDict = enumVersionDictionaries
				.getMember().get(enumValue.getClass());
		// String strValue = enumValue.toString();
		if (enumVersionDict.containsKey(enumValue.toString())) {
			ExchangeVersion enumVersion = enumVersionDict.get(enumValue
					.toString());
			int i = requestVersion.compareTo(enumVersion);
			if (i < 0) {
				throw new ServiceVersionException(String.format("%S,%S,%S,%S",
						Strings.EnumValueIncompatibleWithRequestVersion,
						enumValue.toString(), enumValue.getClass().getName(),
						enumVersion));
			}
		}
	}

	/**
	 * Validates service object version against the request version.
	 *
	 * @param serviceObject
	 *            The service object.
	 * @param requestVersion
	 *            The request version.
	 * @throws ServiceVersionException
	 *             Raised if this service object type requires a later version
	 *             of Exchange.
	 */
	protected static void validateServiceObjectVersion(
			ServiceObject serviceObject, ExchangeVersion requestVersion)
			throws ServiceVersionException {
		ExchangeVersion minimumRequiredServerVersion = serviceObject
				.getMinimumRequiredServerVersion();

		if (requestVersion.ordinal() < minimumRequiredServerVersion.ordinal()) {
			String msg = String.format(
					Strings.ObjectTypeIncompatibleWithRequestVersion,
					serviceObject.getClass().getName(),
					minimumRequiredServerVersion.toString());
			throw new ServiceVersionException(msg);
		}
	}

	/**
	 * Validates property version against the request version.
	 *
	 * @param service
	 *				The Exchange service.
	 * @param minimumServerVersion
	 *							 The minimum server version
	 * @param propertyName
	 *					 The property name
	 * @throws ServiceVersionException
	 *								 The service version exception
	 */
    protected static void validatePropertyVersion(
        ExchangeService service,
        ExchangeVersion minimumServerVersion,
        String propertyName) throws ServiceVersionException
    {
        if (service.getRequestedServerVersion().ordinal() <
        		minimumServerVersion.ordinal())
        {
            throw new ServiceVersionException(
                String.format(
                Strings.PropertyIncompatibleWithRequestVersion,
                propertyName,
                minimumServerVersion));
        }
    }

	/**
	 * Validate method version.
	 *
	 * @param service
	 *            the service
	 * @param minimumServerVersion
	 *            the minimum server version
	 * @param methodName
	 *            the method name
	 * @throws ServiceVersionException
	 *             the service version exception
	 */
	protected static void validateMethodVersion(ExchangeService service,
			ExchangeVersion minimumServerVersion, String methodName)
			throws ServiceVersionException {
		if (service.getRequestedServerVersion().ordinal() <
				minimumServerVersion.ordinal())

		{
			throw new ServiceVersionException(String.format(
					Strings.MethodIncompatibleWithRequestVersion, methodName,
					minimumServerVersion));
		}
	}

	/**
	 * Validates class version against the request version.
	 *
	 * @param service
	 *            the service
	 * @param minimumServerVersion The minimum server version that supports the method.
	 * @param className Name of the class.
	 * @throws ServiceVersionException
	 */
    protected static void validateClassVersion(
        ExchangeService service,
        ExchangeVersion minimumServerVersion,
        String className) throws ServiceVersionException
    {
        if (service.getRequestedServerVersion().ordinal() <
        		minimumServerVersion.ordinal())
        {
            throw new ServiceVersionException(
                String.format(
                Strings.ClassIncompatibleWithRequestVersion,
                className,
                minimumServerVersion));
        }
    }

    /**
	 * Validates domain name (null value allowed)
	 *
	 * @param domainName
	 *            Domain name.
	 * @param paramName	 Parameter name.
     * @throws ArgumentException
	 */
    protected static void validateDomainNameAllowNull(String domainName,
    		String paramName) throws ArgumentException {
        if (domainName != null)
        {
    		Pattern domainNamePattern = Pattern.compile(DomainRegex);
    		Matcher domainNameMatcher = domainNamePattern.matcher(domainName);
			if (!domainNameMatcher.find())
            {
                throw new ArgumentException(String.format(Strings.
                		InvalidDomainName, domainName), paramName);
            }
        }
    }

    /**
	 * Builds the enum dict.
	 *
	 * @param <E>
	 *            the element type
	 * @param c
	 *            the c
	 * @return the map
	 */
	private static <E extends Enum<E>> Map<String, ExchangeVersion>
	buildEnumDict(Class<E> c) {
		Map<String, ExchangeVersion> dict =
			new HashMap<String, ExchangeVersion>();
		Field[] fields = c.getDeclaredFields();
		for (Field f : fields) {
			if (f.isEnumConstant()
					&& f.isAnnotationPresent(RequiredServerVersion.class)) {
				RequiredServerVersion ewsEnum = f
						.getAnnotation(RequiredServerVersion.class);
				String fieldName = f.getName();
				ExchangeVersion exchangeVersion = ewsEnum.version();
				dict.put(fieldName, exchangeVersion);
			}
		}
		return dict;
	}

    /**
	 * Builds the enum to schema mapping dictionary.
	 *
	 * @param c
	 *            class type
	 * @return The mapping from enum to schema name
	 *
	 */
	private static Map<String, String> buildEnumToSchemaDict(Class<?> c) {
		Map<String, String> dict = new HashMap<String, String>();
		Field[] fields = c.getFields();
		for (Field f : fields) {
			if (f.isEnumConstant() && f.isAnnotationPresent(EwsEnum.class)) {
				EwsEnum ewsEnum = f.getAnnotation(EwsEnum.class);
				String fieldName = f.getName();
				String schemaName = ewsEnum.schemaName();
				if (!schemaName.isEmpty()) {
					dict.put(fieldName, schemaName);
				}
			}
		}
		return dict;
	}

	/**
	 * Gets the enumerated object count.
	 *
	 * @param <T>
	 *            the generic type
	 * @param objects
	 *            The objects.
	 * @return Count of objects in iterator.
	 */
	protected static <T> int getEnumeratedObjectCount(Iterator<T> objects) {
		int count = 0;
		while (objects != null && objects.hasNext()) {
			@SuppressWarnings("unused")
			Object obj = objects.next();
			count++;
		}
		return count;
	}

	/**
	 * Gets the enumerated object at.
	 *
	 * @param <T>
	 *            the generic type
	 * @param objects
	 *            the objects
	 * @param index
	 *            the index
	 * @return the enumerated object at
	 */
	protected static <T> Object getEnumeratedObjectAt(Iterable<T> objects,
			int index) {
		int count = 0;
		for (Object obj : objects) {
			if (count == index) {
				return obj;
			}
			count++;
		}
		throw new IndexOutOfBoundsException(
				Strings.IEnumerableDoesNotContainThatManyObject);
	}

    /**
	 * Count characters in string that match a condition.
	 *
	 * @param str
	 *				The string.
	 * @param charPredicate
	 * 				Predicate to evaluate for each character in the string.
	 * @return  Count of characters that match condition expressed by predicate.
     * @throws ServiceLocalException
	 */
    protected static int countMatchingChars(String str,
    		IPredicate<Character> charPredicate) throws ServiceLocalException {
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
        	if (charPredicate.predicate(Character.valueOf(str.charAt(i)))) {
                count++;
            }
		}

        return count;
    }

    /**
	 * Determines whether every element in the collection
	 * matches the conditions defined by the specified predicate.
	 *
	 * @param typeparam T
	 *				Entry type.
	 * @param collection
	 * 				The collection.
	 * @param predicate
	 * 				Predicate that defines the conditions
	 * to check against the elements.
	 * @return  True if every element in the collection matches
	 * the conditions defined by the specified predicate; otherwise, false.
     * @throws ServiceLocalException
	 */
    protected static <T> boolean trueForAll(Iterable<T> collection,
    		IPredicate<T> predicate) throws ServiceLocalException {
        for (T entry : collection)
        {
            if (!predicate.predicate(entry))
            {
                return false;
            }
        }

        return true;
    }

    /**
	 * Call an action for each member of a collection.
	 *
	 * @param typeparam T
	 *				Collection element type.
	 * @param collection
	 * 				The collection.
	 * @param action
	 * 				The action to apply.
	 */
    protected static <T> void forEach(Iterable<T> collection, IAction<T> action)
    {
        for (T entry : collection)
        {
            action.action(entry);
        }
    }
}


text:
package com.maalaang.waltz.gcm;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import java.io.IOException;

/**
 * Created by User on 2015-02-06.
 */
public class GcmModule
{
    // for GCM
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";

    private GoogleCloudMessaging _gcm;
    private String _regId;
    private String TAG = "gcm test";
    private String GCM_SHARED_PREFERENCE_NAME = "default";

    private GcmEvent _callbackGcm = null;

    public void setGcmListener(GcmEvent l)
    {
        _callbackGcm = l;
    }

    /**
     * Substitute you own sender ID here. This is the project number you got
     * from the API Console, as described in "Getting Started."
     */

    private static final String SENDER_ID = "494342881186";

    /**
     * @return Application's version code from the {@code PackageManager}.
     */
    private static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // should never happen
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    /**
     * @return Application's {@code SharedPreferences}.
     */
    private SharedPreferences getGCMPreferences(Context context) {
        // This sample app persists the registration ID in shared preferences, but
        // how you store the regID in your app is up to you.

        return context.getSharedPreferences(GCM_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
    }

    /**
     * Gets the current registration ID for application on GCM service.
     *

     * If result is empty, the app needs to register.
     *
     * @return registration ID, or empty string if there is no existing
     *         registration ID.
     */
    public String getRegistrationId(Context context) {
        final SharedPreferences prefs = getGCMPreferences(context);
        String registrationId = prefs.getString(PROPERTY_REG_ID, "");
        if (registrationId.isEmpty()) {
            Log.i(TAG, "Registration not found.");
            return "";
        }
        // Check if app was updated; if so, it must clear the registration ID
        // since the existing regID is not guaranteed to work with the new
        // app version.
        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
        int currentVersion = getAppVersion(context);
        if (registeredVersion != currentVersion) {
            Log.i(TAG, "App version changed.");
            return "";
        }
        return registrationId;
    }

    /**
     * Registers the application with GCM servers asynchronously.
     *

     * Stores the registration ID and app versionCode in the application's
     * shared preferences.
     */
    // gcm 서버에 접속해서 registration id를 발급받는다.
    private void registerInBackground(final Context context)
    {
        new AsyncTask<Void, Void, String>()
        {
            @Override
            protected String doInBackground(Void... params)
            {
                String msg = "";
                try
                {
                    if (_gcm == null)
                    {
                        _gcm = GoogleCloudMessaging.getInstance(context);
                    }
                    _regId = _gcm.register(SENDER_ID);
                    msg = "Device registered, registration ID=" + _regId;

                    // For this demo: we don't need to send it because the device
                    // will send upstream messages to a server that echo back the
                    // message using the 'from' address in the message.

                    // Persist the regID - no need to register again.
                    storeRegistrationId(context, _regId);
                }
                catch (IOException ex)
                {
                    msg = "Error :" + ex.getMessage();
                    // If there is an error, don't just keep trying to register.
                    // Require the user to click a button again, or perform
                    // exponential back-off.
                }

                return msg;
            }

            @Override
            protected void onPostExecute(String msg)
            {
                Log.d("MainActivity.java | onPostExecute", "|" + msg + "|");
                Log.d(TAG, msg);
            }
        }.execute(null, null, null);
    }

    /**
     * Stores the registration ID and app versionCode in the application's
     * {@code SharedPreferences}.
     *
     * @param context application's context.
     * @param regId registration ID
     */
    private void storeRegistrationId(Context context, String regId) {
        final SharedPreferences prefs = getGCMPreferences(context);
        int appVersion = getAppVersion(context);
        Log.i(TAG, "Saving regId on app version " + appVersion);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(PROPERTY_REG_ID, regId);
        editor.putInt(PROPERTY_APP_VERSION, appVersion);
        editor.commit();
    }

    public void initGcm(Context context)
    {
        // google play service가 사용가능한가
        if (checkPlayServices(context))
        {
            _gcm = GoogleCloudMessaging.getInstance(context);
            _regId = getRegistrationId(context);

            if (TextUtils.isEmpty(_regId))
                registerInBackground(context);
        }
        else
        {
            Log.i("MainActivity.java | onCreate", "|No valid Google Play Services APK found.|");
        }
    }

    /**
     * Check the device to make sure it has the Google Play Services APK. If
     * it doesn't, display a dialog that allows users to download the APK from
     * the Google Play Store or enable it in the device's system settings.
     */
    private boolean checkPlayServices(Context context) {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(context);
        if (resultCode != ConnectionResult.SUCCESS) {
            if( _callbackGcm != null )
                _callbackGcm.OnGooglePlayServicesNotAvailable(resultCode);
            return false;
        }
        return true;
    }

}


text:
package com.fitpay.android.paymentdevice.impl.ble;

/**
 * Data reader interface
 */
interface DataReader {
    void onRead(byte[] data);
}


text:
package v6

import (
	"code.cloudfoundry.org/cli/command"
	"code.cloudfoundry.org/cli/command/flag"
	"code.cloudfoundry.org/cli/command/translatableerror"
)

type StopCommand struct {
	RequiredArgs    flag.AppName `positional-args:"yes"`
	usage           interface{}  `usage:"CF_NAME stop APP_NAME"`
	relatedCommands interface{}  `related_commands:"restart, scale, start"`
}

func (StopCommand) Setup(config command.Config, ui command.UI) error {
	return nil
}

func (StopCommand) Execute(args []string) error {
	return translatableerror.UnrefactoredCommandError{}
}


text:
/*
 *   __________   ____   ____   ____  ____
 *  /  ___/  _ \_/ ___\ / ___\_/ __ \/  _ \
 *  \___ (  <_> )  \___/ /_/  >  ___(  <_> )
 * /____  >____/ \___  >___  / \___  >____/
 *      \/           \/_____/      \/
 *
 *      Social Media Geo-Inferencing
 *             OpenSextant
 */
package org.opensextant.extractors.geo.social;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrServerException;
import org.opensextant.ConfigException;
import org.opensextant.data.Country;
import org.opensextant.data.Geocoding;
import org.opensextant.data.Place;
import org.opensextant.data.social.Message;
import org.opensextant.data.social.Tweet;
import org.opensextant.extractors.geo.SolrGazetteer;
import org.opensextant.extractors.xcoord.GeocoordPrecision;
import org.opensextant.util.GeonamesUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

/**
 * A base-class that has the various hooks for logging, dev/test/evaluation,
 * common dictionaries/resources, and helpful connectivity items.
 *
 * @author ubaldino
 */
public abstract class SocialGeo {

    protected final Logger log = LoggerFactory.getLogger(getClass());
    protected boolean evalMode = log.isDebugEnabled();

    public String inferencerID = null;
    public String inferencerDescription = null;

    protected GeonamesUtility countries = null;
    /** If you populate allCountries with */
    protected Map<String, Country> allCountries = null;

    /** A particular hashing of the list of country names. */
    protected Map<String, Country> basicCountryNames = null;

    public SocialGeo() {
    }

    /**
     * Configure your implementation.
     *
     * @throws ConfigException
     */
    public abstract void configure() throws ConfigException;

    /**
     * Release resources quietly.
     */
    public abstract void close();

    /**
     * Generally useful test of string values.
     *
     * @param v
     * @return
     */
    public static boolean isValue(String v) {
        return isNotBlank(v);
    }

    /**
     * This score as a boost for any sort of disambiguation of ties or close scores
     * in predictions.
     *
     * <pre>
     *
     * Points:  A Country may score in 0 or more of these three categories: TZ, UTC, LANG.
     *
     *      TZ
     * +3 - Country contains timezone named by Tweet.timezone
     *
     *      UTC
     * +3 - Country contains UTC offset named by Tweet.utcOffset (Hours);
     * +4 - Or if Tweet is in period of DST and Country observes that DST offset.
     *      This is slightly less believable because users apparently do not always adjust TZ and time on devices.
     *      Just the same, if country uses DST and so is user, then that is more significant than without
     *
     *      LANG
     * +3 - Language of User and of Text are both Primary language of Country
     * +2 - either language is Primary language of Country
     * +1 - language of text is spoken in Country
     *
     *      LON
     *      TODO:  consider (Country.LatLon ~ Tweet.UTC) ? within 5 degrees.  Countries vary by size this
     *      makes little sense.  But for Cities and States it makes more sense.
     *
     * MAX score is 3 + 4 + 3 = 10
     * </pre>
     *
     * @param C
     *           a country prediction for the tweet.
     * @param tw
     *           the tweet
     * @return score 1 to ~20
     */
    public int scoreCountryPrediction(Country C, Tweet tw) {

        if (C == null || tw == null) {
            return 0;
        }

        int score = 0;

        // We value the positional information from TZ
        // However this provides some notion of latitude/longitude,
        // Where TZ offers mainly just longitude.
        //
        if (isValue(tw.timezone)) {
            if (C.containsTimezone(tw.timezone)) {
                score += 3;
            }
        }

        // We value the positional information from UTC offset
        // Between DST and non-DST periods in the year,
        // There is only a slight difference in weight:
        // If a user's clock changes with DST, then we favor countries
        // that recognize the time change over ones that don't.
        //
        if (Message.validateUTCOffset(tw.utcOffset)) {
            if (tw.isDST && C.containsDSTOffset(tw.utcOffsetHours)) {
                score += 4;
            } else if (C.containsUTCOffset(tw.utcOffsetHours)) {
                score += 3;
            }
        }

        // Languages such as Arabic, English, etc. are world languages.
        // They are less specific to a country. But may help disambiguate ties.
        boolean ulang1 = C.isPrimaryLanguage(tw.userLang);
        boolean lang1 = C.isPrimaryLanguage(tw.lang);
        if (ulang1 && lang1) {
            score += 3;
        } else if (ulang1 || lang1) {
            score += 2;
        } else if (C.isSpoken(tw.lang)) {
            score += 1;
        }

        return score;
    }

    /**
     * Create a lookup of the most common country names.
     * This is just a pure ASCII listing... of ISO country names.
     * To get more country names, populateAllCountries() should be used.
     */
    public void populateBasicCountryNames() {
        basicCountryNames = new HashMap<>();
        for (Country c : countries.getCountries()) {
            basicCountryNames.put(c.getNamenorm(), c);
        }
        basicCountryNames.put("united states", countries.getCountry("US"));
    }

    /**
     * Populate the allCountries listing. Not all pipeline apps make use of
     * SolrGazetteer or do geo work
     * so this is not part of setup.
     *
     * @param gaz
     */
    public void populateAllCountries(SolrGazetteer gaz) {
        // SolrGazetteer has full Country metadata, like
        // GeonamesUtility lists offical countries (with TZ, region, aliases, codes)
        // SolrGazetteer lists more aliases/name variants.
        // So have Map( variant => Country ), where Country is official one.
        //
        allCountries = new HashMap<>();

        // Gather 'Official names'
        for (Country C : countries.getCountries()) {
            // NAME: 'United States of America'
            allCountries.put(C.getName().toLowerCase(), C);
            // ISO alpha-2 'US'
            allCountries.put(C.CC_ISO2.toLowerCase(), C);
            // ISO alpha-3 'USA'
            allCountries.put(C.CC_ISO3.toLowerCase(), C);
        }

        // Gather name variants from anything that looks like PCLI or PCLI* in
        // gazetteer:
        //
        for (String cc : gaz.getCountries().keySet()) {
            Country alt = gaz.getCountries().get(cc);
            Country C = countries.getCountry(cc);
            // NAME: 'United States of America'
            allCountries.put(alt.getName().toLowerCase(), C);
            // ISO alpha-2 'US'
            allCountries.put(alt.CC_ISO2.toLowerCase(), C);
            // ISO alpha-3 'USA'
            allCountries.put(alt.CC_ISO3.toLowerCase(), C);
            for (String a : alt.getAliases()) {
                // Aliases: 'U.S.A', 'US of A', 'America', etc.
                //
                allCountries.put(a.toLowerCase(), C);
            }
        }
    }

    /**
     * Geonames Helpers. Attach Province name if useful.
     * Ideally keep data coded in databases, and render name at presentation or
     * export time, if needed.
     * But no need to store superfluous name data that is just a reflection of
     * things that are coded.
     *
     * @throws IOException
     */
    public void loadProvinceNames() throws IOException {
        if (countries == null) {
            countries = new GeonamesUtility();
        }
        countries.loadWorldAdmin1Metadata();
    }

    protected final Map<String, Place> US_STATES = new HashMap<>();

    /**
     * Lookup US States.
     *
     * @param name
     * @return
     */
    public Place getUSStateByName(String name) {
        return US_STATES.get(name.toLowerCase());
    }

    /**
     * A dot-separated code, country code + FIPS numeric
     *
     * @param code
     *             CC.FF
     * @return
     */
    public Place getUSStateByCode(String code) {
        return US_STATES.get(code.toUpperCase());
    }

    /**
     * CAVEAT: For now this only loads US states, despite us loading
     *
     * @throws IOException
     */
    public void loadUSStates() throws IOException {

        if (countries == null) {
            countries = new GeonamesUtility();
        }

        for (Place p : countries.getUSStateMetadata()) {
            US_STATES.put(p.getPlaceName().toLowerCase(), p);
            US_STATES.put(p.getAdmin1PostalCode().toUpperCase(), p);
        }
    }

    protected double getConfidence(double c) {
        return BigDecimal.valueOf(c).setScale(3, RoundingMode.FLOOR).doubleValue();
    }

    /**
     * @param nm
     * @return
     */
    public Country getCountryNamed(String nm) {
        if (nm == null) {
            return null;
        }
        if (allCountries == null) {
            return null;
        }
        return allCountries.get(nm.toLowerCase());
    }

    public Place inferPlaceRecursively(SolrGazetteer gaz, Geocoding poi) throws SolrServerException, IOException {
        return inferPlaceRecursively(gaz, poi, false);
    }

    /**
     * set Province name from given codes on somePlace.
     *
     * @param somePlace Place object with CC and ADM1 codes set.
     */
    public void setProvinceName(Place somePlace) {
        /* don't need it. */
        if (somePlace.getAdmin1Name() != null) {
            return;
        }
        /* can't get it. no code */
        if (somePlace.getAdmin1() == null) {
            return;
        }

        Place adm1 = countries.getProvince(somePlace.getCountryCode(), somePlace.getAdmin1());
        if (adm1 != null) {
            somePlace.setAdmin1Name(adm1.getPlaceName());
            somePlace.setAdminName(adm1.getPlaceName());
        }
    }

    /**
     * Try to find closest P/PPL* (city or village) within 5 km. Or a local
     * site or landmark.
     * If not try at a radius = 10, then at 30 KM, and still if not, try a region,
     * say ADM1
     * or ADM2 place boundary if one is nearby within 100 KM. If NOT, ... then
     * maybe you are in a remote, sparse territory or over water.
     * TODO: Province ID is helpful for many things -- missing ADM1 codes is a
     * general problem.
     * Fix missing ADM1 codes in gazetteer, e.g., use ESRI free data, geonames.org,
     * etc.
     * NOTE: there are not any missing ADM1 codes; USGS is solid.
     * TODO: Solr 4.x has a major memory problem when trying to find closest points.
     * In theory it should be indexed rather well, however for geodetic search it
     * tries to load ALL
     * the index for that 'geo' field into RAM (based on experience). From there it
     * can sort geodetically
     * to find a closest point. This is not helpful -- so as a work around this
     * recursive search outward
     * finds any items close by (SolrGazetteer.placeAt() sorts results outside of
     * Solr). The issue is
     * that the search returns only first 25 rows of unsorted results, then sorts
     * geodetically.
     * So for this work around try to minimize results by select feature types or
     * something.
     *
     * @param gaz
     *                    an intialized SolrGazetteer
     * @param poi
     *                    point of interest
     * @param requireADM1 true if ADM1 level resolution is desired.
     * @return a single place that appears to be closest to POI
     * @throws SolrServerException
     * @throws IOException
     */
    public Place inferPlaceRecursively(SolrGazetteer gaz, Geocoding poi, boolean requireADM1)
            throws SolrServerException, IOException {

        /*
         * Find city within 5KM
         */
        Place city = gaz.placeAt(poi, 5, "P");

        if (!requireADM1 && city != null) {
            return city;
        }
        /*
         * Looking for a positive Province ID using ADM1, if requested.
         * This searches recursively until a good entry is found.
         */
        if (requireADM1 && city != null) {
            if (city.getAdmin1() != null) {
                return city;
            }
        }

        /*
         * Find site, place or admin boundary within 10KM
         */
        Place city2 = gaz.placeAt(poi, 10, "(P A)");

        /* Found something */
        if (!requireADM1 && city2 != null) {
            return city2;
        }

        /* Found something, but improve Province ID */
        if (requireADM1 && city2 != null) {
            if (city2.getAdmin1() != null && city != null) {
                city.setAdmin1(city2.getAdmin1());
                return city;
            }
        }

        /*
         * Find city within 30KM -- If previous searches did not succeed with ADM1,
         * use previously found entry by add ADM1 from here if possible.
         */
        Place city3 = gaz.placeAt(poi, 30, "(P A)");
        if (!requireADM1 && city3 != null) {
            return city3;
        }

        if (requireADM1 && city3 != null) {
            if (city3.getAdmin1() != null && city != null) {
                /*
                 * We've gone too far afield in search of province ID.
                 * Return original city, which was closest. Caller may have to use ADM1=0
                 * (country default)
                 */
                if (city.getCountryCode() != null) {
                    // At 30 KM, we're more cautious about inheriting CC across entries.
                    if (city.getCountryCode().equals(city3.getCountryCode())) {
                        city.setAdmin1(city3.getAdmin1());
                    }
                    // Otherwise ADM1 is not set, it was missing in original query.
                    // Return first choice as-is.
                    return city;
                }
            }
        }

        if (city != null) {
            return city;
        }

        /*
         * Anything? within 50km. Gave up on ADM1 requirement here...
         */
        List<Place> anyPlaces = gaz.placesAt(poi, 50);
        if (anyPlaces != null) {
            city = SolrGazetteer.closest(poi, anyPlaces);
            if (city != null) {
                return city;
            }
        }

        /* Admin Region? */
        return gaz.placeAt(poi, 100, "A");
    }

    /**
     * facilitate getting a simple precision metric. +/- 1m is sufficient for
     * tracking points extracted from text.
     *
     * @param geo
     * @param prec
     */
    protected static void flattenPrecision(Geocoding geo, GeocoordPrecision prec) {
        if (prec.precision < 1 && prec.precision > 0) {
            geo.setPrecision(1);
        } else {
            geo.setPrecision((int) prec.precision);
        }
    }
}


text:
namespace ntp_tiles {

// The enum demonstrates the type of tile that has been deleted post default
// app migration as part of the bug fix.
//
// These values must stay in sync with the TypeOfDeletedMostVisitedApp enum in
// enums.xml.

enum class DeletedTileType {
  // Default app from most visited sites.
  kMostVisitedSite = 0,

  // Default app from custom links.
  kCustomLink = 1,

  kMaxValue = kCustomLink
};

}  // namespace ntp_tiles

#endif  // COMPONENTS_NTP_TILES_DELETED_TILE_TYPE_H_


text:
package 'python-software-properties'

bash 'apt_ppa' do
  code <<-EOH
    sudo add-apt-repository ppa:ondrej/php -y
    sudo apt-get update
    sudo apt-get install php7.1 -y --force-yes
    sudo apt-get install php7.1-dev -y --force-yes
    sudo apt-get install php7.1-mcrypt -y --force-yes
    sudo apt-get install php7.1-xml -y --force-yes
    EOH
end

package 'apache2' do
  action :remove
end

bash 'install_composer' do
  code <<-EOH
    curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/bin --filename=composer
    EOH
  not_if { ::File.exists?("/usr/bin/composer") }
end


text:
<title>OGRE: OgreMemoryAllocatedObject.h Source File - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

File List

File Members

OgreMain

include

OgreMemoryAllocatedObject.h

Go to the documentation of this file.

00001
00028
00029 #ifndef __AllocatedObject_H__
00030 #define __AllocatedObject_H__
00031
00032 #include "OgrePrerequisites.h"
00033
00034 // Anything that has done a #define new <blah> will screw operator new definitions up
00035 // so undefine
00036 #ifdef new
00037 #  undef new
00038 #endif
00039 #ifdef delete
00040 #  undef delete
00041 #endif
00042
00043 namespace Ogre
00044 {
00056     template <class Alloc>
00057     class _OgreExport AllocatedObject
00058     {
00059     public:
00060         explicit AllocatedObject()
00061         { }
00062
00063         ~AllocatedObject()
00064         { }
00065
00067         void* operator new(size_t sz, const char* file, int line, const char* func)
00068         {
00069             return Alloc::allocateBytes(sz, file, line, func);
00070         }
00071
00072         void* operator new(size_t sz)
00073         {
00074             return Alloc::allocateBytes(sz);
00075         }
00076
00078         void* operator new(size_t sz, void* ptr)
00079         {
00080             (void) sz;
00081             return ptr;
00082         }
00083
00085         void* operator new[] ( size_t sz, const char* file, int line, const char* func )
00086         {
00087             return Alloc::allocateBytes(sz, file, line, func);
00088         }
00089
00090         void* operator new[] ( size_t sz )
00091         {
00092             return Alloc::allocateBytes(sz);
00093         }
00094
00095         void operator delete( void* ptr )
00096         {
00097             Alloc::deallocateBytes(ptr);
00098         }
00099
00100         // Corresponding operator for placement delete (second param same as the first)
00101         void operator delete( void* ptr, void* )
00102         {
00103             Alloc::deallocateBytes(ptr);
00104         }
00105
00106         // only called if there is an exception in corresponding 'new'
00107         void operator delete( void* ptr, const char* , int , const char*  )
00108         {
00109             Alloc::deallocateBytes(ptr);
00110         }
00111
00112         void operator delete[] ( void* ptr )
00113         {
00114             Alloc::deallocateBytes(ptr);
00115         }
00116
00117
00118         void operator delete[] ( void* ptr, const char* , int , const char*  )
00119         {
00120             Alloc::deallocateBytes(ptr);
00121         }
00122     };
00123
00124
00128 }
00129 #endif

Copyright © 2008 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Sat Jan 14 2012 18:40:43


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/keyboard_select" android:title="@string/menu_keyboard_select" android:showAsAction="ifRoom"/>
    <item android:id="@+id/keyboard_setting" android:title="@string/menu_keyboard_setting" android:showAsAction="ifRoom"/>
</menu>