text:
module HairTrigger
  module Adapter
    def create_trigger(name = nil, options = {})
      if name.is_a?(Hash)
        options = name
        name = nil
      end
      ::HairTrigger::Builder.new(name, options.merge(:execute => true, :adapter => self))
    end

    def drop_trigger(name, table, options = {})
      ::HairTrigger::Builder.new(name, options.merge(:execute => true, :drop => true, :table => table, :adapter => self)).all{}
    end

    def normalize_mysql_definer(definer)
      user, host = definer.split('@')
      host = @config[:host] || 'localhost' if host == '%'
      "'#{user}'@'#{host}'" # SHOW TRIGGERS doesn't quote them, but we need quotes for creating a trigger
    end

    def implicit_mysql_definer
      "'#{@config[:username] || 'root'}'@'#{@config[:host] || 'localhost'}'"
    end

    def triggers(options = {})
      triggers = {}
      name_clause = options[:only] ? "IN ('" + options[:only].join("', '") + "')" : nil
      adapter_name = HairTrigger.adapter_name_for(self)
      case adapter_name
        when :sqlite
          select_rows("SELECT name, sql FROM sqlite_master WHERE type = 'trigger' #{name_clause ? " AND name " + name_clause : ""}").each do |(name, definition)|
            triggers[name] = quote_table_name_in_trigger(definition) + ";\n"
          end
        when :mysql
          select_rows("SHOW TRIGGERS").each do |(name, event, table, actions, timing, created, sql_mode, definer)|
            definer = normalize_mysql_definer(definer)
            next if options[:only] && !options[:only].include?(name)
            triggers[name.strip] = <<-SQL
CREATE #{definer != implicit_mysql_definer ? "DEFINER = #{definer} " : ""}TRIGGER #{name} #{timing} #{event} ON `#{table}`
FOR EACH ROW
#{actions}
            SQL
          end
        when :postgresql, :postgis
          function_conditions = "(SELECT typname FROM pg_type WHERE oid = prorettype) = 'trigger'"
          function_conditions << <<-SQL unless options[:simple_check]
            AND oid IN (
              SELECT tgfoid
              FROM pg_trigger
              WHERE NOT tgisinternal AND tgconstrrelid = 0 AND tgrelid IN (
                SELECT oid FROM pg_class WHERE relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')
              )
            )
          SQL

          sql = <<-SQL
            SELECT tgname::varchar, pg_get_triggerdef(oid, true)
            FROM pg_trigger
            WHERE NOT tgisinternal AND tgconstrrelid = 0 AND tgrelid IN (
              SELECT oid FROM pg_class WHERE relnamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'public')
            )

            #{name_clause ? " AND tgname::varchar " + name_clause : ""}
            UNION
            SELECT proname || '()', pg_get_functiondef(oid)
            FROM pg_proc
            WHERE #{function_conditions}
              #{name_clause ? " AND (proname || '()')::varchar " + name_clause : ""}
          SQL
          select_rows(sql).each do |(name, definition)|
            triggers[name] = quote_table_name_in_trigger(definition)
          end
        else
          raise "don't know how to retrieve #{adapter_name} triggers yet"
      end
      triggers
    end

    # a bit hacky, but we need to ensure the table name is always quoted
    # on the way out, not just for reserved words. this is because we
    # always quote on the way in, so we need them to match exactly
    # when diffing
    def quote_table_name_in_trigger(definition)
      pattern = /
        (
          CREATE\sTRIGGER\s+
          \S+\s+
          (BEFORE|AFTER|INSTEAD\s+OF)\s+
          (INSERT|UPDATE|DELETE|TRUNCATE)\s+
          (OR\s+(INSERT|UPDATE|DELETE|TRUNCATE)\s+)*
          (ON\s+)
        )
        (\w+) # quote if not already quoted
      /ixm
      definition.sub(pattern, '\\1"\\7"')
    end
  end
end


text:
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#ifndef BITCOIN_RANDOM_H
#define BITCOIN_RANDOM_H

#include "uint256.h"

#include <functional>
#include <stdint.h>

/**
 * Functions to gather random data via the libsodium CSPRNG
 */
void GetRandBytes(unsigned char* buf, size_t num);
uint64_t GetRand(uint64_t nMax);
int GetRandInt(int nMax);
uint256 GetRandHash();

/**
 * Identity function for MappedShuffle, so that elements retain their original order.
 */
 int GenIdentity(int n);

/**
 * Rearranges the elements in the range [first,first+len) randomly, assuming
 * that gen is a uniform random number generator. Follows the same algorithm as
 * std::shuffle in C++11 (a Durstenfeld shuffle).
 *
 * The elements in the range [mapFirst,mapFirst+len) are rearranged according to
 * the same permutation, enabling the permutation to be tracked by the caller.
 *
 * gen takes an integer n and produces a uniform random output in [0,n).
 */
template <typename RandomAccessIterator, typename MapRandomAccessIterator>
void MappedShuffle(RandomAccessIterator first,
                   MapRandomAccessIterator mapFirst,
                   size_t len,
                   std::function<int(int)> gen)
{
    for (size_t i = len-1; i > 0; --i) {
        auto r = gen(i+1);
        assert(r >= 0);
        assert(r <= i);
        std::swap(first[i], first[r]);
        std::swap(mapFirst[i], mapFirst[r]);
    }
}

/**
 * Seed insecure_rand using the random pool.
 * @param Deterministic Use a deterministic seed
 */
void seed_insecure_rand(bool fDeterministic = false);

/**
 * MWC RNG of George Marsaglia
 * This is intended to be fast. It has a period of 2^59.3, though the
 * least significant 16 bits only have a period of about 2^30.1.
 *
 * @return random value
 */
extern uint32_t insecure_rand_Rz;
extern uint32_t insecure_rand_Rw;
static inline uint32_t insecure_rand(void)
{
    insecure_rand_Rz = 36969 * (insecure_rand_Rz & 65535) + (insecure_rand_Rz >> 16);
    insecure_rand_Rw = 18000 * (insecure_rand_Rw & 65535) + (insecure_rand_Rw >> 16);
    return (insecure_rand_Rw << 16) + insecure_rand_Rz;
}

#endif // BITCOIN_RANDOM_H

redpajama_set_name: RedPajamaGithub


text:
module Eve
  class BlueprintManufacturingMaterial < ApplicationRecord
    belongs_to :blueprint,
      class_name: "Eve::Blueprint",
      primary_key: "type_id"

    belongs_to :type,
      primary_key: "type_id",
      optional: true
  end
end


text:
<nb-range-datepicker #abc="nbRangeDatePicker"></nb-range-datepicker>
<nb-range-datepicker disabled></nb-range-datepicker>

<p>
    your selected: {{ abc.value.startDate | date: "yyyy-MM-dd" }} ~ {{ abc.value.endDate | date: "yyyy-MM-dd" }}
</p>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pleospora infectoria var. sacchari Speg.

### Remarks
null


text:
package com.andrels.anjsonparser.parser;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.andrels.anjsonparser.annotation.JSONAttribute;
import com.andrels.anjsonparser.annotation.JSONType;
import com.andrels.anjsonparser.exception.JSONParserFailureException;

/**
 *
 * @author Andre L. Santos <andrelimasantos@gmail.com>
 * @since 8 de dez de 2016
 *
 * Parser to/from JSON
 */
public class JSONParser {
	private static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
	private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT, Locale.getDefault());

	/**
	 * Serialize a java.lang.Object annoted with @JSONType
	 * into JSON
	 * @param object
	 * @return JSONObject
	 * @see org.json.JSONObject, com.andrels.anjsonparser.annotation.JSONType
	 */
	public JSONObject serialize(Object object){
		Class<?> clazz = object.getClass();
		JSONObject json = null;
		if(clazz.isAnnotationPresent(JSONType.class)){
			json = new JSONObject();

			try{
				Collection<Field> fields = getAnnotedFields(clazz);

				for(Field f : fields){
					JSONAttribute annotation = f.getAnnotation(JSONAttribute.class);
					Class<?> type = f.getType();
					String attributeName = annotation.getGetterSetterName().length() > 0 ? annotation.getGetterSetterName() : annotation.name();
					String getterName = getGetterName(annotation, f);

					Method m = clazz.getMethod(getterName, (Class<?>[])null);
					Object value = m.invoke(object, (Object[])null);

					if(value != null && Calendar.class.isAssignableFrom(value.getClass())){
						value = ((Calendar)value).getTime();
					}

					if(value == null){
						json.put(attributeName, JSONObject.NULL);
					}
					else if(String.class.equals(type)){
						json.put(attributeName, (String)value);
					}
					else if(Integer.class.equals(type) || int.class.equals(type)){
						json.put(attributeName, (Integer)value);
					}
					else if(Long.class.equals(type) || long.class.equals(type)){
						json.put(attributeName, (Long)value);
					}
					else if(Double.class.equals(type) || double.class.equals(type)){
						json.put(attributeName, (Double)value);
					}
					else if(Boolean.class.equals(type) || boolean.class.equals(type)){
						json.put(attributeName, (Boolean)value);
					}
					else if(value instanceof Collection){
						json.put(attributeName, serialize((Collection<?>)value));
					}
					else if(Date.class.isAssignableFrom(value.getClass())){
						json.put(attributeName, sdf.format((Date)value));
					}
					else if(type.isArray()){
						json.put(attributeName, serialize(Arrays.asList((Object[])value)));
					}
					else{
						json.put(attributeName,  serialize(value));
					}
				}
			}catch(NoSuchMethodException e){
				//TODO
			}catch(Exception e){
				//TODO
			}
		}
		return json;
	}

	/**
     * Serialize a java.util.Collection
     * into JSON array
     * @param objects
     * @return JSONObject
     * @see org.json.JSONArray
     */
	public JSONArray serialize(Collection<?> collection){
		JSONArray jsonArray = new JSONArray();
		for(Object object : collection){
			if(object.getClass().isAnnotationPresent(JSONType.class)){
				jsonArray.put(serialize(object));
			}
		}
		return jsonArray;
	}

	/**
	 * Parse JSON String into typed <T> Object, since annoted with JSONType
	 * @param json
	 * @param clazz
	 * @return
	 * @throws JSONParserFailureException
	 *
	 * @see com.andrels.anjsonparser.annotation.JSONType
	 */
	public <T>T parse(String json, Class<T> clazz) throws JSONParserFailureException{
		try {
			return parse(new JSONObject(json), clazz);
		} catch (JSONException e) {
			throw new JSONParserFailureException(e.getMessage(), e);
		}
	}

	public <T>T parse(JSONObject json, Class<T> clazz) throws JSONParserFailureException{
		if(clazz.isAnnotationPresent(JSONType.class) && json != null){
			try{
				T object = clazz.newInstance();
				List<Field> fields = new LinkedList<Field>();

				Class<?> c = clazz;
				while(c != null){
					fields.addAll(Arrays.asList(c.getDeclaredFields()));
					c = c.getSuperclass();
				}

				for(Field f : fields){
					if(f.isAnnotationPresent(JSONAttribute.class)){
						JSONAttribute annotation = f.getAnnotation(JSONAttribute.class);
						Class<?> type = f.getType();
						f.getDeclaringClass();
						String attributeName = annotation.getGetterSetterName().length() > 0 ? annotation.getGetterSetterName() : annotation.name();
						String setterName = getSetterName(annotation, f);

						Method m = clazz.getMethod(setterName, f.getType());

						if(!json.isNull(attributeName)){
							if(String.class.equals(type)){
								m.invoke(object, json.optString(attributeName));
							}
							else if(Integer.class.equals(type) || int.class.equals(type)){
								m.invoke(object, json.optInt(attributeName));
							}
							else if(Long.class.equals(type) || long.class.equals(type)){
								m.invoke(object, json.optLong(attributeName));
							}
							else if(Double.class.equals(type) || double.class.equals(type)){
								m.invoke(object, json.optDouble(attributeName));
							}
							else if(Boolean.class.equals(type) || boolean.class.equals(type)){
								m.invoke(object, json.optBoolean(attributeName));
							}
							else if(type.isArray()){
								m.invoke(object, (Object)parse(json.optJSONArray(attributeName), annotation.collectionArrayClass()));
							}
							else if(type.isInstance((Collection<?>)new ArrayList<Object>())){
								Object[] objs = parse(json.optJSONArray(attributeName), annotation.collectionArrayClass());
								if(objs != null){
									m.invoke(object, Arrays.asList(objs));
								}
							}
							else{
								m.invoke(object, parse(json.getJSONObject(attributeName), m.getParameterTypes()[0]));
							}
						}
					}
				}
				return object;
			}catch(NoSuchMethodException e){
				throw new JSONParserFailureException(e.getMessage(), e);
			}catch(Exception e){
				throw new JSONParserFailureException(e.getMessage(), e);
			}
		}
		return null;
	}

	public Object[] parse(JSONArray jsonArray, Class<?> classIns){
		if(classIns.isAnnotationPresent(JSONType.class) && jsonArray != null){
			Object nArray = Array.newInstance(classIns, jsonArray.length());
			for(int i = 0; i < jsonArray.length(); i++){
				try{
					Array.set(nArray, i, parse(jsonArray.optJSONObject(i), classIns));
				}
				catch(Exception e){
					//TODO
				}
			}
			return (Object[])nArray;
		}

		return null;
	}

	private String getGetterName(JSONAttribute annotation, Field field){
		String getterName = (annotation.getGetterSetterName().length() > 0 ? annotation.getGetterSetterName() : field.getName());
		getterName = Character.toUpperCase(getterName.charAt(0)) + getterName.substring(1);
		return "get"+getterName;
	}

	private String getSetterName(JSONAttribute annotation, Field field){
		String getterName = (annotation.getGetterSetterName().length() > 0 ? annotation.getGetterSetterName() : field.getName());
		getterName = Character.toUpperCase(getterName.charAt(0)) + getterName.substring(1);
		return "set"+getterName;
	}

	private Collection<Field> getAnnotedFields(Class<?> clazz){
		ArrayList<Field> fields = new ArrayList<Field>();
		if(clazz.isAnnotationPresent(JSONType.class)){
			if(clazz.getSuperclass().isAnnotationPresent(JSONType.class)){
				fields.addAll(getAnnotedFields(clazz.getSuperclass()));
			}

			for(Field f : clazz.getDeclaredFields()){
				if(f.isAnnotationPresent(JSONAttribute.class)){
					fields.add(f);
				}
			}
		}
		return fields;
	}
}


text:
from bot import Command, categories
import random

hearts = ['heart', 'hearts', 'yellow_heart', 'green_heart', 'blue_heart', 'purple_heart']

class Respects(Command):
    def __init__(self, bot):
        super().__init__(bot)
        self.name = 'respects'
        self.aliases = ['f']
        self.help = '$[respects-help]'
        self.category = categories.FUN

    async def handle(self, cmd):
        hearts_m = ''
        for x in range(random.randint(1, 3)):
            hearts_m = ' :' + random.choice(hearts) + ':'

        if cmd.text != '':
            await cmd.answer('$[respects-paid-to]', withname=False, locales={'thing': cmd.text, 'hearts': hearts_m})
        else:
            await cmd.answer('$[respects-paid]', withname=False, locales={'hearts': hearts_m})


text:
<!DOCTYPE html>

	<title>

            Greely Accounting Services -

    Complete profile - Canadian Company Capabilities - Industries and Business - Industry Canada
  </title>

<meta charset="utf-8" />
<meta name="dcterms.language" title="ISO639-2" content="eng" />
<meta name="dcterms.title" content="" />
<meta name="description" content="" />
<meta name="dcterms.description" content="" />
<meta name="dcterms.type" content="report, data set" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.subject" content="businesses, industry" />
<meta name="dcterms.issued" title="W3CDTF" content="" />
<meta name="dcterms.modified" title="W3CDTF" content="" />
<meta name="keywords" content="" />

<meta name="dcterms.creator" content="" />
<meta name="author" content="" />
<meta name="dcterms.created" title="W3CDTF" content="" />
<meta name="dcterms.publisher" content="" />
<meta name="dcterms.audience" title="icaudience" content="" />
<meta name="dcterms.spatial" title="ISO3166-1" content="" />
<meta name="dcterms.spatial" title="gcgeonames" content="" />
<meta name="dcterms.format" content="HTML" />
<meta name="dcterms.identifier" title="ICsiteProduct" content="536" />

<meta http-equiv="X-UA-Compatible" content="IE=edge">

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

<meta name = "format-detection" content = "telephone=no">

<meta name="robots" content="noarchive">

<link href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/wet-boew.min.css">

<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/theme.min.css">

<link rel="stylesheet" href="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/css/noscript.min.css" />

<link rel="stylesheet" href="/eic/home.nsf/css/add_WET_4-0_Canada_Apps.css">

  	<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
  	<link href="/app/ccc/srch/css/print.css" media="print" rel="stylesheet" type="text/css" />

<meta property="legalName" content="Department_of_Industry">

Skip to main content

Skip to "About this site"

Language selection

Français

<object type="image/svg+xml" tabindex="-1" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/sig-blk-en.svg"></object> Government of Canada

Search and menus

Search and menus

Topics menu

Jobs

Immigration

Travel

Business

Benefits

Health

Taxes

More services

You are here:

Home

Industries and Business

Canadian Company Capabilities

<input id="showMore" type="hidden" value='more'/>
<input id="showLess" type="hidden" value='less'/>

 Company profile - Canadian Company Capabilities

New Search |

<form name="searchForm" method="post" action="/app/ccc/srch/bscSrch.do">

          <input type="hidden" name="lang" value="eng" />
          <input type="hidden" name="profileId" value="" />
          <input type="hidden" name="prtl" value="1" />
          <input type="hidden" name="searchPage" value="%2Fapp%2Fccc%2Fsrch%2FcccBscSrch.do%3Flang%3Deng%26amp%3Bprtl%3D1%26amp%3Btagid%3D"  />

          <input type="hidden" name="V_SEARCH.scopeCategory" value="CCC.Root" />

          <input type="hidden" name="V_SEARCH.depth" value="1" />
          <input type="hidden" name="V_SEARCH.showStricts" value="false" />
          <input id="repeatSearchBtn" class="btn btn-link" type="submit" value="Return to search results" />

  </form>

| Previous Company

| Next Company

      Third-Party Information Liability Disclaimer

Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.

      Greely Accounting Services

Legal/Operating Name:

Greely Accounting Services

http://www.greelyaccounting.ca

stevearuyter@gmail.com

Mailing Address:

              	<address class="mrgn-bttm-md">

                   6542 Greely West Dr.

                    GREELY,

                    Ontario

                  K4P 1B5

                </address>

Location Address:

              	         <address class="mrgn-bttm-md">

                   6542 Greely West Dr.

                    GREELY,

                    Ontario

                  K4P 1B5

                         </address>

Tel.:
		      (613) 292-4509

Fax:

Company Profile

            Greely Accounting Services provides tangible and intangible value to our clients. Our objective is to help small and medium-size businesses grow. We don't look at the business from a historical perspective as many ordinary accounting firms do, but actively work with you to develop the business and improve it.

We provide quality accounting services to small and medium size companies in the Ottawa area. Our staff can provide advice to owners on how to maximize their small business tax deductions and minimize the amount of tax.

Thinking of growing your business, we can help you decide on which strategies work best for your business.

Our focus is achieved through practical, customer focused, strategic solutions developed in partnership with our clients. We accomplish this by providing clearly defined, highly structured and extremely responsive services. •We bring peace of mind for our clients

•We work to make the complex understandable

•We act in an advisory role to our clients that enable them to make better informed business decisions

•We desire to help our clients make more money and sleep better

Greely Accounting Services excel in meeting and exceeding the needs of entrepreneurs and business owners. We work closely with our clients to provide insight and assistance into the controls and financial management of their business.

				Full profile

				Full profile

				Contact information

                Steve
                Ruyter

                  Title:

                Secretary

                    Area of Responsibility:

                    Finance/Accounting.

                  Telephone:

                (613) 292-4509

                    Email:

                  stevearuyter@gmail.com

  top of page

				Company description

            Exporting:

              No

                Primary Industry (NAICS):

				541212 - Offices of Accountants

            Alternate Industries (NAICS):

            541213 - Tax Preparation Services

            541215 - Bookkeeping, Payroll and Related Services

            Primary Business Activity:

            Services

				Product / Service / Licensing

                              Service Name:

                            accounting and tax

                            Accounting System and Design

• Starting a new company?

•Overhauling an existing company?

Greely Accounting Services will design your custom accounting system, one that saves you time, effort, and ends frustration.  Experience an accounting system that works the way you need it to work.

We have experience with a variety of accounting packages and can recommend and install the software that best suits your needs.

Bookkeeping and Accounting

Careful record keeping is essential.  It is a challenge to maintain accurate supporting records and receipts for tax, managerial, and financial statement purposes.  Allow Greely Accounting Services keep the books and accounts, and you can focus your energies where they are needed.

If you are planning to finance the expansion of your business; if you decide to merge or sell; if you want to know how well your business is doing, proper bookkeeping is imperative.

Budgets

Budgeting is a key component of a successful business.  In particular; if your revenues are relatively stable from year-to-year, then careful budgeting, combined with ongoing monitoring of actual income and expenses, can help control your expenditures.  Contact Greely Accounting Services and allow us help you prepare your budgets.

Cash Flow Projections

Whether your company is having a good year or not, cash management is crucial.   •When will your receivables come in?

•Are you paying your bills too quickly?

•Will you be able to meet next month's payroll?

•How much cash will you have in three months, in six months?

•Will you need a bank line of credit this year?

Greely Accounting Services can provide the answers to these and many others questions.

Financial Statement Preparation

 Regular financial statements are necessary for a company's fiscal health.  Generally prepared monthly, these statements provide an up-to-date view of your company's assets and liabilities, and your revenue and expenses.

Well-prepared financial statements indicate much more than just actual figures.  If you are working with a budget, these statements can reveal the discrepancies between anticipated and actual results.  A recommended monthly financial statement can highlight areas of concern in time for you to take action.

Personal and Corporate Income Tax

 Are you paying too much tax, too little?  Like many small business owners and many corporations, you probably aren't absolutely certain.  Save yourself time, work and frustration.  Have your tax returns prepared expertly by the professionals at Greely Accounting Services.

  top of page

					Third-Party Information Liability Disclaimer

					Some of the information on this Web page has been provided by external sources. The Government of Canada is not responsible for the accuracy, reliability or currency of the information supplied by external sources. Users wishing to rely upon this information should consult directly with the source of the information. Content provided by external sources is not subject to official languages, privacy and accessibility requirements.

				Contacts

				Contact information

                Steve
                Ruyter

                  Title:

                Secretary

                    Area of Responsibility:

                    Finance/Accounting.

                  Telephone:

                (613) 292-4509

                    Email:

                  stevearuyter@gmail.com

				Description

				Company description

            Exporting:

              No

                Primary Industry (NAICS):

				541212 - Offices of Accountants

            Alternate Industries (NAICS):

            541213 - Tax Preparation Services

            541215 - Bookkeeping, Payroll and Related Services

            Primary Business Activity:

            Services

				Products, services and licensing

				Product / Service / Licensing

                              Service Name:

                            accounting and tax

                            Accounting System and Design

• Starting a new company?

•Overhauling an existing company?

Greely Accounting Services will design your custom accounting system, one that saves you time, effort, and ends frustration.  Experience an accounting system that works the way you need it to work.

We have experience with a variety of accounting packages and can recommend and install the software that best suits your needs.

Bookkeeping and Accounting

Careful record keeping is essential.  It is a challenge to maintain accurate supporting records and receipts for tax, managerial, and financial statement purposes.  Allow Greely Accounting Services keep the books and accounts, and you can focus your energies where they are needed.

If you are planning to finance the expansion of your business; if you decide to merge or sell; if you want to know how well your business is doing, proper bookkeeping is imperative.

Budgets

Budgeting is a key component of a successful business.  In particular; if your revenues are relatively stable from year-to-year, then careful budgeting, combined with ongoing monitoring of actual income and expenses, can help control your expenditures.  Contact Greely Accounting Services and allow us help you prepare your budgets.

Cash Flow Projections

Whether your company is having a good year or not, cash management is crucial.   •When will your receivables come in?

•Are you paying your bills too quickly?

•Will you be able to meet next month's payroll?

•How much cash will you have in three months, in six months?

•Will you need a bank line of credit this year?

Greely Accounting Services can provide the answers to these and many others questions.

Financial Statement Preparation

 Regular financial statements are necessary for a company's fiscal health.  Generally prepared monthly, these statements provide an up-to-date view of your company's assets and liabilities, and your revenue and expenses.

Well-prepared financial statements indicate much more than just actual figures.  If you are working with a budget, these statements can reveal the discrepancies between anticipated and actual results.  A recommended monthly financial statement can highlight areas of concern in time for you to take action.

Personal and Corporate Income Tax

 Are you paying too much tax, too little?  Like many small business owners and many corporations, you probably aren't absolutely certain.  Save yourself time, work and frustration.  Have your tax returns prepared expertly by the professionals at Greely Accounting Services.

    Last Update Date 2015-12-15

Date Modified:

      <time>2017-03-02</time>

About government

Contact us

Departments and agencies

Public service and military

News

Treaties, laws and regulations

Government-wide reporting

Prime Minister

How government works

Open government

About this site

Social media

Mobile applications

About Canada.ca

Terms and conditions

Privacy

Top of Page

<object type="image/svg+xml" tabindex="-1" role="img" data="/utils/scripts/_WET_4-0/apps/themes-dist/gcweb/assets/wmms-blk.svg" aria-label="Symbol of the Government of Canada"></object>


text:
//
// Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// A copy of the License is located at
//
// http://aws.amazon.com/apache2.0
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
//
package org.jenkinsci.plugins.awsdevicefarm;

/**
 * Exception class for the the Device Farm Jenkins plugin.
 */
public class AWSDeviceFarmException extends Exception {
    /**
     * Wrapper for generic Exceptions.
     *
     * @param message The message to add to the exception.
     */
    public AWSDeviceFarmException(String message) {
        super(message);
    }
}


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _react = _interopRequireDefault(require("react"));

var _styledComponents = require("styled-components");

var sheetByPathname = new Map(); // eslint-disable-next-line react/prop-types,react/display-name

exports.wrapRootElement = function (_ref) {
  var element = _ref.element,
      pathname = _ref.pathname;
  var sheet = new _styledComponents.ServerStyleSheet();
  sheetByPathname.set(pathname, sheet);
  return /*#__PURE__*/_react.default.createElement(_styledComponents.StyleSheetManager, {
    sheet: sheet.instance
  }, element);
};

exports.onRenderBody = function (_ref2) {
  var setHeadComponents = _ref2.setHeadComponents,
      pathname = _ref2.pathname;
  var sheet = sheetByPathname.get(pathname);

  if (sheet) {
    setHeadComponents([sheet.getStyleElement()]);
    sheetByPathname.delete(pathname);
  }
};


text:
package com.khartec.waltz.web.endpoints.api;

import com.khartec.waltz.model.IdSelectionOptions;
import com.khartec.waltz.model.software_catalog.SoftwareCatalog;
import com.khartec.waltz.model.software_catalog.SoftwareSummaryStatistics;
import com.khartec.waltz.service.software_catalog.SoftwareCatalogService;
import com.khartec.waltz.web.DatumRoute;
import com.khartec.waltz.web.endpoints.Endpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import spark.Request;
import spark.Response;

import java.io.IOException;

import static com.khartec.waltz.web.WebUtilities.*;
import static com.khartec.waltz.web.endpoints.EndpointUtilities.getForDatum;
import static com.khartec.waltz.web.endpoints.EndpointUtilities.postForDatum;

@Service
public class SoftwareCatalogEndpoint implements Endpoint {

    private static final String BASE_URL = mkPath("api", "software-catalog");

    private final SoftwareCatalogService service;

    @Autowired
    public SoftwareCatalogEndpoint(SoftwareCatalogService service) {
        this.service = service;
    }

    @Override
    public void register() {

        String makeCatalogForAppIdsPath = mkPath(BASE_URL, "apps");
        String calculateStatsForAppIdSelectorPath = mkPath(BASE_URL, "stats");

        DatumRoute<SoftwareCatalog> makeCatalogForAppIdsRoute = (request, response) ->
                service.makeCatalogForAppIds(readIdsFromBody(request));

        DatumRoute<SoftwareSummaryStatistics> calculateStatsForAppIdSelectorRoute = (request, response)
                -> service.calculateStatisticsForAppIdSelector(readIdSelectionOptionsFromBody(request));

        getForDatum(mkPath(BASE_URL, "package-id", ":id"), this::getByPackageIdRoute);
        getForDatum(mkPath(BASE_URL, "version-id", ":id"), this::getByVersionIdRoute);
        getForDatum(mkPath(BASE_URL, "licence-id", ":id"), this::getByLicenceIdRoute);
        postForDatum(mkPath(BASE_URL, "selector"), this::findBySelectorRoute);
        postForDatum(makeCatalogForAppIdsPath, makeCatalogForAppIdsRoute);
        postForDatum(calculateStatsForAppIdSelectorPath, calculateStatsForAppIdSelectorRoute);

    }

    private SoftwareCatalog getByPackageIdRoute(Request request, Response response) {
        long id = getId(request);
        return service.getByPackageId(id);
    }

    private SoftwareCatalog getByVersionIdRoute(Request request, Response response) {
        long id = getId(request);
        return service.getByVersionId(id);
    }

    private SoftwareCatalog getByLicenceIdRoute(Request request, Response response) {
        long id = getId(request);
        return service.getByLicenceId(id);
    }

    private SoftwareCatalog findBySelectorRoute(Request request, Response response) throws IOException {
        IdSelectionOptions options = readIdSelectionOptionsFromBody(request);
        return service.findBySelector(options);
    }

}


text:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>BLAKE2s PWA</title>
  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">
  <link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons">
  <link rel="manifest" href="manifest.json">

  <link rel="stylesheet" href="bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

Blake2s PWA

        (niceware soon™)

no-downsaur edition

        <form>

            master secret

              <input type="password" class="form-control form-control-lg" id="input" placeholder="masterpass">

            size

              <input type="number" class="form-control form-control-sm" id="digest-length" value="10" min="1" max="32">

            domain

              <input type="text" class="form-control form-control-lg" id="key" placeholder="domain">

              <button type="button" class="btn btn-outline-success btn-lg btn-block" onclick="calculateDigest()">Digest =></button>

                <textarea class="form-control" id="digest" rows="2"></textarea>

        </form>


text:
#ifndef WEBRTC_MODULES_DESKTOP_CAPTURE_SHARED_DESKTOP_FRAME_H_
#define WEBRTC_MODULES_DESKTOP_CAPTURE_SHARED_DESKTOP_FRAME_H_

#include "webrtc/modules/desktop_capture/desktop_frame.h"
#include "webrtc/system_wrappers/interface/scoped_refptr.h"

namespace webrtc {

// SharedDesktopFrame is a DesktopFrame that may have multiple instances all
// sharing the same buffer.
class SharedDesktopFrame : public DesktopFrame {
 public:
  virtual ~SharedDesktopFrame();

  static SharedDesktopFrame* Wrap(DesktopFrame* desktop_frame);

  // Returns the underlying instance of DesktopFrame.
  DesktopFrame* GetUnderlyingFrame();

  // Creates a clone of this object.
  SharedDesktopFrame* Share();

  // Checks if the frame is currently shared. If it returns false it's
  // guaranteed that there are no clones of the object.
  bool IsShared();

 private:
  class Core;

  SharedDesktopFrame(scoped_refptr<Core> core);

  scoped_refptr<Core> core_;

  DISALLOW_COPY_AND_ASSIGN(SharedDesktopFrame);
};

}  // namespace webrtc

#endif  // WEBRTC_MODULES_DESKTOP_CAPTURE_SHARED_DESKTOP_FRAME_H_


text:
package org.apache.ode.bpel.engine;

import org.apache.ode.bpel.iapi.*;
import org.apache.ode.bpel.iapi.Scheduler.JobDetails;
import org.apache.ode.bpel.rapi.ResourceModel;
import org.apache.ode.bpel.dao.MessageExchangeDAO;
import org.apache.ode.bpel.dao.ProcessInstanceDAO;
import org.apache.ode.bpel.dao.ResourceRouteDAO;
import org.apache.ode.bpel.common.FaultException;
import org.apache.ode.bpel.rapi.InvalidProcessException;
import org.apache.ode.bpel.evt.NewProcessInstanceEvent;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Callable;

public class ODERESTProcess extends ODEProcess {

    private ConcurrentHashMap<ResourceModel,String> _staticResources = new ConcurrentHashMap<ResourceModel,String>();

    private ArrayList<Resource> _instantiatingResources = new ArrayList<Resource>();

    public ODERESTProcess(BpelServerImpl server, ProcessConf conf, BpelEventListener debugger, IncomingMessageExchangeCache mexCache) {
        super(server, conf, debugger, mexCache);
        _processModel = conf.getProcessModel();
        _runtime = buildRuntime(_processModel.getModelVersion());
        _runtime.init(_pconf, _processModel);
    }

    public Collection<String> initResources() {
        if (_staticResources.size() > 0 ) return _staticResources.values();

        // Caching instantiating resource urls as those can be expressions
        ArrayList<String> addresses = new ArrayList<String>();
        for (ResourceModel resourceModel : _processModel.getProvidedResources()) {
            if (resourceModel.isInstantiateResource()) {
                try {
                    String addr = _runtime.extractAddress(resourceModel);
                    addresses.add(addr);
                    _staticResources.put(resourceModel, addr);
                } catch (FaultException e) {
                    throw new BpelEngineException(e);
                }
            }
        }
        return addresses;
    }

    void activate(Contexts contexts) {
        _contexts = contexts;
        bounceProcessDAO();
        // Resources to activate are the instantiating ones plus the waiting routes.

        List<ResourceRouteDAO> rrDaos;
        try {
            rrDaos = _contexts.execTransaction(new Callable<List<ResourceRouteDAO>>() {
                public List<ResourceRouteDAO> call() throws Exception {
                    return _contexts.dao.getConnection().getAllResourceRoutes();
                }
            });
        } catch (Exception ex) {
            String errmsg = "DbError";
            __log.error(errmsg, ex);
            throw new BpelEngineException(errmsg, ex);
        }

        for (ResourceRouteDAO rrDao : rrDaos) {
            Resource resource = new Resource(rrDao.getUrl(), "application/xml", rrDao.getMethod());
            _contexts.bindingContext.activateProvidedResource(resource);
            _instantiatingResources.add(resource);
        }

        // Activating instantiating resources
        for (ResourceModel resourceModel : _staticResources.keySet()) {
            Resource resource = new Resource(_staticResources.get(resourceModel),
                    "application/xml", resourceModel.getMethod());
            _contexts.bindingContext.activateProvidedResource(resource);
            _instantiatingResources.add(resource);
        }
    }

    void deactivate() {
        for (ResourceModel resourceModel : _staticResources.keySet()) {
            Resource resource = new Resource(_staticResources.get(resourceModel),
                    "application/xml", resourceModel.getMethod());
            _contexts.bindingContext.deactivateProvidedResource(resource);
        }
    }

    void invokeProcess(final MessageExchangeDAO mexdao) {
        if (_pconf.getState() == ProcessState.RETIRED) {
            throw new InvalidProcessException("Process is retired.", InvalidProcessException.RETIRED_CAUSE_CODE);
        }
        mexdao.setProcess(getProcessDAO());

        try {
            boolean instantiatingResource = isInstantiating(mexdao.getResource());
            InvocationStyle istyle = mexdao.getInvocationStyle();

            if (instantiatingResource) {
                ProcessInstanceDAO newInstance = getProcessDAO().createInstance(null);
                newInstance.setInstantiatingUrl(mexdao.getResource());

                // send process instance event
                NewProcessInstanceEvent evt = new NewProcessInstanceEvent(getProcessModel().getQName(),
                        getProcessDAO().getProcessId(), newInstance.getInstanceId());
                evt.setMexId(mexdao.getMessageExchangeId());
                saveEvent(evt, newInstance);

                mexdao.setCorrelationStatus(MyRoleMessageExchange.CorrelationStatus.CREATE_INSTANCE.toString());
                mexdao.setInstance(newInstance);

                doInstanceWork(mexdao.getInstance().getInstanceId(), new Callable<Void>() {
                    public Void call() {
                        executeCreateInstance(mexdao);
                        return null;
                    }
                });
            } else {
                // TODO avoid reloading the resource routing, it's just been loaded by the server on mex creation
                String[] urlMeth = mexdao.getResource().split("~");
                ResourceRouteDAO rr = _contexts.dao.getConnection().getResourceRoute(urlMeth[0], urlMeth[1]);
                if (rr == null) throw new BpelEngineException("NoSuchResource: " + mexdao.getResource());

                mexdao.setInstance(rr.getInstance());
                mexdao.setChannel(rr.getPickResponseChannel() + "&" + rr.getSelectorIdx());

                if (istyle == InvocationStyle.TRANSACTED) {
                    doInstanceWork(mexdao.getInstance().getInstanceId(), new Callable<Void>() {
                        public Void call() {
                            executeContinueInstanceMyRoleRequestReceived(mexdao);
                            return null;
                        }
                    });
                } else /* non-transacted style */ {
                    JobDetails j = new JobDetails();
                    j.setType(Scheduler.JobType.MYROLE_INVOKE);
                    j.setInstanceId(mexdao.getInstance().getInstanceId());
                    j.setMexId(mexdao.getMessageExchangeId());
                    // Could be different to this pid when routing to an older version
                    j.setProcessId(mexdao.getInstance().getProcess().getProcessId());

                    scheduleJob(j, null);
                }
                // Cleaning up
                _contexts.dao.getConnection().deleteResourceRoute(urlMeth[0], urlMeth[1]);
            }
        } finally {
            // If we did not get an ACK during this method, then mark this MEX as needing an ASYNC wake-up
            if (mexdao.getStatus() != MessageExchange.Status.ACK) mexdao.setStatus(MessageExchange.Status.ASYNC);
        }
    }

    void invokePartner(MessageExchangeDAO mexdao) {
        // TODO p2p short-circuiting
        mexdao.setStatus(MessageExchange.Status.REQ);
        try {
            String[] resStr = mexdao.getResource().split("~");
            RESTOutMessageExchangeImpl outMex = new RESTOutMessageExchangeImpl(this, mexdao.getInstance().getInstanceId(),
                    mexdao.getMessageExchangeId(), new Resource(resStr[0], "application/xml", resStr[1]));
            outMex.request();

            scheduleRunnable(new UnreliableInvoker(outMex));

            // Scheduling a verification to see if the invoke has really been processed. Otherwise
            // we put it in activity recovery mode (case of a server crash during invocation).
            // TODO the event needs a way to load a mex with getMessageExchange(), not available for now
//            scheduleInvokeCheck(mexdao);
        } finally {
            if (mexdao.getStatus() != MessageExchange.Status.ACK)
                mexdao.setStatus(MessageExchange.Status.ASYNC);
        }
    }

    void onRestMexAck(MessageExchangeDAO mexdao, MessageExchange.Status old, String url) {
        if (mexdao.getPipedMessageExchangeId() != null) /* p2p */{
            p2pCall(mexdao, old);
        } else /* not p2p */{
            RESTInMessageExchangeImpl mymex = (RESTInMessageExchangeImpl) _incomingMexCache.get(mexdao, this);
            mymex.load(mexdao);
            mymex.getResource().setUrl(url);
            if (old == MessageExchange.Status.ASYNC) {
                // Updating url for instantiating mexs so that the created resource url can be returned to the caller
                mymex.onAsyncAck(mexdao);
            }
        }
    }

    // Restful processes don't lazy load their OModel, they need it right away to access the instantiating resource
    protected void latch(int s) { }
    protected void releaseLatch(int s) { }
    protected boolean isLatched(int s) { return false; }
    protected void hydrate() { }
    protected void dehydrate() { }

    public RESTInMessageExchange createRESTMessageExchange(Resource resource, String clientKey) {
        // TODO check the resource matches a provided one
        RESTInMessageExchangeImpl mex = new RESTInMessageExchangeImpl(this, clientKey, resource);
        _incomingMexCache.put(mex);
        return mex;
    }

    MessageExchangeImpl recreateIncomingMex(MessageExchangeDAO mexdao) {
        Resource resource = getResource(mexdao.getResource());
        return new RESTInMessageExchangeImpl(this, mexdao.getMessageExchangeId(), resource);
    }

    public Resource getResource(String serializedForm) {
        int sep = serializedForm.indexOf("~");
        String url = serializedForm.substring(0, sep);
        String method = serializedForm.substring(sep + 1);

        return new Resource(url, "application/xml", method);
    }

    public Resource getInstantiatingUrl(ProcessInstanceDAO instanceDao) {
        return getResource(instanceDao.getInstantiatingUrl());
    }

    protected boolean isInstantiating(String serialized) {
        return isInstantiating(getResource(serialized));
    }
    protected boolean isInstantiating(Resource res) {
        for (Map.Entry<ResourceModel, String> resourceModel : _staticResources.entrySet()) {
            if (resourceModel.getValue().equals(res.getUrl())
                    && resourceModel.getKey().getMethod().equals(res.getMethod())
                    && resourceModel.getKey().isInstantiateResource()) return true;
        }
        return false;
    }

    class UnreliableInvoker implements Runnable {

        RESTOutMessageExchangeImpl _restMex;

        public UnreliableInvoker(RESTOutMessageExchangeImpl mex) {
            _restMex = mex;
        }

        public void run() {
            Throwable err = null;
            try {
                _contexts.mexContext.invokeRestful(_restMex);
                _restMex.setState(RESTOutMessageExchangeImpl.State.HOLD);
            } catch (Throwable t) {
                _restMex.setState(RESTOutMessageExchangeImpl.State.DEAD);
                err = t;
            }

            // Handle system failure in a transaction
            final Throwable ferr = err;
            if (ferr != null) {
                __log.debug("Request failure from instance " + _restMex.getIID() + " for url " + _restMex.getTargetResource().getUrl());
                enqueueInstanceTransaction(_restMex.getIID(),  new Runnable() {
                    public void run() {
                        MessageExchangeDAO mexdao = loadMexDao(_restMex.getMessageExchangeId());
                        MexDaoUtil.setFailed(mexdao, MessageExchange.FailureType.OTHER, ferr.toString());
                        _restMex.setState(RESTOutMessageExchangeImpl.State.DEAD);
                    }
                } );
                return;
            }

            // We proceed handling the response in a transaction. Note that if for some reason the following transaction
            // fails, the unreliable invoke will be in an "unknown" state, and will require manual intervention to either
            // retry or force fail.
            enqueueInstanceTransaction(_restMex.getIID(),  new Runnable() {
                public void run() {
                   MessageExchangeDAO mexdao = loadMexDao(_restMex.getMessageExchangeId());
                   if (_restMex.getStatus() == MessageExchange.Status.ACK) {
                        _restMex.save(mexdao);
                        _restMex.setState(RESTOutMessageExchangeImpl.State.DEAD);
                    } else if (_restMex.getStatus() == MessageExchange.Status.REQ) {
                        MexDaoUtil.setFailed(mexdao, MessageExchange.FailureType.NO_RESPONSE, "No Response");
                        _restMex.setState(RESTOutMessageExchangeImpl.State.DEAD);
                    } else {
                        // Internal error that should not be possible.
                        __log.fatal("InternalError: Unexpected message exchange state!");
                        MexDaoUtil.setFailed(mexdao, MessageExchange.FailureType.OTHER, "Unexpected message exchange state");
                    }

                    executeContinueInstancePartnerRoleResponseReceived(mexdao);
                }
            });
        }
    }
}


text:
using Sitecore.DataExchange;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SF.Feature.DEF.General.Plugins
{
    public class NamedPluginSettings
    {
        public NamedPluginSettings()
        {
            Plugins = new Dictionary<string, IPlugin>();
        }

        public Dictionary<string, IPlugin> Plugins { get; set; }

        public T GetPlugin<T>(string name) where T : class, IPlugin
        {
            if (Plugins.ContainsKey(name))
            {
                return Plugins[name] as T;
            }
            return null;
        }
    }
}


text:
package com.google.code.linkedinapi.schema.impl;

import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.google.code.linkedinapi.schema.ApiStandardProfileRequest;
import com.google.code.linkedinapi.schema.Editor;
import com.google.code.linkedinapi.schema.SiteStandardProfileRequest;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "id",
    "firstName",
    "lastName",
    "headline",
    "apiStandardProfileRequest",
    "siteStandardProfileRequest"
})
@XmlRootElement(name = "editor")
public class EditorImpl
    implements Serializable, Editor
{

    private final static long serialVersionUID = 2461660169443089969L;
    @XmlElement(required = true)
    @XmlJavaTypeAdapter(CollapsedStringAdapter.class)
    protected String id;
    @XmlElement(name = "first-name", required = true)
    protected String firstName;
    @XmlElement(name = "last-name", required = true)
    protected String lastName;
    @XmlElement(required = true)
    protected String headline;
    @XmlElement(name = "api-standard-profile-request", required = true, type = ApiStandardProfileRequestImpl.class)
    protected ApiStandardProfileRequestImpl apiStandardProfileRequest;
    @XmlElement(name = "site-standard-profile-request", required = true, type = SiteStandardProfileRequestImpl.class)
    protected SiteStandardProfileRequestImpl siteStandardProfileRequest;

    public String getId() {
        return id;
    }

    public void setId(String value) {
        this.id = value;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String value) {
        this.firstName = value;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String value) {
        this.lastName = value;
    }

    public String getHeadline() {
        return headline;
    }

    public void setHeadline(String value) {
        this.headline = value;
    }

    public ApiStandardProfileRequest getApiStandardProfileRequest() {
        return apiStandardProfileRequest;
    }

    public void setApiStandardProfileRequest(ApiStandardProfileRequest value) {
        this.apiStandardProfileRequest = ((ApiStandardProfileRequestImpl) value);
    }

    public SiteStandardProfileRequest getSiteStandardProfileRequest() {
        return siteStandardProfileRequest;
    }

    public void setSiteStandardProfileRequest(SiteStandardProfileRequest value) {
        this.siteStandardProfileRequest = ((SiteStandardProfileRequestImpl) value);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="se.su.dsv.scipro.android"
          android:versionCode="10"
          android:versionName="0.10">
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.VIBRATE"/>
    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="7"/>

    <application android:name="SciProApplication" android:icon="@drawable/icon_android"
                 android:label="@string/app_name">

        <activity
                android:name=".activity.SupervisorHome"
                android:label="@string/app_name"
                android:theme="@style/Theme.SciPro">
        </activity>

        <activity
                android:name=".activity.Authenticate"
                android:label="@string/app_name"
                android:theme="@style/Theme.SciPro">

        </activity>

        <activity
                android:name=".activity.NewMessage"
                android:label="@string/title_new_message"
                android:theme="@style/Theme.SciPro">
        </activity>

        <activity
                android:name=".Preferences"
                android:label="@string/title_preferences">
        </activity>

        <activity
                android:name=".activity.ProjectView"
                android:label="@string/title_project"
                android:theme="@style/Theme.SciPro">
        </activity>

        <activity
                android:name=".activity.PrivateMessageView"
                android:label="@string/title_message"
                android:theme="@style/Theme.SciPro">
        </activity>

        <activity
                android:name=".activity.PrivateMessages"
                android:label="@string/title_messages"
                android:theme="@style/Theme.SciPro">
        </activity>
        <activity android:name=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <activity
                android:name=".activity.StatusCheckIn"
                android:label="@string/app_name"
                android:theme="@style/Theme.SciPro"/>

        <service android:name=".services.UpdaterService"/>

    </application>
</manifest>


text:
package org.unitime.timetable.server.solver;

import java.util.BitSet;
import java.util.Collections;
import java.util.Iterator;

import org.unitime.localization.impl.Localization;
import org.unitime.timetable.gwt.resources.GwtConstants;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.shared.TimetableGridInterface.TimetableGridBackground;
import org.unitime.timetable.gwt.shared.TimetableGridInterface.TimetableGridCell;
import org.unitime.timetable.gwt.shared.TimetableGridInterface.TimetableGridModel;
import org.unitime.timetable.model.PreferenceLevel;
import org.unitime.timetable.solver.ui.AssignmentPreferenceInfo;

/**
 * @author Tomas Muller
 */
public class TimetableGridHelper {
	protected static GwtMessages MSG = Localization.create(GwtMessages.class);
	protected static GwtConstants CONST = Localization.create(GwtConstants.class);

	public static enum ResourceType {
		ROOM,
		INSTRUCTOR,
		DEPARTMENT,
		CURRICULUM,
		SUBJECT_AREA,
		STUDENT_GROUP,
	}

	public static enum BgMode {
		None,
		TimePref,
		RoomPref,
		StudentConf,
		InstructorBtbPref,
		DistributionConstPref,
		Perturbations,
		PerturbationPenalty,
		HardConflicts,
		DepartmentalBalancing,
		TooBigRooms,
		StudentGroups,
	}

	public static enum OrderBy {
		NameAsc,
		NameDesc,
		SizeAsc,
		SizeDesc,
	    TypeAsc,
	    TypeDesc,
	    UtilizationAsc,
	    UtilizationDesc,
	}

	public static enum DisplayMode {
		InRow,
		PerWeekHorizontal,
		PerWeekVertical,
		WeekByWeekHorizontal,
	}

	public static String sBgColorEmpty = "rgb(255,255,255)";
	public static String sBgColorRequired = "rgb(80,80,200)";
	public static String sBgColorStronglyPreferred = "rgb(40,180,60)";
	public static String sBgColorPreferred = "rgb(170,240,60)";
	public static String sBgColorNeutral = "rgb(240,240,240)";
	public static String sBgColorDiscouraged = "rgb(240,210,60)";
	public static String sBgColorStronglyDiscouraged = "rgb(240,120,60)";
	public static String sBgColorProhibited = "rgb(220,50,40)";
	public static String sBgColorNotAvailable = "rgb(200,200,200)";
	public static String sBgColorNotAvailableButAssigned = sBgColorProhibited;

    public static String pref2color(String pref) {
    	return PreferenceLevel.prolog2bgColor(pref);
    }

    public static String pref2color(int pref) {
    	return PreferenceLevel.prolog2bgColor(PreferenceLevel.int2prolog(pref));
    }

    public static String conflicts2color(int nrConflicts) {
        if (nrConflicts>15) nrConflicts = 15;
        String color = null;
        if (nrConflicts==0) {
            color = "rgb(240,240,240)";
        } else if (nrConflicts<5) {
            color = "rgb(240,"+(240-(30*nrConflicts/5))+","+(240-(180*nrConflicts/5))+")";
        } else if (nrConflicts<10) {
            color = "rgb(240,"+(210-(90*(nrConflicts-5)/5))+",60)";
        } else {
            color = "rgb("+(240-(20*(nrConflicts-10)/5))+","+(120-(70*(nrConflicts-10)/5))+","+(60-(20*(nrConflicts-10)/5))+")";
        }
        return color;
    }

    public static String conflicts2colorFast(int nrConflicts) {
        if (nrConflicts==0) return "rgb(240,240,240)";
        if (nrConflicts==1) return "rgb(240,210,60)";
        if (nrConflicts==2) return "rgb(240,120,60)";
        return "rgb(220,50,40)";
    }

	public static String hardConflicts2pref(AssignmentPreferenceInfo assignmentInfo) {
		if (assignmentInfo==null) return PreferenceLevel.sNeutral;
		String pref = PreferenceLevel.sNeutral;
		if (assignmentInfo.getNrRoomLocations()==1 && assignmentInfo.getNrTimeLocations()==1) pref = PreferenceLevel.sRequired;
		else if (assignmentInfo.getNrSameTimePlacementsNoConf()>0) pref=PreferenceLevel.sStronglyPreferred;
		else if (assignmentInfo.getNrTimeLocations()>1 && assignmentInfo.getNrSameRoomPlacementsNoConf()>0) pref=PreferenceLevel.sProhibited;
		else if (assignmentInfo.getNrTimeLocations()>1) pref=PreferenceLevel.sNeutral;
		else if (assignmentInfo.getNrSameRoomPlacementsNoConf()>0) pref=PreferenceLevel.sDiscouraged;
		else if (assignmentInfo.getNrRoomLocations()>1) pref=PreferenceLevel.sStronglyDiscouraged;
		else pref=PreferenceLevel.sRequired;
		return pref;
	}

	private static int gradient(int min, int v1, int max, int v2, int value) {
    	return (value <= min ? v1 : value >= max ? v2 : v1 + (v2 - v1) * (value - min) / (max - min));
    }

    public static String percentage2color(int p) {
    	int[] points = new int[] {   0,  20,  40,  60,  80, 100 };
    	int[] r = new int[] {      220, 240, 240, 240,  70,  30 };
    	int[] g = new int[] {       50, 120, 210, 240, 230, 160 };
    	int[] b = new int[] {       40,  60,  60, 240,  30,  60 };
    	for (int i = 1; i < points.length; i++) {
    		if (p <= points[i])
    			return
    				"rgb(" + gradient(points[i-1], r[i-1], points[i], r[i], p) + "," +
    				gradient(points[i-1], g[i-1], points[i], g[i], p) + "," +
    				gradient(points[i-1], b[i-1], points[i], b[i], p) + ")";
    	}
    	return "rgb(" + r[points.length - 1] + "," + g[points.length - 1] + "," + b[points.length - 1] + ")";
    }

    public static String pattern2string(BitSet pattern) {
    	StringBuffer ret = new StringBuffer();
    	for (int i = 0; i < pattern.length(); i++)
    		ret.append(pattern.get(i) ? '1' : '0');
    	return ret.toString();
    }

    public static class Combine<T> implements Iterable<T> {
    	private Iterable<T>[] iItems;

    	public Combine(Iterable<T>... items) {
    		iItems = items;
    	}

		@Override
		public Iterator<T> iterator() {
			return new CombinedIterator<T>(iItems);
		}
    }

    public static class CombinedIterator<T> implements Iterator<T> {
    	private Iterable<T>[] iItems;
    	private Iterator<T> iIterator;
    	private int iIdx;

    	public CombinedIterator(Iterable<T>... items) {
    		iItems = items;
    		iIdx = -1;
    		iIterator = null;
    	}

		@Override
		public boolean hasNext() {
			if (iIterator != null && iIterator.hasNext()) return true;
			while (true) {
				iIdx++;
				if (iIdx >= iItems.length) return false;
				iIterator = iItems[iIdx].iterator();
				if (iIterator.hasNext()) return true;
			}
		}

		@Override
		public T next() {
			return iIterator.next();
		}

		@Override
		public void remove() {
			iIterator.remove();
		}
    }

	private static void setCell(TimetableGridCell[][][] data, int day, int slot, int idx, TimetableGridCell cell) {
		if (data[day][slot]==null) {
			data[day][slot] = new TimetableGridCell[idx+1];
			for (int i = 0; i < idx; i++)
				data[day][slot][i] = null;
			data[day][slot][idx] = cell;
		} else if (data[day][slot].length <= idx) {
			TimetableGridCell[] old = data[day][slot];
			data[day][slot] = new TimetableGridCell[idx+1];
			for (int i = 0; i < idx; i++)
				data[day][slot][i] = (i < old.length ? old[i] : null);
			data[day][slot][idx] = cell;
		} else {
			data[day][slot][idx] = cell;
		}
	}

	private static TimetableGridCell getCell(TimetableGridCell[][][] data, int day, int slot, int idx) {
		if (data[day][slot] == null) return null;
		if (data[day][slot].length <= idx) return null;
		return data[day][slot][idx];
	}

	private static int getIndex(TimetableGridCell[][][] data, int day, int slot, int length) {
		idx: for (int idx = 0;; idx++) {
			for (int i = 0; i < length; i++)
				if (getCell(data, day, slot + i, idx) != null) continue idx;
			return idx;
		}
	}

	private static void addCell(TimetableGridCell[][][] data, int day, int slot, int length, TimetableGridCell cell) {
		int idx = getIndex(data, day, slot, length);
		for (int i = 0; i < length; i++)
			setCell(data, day, slot + i, idx, cell);
	}

	private static int nrEmptyAbove(TimetableGridCell[][][] data, int day, int slot, int index, int length, TimetableGridCell cell) {
		for (int idx = index + 1; idx < length; idx++) {
			for (int i = 0; i < cell.getLength(); i++)
				if (getCell(data, day, slot + i, idx) != null) return idx - index - 1;
		}
		return length - index - 1;
	}

	private static int nrCells(TimetableGridCell[][][] data, int day, int slot) {
		if (data[day][slot] == null) return 0;
		int ret = 0;
		for (int i = 0; i < data[day][slot].length; i++)
			if (data[day][slot][i] != null)
				ret++;
		return ret;
	}

	private static boolean isUselessFirst(TimetableGridCell[][][] data, int d, int s) {
    	if (s - 1 < 0 || s + 6 >= 288) return false;
    	return (nrCells(data, d, s - 1) != 0 &&
           		nrCells(data, d, s + 0) == 0 &&
           		nrCells(data, d, s + 1) == 0 &&
           		nrCells(data, d, s + 2) == 0 &&
           		nrCells(data, d, s + 3) == 0 &&
           		nrCells(data, d, s + 4) == 0 &&
           		nrCells(data, d, s + 5) == 0 &&
           		nrCells(data, d, s + 6) != 0);
	}

	private static boolean isUseless(TimetableGridCell[][][] data, int d, int s) {
		return isUselessFirst(data, d, s) ||
			isUselessFirst(data, d, s - 1) ||
			isUselessFirst(data, d, s - 2) ||
			isUselessFirst(data, d, s - 3) ||
			isUselessFirst(data, d, s - 4) ||
			isUselessFirst(data, d, s - 5);
	}

	public static void initBgModeUselessSlots(TimetableGridModel model, TimetableGridCell[][][] data) {
        for (int d = 0; d < data.length; d++) {
        	int start = 0; Integer lastPref = null;
            for (int s = 0; s < 288; s++) {
            	Integer pref = null;
            	if (model.isAvailable(d, s)) {
            		pref = 0;
                    if (nrCells(data, d, s)==0) {
                    	if (isUseless(data, d, s)) pref=4;
                    	switch (d) {
                    		case 0 :
                    			if (nrCells(data, 2, s)!=0 && nrCells(data, 4, s)!=0) pref++;
                    			break;
                    		case 1 :
                    			if (nrCells(data, 3, s)!=0) pref++;
                    			break;
                    		case 2 :
                    			if (nrCells(data, 0, s)!=0 && nrCells(data, 4, s)!=0) pref++;
                    			break;
                    		case 3 :
                    			if (nrCells(data, 1, s)!=0) pref++;
                    			break;
                    		case 4 :
                    			if (nrCells(data, 0, s)!=0 && nrCells(data, 2, s)!=0) pref++;
                    			break;
                    	}
                    }
            	}
            	if (lastPref != null && !lastPref.equals(pref)) {
            		TimetableGridBackground bg = new TimetableGridBackground();
            		bg.setDay(d);
            		bg.setSlot(start);
            		bg.setLength(s - start);
            		bg.setAvailable(true);
            		bg.setBackground(pref2color(PreferenceLevel.sNeutral));
                    if (lastPref > 4)
                    	bg.setBackground(pref2color(PreferenceLevel.sProhibited));
                    else if (lastPref == 4)
                    	bg.setBackground(pref2color(PreferenceLevel.sStronglyDiscouraged));
                    else if (lastPref > 0)
                    	bg.setBackground(pref2color(PreferenceLevel.sDiscouraged));
                    model.addBackground(bg);
            		lastPref = pref; start = s;
            	} else if (lastPref == null && pref != null) {
            		lastPref = pref; start = s;
            	}
            }
            if (lastPref != null) {
            	TimetableGridBackground bg = new TimetableGridBackground();
        		bg.setDay(d);
        		bg.setSlot(start);
        		bg.setLength(288 - start);
        		bg.setAvailable(true);
        		bg.setBackground(pref2color(PreferenceLevel.sNeutral));
                if (lastPref > 4)
                	bg.setBackground(pref2color(PreferenceLevel.sProhibited));
                else if (lastPref == 4)
                	bg.setBackground(pref2color(PreferenceLevel.sStronglyDiscouraged));
                else if (lastPref > 0)
                	bg.setBackground(pref2color(PreferenceLevel.sDiscouraged));
                model.addBackground(bg);
            }
        }
	}

	public static void computeIndexes(TimetableGridModel model, TimetableGridContext context) {
		Collections.sort(model.getCells());

		if (context.getDisplayMode() == DisplayMode.WeekByWeekHorizontal.ordinal()) {
			TimetableGridCell[][][] weekData = new TimetableGridCell[365][288][];
			for (int d = 0; d < 365; d++)
				for (int s = 0; s < 288; s++)
					weekData[d][s] = null;
			for (TimetableGridCell cell: model.getCells()) {
				for (int d = 0; d < 365; d++) {
					int date = d + model.getFirstSessionDay();
					int day = d % 7;
					if (day == cell.getDay() && cell.hasDate(date))
						addCell(weekData, date, cell.getSlot(), cell.getLength(), cell);
				}
			}
			for (int d = 0; d < 365; d++) {
				int length = 0;
				for (int s = 0; s < 288; s++)
					if (weekData[d][s] != null && weekData[d][s].length > length) length = weekData[d][s].length;
				int[] maxLines = new int[length];
				int index = 0;
				for (int idx = 0; idx < length; idx++) {
					maxLines[idx] = 0;
					for (int s = 0; s < 288; s++) {
						TimetableGridCell c = getCell(weekData, d, s, idx);
						if (c != null && maxLines[idx] < c.getMinLines(context.isShowRoom(), context.isShowInstructor(), context.isShowTime(), context.isShowPreference(), context.isShowDate()))
							maxLines[idx] = c.getMinLines(context.isShowRoom(), context.isShowInstructor(), context.isShowTime(), context.isShowPreference(), context.isShowDate());
					}
					for (int s = 0; s < 288; s++) {
						TimetableGridCell c = getCell(weekData, d, s, idx);
						if (c != null) {
							c.setNrLines(maxLines[idx]); c.setIndex(index);
						}
					}
					index += maxLines[idx];
				}
				if (context.getResourceType() <= 1)
					for (int idx = 0; idx < length; idx++) {
						for (int s = 0; s < 288; s++) {
							TimetableGridCell c = getCell(weekData, d, s, idx);
							if (c != null && c.getSlot() == s) {
								int empty = nrEmptyAbove(weekData, d, s, idx, length, c);
								if (empty > 0) {
									int lines = maxLines[idx];
									for (int i = 1; i <= empty; i++)
										lines += maxLines[idx + i];
									c.setNrLines(lines);
								}
							}
						}
					}
			}
			if (context.isShowFreeTimes()) {
				TimetableGridCell[][][] data = new TimetableGridCell[7][288][];
				for (int d = 0; d < 7; d++)
					for (int s = 0; s < 288; s++)
						data[d][s] = null;
				for (TimetableGridCell cell: model.getCells())
					addCell(data, cell.getDay(), cell.getSlot(), cell.getLength(), cell);
				initBgModeUselessSlots(model, data);
			}
		} else {
			TimetableGridCell[][][] data = new TimetableGridCell[7][288][];
			for (int d = 0; d < 7; d++)
				for (int s = 0; s < 288; s++)
					data[d][s] = null;
			for (TimetableGridCell cell: model.getCells()) {
				addCell(data, cell.getDay(), cell.getSlot(), cell.getLength(), cell);
			}
			if (context.isVertical()) {
				for (int d = 0; d < 7; d++) {
					int length = 0;
					for (int s = 0; s < 288; s++)
						if (data[d][s] != null && data[d][s].length > length) length = data[d][s].length;
					for (int idx = 0; idx < length; idx++) {
						for (int s = 0; s < 288; s++) {
							TimetableGridCell c = getCell(data, d, s, idx);
							if (c != null) {
								c.setIndex(idx); c.setNrLines(1);
							}
						}
					}
					if (context.getResourceType() <= 1)
						for (int idx = 0; idx < length; idx++) {
							for (int s = 0; s < 288; s++) {
								TimetableGridCell c = getCell(data, d, s, idx);
								if (c != null && c.getSlot() == s) {
									int empty = nrEmptyAbove(data, d, s, idx, length, c);
									if (empty > 0)
										c.setNrLines(1 + empty);
								}
							}
						}
				}
			} else {
				for (int d = 0; d < 7; d++) {
					int length = 0;
					for (int s = 0; s < 288; s++)
						if (data[d][s] != null && data[d][s].length > length) length = data[d][s].length;
					int[] maxLines = new int[length];
					int index = 0;
					for (int idx = 0; idx < length; idx++) {
						maxLines[idx] = 0;
						for (int s = 0; s < 288; s++) {
							TimetableGridCell c = getCell(data, d, s, idx);
							if (c != null && maxLines[idx] < c.getMinLines(context.isShowRoom(), context.isShowInstructor(), context.isShowTime(), context.isShowPreference(), context.isShowDate()))
								maxLines[idx] = c.getMinLines(context.isShowRoom(), context.isShowInstructor(), context.isShowTime(), context.isShowPreference(), context.isShowDate());
						}
						for (int s = 0; s < 288; s++) {
							TimetableGridCell c = getCell(data, d, s, idx);
							if (c != null) {
								c.setNrLines(maxLines[idx]); c.setIndex(index);
							}
						}
						index += maxLines[idx];
					}
					if (context.getResourceType() <= 1)
						for (int idx = 0; idx < length; idx++) {
							for (int s = 0; s < 288; s++) {
								TimetableGridCell c = getCell(data, d, s, idx);
								if (c != null && c.getSlot() == s) {
									int empty = nrEmptyAbove(data, d, s, idx, length, c);
									if (empty > 0) {
										int lines = maxLines[idx];
										for (int i = 1; i <= empty; i++)
											lines += maxLines[idx + i];
										c.setNrLines(lines);
									}
								}
							}
						}
				}
			}
			if (context.isShowFreeTimes())
				initBgModeUselessSlots(model, data);
		}

		if (context.getBgMode() == BgMode.None.ordinal())
			for (TimetableGridCell cell: model.getCells())
				if (!sBgColorNotAvailable.equals(cell.getBackground()))
					for (int s = 0; s < cell.getLength(); s++) {
						if (!model.isAvailable(cell.getDay(), cell.getSlot() + s)) {
							cell.setBackground(sBgColorNotAvailableButAssigned);
							break;
						}
					}
	}
}


text:
<?php
namespace Scalr\Service;

use Scalr\Service\Aws\Plugin\EventObserver;
use Scalr\Service\Aws\EntityManager;
use Scalr\DependencyInjection\Container;
use Scalr\Service\Aws\ServiceInterface;
use Scalr\Service\Aws\Client\ClientException;
use Scalr\Service\Aws\Ec2\DataType\RegionInfoList;

/**
 * Amazon Web Services software development kit
 *
 * @author   Vitaliy Demidov  <vitaliy@scalr.com>
 * @since    18.09.2012
 *
 * @property-read  \Scalr\Service\Aws\Elb        $elb        Amazon Elastic Load Balancer (ELB) service interface instance
 * @property-read  \Scalr\Service\Aws\CloudWatch $cloudWatch Amazon CloudWatch service interface instance
 * @property-read  \Scalr\Service\Aws\Sqs        $sqs        Amazon Simple Queue Service (SQS) interface instance
 * @property-read  \Scalr\Service\Aws\S3         $s3         Amazon Simple Storage Service (S3) interface instance
 * @property-read  \Scalr\Service\Aws\Iam        $iam        Amazon Identity and Access Management Service (IAM) interface instance
 * @property-read  \Scalr\Service\Aws\Ec2        $ec2        Amazon Elastic Compute Cloud (EC2) service interface instance
 * @property-read  \Scalr\Service\Aws\CloudFront $cloudFront Amazon CloudFront service interface instance
 * @property-read  \Scalr\Service\Aws\Rds        $rds        Amazon Relational Database Service (RDS) interface instance
 * @property-read  \Scalr\Service\Aws\Route53    $route53    Amazon Route53 service interface instance
 * @property-read  \Scalr\Service\Aws\Kms        $kms        Amazon KMS interface instance
 */
class Aws
{

    const CLIENT_QUERY = 'Query';

    const CLIENT_SOAP  = 'Soap';

    /**
     * United States East (Northern Virginia) Region.
     */
    const REGION_US_EAST_1 = 'us-east-1';

    /**
     * United States West (Northern California) Region.
     */
    const REGION_US_WEST_1 = 'us-west-1';

    /**
     * United States West (Oregon) Region.
     */
    const REGION_US_WEST_2 = 'us-west-2';

    /**
     * Europe West (Ireland) Region.
     */
    const REGION_EU_WEST_1 = 'eu-west-1';

    /**
     * Europe Central (Frankfurt) Region.
     */
    const REGION_EU_CENTRAL_1 = 'eu-central-1';

    /**
     * Asia Pacific Southeast (Singapore) Region.
     */
    const REGION_AP_SOUTHEAST_1 = 'ap-southeast-1';

    /**
     * Sydney
     */
    const REGION_AP_SOUTHEAST_2 = 'ap-southeast-2';

    /**
     * Asia Pacific Northeast (Tokyo) Region.
     */
    const REGION_AP_NORTHEAST_1 = 'ap-northeast-1';

    /**
     * South America (Sao Paulo) Region.
     */
    const REGION_SA_EAST_1 = 'sa-east-1';

    /**
     * China North 1 (China)
     */
    const REGION_CN_NORTH_1 = 'cn-north-1';

    /**
     * GovCloud (US)
     */
    const REGION_US_GOV_WEST_1 = 'us-gov-west-1';

    /**
     * United States East (Northern Virginia) Region Hosted Zone Id.
     */
    const ZONE_ID_US_EAST_1 = 'Z3AQBSTGFYJSTF';

    /**
     * United States West (Northern California) Region Hosted Zone Id.
     */
    const ZONE_ID_US_WEST_1 = 'Z2F56UZL2M1ACD';

    /**
     * United States West (Oregon) Region Hosted Zone Id.
     */
    const ZONE_ID_US_WEST_2 = 'Z3BJ6K6RIION7M';

    /**
     * Europe West (Ireland) Region Hosted Zone Id.
     */
    const ZONE_ID_EU_WEST_1 = 'Z1BKCTXD74EZPE';

    /**
     * Europe Central (Frankfurt) Region Hosted Zone Id.
     */
    const ZONE_ID_EU_CENTRAL_1 = 'Z21DNDUVLTQW6Q';

    /**
     * Asia Pacific Southeast (Singapore) Region Hosted Zone Id.
     */
    const ZONE_ID_AP_SOUTHEAST_1 = 'Z3O0J2DXBE1FTB';

    /**
     * Sydney Hosted Zone Id
     */
    const ZONE_ID_AP_SOUTHEAST_2 = 'Z1WCIGYICN2BYD';

    /**
     * Asia Pacific Northeast (Tokyo) Region Hosted Zone Id.
     */
    const ZONE_ID_AP_NORTHEAST_1 = 'Z2M4EHUR26P7ZW';

    /**
     * South America (Sao Paulo) Region Hosted Zone Id.
     */
    const ZONE_ID_SA_EAST_1 = 'Z7KQH4QJS55SO';

    /**
     * GovCloud (US) Hosted Zone Id
     */
    const ZONE_ID_US_GOV_WEST_1 = 'Z31GFT0UA1I2HV';

    /**
     * Elastic Load Balancer Web service interface
     */
    const SERVICE_INTERFACE_ELB = 'elb';

    /**
     * Amazon CloudWatch Web service interface
     */
    const SERVICE_INTERFACE_CLOUD_WATCH = 'cloudWatch';

    /**
     * Amazon Simple Queue Service interface
     */
    const SERVICE_INTERFACE_SQS = 'sqs';

    /**
     * Amazon Simple Storage Service interface
     */
    const SERVICE_INTERFACE_S3 = 's3';

    /**
     * Amazon Identity and Access Management Service interface
     */
    const SERVICE_INTERFACE_IAM = 'iam';

    /**
     * Amazon Elastic Compute Cloud service interface
     */
    const SERVICE_INTERFACE_EC2 = 'ec2';

    /**
     * Amazon CloudFront service interface
     */
    const SERVICE_INTERFACE_CLOUD_FRONT = 'cloudFront';

    /**
     * Amazon Route53 service interface
     */
    const SERVICE_INTERFACE_ROUTE53 = 'route53';

    /**
     * Amazon RDS service interface
     */
    const SERVICE_INTERFACE_RDS = 'rds';

    /**
     * Amazon Key Management Service interface
     */
    const SERVICE_INTERFACE_KMS = 'kms';

    /**
     * Access Key Id
     * @var string
     */
    private $accessKeyId;

    /**
     * Secret Access Key
     * @var string
     */
    private $secretAccessKey;

    /**
     * X.509 certificate
     * @var string
     */
    private $certificate;

    /**
     * Private key for certificate
     * @var string
     */
    private $privateKey;

    /**
     * AWS Entity Manager
     * @var EntityManager
     */
    private $entityManager;

    /**
     * Whether debug is enabled or not.
     *
     * @var bool
     */
    private $debug = false;

    /**
     * Region for AWS
     *
     * @var string
     */
    private $region;

    /**
     * @var Container
     */
    protected $container;

    /**
     * Reflection class of Aws
     *
     * @var \ReflectionClass
     */
    private static $reflection;

    /**
     * Array of the instances of the service interfaces
     *
     * @var array
     */
    private $serviceInterfaces = array();

    /**
     * The quantity of the processed queries to the AWS API
     *
     * @var int
     */
    public $queriesQuantity = 0;

    /**
     * AWS Client event observer
     *
     * @var EventObserver
     */
    private $eventObserver;

    /**
     * An environment object
     *
     * @var \Scalr_Environment
     */
    private $environment;

    /**
     * The number of AWS Account
     *
     * @var string
     */
    private $awsAccountNumber;

    /**
     * Proxy Host
     *
     * @var string
     */
    private $proxyHost;

    /**
     * Proxy Port
     *
     * @var int
     */
    private $proxyPort;

    /**
     * The username that is used for proxy
     *
     * @var string
     */
    private $proxyUser;

    /**
     * Proxy password
     *
     * @var string
     */
    private $proxyPass;

    /**
     * The type of the proxy
     *
     * @var int
     */
    private $proxyType;

    /**
     * Constructor
     *
     * @param   string     $accessKeyId      AWS access key id
     * @param   string     $secretAccessKey  AWS secret access key
     * @param   string     $region           optional An AWS region. (Aws::REGION_US_EAST_1)
     * @param   string     $certificate      optional AWS x.509 certificate (It's used only for Soap API)
     * @param   string     $privateKey       optional Private Key (It's used only for Soap API)
     */
    public function __construct($accessKeyId, $secretAccessKey, $region = null, $certificate = null, $privateKey = null)
    {
        $this->container = \Scalr::getContainer();
        $this->region = $region;
        $this->accessKeyId = $accessKeyId;
        $this->secretAccessKey = $secretAccessKey;
        $this->entityManager = new EntityManager();
        $this->certificate = $certificate;
        $this->privateKey = $privateKey;
    }

    /**
     * Set proxy configuration to connect to AWS services
     * @param string $host
     * @param integer $port
     * @param string $user
     * @param string $pass
     * @param string $type Allowed values 4 - SOCKS4, 5 - SOCKS5, 0 - HTTP
     */
    public function setProxy($host, $port = 3128, $user = null, $pass = null, $type = 0)
    {
        $this->proxyHost = $host;
        $this->proxyPort = $port;
        $this->proxyUser = $user;
        $this->proxyPass = $pass;
        $this->proxyType = $type;
    }

    public function getProxy()
    {
        return ($this->proxyHost) ? array(
            'host' => $this->proxyHost,
            'port' => $this->proxyPort,
            'user' => $this->proxyUser,
            'pass' => $this->proxyPass,
            'type' => $this->proxyType
        ) : false;
    }

    /**
     * Gets container
     *
     * @return Container
     */
    public function getContainer()
    {
        return $this->container;
    }

    /**
     * Retrieves AWS Account Number
     *
     * @return  string  Returns AWS Account number for current user
     * @throws  ClientException
     */
    public function getAccountNumber()
    {
        if ($this->awsAccountNumber === null) {
            try {
                $arr = preg_split('/\:/', $this->iam->user->fetch()->arn);
                $this->awsAccountNumber = $arr[4];
            } catch (ClientException $e) {
                if (preg_match('/arn\:aws[\w-]*\:iam\:\:(\d+)\:user/', $e->getMessage(), $matches)) {
                    $this->awsAccountNumber = $matches[1];
                } else {
                    throw $e;
                }
            }
        }
        return $this->awsAccountNumber;
    }

    /**
     * Retrieves AWS username
     *
     * @return  string  Returns AWS username
     * @throws  ClientException
     */
    public function getUsername()
    {
        try {
            return $this->iam->user->fetch()->userName;
        } catch (ClientException $e) {}
    }

    /**
     * Retrieves AWS user arn
     *
     * @return  string  Returns AWS user arn
     * @throws  ClientException
     */
    public function getUserArn()
    {
        try {
             return $this->iam->user->fetch()->arn;
        } catch (ClientException $e) {
            if (preg_match('/arn\:aws[\w-]*\:iam\:\:(\d+)\:user/', $e->getMessage(), $matches)) {
                return $matches[0];
            } else {
                throw $e;
            }
        }
    }

    /**
     * Gets region
     *
     * @return    string   Returns region that has been provided for instance
     */
    public function getRegion()
    {
        return $this->region;
    }

    /**
     * Gets implemented web service interfaces
     *
     * @return     array Returns Returns the list of available (implemented) web service interfaces
     */
    public function getAvailableServiceInterfaces()
    {
        return [
            self::SERVICE_INTERFACE_ELB,
            self::SERVICE_INTERFACE_CLOUD_WATCH,
            self::SERVICE_INTERFACE_CLOUD_FRONT,
            self::SERVICE_INTERFACE_SQS,
            self::SERVICE_INTERFACE_S3,
            self::SERVICE_INTERFACE_IAM,
            self::SERVICE_INTERFACE_EC2,
            self::SERVICE_INTERFACE_RDS,
            self::SERVICE_INTERFACE_ROUTE53,
            self::SERVICE_INTERFACE_KMS,
        ];
    }

    /**
     * Gets available regions
     *
     * @param     bool    $ignoreCache  optional If true it will ignore cache
     * @return    array   Returns list of available regions
     */
    public function getAvailableRegions($ignoreCache = false)
    {
        return self::getCloudLocations();
    }

    /**
     * Gets defined AWS cloud locations
     *
     * @return   array
     */
    public static function getCloudLocations()
    {
        return [
            self::REGION_AP_NORTHEAST_1,
            self::REGION_AP_SOUTHEAST_1,
            self::REGION_AP_SOUTHEAST_2,
            self::REGION_EU_WEST_1,
            self::REGION_EU_CENTRAL_1,
            self::REGION_SA_EAST_1,
            self::REGION_US_EAST_1,
            self::REGION_US_WEST_1,
            self::REGION_US_WEST_2,
            self::REGION_US_GOV_WEST_1,
            self::REGION_CN_NORTH_1,
        ];
    }

    /**
     * Gets defined AWS cloud locations hosted zone ids
     *
     * @return   array
     */
    public static function getCloudLocationsZoneIds()
    {
        return [
            self::REGION_AP_NORTHEAST_1 => self::ZONE_ID_AP_NORTHEAST_1,
            self::REGION_AP_SOUTHEAST_1 => self::ZONE_ID_AP_SOUTHEAST_1,
            self::REGION_AP_SOUTHEAST_2 => self::ZONE_ID_AP_SOUTHEAST_2,
            self::REGION_EU_WEST_1      => self::ZONE_ID_EU_WEST_1,
            self::REGION_EU_CENTRAL_1   => self::ZONE_ID_EU_CENTRAL_1,
            self::REGION_SA_EAST_1      => self::ZONE_ID_SA_EAST_1,
            self::REGION_US_EAST_1      => self::ZONE_ID_US_EAST_1,
            self::REGION_US_WEST_1      => self::ZONE_ID_US_WEST_1,
            self::REGION_US_WEST_2      => self::ZONE_ID_US_WEST_2,
            self::REGION_US_GOV_WEST_1  => self::ZONE_ID_US_GOV_WEST_1,
            //TODO add zone id for China region
        ];
    }

    /**
     * Checks whether provided region is valid.
     *
     * @param    string    $region   AWS region  (Aws::REGION_US_EAST_1)
     * @return   boolean   Returns boolean true if region is valid or false otherwise.
     */
    public function isValidRegion($region)
    {
        if (!in_array($region, $this->getAvailableRegions())) {
            $ret = false;
        } else {
            $ret = true;
        }
        return $ret;
    }

    /**
     * DescribeRegions action
     *
     * @return  RegionInfoList  Returns the list of the RegionInfoData objects on success
     * @throws  ClientException
     * @throws  Ec2Exception
     */
    public function describeRegions()
    {
        return $this->ec2->describeRegions();
    }

    /**
     * Gets reflection class of Aws
     *
     * @return \ReflectionClass  Returns reflection class of Aws
     */
    static public function getReflectionClass()
    {
        if (!isset(self::$reflection)) {
            self::$reflection = new \ReflectionClass(__CLASS__);
        }
        return self::$reflection;
    }

    /**
     * Magic getter
     *
     * @param     string      $name
     * @return    mixed|null
     */
    public function __get($name)
    {
        //Retrieves service provider object
        if (in_array(($n = lcfirst($name)), $this->getAvailableServiceInterfaces())) {
            if (!isset($this->serviceInterfaces[$n])) {
                //It validates region only for the services which it is necessary for.
                if (!in_array($n, array(self::SERVICE_INTERFACE_IAM, self::SERVICE_INTERFACE_S3, self::SERVICE_INTERFACE_CLOUD_FRONT))) {
                    if (!$this->isValidRegion($this->region)) {
                        throw new AwsException(sprintf('Invalid region "%s" for the service "%s"', $this->region, $n));
                    }
                }
                try {
                    $class = __CLASS__ . '\\' . ucfirst($n);
                    /* @var $service ServiceInterface */
                    $service = new $class($this);
                    $this->serviceInterfaces[$n] = $service;
                } catch (\Exception $e) {
                    throw new AwsException('Cannot create service interface instance of ' . $class . ' ' . $e->getMessage());
                }
            } else {
                $service = $this->serviceInterfaces[$n];
            }
            return $service;
        }
        return null;
    }

    /**
     * Gets Access Key Id
     *
     * @return string Returns Access Key Id
     */
    public function getAccessKeyId()
    {
        return $this->accessKeyId;
    }

    /**
     * Gets Secret Access Key
     *
     * @return string Returns Secret Access Key
     */
    public function getSecretAccessKey()
    {
        return $this->secretAccessKey;
    }

    /**
     * Calculates an MD5.Base64digest for the given string.
     *
     * @param   string     $string A string which should digest be calculated for.
     * @return  string     Returns MD5 Base64 digest
     */
    public static function getMd5Base64Digest ($string)
    {
        return base64_encode(pack('H*', md5($string)));
    }

    /**
     * Calculates an MD5.Base64digest for the given file.
     *
     * @param   string     $file   A file path which should digest be calculated for.
     * @return  string     Returns MD5 Base64 digest
     */
    public static function getMd5Base64DigestFile ($file)
    {
        return base64_encode(pack('H*', md5_file($file)));
    }

    /**
     * Gets an AWS Entity Manager
     *
     * This manager helps manipulate with retrieved from AWS objects.
     * These object are stored in the cache.
     *
     * @return  EntityManager Returns an AWS Entity Manager object.
     */
    public function getEntityManager()
    {
        return $this->entityManager;
    }

    /**
     * Get x.509 certificate
     *
     * @return  string Returns x.509 certificate
     */
    public function getCertificate()
    {
        return $this->certificate;
    }

    /**
     * Get private key
     *
     * @return  string Returns private key from certificate
     */
    public function getPrivateKey()
    {
        return $this->privateKey;
    }

    /**
     * Validates certificate and privatekey making AWS SOAP request
     *
     * @return  bool      Returns true on success or throws an exception
     * @throws  \Exception
     */
    public function validateCertificateAndPrivateKey()
    {
        $prevClient = $this->ec2->getApiClientType();
        $this->ec2->setApiClientType(self::CLIENT_SOAP);

        try {
            $exc = null;
            $this->ec2->availabilityZone->describe();
        } catch (\Exception $e) {
            $exc = $e;
        }

        $this->ec2->setApiClientType($prevClient);

        if (isset($exc)) throw $exc;

        return true;
    }

    /**
     * Sets debug flag
     *
     * @param   bool     $debug optional If true it will enable debug mode
     * @return  Aws
     */
    public function setDebug($debug = true)
    {
        $this->debug = (bool) $debug;
        return $this;
    }

    /**
     * Gets debug flag value
     *
     * @return  bool Returns true if debug is enabled.
     */
    public function getDebug()
    {
        return $this->debug;
    }

    /**
     * Resets debug
     *
     * @return  Aws
     */
    public function resetDebug()
    {
        $this->debug = false;
        return $this;
    }

    /**
     * Gets an AWS client event observer
     *
     * @return  \Scalr\Service\Aws\Plugin\EventObserver Returns AWS client event observer
     */
    public function getEventObserver()
    {
        return $this->eventObserver;
    }

    /**
     * Sets an AWS client event observer object associated with this instance
     *
     * @param   \Scalr\Service\Aws\Plugin\EventObserver $eventObserver The event observer
     * @return  Aws
     */
    public function setEventObserver(EventObserver $eventObserver = null)
    {
        $this->eventObserver = $eventObserver;
        return $this;
    }

    /**
     * Sets an Scalr environment object which is associated with the AWS client instance
     *
     * @param   \Scalr_Environment $environment An environment object
     * @return  Aws
     */
    public function setEnvironment(\Scalr_Environment $environment = null)
    {
        $this->environment = $environment;
        return $this;
    }

    /**
     * Gets an Scalr Environment object which is associated with the AWS client instance
     *
     * @return  \Scalr_Environment  Returns Scalr Environment object
     */
    public function getEnvironment()
    {
        return $this->environment;
    }

    /**
     * Gets presigned url signed with aws4 version signing algorithm
     *
     * @param string $service       Service name (ec2, s3)
     * @param string $action        Action name (CopySnapshot)
     * @param string $destRegion    Destination region
     * @param string $objectId      Id of the snapshot, image , etc
     */
    public function getPresignedUrl($service, $action, $destRegion, $objectId)
    {
        $canonicalizedQueryString = '';
        $time = time();
        $options = [
            'X-Amz-Algorithm'       => 'AWS4-HMAC-SHA256',
            'X-Amz-Credential'      => $this->getAccessKeyId() . '/' . gmdate('Ymd', $time) . '/' . $this->getRegion() . '/' . $service . '/aws4_request',
            'X-Amz-Date'            => gmdate('Ymd\THis\Z', $time),
            'X-Amz-Expires'         => '86400',
            'X-Amz-SignedHeaders'   => 'host',
            'SourceRegion'          => $this->getRegion(),
            'Action'                => $action,
            'SourceSnapshotId'      => $objectId,
            'DestinationRegion'     => $destRegion,
        ];

        ksort($options);

        foreach ($options as $k => $v) {
            $canonicalizedQueryString .= '&' . rawurlencode($k) . '=' . rawurlencode($v);
        }

        if ($canonicalizedQueryString !== '') {
            $canonicalizedQueryString = substr($canonicalizedQueryString, 1);
        }

        $canonicalRequest =
            'GET' . "\n"
          . "/\n"
          . $canonicalizedQueryString . "\n"
          . "host:" . $this->{$service}->getUrl() . "\n"
          . "\n"
          . "host" . "\n"
          . hash('sha256', '')
        ;

        $stringToSign = "AWS4-HMAC-SHA256" . "\n"
                      . gmdate('Ymd\THis\Z', $time) . "\n"
                      . gmdate('Ymd', $time) . "/" .  $this->getRegion() . "/" . $service . "/aws4_request" . "\n"
                      . hash('sha256', $canonicalRequest);

        $dateKey = hash_hmac('sha256', gmdate('Ymd', $time), "AWS4" . $this->getSecretAccessKey(), true);
        $dateRegionKey = hash_hmac('sha256', $this->getRegion(), $dateKey, true);
        $dateRegionServiceKey = hash_hmac('sha256', $service, $dateRegionKey, true);
        $signingKey = hash_hmac('sha256', 'aws4_request', $dateRegionServiceKey, true);
        $signature = hash_hmac('sha256', $stringToSign, $signingKey);

        $presignedUrl = "https://" . $this->{$service}->getUrl() . "/?" . $canonicalizedQueryString
                      . "&X-Amz-Signature=" . rawurlencode($signature);

        return $presignedUrl;
    }

}