text:
package net.oauth.example.provider.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;

import net.oauth.OAuthAccessor;
import net.oauth.OAuthConsumer;
import net.oauth.OAuthException;
import net.oauth.OAuthMessage;
import net.oauth.OAuthProblemException;
import net.oauth.OAuthValidator;
import net.oauth.SimpleOAuthValidator;
import net.oauth.server.OAuthServlet;

/**
 * Utility methods for providers that store consumers, tokens and secrets in
 * local cache (HashSet). Consumer key is used as the name, and its credentials are
 * stored in HashSet.
 *
 * @author Praveen Alavilli
 */
public class SampleOAuthProvider {

    public static final OAuthValidator VALIDATOR = new SimpleOAuthValidator();

    private static final Map<String, OAuthConsumer> ALL_CONSUMERS
                    = Collections.synchronizedMap(new HashMap<String,OAuthConsumer>(10));

    private static final Collection<OAuthAccessor> ALL_TOKENS = new HashSet<OAuthAccessor>();

    private static Properties consumerProperties = null;

    public static synchronized void loadConsumers(
            ServletConfig config) throws IOException {
        Properties p = consumerProperties;
        if (p == null) {
            p = new Properties();
            String resourceName = "/"
                    + SampleOAuthProvider.class.getPackage().getName().replace(
                    ".", "/") + "/provider.properties";
            URL resource = SampleOAuthProvider.class.getClassLoader()
            .getResource(resourceName);
            if (resource == null) {
                throw new IOException("resource not found: " + resourceName);
            }
            InputStream stream = resource.openStream();
            try {
                p.load(stream);
            } finally {
                stream.close();
            }
        }
        consumerProperties = p;

        // for each entry in the properties file create a OAuthConsumer
        for(Map.Entry prop : p.entrySet()) {
            String consumer_key = (String) prop.getKey();
            // make sure it's key not additional properties
            if(!consumer_key.contains(".")){
                String consumer_secret = (String) prop.getValue();
                if(consumer_secret != null){
                    String consumer_description = (String) p.getProperty(consumer_key + ".description");
                    String consumer_callback_url =  (String) p.getProperty(consumer_key + ".callbackURL");
                    // Create OAuthConsumer w/ key and secret
                    OAuthConsumer consumer = new OAuthConsumer(
                            consumer_callback_url,
                            consumer_key,
                            consumer_secret,
                            null);
                    consumer.setProperty("name", consumer_key);
                    consumer.setProperty("description", consumer_description);
                    ALL_CONSUMERS.put(consumer_key, consumer);
                }
            }
        }

    }

    public static synchronized OAuthConsumer getConsumer(
            OAuthMessage requestMessage)
            throws IOException, OAuthProblemException {

        OAuthConsumer consumer = null;
        // try to load from local cache if not throw exception
        String consumer_key = requestMessage.getConsumerKey();

        consumer = SampleOAuthProvider.ALL_CONSUMERS.get(consumer_key);

        if(consumer == null) {
            OAuthProblemException problem = new OAuthProblemException("token_rejected");
            throw problem;
        }

        return consumer;
    }

    /**
     * Get the access token and token secret for the given oauth_token.
     */
    public static synchronized OAuthAccessor getAccessor(OAuthMessage requestMessage)
            throws IOException, OAuthProblemException {

        // try to load from local cache if not throw exception
        String consumer_token = requestMessage.getToken();
        OAuthAccessor accessor = null;
        for (OAuthAccessor a : SampleOAuthProvider.ALL_TOKENS) {
            if(a.requestToken != null) {
                if (a.requestToken.equals(consumer_token)) {
                    accessor = a;
                    break;
                }
            } else if(a.accessToken != null){
                if (a.accessToken.equals(consumer_token)) {
                    accessor = a;
                    break;
                }
            }
        }

        if(accessor == null){
            OAuthProblemException problem = new OAuthProblemException("token_expired");
            throw problem;
        }

        return accessor;
    }

    /**
     * Set the access token
     */
    public static synchronized void markAsAuthorized(OAuthAccessor accessor, String userId)
            throws OAuthException {

        // first remove the accessor from cache
        ALL_TOKENS.remove(accessor);

        accessor.setProperty("user", userId);
        accessor.setProperty("authorized", Boolean.TRUE);

        // update token in local cache
        ALL_TOKENS.add(accessor);
    }

    /**
     * Generate a fresh request token and secret for a consumer.
     *
     * @throws OAuthException
     */
    public static synchronized void generateRequestToken(
            OAuthAccessor accessor)
            throws OAuthException {

        // generate oauth_token and oauth_secret
        String consumer_key = (String) accessor.consumer.getProperty("name");
        // generate token and secret based on consumer_key

        // for now use md5 of name + current time as token
        String token_data = consumer_key + System.nanoTime();
        String token = DigestUtils.md5Hex(token_data);
        // for now use md5 of name + current time + token as secret
        String secret_data = consumer_key + System.nanoTime() + token;
        String secret = DigestUtils.md5Hex(secret_data);

        accessor.requestToken = token;
        accessor.tokenSecret = secret;
        accessor.accessToken = null;

        // add to the local cache
        ALL_TOKENS.add(accessor);

    }

    /**
     * Generate a fresh request token and secret for a consumer.
     *
     * @throws OAuthException
     */
    public static synchronized void generateAccessToken(OAuthAccessor accessor)
            throws OAuthException {

        // generate oauth_token and oauth_secret
        String consumer_key = (String) accessor.consumer.getProperty("name");
        // generate token and secret based on consumer_key

        // for now use md5 of name + current time as token
        String token_data = consumer_key + System.nanoTime();
        String token = DigestUtils.md5Hex(token_data);
        // first remove the accessor from cache
        ALL_TOKENS.remove(accessor);

        accessor.requestToken = null;
        accessor.accessToken = token;

        // update token in local cache
        ALL_TOKENS.add(accessor);
    }

    public static void handleException(Exception e, HttpServletRequest request,
            HttpServletResponse response, boolean sendBody)
            throws IOException, ServletException {
        String realm = (request.isSecure())?"https://":"http://";
        realm += request.getLocalName();
        OAuthServlet.handleException(response, e, realm, sendBody);
    }

}


text:
from django.contrib import admin

from .models import Artist

admin.site.register(Artist)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>blast example for the boarding package.</title>
    <link rel="stylesheet" href="index.css">

Blast

      Click to zoom out, click to zoom out...

    <canvas id="canvas" width="400" height="400"></canvas>


text:
/*
Title: @ESBcolor
Description: Unofficial daily update of colors on the Empire State Building.
Author: Stefan Bohacek
Date: July 26, 2015
Tags: twitterbot,active,nyc

Nav: hidden
Robots: index,follow
*/

[![](/content/bots/twitterbots/images/ESBcolor.png)](https://twitter.com/ESBcolor)

A bot that tweets when the [Empire State Building](http://www.esbnyc.com/) is lit up with lights other than the signature white. Created by [Sam Swift](https://twitter.com/swiftsam).

See also [esbnyc.com/explore/tower-lights/calendar](http://www.esbnyc.com/explore/tower-lights/calendar).


text:
package com.datatorrent.stram.engine;

import java.io.Serializable;

import com.datatorrent.api.StringCodec;

/**
 *
 */
public class GenericOperatorProperty
{
  private String s;

  public GenericOperatorProperty(String s)
  {
    this.s = s;
  }

  // This is on purpose not to be a getter.
  public String obtainString()
  {
    return this.s;
  }

  public static class GenericOperatorPropertyStringCodec implements StringCodec<GenericOperatorProperty>, Serializable
  {
    private static final long serialVersionUID = 201403031223L;

    @Override
    public GenericOperatorProperty fromString(String string)
    {
      return new GenericOperatorProperty(string);
    }

    @Override
    public String toString(GenericOperatorProperty pojo)
    {
      return pojo.obtainString();
    }

  }
}


text:
namespace Google.Cloud.Dialogflow.Cx.V3.Snippets
{
    // [START dialogflow_v3_generated_EntityTypes_DeleteEntityType_sync_flattened]
    using Google.Cloud.Dialogflow.Cx.V3;

    public sealed partial class GeneratedEntityTypesClientSnippets
    {
        /// <summary>Snippet for DeleteEntityType</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void DeleteEntityType()
        {
            // Create client
            EntityTypesClient entityTypesClient = EntityTypesClient.Create();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/locations/[LOCATION]/agents/[AGENT]/entityTypes/[ENTITY_TYPE]";
            // Make the request
            entityTypesClient.DeleteEntityType(name);
        }
    }
    // [END dialogflow_v3_generated_EntityTypes_DeleteEntityType_sync_flattened]
}


text:
module Gitlab
  module QuickActions
    module IssueAndMergeRequestActions
      extend ActiveSupport::Concern
      include Gitlab::QuickActions::Dsl

      included do
        # Issue, MergeRequest: quick actions definitions
        desc _('Assign')
        # rubocop: disable CodeReuse/ActiveRecord
        explanation do |users|
          users = quick_action_target.allows_multiple_assignees? ? users : users.take(1)
          "Assigns #{users.map(&:to_reference).to_sentence}."
        end
        # rubocop: enable CodeReuse/ActiveRecord
        params do
          quick_action_target.allows_multiple_assignees? ? '@user1 @user2' : '@user'
        end
        types Issue, MergeRequest
        condition do
          current_user.can?(:"admin_#{quick_action_target.to_ability_name}", project)
        end
        parse_params do |assignee_param|
          extract_users(assignee_param)
        end
        command :assign do |users|
          next if users.empty?

          if quick_action_target.allows_multiple_assignees?
            @updates[:assignee_ids] ||= quick_action_target.assignees.map(&:id)
            @updates[:assignee_ids] += users.map(&:id)
          else
            @updates[:assignee_ids] = [users.first.id]
          end
        end

        desc do
          if quick_action_target.allows_multiple_assignees?
            _('Remove all or specific assignee(s)')
          else
            _('Remove assignee')
          end
        end
        explanation do |users = nil|
          assignees = quick_action_target.assignees
          assignees &= users if users.present? && quick_action_target.allows_multiple_assignees?
          "Removes #{'assignee'.pluralize(assignees.size)} #{assignees.map(&:to_reference).to_sentence}."
        end
        params do
          quick_action_target.allows_multiple_assignees? ? '@user1 @user2' : ''
        end
        types Issue, MergeRequest
        condition do
          quick_action_target.persisted? &&
            quick_action_target.assignees.any? &&
            current_user.can?(:"admin_#{quick_action_target.to_ability_name}", project)
        end
        parse_params do |unassign_param|
          # When multiple users are assigned, all will be unassigned if multiple assignees are no longer allowed
          extract_users(unassign_param) if quick_action_target.allows_multiple_assignees?
        end
        command :unassign do |users = nil|
          if quick_action_target.allows_multiple_assignees? && users&.any?
            @updates[:assignee_ids] ||= quick_action_target.assignees.map(&:id)
            @updates[:assignee_ids] -= users.map(&:id)
          else
            @updates[:assignee_ids] = []
          end
        end

        desc _('Set milestone')
        explanation do |milestone|
          _("Sets the milestone to %{milestone_reference}.") % { milestone_reference: milestone.to_reference } if milestone
        end
        params '%"milestone"'
        types Issue, MergeRequest
        condition do
          current_user.can?(:"admin_#{quick_action_target.to_ability_name}", project) &&
            find_milestones(project, state: 'active').any?
        end
        parse_params do |milestone_param|
          extract_references(milestone_param, :milestone).first ||
            find_milestones(project, title: milestone_param.strip).first
        end
        command :milestone do |milestone|
          @updates[:milestone_id] = milestone.id if milestone
        end

        desc _('Remove milestone')
        explanation do
          _("Removes %{milestone_reference} milestone.") % { milestone_reference: quick_action_target.milestone.to_reference(format: :name) }
        end
        types Issue, MergeRequest
        condition do
          quick_action_target.persisted? &&
            quick_action_target.milestone_id? &&
            current_user.can?(:"admin_#{quick_action_target.to_ability_name}", project)
        end
        command :remove_milestone do
          @updates[:milestone_id] = nil
        end

        desc _('Copy labels and milestone from other issue or merge request')
        explanation do |source_issuable|
          _("Copy labels and milestone from %{source_issuable_reference}.") % { source_issuable_reference: source_issuable.to_reference }
        end
        params '#issue | !merge_request'
        types Issue, MergeRequest
        condition do
          current_user.can?(:"update_#{quick_action_target.to_ability_name}", quick_action_target)
        end
        parse_params do |issuable_param|
          extract_references(issuable_param, :issue).first ||
            extract_references(issuable_param, :merge_request).first
        end
        command :copy_metadata do |source_issuable|
          if source_issuable.present? && source_issuable.project.id == quick_action_target.project.id
            @updates[:add_label_ids] = source_issuable.labels.map(&:id)
            @updates[:milestone_id] = source_issuable.milestone.id if source_issuable.milestone
          end
        end

        desc _('Set time estimate')
        explanation do |time_estimate|
          time_estimate = Gitlab::TimeTrackingFormatter.output(time_estimate)

          _("Sets time estimate to %{time_estimate}.") % { time_estimate: time_estimate } if time_estimate
        end
        params '<1w 3d 2h 14m>'
        types Issue, MergeRequest
        condition do
          current_user.can?(:"admin_#{quick_action_target.to_ability_name}", project)
        end
        parse_params do |raw_duration|
          Gitlab::TimeTrackingFormatter.parse(raw_duration)
        end
        command :estimate do |time_estimate|
          if time_estimate
            @updates[:time_estimate] = time_estimate
          end
        end

        desc _('Add or subtract spent time')
        explanation do |time_spent, time_spent_date|
          if time_spent
            if time_spent > 0
              verb = _('Adds')
              value = time_spent
            else
              verb = _('Subtracts')
              value = -time_spent
            end

            _("%{verb} %{time_spent_value} spent time.") % { verb: verb, time_spent_value: Gitlab::TimeTrackingFormatter.output(value) }
          end
        end
        params '<time(1h30m | -1h30m)> <date(YYYY-MM-DD)>'
        types Issue, MergeRequest
        condition do
          current_user.can?(:"admin_#{quick_action_target.to_ability_name}", quick_action_target)
        end
        parse_params do |raw_time_date|
          Gitlab::QuickActions::SpendTimeAndDateSeparator.new(raw_time_date).execute
        end
        command :spend do |time_spent, time_spent_date|
          if time_spent
            @updates[:spend_time] = {
              duration: time_spent,
              user_id: current_user.id,
              spent_at: time_spent_date
            }
          end
        end

        desc _('Remove time estimate')
        explanation _('Removes time estimate.')
        types Issue, MergeRequest
        condition do
          quick_action_target.persisted? &&
            current_user.can?(:"admin_#{quick_action_target.to_ability_name}", project)
        end
        command :remove_estimate do
          @updates[:time_estimate] = 0
        end

        desc _('Remove spent time')
        explanation _('Removes spent time.')
        condition do
          quick_action_target.persisted? &&
            current_user.can?(:"admin_#{quick_action_target.to_ability_name}", project)
        end
        types Issue, MergeRequest
        command :remove_time_spent do
          @updates[:spend_time] = { duration: :reset, user_id: current_user.id }
        end

        desc _("Lock the discussion")
        explanation _("Locks the discussion")
        types Issue, MergeRequest
        condition do
          quick_action_target.persisted? &&
            !quick_action_target.discussion_locked? &&
            current_user.can?(:"admin_#{quick_action_target.to_ability_name}", quick_action_target)
        end
        command :lock do
          @updates[:discussion_locked] = true
        end

        desc _("Unlock the discussion")
        explanation _("Unlocks the discussion")
        types Issue, MergeRequest
        condition do
          quick_action_target.persisted? &&
            quick_action_target.discussion_locked? &&
            current_user.can?(:"admin_#{quick_action_target.to_ability_name}", quick_action_target)
        end
        command :unlock do
          @updates[:discussion_locked] = false
        end
      end
    end
  end
end


text:
from __future__ import unicode_literals

from django.conf.urls import patterns, url

urlpatterns = patterns(
    "wordpress.views",
    url(r"^load_post$", "load_post_webhook", name="wp_rest_load_post_webhook"),
)


text:
package org.lilliput.chronograph.persistent.epcgraph.test.transformation;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import java.io.IOException;
import java.util.ArrayList;

import org.bson.BsonDocument;
import org.bson.BsonInt32;
import org.oliot.khronos.common.TemporalType;
import org.oliot.khronos.common.Tokens.AC;
import org.oliot.khronos.common.Tokens.Position;
import org.oliot.khronos.persistent.ChronoGraph;
import org.oliot.khronos.persistent.VertexEvent;
import org.oliot.khronos.persistent.recipe.PersistentBreadthFirstSearch;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoDatabase;

public class TransformationQueryTestInternal {
	public static String fileBaseLoc = "/home/jack/test/";
	// db.edges.createIndex({"_outV" : 1, "_t" : 1, "_inV" : 1})
	// db.EventData.createIndex({"inputEPCList.epc":1})

	public static String baseURL = "http://localhost:8080/epcgraph";
	public int transferCount = 308;
	public int iterationCount = 100;

	public void test() throws IOException, InterruptedException {

		File file = new File(fileBaseLoc + this.getClass().getSimpleName() + "-cache-bfs");
		file.createNewFile();
		FileWriter fw = new FileWriter(file);
		BufferedWriter bw = new BufferedWriter(fw);

		String baseEPC = "urn:epc:id:sgtin:0000001.000001.";

		MongoClient client = new MongoClient();
		MongoDatabase db = client.getDatabase("test1");
		db.getCollection("edges").drop();
		db.getCollection("vertices").drop();
		db.getCollection("edges").createIndex(new BsonDocument("_outV", new BsonInt32(1))
				.append("_label", new BsonInt32(1)).append("_t", new BsonInt32(1)).append("_inV", new BsonInt32(1)));
		client.close();

		ChronoGraph g = new ChronoGraph("test1");

		for (int i = 0; i < transferCount; i++) {

			long cTime = System.currentTimeMillis();
			g.addTimestampEdgeProperties(baseEPC + i, baseEPC + (2 * i + 1), "transformTo", cTime, new BsonDocument());
			g.addTimestampEdgeProperties(baseEPC + i, baseEPC + (2 * i + 2), "transformTo", cTime, new BsonDocument());

			Thread.sleep(2000);

			double avg = doTransformationQuery(g);

			System.out.println(i + "\t" + avg);
			bw.write(i + "\t" + avg + "\n");
			bw.flush();
		}
		bw.close();
	}

	public double doTransformationQuery(ChronoGraph g) throws IOException {

		ArrayList<Long> timeList = new ArrayList<Long>();

		String source = "urn:epc:id:sgtin:0000001.000001.0";

		VertexEvent ve = g.getChronoVertex(source).setTimestamp(0l);

		for (int i = 0; i < iterationCount; i++) {

			PersistentBreadthFirstSearch bfs = new PersistentBreadthFirstSearch();

			long pre = System.currentTimeMillis();
			bfs.compute(g, ve, "transformTo", TemporalType.TIMESTAMP, AC.$gt, null, null, null, null, null, null, Position.first,
					"ASC");
			long aft = System.currentTimeMillis();
			long elapsedTime = aft - pre;
			// System.out.println("Elapsed Time: " + elapsedTime);
			timeList.add(elapsedTime);
		}

		double total = timeList.parallelStream().mapToDouble(t -> {
			return t.longValue();
		}).sum();

		return total / iterationCount;
	}
}


text:
// snippet-sourcedescription:[getRealtimeMetrics.js demonstrates how to .]
// snippet-service:[connect]
// snippet-keyword:[JavaScript]
// snippet-sourcesyntax:[javascript]
// snippet-keyword:[Amazon Connect]
// snippet-keyword:[Code Sample]
// snippet-keyword:[getMetricData]
// snippet-sourcetype:[full-example]
// snippet-sourcedate:[2019-10-17]
// snippet-sourceauthor:[Doug-AWS]
// snippet-start:[connect.javascript.getMetricData]
/*
This code uses callbacks to handle asynchronous function responses.
It currently demonstrates using an async-await pattern.
AWS supports both the async-await and promises patterns.
For more information, see the following:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/calling-services-asynchronously.html
https://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
*/
const aws = require('aws-sdk')
const connect = new aws.Connect()

const params = {
  InstanceId: 'Provide your connect instance id',
  EndTime: 1571184000, // enter a new end time
  StartTime: 1571153400, // enter a new start time
  Filters: {
    Queues: ['Provide your connect instance queue id'],
    Channels: ['VOICE']
  },
  HistoricalMetrics: [
    {
      Name: 'AFTER_CONTACT_WORK_TIME',
      Unit: 'SECONDS',
      Statistic: 'AVG'
    },
    {
      Name: 'CONTACTS_QUEUED',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_HANDLED',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'HANDLE_TIME',
      Unit: 'SECONDS',
      Statistic: 'AVG'
    },
    {
      Name: 'CONTACTS_TRANSFERRED_OUT',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_MISSED',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'OCCUPANCY',
      Unit: 'PERCENT',
      Statistic: 'AVG'
    },
    {
      Name: 'QUEUED_TIME',
      Unit: 'SECONDS',
      Statistic: 'MAX'
    },
    {
      Name: 'HOLD_TIME',
      Unit: 'SECONDS',
      Statistic: 'AVG'
    },
    {
      Name: 'SERVICE_LEVEL',
      Threshold: {
        Comparison: 'LT',
        ThresholdValue: 60.0
      },
      Unit: 'PERCENT',
      Statistic: 'AVG'
    },
    {
      Name: 'SERVICE_LEVEL',
      Threshold: {
        Comparison: 'LT',
        ThresholdValue: 120.0
      },
      Unit: 'PERCENT',
      Statistic: 'AVG'
    },
    {
      Name: 'SERVICE_LEVEL',
      Threshold: {
        Comparison: 'LT',
        ThresholdValue: 30.0
      },
      Unit: 'PERCENT',
      Statistic: 'AVG'
    },
    {
      Name: 'CONTACTS_ABANDONED',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_CONSULTED',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_AGENT_HUNG_UP_FIRST',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_HANDLED_INCOMING',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_HANDLED_OUTBOUND',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_HOLD_ABANDONS',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_TRANSFERRED_IN',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_TRANSFERRED_IN_FROM_QUEUE',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CONTACTS_TRANSFERRED_OUT_FROM_QUEUE',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'CALLBACK_CONTACTS_HANDLED',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'API_CONTACTS_HANDLED',
      Unit: 'COUNT',
      Statistic: 'SUM'
    },
    {
      Name: 'ABANDON_TIME',
      Unit: 'SECONDS',
      Statistic: 'AVG'
    },
    {
      Name: 'QUEUE_ANSWER_TIME',
      Unit: 'SECONDS',
      Statistic: 'AVG'
    },
    {
      Name: 'INTERACTION_TIME',
      Unit: 'SECONDS',
      Statistic: 'AVG'
    },
    {
      Name: 'INTERACTION_AND_HOLD_TIME',
      Unit: 'SECONDS',
      Statistic: 'AVG'
    }
  ]
}

exports.handler = async (event) => {
  const result = await connect.getMetricData(params, function (err, data) {
    if (err) {
      console.log(err, err.stack)
    } else {
      console.log(data)
    }
  }).promise()

  var metrics = result.MetricResults
  console.log(metrics[0].Collections)
}
// snippet-end:[connect.javascript.getMetricData]


text:
package com.krux.hyperion.common

import com.krux.hyperion.HyperionContext
import com.krux.hyperion.adt.HString
import com.krux.hyperion.resource.{SparkCluster, Resource}

trait SparkCommandRunner {

  def jobRunner(runsOn: Resource[SparkCluster])(implicit hc: HyperionContext): HString =
    if (runsOn.asManagedResource.exists(_.releaseLabel.nonEmpty)) {
      // Note calling "spark-submit" directly through common-runner.jar is not supported in the
      // current implementation because SparkStep does not accept local jar and the generated
      // arguments are not spark-submit compatible
      s"${hc.scriptUri}run-spark-step-release-label.sh"
    } else {
      s"${hc.scriptUri}run-spark-step.sh"
    }

  def scriptRunner(runsOn: Resource[SparkCluster]): HString =
    // Note we cannot use "command-runner.jar" until SparkStep is reworked to accept local jars and
    // serialization generates the correct arguments
    "s3://elasticmapreduce/libs/script-runner/script-runner.jar"

}


text:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Linq;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Editors;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Rdbms;

using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Factories;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.PropertyEditors;
using Umbraco.Core.Services;
using Umbraco.Core.Dynamics;
using Umbraco.Core.IO;
using Umbraco.Core.Media;

namespace Umbraco.Core.Persistence.Repositories
{
    internal abstract class VersionableRepositoryBase<TId, TEntity> : PetaPocoRepositoryBase<TId, TEntity>
        where TEntity : class, IAggregateRoot
    {
        private readonly IContentSection _contentSection;

        /// <summary>
        /// This is used for unit tests ONLY
        /// </summary>
        internal static bool ThrowOnWarning = false;

        protected VersionableRepositoryBase(IScopeUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax, IContentSection contentSection)
            : base(work, cache, logger, sqlSyntax)
        {
            _contentSection = contentSection;
        }

        #region IRepositoryVersionable Implementation

        /// <summary>
        /// Gets a list of all versions for an <see cref="TEntity"/> ordered so latest is first
        /// </summary>
        /// <param name="id">Id of the <see cref="TEntity"/> to retrieve versions from</param>
        /// <returns>An enumerable list of the same <see cref="TEntity"/> object with different versions</returns>
        public abstract IEnumerable<TEntity> GetAllVersions(int id);

        /// <summary>
        /// Gets a list of all version Ids for the given content item ordered so latest is first
        /// </summary>
        /// <param name="id"></param>
        /// <param name="maxRows">The maximum number of rows to return</param>
        /// <returns></returns>
        public virtual IEnumerable<Guid> GetVersionIds(int id, int maxRows)
        {
            var sql = new Sql();
            sql.Select("cmsDocument.versionId")
                .From<DocumentDto>(SqlSyntax)
                .InnerJoin<ContentDto>(SqlSyntax)
                .On<DocumentDto, ContentDto>(SqlSyntax, left => left.NodeId, right => right.NodeId)
                .InnerJoin<NodeDto>(SqlSyntax)
                .On<ContentDto, NodeDto>(SqlSyntax, left => left.NodeId, right => right.NodeId)
                .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId)
                .Where<NodeDto>(x => x.NodeId == id)
                .OrderByDescending<DocumentDto>(x => x.UpdateDate, SqlSyntax);

            return Database.Fetch<Guid>(SqlSyntax.SelectTop(sql, maxRows));
        }

        public virtual void DeleteVersion(Guid versionId)
        {
            var dto = Database.FirstOrDefault<ContentVersionDto>("WHERE versionId = @VersionId", new { VersionId = versionId });
            if (dto == null) return;

            //Ensure that the lastest version is not deleted
            var latestVersionDto = Database.FirstOrDefault<ContentVersionDto>("WHERE ContentId = @Id ORDER BY VersionDate DESC", new { Id = dto.NodeId });
            if (latestVersionDto.VersionId == dto.VersionId)
                return;

            using (var transaction = Database.GetTransaction())
            {
                PerformDeleteVersion(dto.NodeId, versionId);

                transaction.Complete();
            }
        }

        public virtual void DeleteVersions(int id, DateTime versionDate)
        {
            //Ensure that the latest version is not part of the versions being deleted
            var latestVersionDto = Database.FirstOrDefault<ContentVersionDto>("WHERE ContentId = @Id ORDER BY VersionDate DESC", new { Id = id });
            var list =
                Database.Fetch<ContentVersionDto>(
                    "WHERE versionId <> @VersionId AND (ContentId = @Id AND VersionDate < @VersionDate)",
                    new { VersionId = latestVersionDto.VersionId, Id = id, VersionDate = versionDate });
            if (list.Any() == false) return;

            using (var transaction = Database.GetTransaction())
            {
                foreach (var dto in list)
                {
                    PerformDeleteVersion(id, dto.VersionId);
                }

                transaction.Complete();
            }
        }

        public abstract TEntity GetByVersion(Guid versionId);

        /// <summary>
        /// Protected method to execute the delete statements for removing a single version for a TEntity item.
        /// </summary>
        /// <param name="id">Id of the <see cref="TEntity"/> to delete a version from</param>
        /// <param name="versionId">Guid id of the version to delete</param>
        protected abstract void PerformDeleteVersion(int id, Guid versionId);

        #endregion

        /// <summary>
        /// Gets paged document descendants as XML by path
        /// </summary>
        /// <param name="path">Path starts with</param>
        /// <param name="pageIndex">Page number</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="orderBy"></param>
        /// <param name="totalRecords">Total records the query would return without paging</param>
        /// <returns>A paged enumerable of XML entries of content items</returns>
        public virtual IEnumerable<XElement> GetPagedXmlEntriesByPath(string path, long pageIndex, int pageSize, string[] orderBy, out long totalRecords)
        {
            var query = new Sql().Select(string.Format("umbracoNode.id, cmsContentXml.{0}", SqlSyntax.GetQuotedColumnName("xml")))
                .From("umbracoNode")
                .InnerJoin("cmsContentXml").On("cmsContentXml.nodeId = umbracoNode.id");

            if (path == "-1")
            {
                query.Where("umbracoNode.nodeObjectType = @type", new { type = NodeObjectTypeId });
            }
            else
            {
                query.Where(string.Format("umbracoNode.{0} LIKE (@0)", SqlSyntax.GetQuotedColumnName("path")), path.EnsureEndsWith(",%"));
            }

            //each order by param needs to be in a bracket! see: https://github.com/toptensoftware/PetaPoco/issues/177
            query.OrderBy(orderBy == null
                ? "(umbracoNode.id)"
                : string.Join(",", orderBy.Select(x => string.Format("({0})", SqlSyntax.GetQuotedColumnName(x)))));

            var pagedResult = Database.Page<ContentXmlDto>(pageIndex + 1, pageSize, query);
            totalRecords = pagedResult.TotalItems;
            return pagedResult.Items.Select(dto => XElement.Parse(dto.Xml));
        }

        public int CountDescendants(int parentId, string contentTypeAlias = null)
        {
            var pathMatch = parentId == -1
                ? "-1,"
                : "," + parentId + ",";
            var sql = new Sql();
            if (contentTypeAlias.IsNullOrWhiteSpace())
            {
                sql.Select("COUNT(*)")
                    .From<NodeDto>()
                    .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId)
                    .Where<NodeDto>(x => x.Path.Contains(pathMatch));
            }
            else
            {
                sql.Select("COUNT(*)")
                    .From<NodeDto>()
                    .InnerJoin<ContentDto>()
                    .On<NodeDto, ContentDto>(left => left.NodeId, right => right.NodeId)
                    .InnerJoin<ContentTypeDto>()
                    .On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId)
                    .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId)
                    .Where<NodeDto>(x => x.Path.Contains(pathMatch))
                    .Where<ContentTypeDto>(x => x.Alias == contentTypeAlias);
            }

            return Database.ExecuteScalar<int>(sql);
        }

        public int CountChildren(int parentId, string contentTypeAlias = null)
        {
            var sql = new Sql();
            if (contentTypeAlias.IsNullOrWhiteSpace())
            {
                sql.Select("COUNT(*)")
                    .From<NodeDto>()
                    .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId)
                    .Where<NodeDto>(x => x.ParentId == parentId);
            }
            else
            {
                sql.Select("COUNT(*)")
                    .From<NodeDto>()
                    .InnerJoin<ContentDto>()
                    .On<NodeDto, ContentDto>(left => left.NodeId, right => right.NodeId)
                    .InnerJoin<ContentTypeDto>()
                    .On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId)
                    .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId)
                    .Where<NodeDto>(x => x.ParentId == parentId)
                    .Where<ContentTypeDto>(x => x.Alias == contentTypeAlias);
            }

            return Database.ExecuteScalar<int>(sql);
        }

        /// <summary>
        /// Get the total count of entities
        /// </summary>
        /// <param name="contentTypeAlias"></param>
        /// <returns></returns>
        public int Count(string contentTypeAlias = null)
        {
            var sql = new Sql();
            if (contentTypeAlias.IsNullOrWhiteSpace())
            {
                sql.Select("COUNT(*)")
                    .From<NodeDto>()
                    .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId);
            }
            else
            {
                sql.Select("COUNT(*)")
                    .From<NodeDto>()
                    .InnerJoin<ContentDto>()
                    .On<NodeDto, ContentDto>(left => left.NodeId, right => right.NodeId)
                    .InnerJoin<ContentTypeDto>()
                    .On<ContentTypeDto, ContentDto>(left => left.NodeId, right => right.ContentTypeId)
                    .Where<NodeDto>(x => x.NodeObjectType == NodeObjectTypeId)
                    .Where<ContentTypeDto>(x => x.Alias == contentTypeAlias);
            }

            return Database.ExecuteScalar<int>(sql);
        }

        /// <summary>
        /// This removes associated tags from the entity - used generally when an entity is recycled
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="tagRepo"></param>
        protected void ClearEntityTags(IContentBase entity, ITagRepository tagRepo)
        {
            tagRepo.ClearTagsFromEntity(entity.Id);
        }

        /// <summary>
        /// Updates the tag repository with any tag enabled properties and their values
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="tagRepo"></param>
        protected void UpdatePropertyTags(IContentBase entity, ITagRepository tagRepo)
        {
            foreach (var tagProp in entity.Properties.Where(x => x.TagSupport.Enable))
            {
                if (tagProp.TagSupport.Behavior == PropertyTagBehavior.Remove)
                {
                    //remove the specific tags
                    tagRepo.RemoveTagsFromProperty(
                        entity.Id,
                        tagProp.PropertyTypeId,
                        tagProp.TagSupport.Tags.Select(x => new Tag { Text = x.Item1, Group = x.Item2 }));
                }
                else
                {
                    //assign the tags
                    tagRepo.AssignTagsToProperty(
                        entity.Id,
                        tagProp.PropertyTypeId,
                        tagProp.TagSupport.Tags.Select(x => new Tag { Text = x.Item1, Group = x.Item2 }),
                        tagProp.TagSupport.Behavior == PropertyTagBehavior.Replace);
                }
            }
        }

        private Sql GetFilteredSqlForPagedResults(Sql sql, Func<Tuple<string, object[]>> defaultFilter = null)
        {
            Sql filteredSql;

            // Apply filter
            if (defaultFilter != null)
            {
                //NOTE: It is assumed here that the `sql` already contains a WHERE clause, see UserRepository.GetFilteredSqlForPagedResults
                // for an example of when it's not assumed there's already a WHERE clause

                var filterResult = defaultFilter();

                //NOTE: this is certainly strange - NPoco handles this much better but we need to re-create the sql
                // instance a couple of times to get the parameter order correct, for some reason the first
                // time the arguments don't show up correctly but the SQL argument parameter names are actually updated
                // accordingly - so we re-create it again. In v8 we don't need to do this and it's already taken care of.

                filteredSql = new Sql(sql.SQL, sql.Arguments);
                var args = filteredSql.Arguments.Concat(filterResult.Item2).ToArray();
                filteredSql = new Sql(
                    string.Format("{0} {1}", filteredSql.SQL, filterResult.Item1),
                    args);
                filteredSql = new Sql(filteredSql.SQL, args);
            }
            else
            {
                //copy to var so that the original isn't changed
                filteredSql = new Sql(sql.SQL, sql.Arguments);
            }
            return filteredSql;
        }

        private Sql GetSortedSqlForPagedResults(Sql sql, Direction orderDirection, string orderBy, bool orderBySystemField, Tuple<string, string> nodeIdSelect)
        {

            //copy to var so that the original isn't changed
            var sortedSql = new Sql(sql.SQL, sql.Arguments);

            if (orderBySystemField)
            {
                // Apply order according to parameters
                if (string.IsNullOrEmpty(orderBy) == false)
                {
                    var orderByParams = new[] { GetDatabaseFieldNameForOrderBy(orderBy) };
                    if (orderDirection == Direction.Ascending)
                    {
                        sortedSql.OrderBy(orderByParams);
                    }
                    else
                    {
                        sortedSql.OrderByDescending(orderByParams);
                    }
                }
            }
            else
            {
                // Sorting by a custom field, so set-up sub-query for ORDER BY clause to pull through value
                // from most recent content version for the given order by field
                var sortedInt = string.Format(SqlSyntax.ConvertIntegerToOrderableString, "dataInt");
                var sortedDate = string.Format(SqlSyntax.ConvertDateToOrderableString, "dataDate");
                var sortedString = string.Format("COALESCE({0},'')", "dataNvarchar");
                var sortedDecimal = string.Format(SqlSyntax.ConvertDecimalToOrderableString, "dataDecimal");

                //these are defaults that will be used in the query - they can be overridden for non-versioned entities or document entities
                var versionQuery = " AND cpd.versionId = cd.versionId";
                var newestQuery = string.Empty;

                //cmsDocument needs to filter by the 'newest' parameter in the query
                if (nodeIdSelect.Item1 == "cmsDocument")
                    newestQuery = " AND cd.newest = 1";

                //members do not use versions so clear the versionQuery string
                if (nodeIdSelect.Item1 == "cmsMember")
                    versionQuery = string.Empty;

                //needs to be an outer join since there's no guarantee that any of the nodes have values for this property
                var outerJoinTempTable = string.Format(@"LEFT OUTER JOIN (
                                SELECT CASE
                                    WHEN dataInt Is Not Null THEN {0}
                                    WHEN dataDecimal Is Not Null THEN {1}
                                    WHEN dataDate Is Not Null THEN {2}
                                    ELSE {3}
                                END AS CustomPropVal,
                                cd.{4} AS CustomPropValContentId
                                FROM {5} cd
                                INNER JOIN cmsPropertyData cpd ON cpd.contentNodeId = cd.{4}{6}
                                INNER JOIN cmsPropertyType cpt ON cpt.Id = cpd.propertytypeId
                                WHERE cpt.Alias = @{7}{8}) AS CustomPropData
                                ON CustomPropData.CustomPropValContentId = umbracoNode.id
                ", sortedInt, sortedDecimal, sortedDate, sortedString, nodeIdSelect.Item2, nodeIdSelect.Item1, versionQuery, sortedSql.Arguments.Length, newestQuery);

                //insert this just above the last WHERE
                string newSql = sortedSql.SQL.Insert(sortedSql.SQL.LastIndexOf("WHERE"), outerJoinTempTable);

                var newArgs = sortedSql.Arguments.ToList();
                newArgs.Add(orderBy);

                sortedSql = new Sql(newSql, newArgs.ToArray());

                if (orderDirection == Direction.Descending)
                {
                    sortedSql.OrderByDescending("CustomPropData.CustomPropVal");
                }
                else
                {
                    sortedSql.OrderBy("CustomPropData.CustomPropVal");
                }
            }

            if (orderBySystemField && orderBy != "umbracoNode.id")
            {
                //no matter what we always MUST order the result also by umbracoNode.id to ensure that all records being ordered by are unique.
                // if we do not do this then we end up with issues where we are ordering by a field that has duplicate values (i.e. the 'text' column
                // is empty for many nodes)
                // see: http://issues.umbraco.org/issue/U4-8831
                sortedSql.OrderBy("umbracoNode.id");
            }

            return sortedSql;

        }

        /// <summary>
        /// A helper method for inheritors to get the paged results by query in a way that minimizes queries
        /// </summary>
        /// <typeparam name="TDto">The type of the d.</typeparam>
        /// <param name="query">The query.</param>
        /// <param name="pageIndex">Index of the page.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <param name="totalRecords">The total records.</param>
        /// <param name="nodeIdSelect">The tablename + column name for the SELECT statement fragment to return the node id from the query</param>
        /// <param name="defaultFilter">A callback to create the default filter to be applied if there is one</param>
        /// <param name="processQuery">A callback to process the query result</param>
        /// <param name="orderBy">The order by column</param>
        /// <param name="orderDirection">The order direction.</param>
        /// <param name="orderBySystemField">Flag to indicate when ordering by system field</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">orderBy</exception>
        protected IEnumerable<TEntity> GetPagedResultsByQuery<TDto>(IQuery<TEntity> query, long pageIndex, int pageSize, out long totalRecords,
            Tuple<string, string> nodeIdSelect,
            Func<Sql, PagingSqlQuery<TDto>, IEnumerable<TEntity>> processQuery,
            string orderBy,
            Direction orderDirection,
            bool orderBySystemField,
            Func<Tuple<string, object[]>> defaultFilter = null)
        {
            if (orderBy == null) throw new ArgumentNullException("orderBy");

            // Get base query for returning IDs
            var sqlBaseIds = GetBaseQuery(BaseQueryType.Ids);
            // Get base query for returning all data
            var sqlBaseFull = GetBaseQuery(BaseQueryType.FullMultiple);

            if (query == null) query = new Query<TEntity>();
            var translatorIds = new SqlTranslator<TEntity>(sqlBaseIds, query);
            var sqlQueryIds = translatorIds.Translate();
            var translatorFull = new SqlTranslator<TEntity>(sqlBaseFull, query);
            var sqlQueryFull = translatorFull.Translate();

            //get sorted and filtered sql
            var sqlNodeIdsWithSort = GetSortedSqlForPagedResults(
                GetFilteredSqlForPagedResults(sqlQueryIds, defaultFilter),
                orderDirection, orderBy, orderBySystemField, nodeIdSelect);

            // Get page of results and total count
            IEnumerable<TEntity> result;
            var pagedResult = Database.Page<TDto>(pageIndex + 1, pageSize, sqlNodeIdsWithSort);
            totalRecords = Convert.ToInt32(pagedResult.TotalItems);

            //NOTE: We need to check the actual items returned, not the 'totalRecords', that is because if you request a page number
            // that doesn't actually have any data on it, the totalRecords will still indicate there are records but there are none in
            // the pageResult, then the GetAll will actually return ALL records in the db.
            if (pagedResult.Items.Any())
            {
                //Create the inner paged query that was used above to get the paged result, we'll use that as the inner sub query
                var args = sqlNodeIdsWithSort.Arguments;
                string sqlStringCount, sqlStringPage;
                Database.BuildPageQueries<TDto>(pageIndex * pageSize, pageSize, sqlNodeIdsWithSort.SQL, ref args, out sqlStringCount, out sqlStringPage);

                //We need to make this FULL query an inner join on the paged ID query
                var splitQuery = sqlQueryFull.SQL.Split(new[] { "WHERE " }, StringSplitOptions.None);
                var fullQueryWithPagedInnerJoin = new Sql(splitQuery[0])
                    .Append("INNER JOIN (")
                    //join the paged query with the paged query arguments
                    .Append(sqlStringPage, args)
                    .Append(") temp ")
                    .Append(string.Format("ON {0}.{1} = temp.{1}", nodeIdSelect.Item1, nodeIdSelect.Item2))
                    //add the original where clause back with the original arguments
                    .Where(splitQuery[1], sqlQueryIds.Arguments);

                //get sorted and filtered sql
                var fullQuery = GetSortedSqlForPagedResults(
                    GetFilteredSqlForPagedResults(fullQueryWithPagedInnerJoin, defaultFilter),
                    orderDirection, orderBy, orderBySystemField, nodeIdSelect);

                return processQuery(fullQuery, new PagingSqlQuery<TDto>(Database, sqlNodeIdsWithSort, pageIndex, pageSize));
            }
            else
            {
                result = Enumerable.Empty<TEntity>();
            }

            return result;
        }

        /// <summary>
        /// Gets the property collection for a non-paged query
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="documentDefs"></param>
        /// <returns></returns>
        protected IDictionary<Guid, PropertyCollection> GetPropertyCollection(
            Sql sql,
            IReadOnlyCollection<DocumentDefinition> documentDefs)
        {
            return GetPropertyCollection(new PagingSqlQuery(sql), documentDefs);
        }

        /// <summary>
        /// Gets the property collection for a query
        /// </summary>
        /// <param name="pagingSqlQuery"></param>
        /// <param name="documentDefs"></param>
        /// <returns></returns>
        protected IDictionary<Guid, PropertyCollection> GetPropertyCollection(
            PagingSqlQuery pagingSqlQuery,
            IReadOnlyCollection<DocumentDefinition> documentDefs)
        {
            if (documentDefs.Count == 0) return new Dictionary<Guid, PropertyCollection>();

            //initialize to the query passed in
            var docSql = pagingSqlQuery.PrePagedSql;

            //we need to parse the original SQL statement and reduce the columns to just cmsContent.nodeId, cmsContentVersion.VersionId so that we can use
            // the statement to go get the property data for all of the items by using an inner join
            var parsedOriginalSql = "SELECT {0} " + docSql.SQL.Substring(docSql.SQL.IndexOf("FROM", StringComparison.Ordinal));

            if (pagingSqlQuery.HasPaging)
            {
                //if this is a paged query, build the paged query with the custom column substitution, then re-assign
                docSql = pagingSqlQuery.BuildPagedQuery("{0}");
                parsedOriginalSql = docSql.SQL;
            }
            else if (parsedOriginalSql.InvariantContains("ORDER BY "))
            {
                //now remove everything from an Orderby clause and beyond if this is unpaged data
                parsedOriginalSql = parsedOriginalSql.Substring(0, parsedOriginalSql.LastIndexOf("ORDER BY ", StringComparison.Ordinal));
            }

            //This retrieves all pre-values for all data types that are referenced for all property types
            // that exist in the data set.
            //Benchmarks show that eagerly loading these so that we can lazily read the property data
            // below (with the use of Query intead of Fetch) go about 30% faster, so we'll eagerly load
            // this now since we cannot execute another reader inside of reading the property data.
            var preValsSql = new Sql(@"SELECT a.id, a.value, a.sortorder, a.alias, a.datatypeNodeId
FROM cmsDataTypePreValues a
WHERE EXISTS(
    SELECT DISTINCT b.id as preValIdInner
    FROM cmsDataTypePreValues b
	INNER JOIN cmsPropertyType
	ON b.datatypeNodeId = cmsPropertyType.dataTypeId
    INNER JOIN
	    (" + string.Format(parsedOriginalSql, "cmsContent.contentType") + @") as docData
    ON cmsPropertyType.contentTypeId = docData.contentType
    WHERE a.id = b.id)", docSql.Arguments);

            var allPreValues = Database.Fetch<DataTypePreValueDto>(preValsSql);

            //It's Important with the sort order here! We require this to be sorted by node id,
            // this is required because this data set can be huge depending on the page size. Due
            // to it's size we need to be smart about iterating over the property values to build
            // the document. Before we used to use Linq to get the property data for a given content node
            // and perform a Distinct() call. This kills performance because that would mean if we had 7000 nodes
            // and on each iteration we will perform a lookup on potentially 100,000 property rows against the node
            // id which turns out to be a crazy amount of iterations. Instead we know it's sorted by this value we'll
            // keep an index stored of the rows being read so we never have to re-iterate the entire data set
            // on each document iteration.
            var propSql = new Sql(@"SELECT cmsPropertyData.*
FROM cmsPropertyData
INNER JOIN cmsPropertyType
ON cmsPropertyData.propertytypeid = cmsPropertyType.id
INNER JOIN
	(" + string.Format(parsedOriginalSql, "cmsContent.nodeId, cmsContentVersion.VersionId") + @") as docData
ON cmsPropertyData.versionId = docData.VersionId AND cmsPropertyData.contentNodeId = docData.nodeId
ORDER BY contentNodeId, versionId, propertytypeid
", docSql.Arguments);

            //This does NOT fetch all data into memory in a list, this will read
            // over the records as a data reader, this is much better for performance and memory,
            // but it means that during the reading of this data set, nothing else can be read
            // from SQL server otherwise we'll get an exception.
            var allPropertyData = Database.Query<PropertyDataDto>(propSql);

            var result = new Dictionary<Guid, PropertyCollection>();
            var propertiesWithTagSupport = new Dictionary<string, SupportTagsAttribute>();
            //used to track the resolved composition property types per content type so we don't have to re-resolve (ToArray) the list every time
            var resolvedCompositionProperties = new Dictionary<int, PropertyType[]>();

            //keep track of the current property data item being enumerated
            var propertyDataSetEnumerator = allPropertyData.GetEnumerator();
            var hasCurrent = false; // initially there is no enumerator.Current

            var comparer = new DocumentDefinitionComparer(SqlSyntax);

            try
            {
                //This must be sorted by node id because this is how we are sorting the query to lookup property types above,
                // which allows us to more efficiently iterate over the large data set of property values
                foreach (var def in documentDefs.OrderBy(x => x.Id).ThenBy(x => x.Version, comparer))
                {
                    // get the resolved properties from our local cache, or resolve them and put them in cache
                    PropertyType[] compositionProperties;
                    if (resolvedCompositionProperties.ContainsKey(def.Composition.Id))
                    {
                        compositionProperties = resolvedCompositionProperties[def.Composition.Id];
                    }
                    else
                    {
                        compositionProperties = def.Composition.CompositionPropertyTypes.ToArray();
                        resolvedCompositionProperties[def.Composition.Id] = compositionProperties;
                    }

                    // assemble the dtos for this def
                    // use the available enumerator.Current if any else move to next
                    var propertyDataDtos = new List<PropertyDataDto>();
                    while (hasCurrent || propertyDataSetEnumerator.MoveNext())
                    {
                        //Not checking null on VersionId because it can never be null - no idea why it's set to nullable
                        // ReSharper disable once PossibleInvalidOperationException
                        if (propertyDataSetEnumerator.Current.VersionId.Value == def.Version)
                        {
                            hasCurrent = false; // enumerator.Current is not available
                            propertyDataDtos.Add(propertyDataSetEnumerator.Current);
                        }
                        else
                        {
                            hasCurrent = true;  // enumerator.Current is available for another def
                            break;              // no more propertyDataDto for this def
                        }
                    }

                    var properties = PropertyFactory.BuildEntity(propertyDataDtos, compositionProperties, def.CreateDate, def.VersionDate).ToArray();

                    foreach (var property in properties)
                    {
                        //NOTE: The benchmarks run with and without the following code show very little change so this is not a perf bottleneck
                        var editor = PropertyEditorResolver.Current.GetByAlias(property.PropertyType.PropertyEditorAlias);

                        var tagSupport = propertiesWithTagSupport.ContainsKey(property.PropertyType.PropertyEditorAlias)
                            ? propertiesWithTagSupport[property.PropertyType.PropertyEditorAlias]
                            : TagExtractor.GetAttribute(editor);

                        if (tagSupport != null)
                        {
                            //add to local cache so we don't need to reflect next time for this property editor alias
                            propertiesWithTagSupport[property.PropertyType.PropertyEditorAlias] = tagSupport;

                            //this property has tags, so we need to extract them and for that we need the prevals which we've already looked up
                            var preValData = allPreValues.Where(x => x.DataTypeNodeId == property.PropertyType.DataTypeDefinitionId)
                                .Distinct()
                                .ToArray();

                            var asDictionary = preValData.ToDictionary(x => x.Alias, x => new PreValue(x.Id, x.Value, x.SortOrder));

                            var preVals = new PreValueCollection(asDictionary);

                            var contentPropData = new ContentPropertyData(property.Value, preVals);

                            TagExtractor.SetPropertyTags(property, contentPropData, property.Value, tagSupport);
                        }
                    }

                    if (result.ContainsKey(def.Version))
                    {
                        var msg = string.Format("The query returned multiple property sets for document definition {0}, {1}, {2}", def.Id, def.Version, def.Composition.Name);
                        if (ThrowOnWarning)
                        {
                            throw new InvalidOperationException(msg);
                        }
                        else
                        {
                            Logger.Warn<VersionableRepositoryBase<TId, TEntity>>(msg);
                        }
                    }
                    result[def.Version] = new PropertyCollection(properties);
                }
            }
            finally
            {
                propertyDataSetEnumerator.Dispose();
            }

            return result;

        }

        protected virtual string GetDatabaseFieldNameForOrderBy(string orderBy)
        {
            // Translate the passed order by field (which were originally defined for in-memory object sorting
            // of ContentItemBasic instances) to the database field names.
            switch (orderBy.ToUpperInvariant())
            {
                case "UPDATEDATE":
                    return "cmsContentVersion.VersionDate";
                case "NAME":
                    return "umbracoNode.text";
                case "PUBLISHED":
                    return "cmsDocument.published";
                case "OWNER":
                    //TODO: This isn't going to work very nicely because it's going to order by ID, not by letter
                    return "umbracoNode.nodeUser";
                // Members only
                case "USERNAME":
                    return "cmsMember.LoginName";
                default:
                    //ensure invalid SQL cannot be submitted
                    return Regex.Replace(orderBy, @"[^\w\.,`\[\]@-]", "");
            }
        }

        protected virtual string GetEntityPropertyNameForOrderBy(string orderBy)
        {
            // Translate the passed order by field (which were originally defined for in-memory object sorting
            // of ContentItemBasic instances) to the IMedia property names.
            switch (orderBy.ToUpperInvariant())
            {
                case "OWNER":
                    //TODO: This isn't going to work very nicely because it's going to order by ID, not by letter
                    return "CreatorId";
                case "UPDATER":
                    //TODO: This isn't going to work very nicely because it's going to order by ID, not by letter
                    return "WriterId";
                case "VERSIONDATE":
                    return "UpdateDate";
                default:
                    //ensure invalid SQL cannot be submitted
                    return Regex.Replace(orderBy, @"[^\w\.,`\[\]@-]", "");
            }
        }

        /// <summary>
        /// Deletes all media files passed in.
        /// </summary>
        /// <param name="files"></param>
        /// <returns></returns>
        public virtual bool DeleteMediaFiles(IEnumerable<string> files)
        {
            //ensure duplicates are removed
            files = files.Distinct();

            var allsuccess = true;

            var fs = FileSystemProviderManager.Current.MediaFileSystem;
            Parallel.ForEach(files, file =>
            {
                try
                {
                    if (file.IsNullOrWhiteSpace()) return;

                    var relativeFilePath = fs.GetRelativePath(file);
                    if (fs.FileExists(relativeFilePath) == false) return;

                    var parentDirectory = System.IO.Path.GetDirectoryName(relativeFilePath);

                    // don't want to delete the media folder if not using directories.
                    if (_contentSection.UploadAllowDirectories && parentDirectory != fs.GetRelativePath("/"))
                    {
                        //issue U4-771: if there is a parent directory the recursive parameter should be true
                        fs.DeleteDirectory(parentDirectory, String.IsNullOrEmpty(parentDirectory) == false);
                    }
                    else
                    {
                        fs.DeleteFile(file, true);
                    }
                }
                catch (Exception e)
                {
                    Logger.Error<VersionableRepositoryBase<TId, TEntity>>("An error occurred while deleting file attached to nodes: " + file, e);
                    allsuccess = false;
                }
            });

            return allsuccess;
        }

        /// <summary>
        /// For Paging, repositories must support returning different query for the query type specified
        /// </summary>
        /// <param name="queryType"></param>
        /// <returns></returns>
        protected abstract Sql GetBaseQuery(BaseQueryType queryType);

        internal class DocumentDefinitionCollection : KeyedCollection<ValueType, DocumentDefinition>
        {
            private readonly bool _includeAllVersions;

            /// <summary>
            /// Constructor specifying if all versions should be allowed, in that case the key for the collection becomes the versionId (GUID)
            /// </summary>
            /// <param name="includeAllVersions"></param>
            public DocumentDefinitionCollection(bool includeAllVersions = false)
            {
                _includeAllVersions = includeAllVersions;
            }

            protected override ValueType GetKeyForItem(DocumentDefinition item)
            {
                return _includeAllVersions ? (ValueType)item.Version : item.Id;
            }

            /// <summary>
            /// if this key already exists if it does then we need to check
            /// if the existing item is 'older' than the new item and if that is the case we'll replace the older one
            /// </summary>
            /// <param name="item"></param>
            /// <returns></returns>
            public bool AddOrUpdate(DocumentDefinition item)
            {
                //if we are including all versions then just add, we aren't checking for latest
                if (_includeAllVersions)
                {
                    base.Add(item);
                    return true;
                }

                if (Dictionary == null)
                {
                    base.Add(item);
                    return true;
                }

                var key = GetKeyForItem(item);
                DocumentDefinition found;
                if (TryGetValue(key, out found))
                {
                    //it already exists and it's older so we need to replace it
                    if (item.VersionId > found.VersionId)
                    {
                        var currIndex = Items.IndexOf(found);
                        if (currIndex == -1)
                            throw new IndexOutOfRangeException("Could not find the item in the list: " + found.Version);

                        //replace the current one with the newer one
                        SetItem(currIndex, item);
                        return true;
                    }
                    //could not add or update
                    return false;
                }

                base.Add(item);
                return true;
            }

            public bool TryGetValue(ValueType key, out DocumentDefinition val)
            {
                if (Dictionary == null)
                {
                    val = null;
                    return false;
                }
                return Dictionary.TryGetValue(key, out val);
            }
        }

        /// <summary>
        /// A custom comparer required for sorting entities by GUIDs to match how the sorting of GUIDs works on SQL server
        /// </summary>
        /// <remarks>
        /// MySql sorts GUIDs as a string, MSSQL sorts based on byte sections, this comparer will allow sorting GUIDs to be the same as how SQL server does
        /// </remarks>
        private class DocumentDefinitionComparer : IComparer<Guid>
        {
            private readonly ISqlSyntaxProvider _sqlSyntax;

            public DocumentDefinitionComparer(ISqlSyntaxProvider sqlSyntax)
            {
                _sqlSyntax = sqlSyntax;
            }

            public int Compare(Guid x, Guid y)
            {
                //MySql sorts on GUIDs as strings (i.e. normal)
                if (_sqlSyntax is MySqlSyntaxProvider)
                {
                    return x.CompareTo(y);
                }

                //MSSQL doesn't it sorts them on byte sections!
                return new SqlGuid(x).CompareTo(new SqlGuid(y));
            }
        }

        internal class DocumentDefinition
        {
            /// <summary>
            /// Initializes a new instance of the <see cref="T:System.Object"/> class.
            /// </summary>
            public DocumentDefinition(DocumentDto dto, IContentTypeComposition composition)
            {
                DocumentDto = dto;
                ContentVersionDto = dto.ContentVersionDto;
                Composition = composition;
            }

            public DocumentDefinition(ContentVersionDto dto, IContentTypeComposition composition)
            {
                ContentVersionDto = dto;
                Composition = composition;
            }

            public DocumentDto DocumentDto { get; private set; }
            public ContentVersionDto ContentVersionDto { get; private set; }

            public int Id
            {
                get { return ContentVersionDto.NodeId; }
            }

            public Guid Version
            {
                get { return DocumentDto != null ? DocumentDto.VersionId : ContentVersionDto.VersionId; }
            }

            /// <summary>
            /// This is used to determien which version is the most recent
            /// </summary>
            public int VersionId
            {
                get { return ContentVersionDto.Id; }
            }

            public DateTime VersionDate
            {
                get { return ContentVersionDto.VersionDate; }
            }

            public DateTime CreateDate
            {
                get { return ContentVersionDto.ContentDto.NodeDto.CreateDate; }
            }

            public IContentTypeComposition Composition { get; set; }

        }

        /// <summary>
        /// An object representing a query that may contain paging information
        /// </summary>
        internal class PagingSqlQuery
        {
            public Sql PrePagedSql { get; private set; }

            public PagingSqlQuery(Sql prePagedSql)
            {
                PrePagedSql = prePagedSql;
            }

            public virtual bool HasPaging
            {
                get { return false; }
            }

            public virtual Sql BuildPagedQuery(string selectColumns)
            {
                throw new InvalidOperationException("This query has no paging information");
            }
        }

        /// <summary>
        /// An object representing a query that contains paging information
        /// </summary>
        /// <typeparam name="T"></typeparam>
        internal class PagingSqlQuery<T> : PagingSqlQuery
        {
            private readonly Database _db;
            private readonly long _pageIndex;
            private readonly int _pageSize;

            public PagingSqlQuery(Database db, Sql prePagedSql, long pageIndex, int pageSize) : base(prePagedSql)
            {
                _db = db;
                _pageIndex = pageIndex;
                _pageSize = pageSize;
            }

            public override bool HasPaging
            {
                get { return _pageSize > 0; }
            }

            /// <summary>
            /// Creates a paged query based on the original query and subtitutes the selectColumns specified
            /// </summary>
            /// <param name="selectColumns"></param>
            /// <returns></returns>
            public override Sql BuildPagedQuery(string selectColumns)
            {
                if (HasPaging == false) throw new InvalidOperationException("This query has no paging information");

                var resultSql = string.Format("SELECT {0} {1}", selectColumns, PrePagedSql.SQL.Substring(PrePagedSql.SQL.IndexOf("FROM", StringComparison.Ordinal)));

                //this query is meant to be paged so we need to generate the paging syntax
                //Create the inner paged query that was used above to get the paged result, we'll use that as the inner sub query
                var args = PrePagedSql.Arguments;
                string sqlStringCount, sqlStringPage;
                _db.BuildPageQueries<T>(_pageIndex * _pageSize, _pageSize, resultSql, ref args, out sqlStringCount, out sqlStringPage);

                return new Sql(sqlStringPage, args);
            }
        }
    }
}


text:
package com.cate.javatransmitter;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SwingContainer {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   private JLabel msglabel;
   private JLabel picLabel;

   //private ActionListener action =

   public SwingContainer(){
      prepareGUI();
   }

   /*public static void main(String[] args){
      SwingContainerDemo  swingContainerDemo = new SwingContainerDemo();
      swingContainerDemo.showJPanelDemo();
   }*/

   private void prepareGUI(){
      mainFrame = new JFrame("Java OFDM Barcode Transmitter");
      picLabel = new JLabel();
      mainFrame.setSize(600,650);
      mainFrame.setLocation(2000, 100);
      mainFrame.setLayout(new BoxLayout(mainFrame.getContentPane(), BoxLayout.PAGE_AXIS));
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }
      });
      //headerLabel = new JLabel("", JLabel.CENTER);
      headerLabel = new JLabel("Container in action: JPanel");
      headerLabel.setHorizontalTextPosition(JLabel.CENTER);
      statusLabel = new JLabel("",JLabel.CENTER);

      statusLabel.setSize(350,100);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      controlPanel.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);

      controlPanel.add(picLabel);
      mainFrame.setVisible(true);
   }

//   public void showJPanelDemo(){
//      headerLabel.setText("Container in action: JPanel");
//
//      msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial."
//         , JLabel.CENTER);
//      JPanel panel = new JPanel();
//      panel.setBackground(Color.magenta);
//      panel.setLayout(new FlowLayout());
//      //panel.add(msglabel);
//      //controlPanel.add(panel);
//   }

public void showBarcode(BufferedImage barcode){
//    BufferedImage img=null;
//    URL google = null;
//      try {
//             google = new URL("http://www.google.com/images/srpr/logo11w.png");
//        }
//      catch (IOException e) {
//    // exception handler code here
//    // ...
//        }
//
//      try{
//
//        img = ImageIO.read(google);
//
//      }
//      catch (IOException e) {
//
//      }

//      int w = img.getWidth(null);
//      int h = img.getHeight(null);
      picLabel.setIcon(new ImageIcon(barcode));
//      BufferedImage myPicture1=null;
//       try {
//           myPicture1 = ImageIO.read(new File("c:\\logo11w.png"));
//       } catch (IOException ex) {
//           Logger.getLogger(SwingContainer.class.getName()).log(Level.SEVERE, null, ex);
//       }
//      BufferedImage myPicture2=null;
//       try {
//           myPicture2 = ImageIO.read(new File("c:\\erassm.gif"));
//       } catch (IOException ex) {
//           Logger.getLogger(SwingContainer.class.getName()).log(Level.SEVERE, null, ex);
//       }

//      Timer timer;
//      for (int i=0;i<100;i++){
//        picLabel.setIcon(new ImageIcon(barcode));
//          try {
//              Thread.sleep(100);
//          } catch (InterruptedException ex) {
//              Logger.getLogger(SwingContainer.class.getName()).log(Level.SEVERE, null, ex);
//          }
//        picLabel.setIcon(new ImageIcon(myPicture1));
//          try {
//              Thread.sleep(100);
//          } catch (InterruptedException ex) {
//              Logger.getLogger(SwingContainer.class.getName()).log(Level.SEVERE, null, ex);
//          }
//        }
//    picLabel.setIcon(new ImageIcon(barcode));
    }
}


text:
package examples.stackexchange;

public class SitesWrapper {

	private Site[] api_sites;

	public Site[] getSites() {
		return api_sites;
	}

}


text:
<?php

// No direct access.
defined('_JEXEC') or die; ?>

<?php echo JHtml::_('sliders.panel', JText::_('JGLOBAL_FIELDSET_PUBLISHING'), 'publishing-details'); ?>

	<fieldset class="panelform">
	<legend class="element-invisible"><?php echo JText::_('COM_CONTENT_FIELDSET_PUBLISHING'); ?></legend>

<?php echo $this->form->getLabel('created_user_id'); ?>
			<?php echo $this->form->getInput('created_user_id'); ?>

			<?php if (intval($this->item->created_time)) : ?>

<?php echo $this->form->getLabel('created_time'); ?>
				<?php echo $this->form->getInput('created_time'); ?>

			<?php endif; ?>

			<?php if ($this->item->modified_user_id) : ?>

<?php echo $this->form->getLabel('modified_user_id'); ?>
				<?php echo $this->form->getInput('modified_user_id'); ?>

<?php echo $this->form->getLabel('modified_time'); ?>
				<?php echo $this->form->getInput('modified_time'); ?>

			<?php endif; ?>

	</fieldset>

<?php $fieldSets = $this->form->getFieldsets('params');

foreach ($fieldSets as $name => $fieldSet) :
	$label = !empty($fieldSet->label) ? $fieldSet->label : 'COM_CATEGORIES_'.$name.'_FIELDSET_LABEL';
	echo JHtml::_('sliders.panel', JText::_($label), $name.'-options');
	if (isset($fieldSet->description) && trim($fieldSet->description)) :
		echo '
'.$this->escape(JText::_($fieldSet->description)).'
';
	endif;
	?>
	<fieldset class="panelform">
	<legend class="element-invisible"><?php echo JText::_($label); ?></legend>

		<?php foreach ($this->form->getFieldset($name) as $field) : ?>

<?php echo $field->label; ?>
			<?php echo $field->input; ?>

		<?php endforeach; ?>

		<?php if ($name=='basic'):?>

<?php echo $this->form->getLabel('note'); ?>
			<?php echo $this->form->getInput('note'); ?>

		<?php endif;?>

	</fieldset>
<?php endforeach; ?>


text:
using ExtendedXmlSerializer.ExtensionModel.Types;
using System;
using System.Reflection;

namespace ExtendedXmlSerializer.ReflectionModel
{
	static class Support<T>
	{
		public static Type Key { get; } = typeof(T);

		public static TypeInfo Metadata { get; } = typeof(T).GetTypeInfo();

		public static Func<T> New { get; } = DefaultActivators.Default.New<T>;

		public static Func<T> NewOrSingleton { get; } = Activators.Default.New<T>;
	}
}


text:
#import "AgoraChatVideoBubbleView.h"

#import "AgoraMessageModel.h"

#define MAX_SIZE 250

@interface AgoraChatVideoBubbleView ()

@property (strong, nonatomic) UIButton *videoPlayButton;

@end

@implementation AgoraChatVideoBubbleView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer.masksToBounds = YES;
        self.contentMode = UIViewContentModeScaleAspectFill;
        self.layer.cornerRadius = 10.f;

        self.videoPlayButton = [UIButton buttonWithType:UIButtonTypeCustom];
        UIImage *backgroundImage = [UIImage imageNamed:@"Icon_Play"];
        [self.videoPlayButton setBackgroundImage:backgroundImage forState:UIControlStateNormal];
        [self addSubview:self.videoPlayButton];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    CGFloat width = 50.0f;
    CGFloat height = 50.0f;
    CGFloat x = self.frame.size.width/2 - width/2;
    CGFloat y = self.frame.size.height/2 - height/2;
    [self.videoPlayButton setFrame:CGRectMake(x, y, width, height)];
}

- (CGSize)sizeThatFits:(CGSize)size
{
    CGSize retSize;
    VideoMessageBody *body = (VideoMessageBody*)self.model.message.body;
    if (self.model.message.ext) {
        retSize = CGSizeMake(0, 0);
    } else {
        retSize = body.thumbnailSize;
    }
    if (retSize.width == 0 || retSize.height == 0) {
        retSize.width = MAX_SIZE;
        retSize.height = MAX_SIZE;
    }
    if (retSize.width > retSize.height) {
        CGFloat height =  MAX_SIZE / retSize.width  *  retSize.height;
        retSize.height = height;
        retSize.width = MAX_SIZE;
    }else {
        CGFloat width = MAX_SIZE / retSize.height * retSize.width;
        retSize.width = width;
        retSize.height = MAX_SIZE;
    }
    if (self.model.message.ext) {
        retSize.height = MAX_SIZE / 4 * 3;
    }
    return retSize;
}

- (void)setModel:(AgoraMessageModel*)model;
{
    [super setModel:model];

    VideoMessageBody *videoBody = (VideoMessageBody *)model.message.body;
    if ([videoBody.thumbnailLocalPath length] > 0) {
        NSData *thumbnailImageData = [NSData dataWithContentsOfFile:videoBody.thumbnailLocalPath];
        if (thumbnailImageData.length) {
            self.backImageView.image = [UIImage imageWithData:thumbnailImageData];
        }
    } else {
        [self.backImageView sd_setImageWithURL:[NSURL URLWithString:videoBody.thumbnailRemotePath] placeholderImage:nil];
    }
}

+ (CGFloat)heightForBubbleWithMessageModel:(AgoraMessageModel *)model
{
    CGSize retSize;
    VideoMessageBody *body = (VideoMessageBody*)model.message.body;
    if (model.message.ext) {
        retSize = CGSizeMake(0, 0);
    } else {
        retSize = body.thumbnailSize;
    }
    if (retSize.width == 0 || retSize.height == 0) {
        retSize.width = MAX_SIZE;
        retSize.height = MAX_SIZE;
    }
    if (retSize.width > retSize.height) {
        CGFloat height =  MAX_SIZE / retSize.width  *  retSize.height;
        retSize.height = height;
        retSize.width = MAX_SIZE;
    }else {
        CGFloat width = MAX_SIZE / retSize.height * retSize.width;
        retSize.width = width;
        retSize.height = MAX_SIZE;
    }
    if (model.message.ext) {
        retSize.height = MAX_SIZE / 4 * 3;
    }

    return retSize.height;
}

@end


text:
%/* ----------------------------------------------------------- */
%/*                                                             */
%/*                          ___                                */
%/*                       |_| | |_/   SPEECH                    */
%/*                       | | | | \   RECOGNITION               */
%/*                       =========   SOFTWARE                  */
%/*                                                             */
%/*                                                             */
%/* ----------------------------------------------------------- */
%/*         Copyright: Microsoft Corporation                    */
%/*          1995-2000 Redmond, Washington USA                  */
%/*                    http://www.microsoft.com                */
%/*                                                             */
%/*   Use of this software is governed by a License Agreement   */
%/*    ** See the file License for the Conditions of Use  **    */
%/*    **     This banner notice must not be removed      **    */
%/*                                                             */
%/* ----------------------------------------------------------- */
%
% HTKBook - Steve Young and Dave Ollason  11/11/95
%

\newpage
\mysect{HSmooth}{HSmooth}

\mysubsect{Function}{HSmooth-Function}

\index{hsmooth@\htool{HSmooth}|(}
This program is used to smooth a set of context-dependent tied mixture
or discrete HMM's using deleted interpolation.
The program operates as a replacement for the second pass of \htool{HERest}
when working in {\it parallel mode}\footnote{It is not,of course,
necessary to have multiple processors to use this program since each
`parallel' activation can be executed sequentially on a single
processor}.  It reads in the $N$ sets of accumulator files containing the
statistics accumulated during the first pass and then interpolates the
mixture weights between each context dependent model and its corresponding
context independent version.  The interpolation weights are chosen to
maximise the likelihood of each deleted block with respect to the
probability distributions estimated from all other blocks.

\mysubsect{Use}{HSmooth-Use}

\htool{HSmooth} is invoked via the command line
\begin{verbatim}
   HSmooth [options] hmmList accFile ...
\end{verbatim}
where {\tt hmmList} contains the list of context dependent models
to be smoothed and each {\tt accFile} is a file of the form
{\tt HERN.acc} dumped by a previous execution of \htool{HERest} with the {\tt -p}
option set to {\tt N}.  The HMM definitions are loaded and then for
every state and stream of every context dependent model X, the optimal
interpolation weight is found for smoothing between the mixture
weights determined from the X accumulators alone and those determined
from the context independent version of X.  The latter is computed simply
by summing the accumulators across all context dependent allophones of X.

The detailed operation of \htool{HSmooth} is controlled by the following
command line options
\begin{optlist}
  \ttitem{-b f}  Set the value of epsilon for convergence
      in the binary chop  optimisation procedure to {\tt f}.
       The binary chop  optimisation procedure for each
       interpolation weight terminates when the gradient is
       within epsilon of zero (default 0.001).

  \ttitem{-c N}  Set maximum number of interpolation iterations
       for the binary chop  optimisation procedure to be N
       (default 16).

\ttitem{-d dir} Normally \htool{HSmooth} expects to find the HMM definitions
      in the current directory.  This option tells \htool{HSmooth} to look in
      the directory {\tt dir} to find them.

   \ttitem{-m N}  Set the minimum number of training examples
    required for any model to {\tt N}.  If the actual number
    falls below this value, the HMM is not updated and the original
    parameters are used for the new version (default value 1).

  \ttitem{-o ext}  This causes the file name extensions of the
      original models (if any) to be replaced by {\tt ext}.

  \ttitem{-s file} This causes statistics on occupation of each
      state to be output to the named file.

  \ttitem{-u flags} By default, \htool{HSmooth} updates all of the HMM parameters,
      that is, means, variances and transition probabilities. This
      option causes just the parameters indicated by the {\tt flags}
      argument to be updated, this argument is a string containing one
      or more of the letters {\tt m} (mean), {\tt v} (variance) ,
      {\tt t} (transition) and {\tt w} (mixture weight).  The
      presence of a letter enables
      the updating of the corresponding parameter set.

  \ttitem{-v f}  This sets the minimum variance (i.e. diagonal element of
      the covariance matrix) to the real value {\tt f} (default value
      0.0).

  \ttitem{-w f}  Any mixture weight which falls below the global
            constant {\tt MINMIX} is treated as being zero.
      When this parameter is  set,  all mixture weights  are floored
      to {\tt f * MINMIX}.

  \ttitem{-x ext}  By default, \htool{HSmooth} expects a HMM definition for
      the model X to be stored in a file called {\tt X}.  This
      option causes \htool{HSmooth} to look for the HMM definition in the
      file {\tt X.ext}.

\stdoptB
\stdoptH
\stdoptM

\end{optlist}
\stdopts{HSmooth}

\mysubsect{Tracing}{HSmooth-Tracing}

\htool{HSmooth} supports the following trace options where each
trace flag is given using an octal base
\begin{optlist}
   \ttitem{00001} basic progress reporting.
   \ttitem{00002} show interpolation weights.
   \ttitem{00004} give details of optimisation algorithm.
\end{optlist}
Trace flags are set using the \texttt{-T} option or the  \texttt{TRACE}
configuration variable.
\index{hsmooth@\htool{HSmooth}|)}

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "../htkbook"
%%% End: