text:
package com.hast.exchangerate.general.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

import com.hast.exchangerate.App;
import com.hast.rateofexchange.R;
import com.hast.exchangerate.general.models.UnifiedBankResponse;
import com.hast.exchangerate.general.models.WidgetInfo;
import com.hast.exchangerate.mvp.presenters.IWidgetPresenter;
import com.hast.exchangerate.mvp.views.IWidgetView;

import javax.inject.Inject;

/**
 * Created by Konstantyn Zakharchenko on 24.05.2017.
 */

public class WidgetProvider extends AppWidgetProvider implements IWidgetView {
    @Inject
    IWidgetPresenter presenter;

    AppWidgetManager appWidgetManager;
    Context context;
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        this.context = context;
        // Retrieve the widget's layout//
        this.appWidgetManager = appWidgetManager;
        App.getAppComponent().inject(this);
        presenter.setView(this);
        //views = new RemoteViews(context.getPackageName(), R.layout.activity_main);

        ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);

        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
        for (int widgetId : allWidgetIds) {
            // create some random data
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
            Log.w("WidgetExample", "works");
            // Set the text

            // Register an onClickListener
            Intent intent = new Intent(context, WidgetProvider.class);

            intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                    0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            views.setOnClickPendingIntent(R.id.update, pendingIntent);
            presenter.getBankData(widgetId);

        }

// Tell the AppWidgetManager to perform an update on this application widget//
//        appWidgetManager.updateAppWidget(currentWidgetId, views);
    }

    @Override
    public void onError() {

    }

    @Override
    public void onStartLoading() {

    }

    @Override
    public void onFinishLoading() {

    }

    @Override
    public void showResponse(WidgetInfo widgetInfo, UnifiedBankResponse bankResponse) {
        Log.d("showResponse", "done");
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
        views.setTextViewText(R.id.bankName, widgetInfo.getChoosenBank().name());
        views.setTextViewText(R.id.rateToBuy, "" + bankResponse.getBuy());
        views.setTextViewText(R.id.rateToSale, "" + bankResponse.getSale());
        appWidgetManager.updateAppWidget(widgetInfo.getWidgetId(), views);
    }
}


text:
#ifndef _CUEIFY_SESSIONS_PRIVATE_H
#define _CUEIFY_SESSIONS_PRIVATE_H

#include <cueify/types.h>
#include "device_private.h"

/** Internal structure to hold multi-session data. */
typedef struct {
    /** Number of the first session in the TOC. */
    uint8_t first_session_number;
    /** Number of the last session in the TOC. */
    uint8_t last_session_number;
    /** Sub-Q-channel content format of the first track in the last session. */
    uint8_t track_adr;
    /** Track control flags of the first track in the last session. */
    uint8_t track_control;
    /** Track number of the first track in the last session. */
    uint8_t track_number;
    /** Offset of the start of the first track in the last session (LBA). */
    uint32_t track_lba;
} cueify_sessions_private;

/**
 * Unportable read of the multisession TOC of the disc in the optical
 * disc device associated with a device handle.
 *
 * @param d an opened device handle
 * @param s a multisession instance to populate
 * @return CUEIFY_OK if the multisession data was successfully read;
 *         otherwise an appropriate error code is returned
 */
int cueify_device_read_sessions_unportable(cueify_device_private *d,
					   cueify_sessions_private *s);

#endif  /* _CUEIFY_SESSIONS_PRIVATE_H */

redpajama_set_name: RedPajamaGithub


text:
package io.cdap.plugin;

import io.cdap.cdap.api.artifact.ArtifactSummary;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.cdap.api.data.schema.Schema;
import io.cdap.cdap.api.dataset.table.Table;
import io.cdap.cdap.datapipeline.DataPipelineApp;
import io.cdap.cdap.datapipeline.SmartWorkflow;
import io.cdap.cdap.etl.api.batch.BatchAggregator;
import io.cdap.cdap.etl.mock.batch.MockSink;
import io.cdap.cdap.etl.mock.batch.MockSource;
import io.cdap.cdap.etl.mock.test.HydratorTestBase;
import io.cdap.cdap.etl.proto.v2.ETLBatchConfig;
import io.cdap.cdap.etl.proto.v2.ETLPlugin;
import io.cdap.cdap.etl.proto.v2.ETLStage;
import io.cdap.cdap.proto.ProgramRunStatus;
import io.cdap.cdap.proto.artifact.AppRequest;
import io.cdap.cdap.proto.id.ApplicationId;
import io.cdap.cdap.proto.id.ArtifactId;
import io.cdap.cdap.proto.id.NamespaceId;
import io.cdap.cdap.test.ApplicationManager;
import io.cdap.cdap.test.DataSetManager;
import io.cdap.cdap.test.TestConfiguration;
import io.cdap.cdap.test.WorkflowManager;
import io.cdap.plugin.statistics.StatisticsOld;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Unit tests for our plugins.
 */
public class PipelineTest extends HydratorTestBase {
  private static final ArtifactSummary APP_ARTIFACT = new ArtifactSummary("data-pipeline", "1.0.0");
  @ClassRule
  public static final TestConfiguration CONFIG = new TestConfiguration("explore.enabled", false);

  @BeforeClass
  public static void setupTestClass() throws Exception {
    ArtifactId parentArtifact = NamespaceId.DEFAULT.artifact(APP_ARTIFACT.getName(), APP_ARTIFACT.getVersion());

    // add the data-pipeline artifact and mock plugins
    setupBatchArtifacts(parentArtifact, DataPipelineApp.class);

    // add our plugins artifact with the data-pipeline artifact as its parent.
    // this will make our plugins available to data-pipeline.
    addPluginArtifact(NamespaceId.DEFAULT.artifact("example-plugins", "1.0.0"),
                      parentArtifact,
                      DataProfiler.class);
  }

  @Test
  public void testStringCaseTransform() throws Exception {
    String inputName = "input";
    String outputName = "output";

    // write the input
    Schema schema = Schema.recordOf(
      "data",
      Schema.Field.of("s", Schema.nullableOf(Schema.of(Schema.Type.STRING))),
      Schema.Field.of("i", Schema.nullableOf(Schema.of(Schema.Type.INT))),
      Schema.Field.of("l", Schema.nullableOf(Schema.of(Schema.Type.LONG))),
      Schema.Field.of("f", Schema.nullableOf(Schema.of(Schema.Type.FLOAT))),
      Schema.Field.of("d", Schema.nullableOf(Schema.of(Schema.Type.DOUBLE))),
      Schema.Field.of("b", Schema.nullableOf(Schema.of(Schema.Type.BOOLEAN))));

    // create the pipeline config
    ETLBatchConfig pipelineConfig = ETLBatchConfig.builder("* * * * *")
      .addStage(new ETLStage("source", MockSource.getPlugin(inputName, schema)))
      .addStage(new ETLStage("sink", MockSink.getPlugin(outputName)))
      .addStage(new ETLStage("fieldStats", new ETLPlugin(DataProfiler.NAME, BatchAggregator.PLUGIN_TYPE,
                                                         ImmutableMap.<String, String>of())))
      .addConnection("source", "fieldStats")
      .addConnection("fieldStats", "sink")
      .build();

    // create the pipeline
    ApplicationId pipelineId = NamespaceId.DEFAULT.app("testPipeline");
    ApplicationManager appManager = deployApplication(pipelineId, new AppRequest<>(APP_ARTIFACT, pipelineConfig));

    List<StructuredRecord> input = ImmutableList.of(
      StructuredRecord.builder(schema)
        .set("s", "ab").set("i", 0).set("l", 0L).set("f", 0f).set("d", 0d).set("b", true).build(),
      StructuredRecord.builder(schema)
        .set("s", "xy").set("i", -10).set("l", -10L).set("f", -10f).set("d", -10d).set("b", true).build(),
      StructuredRecord.builder(schema)
        .set("s", "a").set("i", 10).set("l", 10L).set("f", 10f).set("d", 10d).set("b", false).build(),
      StructuredRecord.builder(schema)
        .set("s", "").set("i", 0).set("l", 0L).set("f", 0f).set("d", 0d).set("b", false).build(),
      StructuredRecord.builder(schema).build());

    DataSetManager<Table> inputManager = getDataset(inputName);
    MockSource.writeInput(inputManager, input);

    WorkflowManager workflowManager = appManager.getWorkflowManager(SmartWorkflow.NAME);
    workflowManager.start();
    workflowManager.waitForRun(ProgramRunStatus.COMPLETED, 4, TimeUnit.MINUTES);

    // check output
    StatisticsOld stats = new StatisticsOld();
    Set<StructuredRecord> expected = new HashSet<>();
    for (Schema.Field field : schema.getFields()) {
      stats.reset();
      String fieldName = field.getName();
      Schema fieldSchema = field.getSchema();
      Schema.Type fieldType = fieldSchema.isNullable() ? fieldSchema.getNonNullable().getType() : fieldSchema.getType();
      for (StructuredRecord record : input) {
        stats.update(fieldType, record.get(fieldName));
      }
      expected.add(stats.toRecord(fieldName));
    }

    DataSetManager<Table> outputManager = getDataset(outputName);
    List<StructuredRecord> outputRecords = MockSink.readOutput(outputManager);
    Assert.assertEquals(expected.size(), outputRecords.size());
    // TODO: Compare the values.
  }
}


text:
from __future__ import unicode_literals

import json

import boto
import boto.s3
import boto.s3.key
import boto.cloudformation
from boto.exception import BotoServerError
import sure  # noqa
# Ensure 'assert_raises' context manager support for Python 2.6
import tests.backport_assert_raises  # noqa
from nose.tools import assert_raises

from moto import mock_cloudformation, mock_s3

dummy_template = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Stack 1",
    "Resources": {},
}

dummy_template2 = {
    "AWSTemplateFormatVersion": "2010-09-09",
    "Description": "Stack 2",
    "Resources": {},
}

dummy_template_json = json.dumps(dummy_template)
dummy_template_json2 = json.dumps(dummy_template2)

@mock_cloudformation
def test_create_stack():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks()[0]
    stack.stack_name.should.equal('test_stack')
    stack.get_template().should.equal(dummy_template)

@mock_cloudformation
def test_creating_stacks_across_regions():
    west1_conn = boto.cloudformation.connect_to_region("us-west-1")
    west1_conn.create_stack("test_stack", template_body=dummy_template_json)

    west2_conn = boto.cloudformation.connect_to_region("us-west-2")
    west2_conn.create_stack("test_stack", template_body=dummy_template_json)

    list(west1_conn.describe_stacks()).should.have.length_of(1)
    list(west2_conn.describe_stacks()).should.have.length_of(1)

@mock_cloudformation
def test_create_stack_with_notification_arn():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack_with_notifications",
        template_body=dummy_template_json,
        notification_arns='arn:aws:sns:us-east-1:123456789012:fake-queue'
    )

    stack = conn.describe_stacks()[0]
    [n.value for n in stack.notification_arns].should.contain('arn:aws:sns:us-east-1:123456789012:fake-queue')

@mock_cloudformation
@mock_s3
def test_create_stack_from_s3_url():
    s3_conn = boto.s3.connect_to_region('us-west-1')
    bucket = s3_conn.create_bucket("foobar")
    key = boto.s3.key.Key(bucket)
    key.key = "template-key"
    key.set_contents_from_string(dummy_template_json)
    key_url = key.generate_url(expires_in=0, query_auth=False)

    conn = boto.cloudformation.connect_to_region('us-west-1')
    conn.create_stack('new-stack', template_url=key_url)

    stack = conn.describe_stacks()[0]
    stack.stack_name.should.equal('new-stack')
    stack.get_template().should.equal(dummy_template)

@mock_cloudformation
def test_describe_stack_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack.stack_name.should.equal('test_stack')

@mock_cloudformation
def test_describe_stack_by_stack_id():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack_by_id = conn.describe_stacks(stack.stack_id)[0]
    stack_by_id.stack_id.should.equal(stack.stack_id)
    stack_by_id.stack_name.should.equal("test_stack")

@mock_cloudformation
def test_describe_deleted_stack():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    stack = conn.describe_stacks("test_stack")[0]
    stack_id = stack.stack_id
    conn.delete_stack(stack.stack_id)
    stack_by_id = conn.describe_stacks(stack_id)[0]
    stack_by_id.stack_id.should.equal(stack.stack_id)
    stack_by_id.stack_name.should.equal("test_stack")
    stack_by_id.stack_status.should.equal("DELETE_COMPLETE")

@mock_cloudformation
def test_get_template_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    template = conn.get_template("test_stack")
    template.should.equal(dummy_template)

@mock_cloudformation
def test_list_stacks():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )
    conn.create_stack(
        "test_stack2",
        template_body=dummy_template_json,
    )

    stacks = conn.list_stacks()
    stacks.should.have.length_of(2)
    stacks[0].template_description.should.equal("Stack 1")

@mock_cloudformation
def test_delete_stack_by_name():
    conn = boto.connect_cloudformation()
    conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    conn.list_stacks().should.have.length_of(1)
    conn.delete_stack("test_stack")
    conn.list_stacks().should.have.length_of(0)

@mock_cloudformation
def test_delete_stack_by_id():
    conn = boto.connect_cloudformation()
    stack_id = conn.create_stack(
        "test_stack",
        template_body=dummy_template_json,
    )

    conn.list_stacks().should.have.length_of(1)
    conn.delete_stack(stack_id)
    conn.list_stacks().should.have.length_of(0)
    with assert_raises(BotoServerError):
        conn.describe_stacks("test_stack")

    conn.describe_stacks(stack_id).should.have.length_of(1)

@mock_cloudformation
def test_bad_describe_stack():
    conn = boto.connect_cloudformation()
    with assert_raises(BotoServerError):
        conn.describe_stacks("bad_stack")

@mock_cloudformation()
def test_cloudformation_params():
    dummy_template = {
        "AWSTemplateFormatVersion": "2010-09-09",
        "Description": "Stack 1",
        "Resources": {},
        "Parameters": {
            "APPNAME": {
                "Default": "app-name",
                "Description": "The name of the app",
                "Type": "String"
            }
        }
    }
    dummy_template_json = json.dumps(dummy_template)
    cfn = boto.connect_cloudformation()
    cfn.create_stack('test_stack1', template_body=dummy_template_json, parameters=[('APPNAME', 'testing123')])
    stack = cfn.describe_stacks('test_stack1')[0]
    stack.parameters.should.have.length_of(1)
    param = stack.parameters[0]
    param.key.should.equal('APPNAME')
    param.value.should.equal('testing123')

# @mock_cloudformation
# def test_update_stack():
#     conn = boto.connect_cloudformation()
#     conn.create_stack(
#         "test_stack",
#         template_body=dummy_template_json,
#     )

#     conn.update_stack("test_stack", dummy_template_json2)

#     stack = conn.describe_stacks()[0]
#     stack.get_template().should.equal(dummy_template2)


text:
'''The story module.'''

from . import views


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Group do
  before(:each) do
    @group = groups(:public)
    @private_group = groups(:private)
    @hidden_group = groups(:hidden)
  end

  describe "attributes" do
    it "should be valid" do
      create_group.should be_valid
    end

    it "should require name" do
      p = create_group(:name => nil)
      p.errors.on(:name).should_not be_nil
    end

    it "should be valid even with a nil description" do
      p = create_group(:description => nil)
      p.should be_valid
    end
  end

  describe "callbacks" do
    it "should create membership for owner upon group create" do
      g = create_group(:save => true)
      g.dogs.should contain(g.owner)
    end
  end

  describe "length validations" do
    it "should enforce a maximum name length" do
      @group.should have_maximum(:name, Group::MAX_NAME)
    end

    it "should enforce a maximum description length" do
      @group.should have_maximum(:description, Group::MAX_DESCRIPTION)
    end
  end

  describe "activity associations" do

#    it "should log an activity if description changed" do
#      @group.update_attributes(:description => "New Description")
#      activity = Activity.find_by_item_id(@group)
#      Activity.global_feed.should contain(activity)
#    end
#
#    it "should not log an activity if description didn't change" do
#      @group.save!
#      activity = Activity.find_by_item_id(@group)
#      Activity.global_feed.should_not contain(activity)
#    end

# TODO : need activity to be polymorphic for this to work
#    it "should disappear if the group is destroyed" do
#      group = create_group(:save => true)
#      group.update_attributes(:name => "New name")
#
#      Activity.find_all_by_dog_id(group.owner).should_not be_empty
#      group.destroy
#      Activity.find_all_by_dog_id(group.owner).should be_empty
#      Feed.find_all_by_dog_id(group.owner).should be_empty
#    end

    it "should log an activity when the group is created" do
      lambda do
        group = create_group(:save => true)
      end.should change(Activity, :count).by(2)
    end
  end

  describe "utility methods" do
    it "should have the right to_param method" do
      # Dog params should have the form '1-michael-hartl'.
      param = "#{@group.id}-public"
      @group.to_param.should == param
    end

    it "should have a safe uri" do
      @group.name = "Michael & Hartl"
      param = "#{@group.id}-michael-and-hartl"
      @group.to_param.should == param
    end

    it "should identify public groups" do
      @group.public?.should == true
      @private_group.public?.should == false
    end

    it "should identify private groups" do
      @private_group.private?.should == true
      @group.private?.should == false
    end

    it "should identify hidden groups" do
      @hidden_group.hidden?.should == true
      @group.hidden?.should == false
    end

    it "should check if the person is the owner of the group" do
      @group.owner?(people(:quentin)).should == true
      @group.owner?(people(:aaron)).should == false
    end

    it "should identify people with invited dogs" do
      @group.has_invited?(dogs(:buba)).should == true
      @group.has_invited?(dogs(:dana)).should == false
    end

    it "should return owner's owner as person" do
      @group.person.should == @group.owner.owner
    end
  end

  describe "associations" do

    before(:each) do
      @member = dogs(:max)
    end

    describe "memberships" do
      it "should have memberships" do
        @group.memberships.should_not be_nil
      end

      describe "accepted" do
        it "should have dogs" do
          @group.dogs.should contain(dogs(:nola))
        end

        it "should exclude dogs with inactive owners" do
          member = dogs(:nola)
          @group.dogs.should contain(member)
          member.owner.toggle!(:deactivated)
          @group.reload.dogs.should_not contain(member)
        end

        it "should exclude deactivated dogs" do
          member = dogs(:nola)
          @group.dogs.should contain(member)
          member.toggle!(:deactivated)
          @group.reload.dogs.should_not contain(member)
        end
      end

      describe "pending requests" do
        it "should have pending membership requests" do
          @private_group.pending_requests.should contain(dogs(:buba))
        end

        it "should exclude dogs with inactive owners" do
          member = dogs(:buba)
          @private_group.pending_requests.should contain(member)
          member.owner.toggle!(:deactivated)
          @private_group.reload.pending_requests.should_not contain(member)
        end

        it "should exclude deactivated dogs" do
          member = dogs(:buba)
          @private_group.pending_requests.should contain(member)
          member.toggle!(:deactivated)
          @private_group.reload.pending_requests.should_not contain(member)
        end
      end

      describe "pending invitations" do
        it "should have pending membership invitations" do
          @hidden_group.pending_invitations.should contain(dogs(:dana))
        end

        it "should exclude dogs with inactive owners" do
          member = dogs(:dana)
          @hidden_group.pending_invitations.should contain(member)
          member.owner.toggle!(:deactivated)
          @hidden_group.reload.pending_invitations.should_not contain(member)
        end

        it "should exclude deactivated dogs" do
          member = dogs(:dana)
          @hidden_group.pending_invitations.should contain(member)
          member.toggle!(:deactivated)
          @hidden_group.reload.pending_invitations.should_not contain(member)
        end
      end
    end

    it "should have associated photos" do
      @group.photos.should_not be_nil
    end

    it "should not currently have any photos" do
      @group.photos.should be_empty
    end

    it "should have an associated blog on creation" do
      group = create_group(:save => true)
      group.blog.should_not be_nil
    end

    it "should have many wall comments" do
      @group.comments.should be_a_kind_of(Array)
      @group.comments.should_not be_empty
    end

    it "should have many people" do
      @group.people.should_not be_nil
    end

    it "should have an owner" do
      @group.owner.should == dogs(:dana)
    end

    it "should have associated galleries" do
      @group.galleries.should_not be_nil
    end

    it "should have associated events" do
      @private_group.events.should_not be_nil
      @private_group.events.should be_a_kind_of(Array)
    end
  end

  describe "photo methods" do

    before(:each) do
      @photo_1 = mock_photo(:avatar => true)
      @photo_2 = mock_photo
      @photos = [@photo_1, @photo_2]
      @photos.stub!(:find_all_by_avatar).and_return([@photo_1])
      @group.stub!(:photos).and_return(@photos)
    end

    it "should have a photo method" do
      @group.should respond_to(:photo)
    end

    it "should have a non-nil primary photo" do
      @group.photo.should_not be_nil
    end

    it "should have other photos" do
      @group.other_photos.should_not be_empty
    end

    it "should have the right other photos" do
      @group.other_photos.should == (@photos - [@group.photo])
    end

    it "should have a main photo" do
      @group.main_photo.should == @group.photo.public_filename
    end

    it "should have a thumbnail" do
      @group.thumbnail.should_not be_nil
    end

    it "should have an icon" do
      @group.icon.should_not be_nil
    end

    it "should have sorted photos" do
      @group.sorted_photos.should == [@photo_1, @photo_2]
    end
  end

  describe "class methods" do
    it "should not return hidden groups" do
      Group.not_hidden.should_not contain(@hidden_group)
    end

    it "should return public groups" do
      Group.not_hidden.should contain(@group)
    end

    it "should return private groups" do
      Group.not_hidden.should contain(@private_group)
    end
  end

  protected

    def create_group(options = {})
      record = dogs(:dana).groups.build({ :name => 'Group', :description => 'A new group', :mode => 0 }.merge(options))
      record.valid?
      record.save! if options[:save]
      record
    end
end


text:
package datadog

type TextSize struct {
	Size *int
	Auto *bool
}

type TileDef struct {
	Events   []TileDefEvent      `json:"events,omitempty"`
	Markers  []TimeseriesMarker  `json:"markers,omitempty"`
	Requests []TimeseriesRequest `json:"requests,omitempty"`
	Viz      *string             `json:"viz,omitempty"`
}

type TimeseriesRequest struct {
	Query              *string                 `json:"q,omitempty"`
	Type               *string                 `json:"type,omitempty"`
	ConditionalFormats []ConditionalFormat     `json:"conditional_formats,omitempty"`
	Style              *TimeseriesRequestStyle `json:"style,omitempty"`
}

type TimeseriesRequestStyle struct {
	Palette *string `json:"palette,omitempty"`
}

type TimeseriesMarker struct {
	Label *string `json:"label,omitempty"`
	Type  *string `json:"type,omitempty"`
	Value *string `json:"value,omitempty"`
}

type TileDefEvent struct {
	Query *string `json:"q"`
}

type AlertValueWidget struct {
	TitleSize    *int    `json:"title_size,omitempty"`
	Title        *bool   `json:"title,omitempty"`
	TitleAlign   *string `json:"title_align,omitempty"`
	TextAlign    *string `json:"text_align,omitempty"`
	TitleText    *string `json:"title_text,omitempty"`
	Precision    *int    `json:"precision,omitempty"`
	AlertId      *int    `json:"alert_id,omitempty"`
	Timeframe    *string `json:"timeframe,omitempty"`
	AddTimeframe *bool   `json:"add_timeframe,omitempty"`
	Y            *int    `json:"y,omitempty"`
	X            *int    `json:"x,omitempty"`
	TextSize     *string `json:"text_size,omitempty"`
	Height       *int    `json:"height,omitempty"`
	Width        *int    `json:"width,omitempty"`
	Type         *string `json:"type,omitempty"`
	Unit         *string `json:"unit,omitempty"`
}

type ChangeWidget struct {
	TitleSize  *int     `json:"title_size,omitempty"`
	Title      *bool    `json:"title,omitempty"`
	TitleAlign *string  `json:"title_align,omitempty"`
	TitleText  *string  `json:"title_text,omitempty"`
	Height     *int     `json:"height,omitempty"`
	Width      *int     `json:"width,omitempty"`
	X          *int     `json:"y,omitempty"`
	Y          *int     `json:"x,omitempty"`
	Aggregator *string  `json:"aggregator,omitempty"`
	TileDef    *TileDef `json:"tile_def,omitempty"`
}

type GraphWidget struct {
	TitleSize  *int     `json:"title_size,omitempty"`
	Title      *bool    `json:"title,omitempty"`
	TitleAlign *string  `json:"title_align,omitempty"`
	TitleText  *string  `json:"title_text,omitempty"`
	Height     *int     `json:"height,omitempty"`
	Width      *int     `json:"width,omitempty"`
	X          *int     `json:"y,omitempty"`
	Y          *int     `json:"x,omitempty"`
	Type       *string  `json:"type,omitempty"`
	Timeframe  *string  `json:"timeframe,omitempty"`
	LegendSize *int     `json:"legend_size,omitempty"`
	Legend     *bool    `json:"legend,omitempty"`
	TileDef    *TileDef `json:"tile_def,omitempty"`
}

type EventTimelineWidget struct {
	TitleSize  *int    `json:"title_size,omitempty"`
	Title      *bool   `json:"title,omitempty"`
	TitleAlign *string `json:"title_align,omitempty"`
	TitleText  *string `json:"title_text,omitempty"`
	Height     *int    `json:"height,omitempty"`
	Width      *int    `json:"width,omitempty"`
	X          *int    `json:"y,omitempty"`
	Y          *int    `json:"x,omitempty"`
	Type       *string `json:"type,omitempty"`
	Timeframe  *string `json:"timeframe,omitempty"`
	Query      *string `json:"query,omitempty"`
}

type AlertGraphWidget struct {
	TitleSize    *int    `json:"title_size,omitempty"`
	VizType      *string `json:"timeseries,omitempty"`
	Title        *bool   `json:"title,omitempty"`
	TitleAlign   *string `json:"title_align,omitempty"`
	TitleText    *string `json:"title_text,omitempty"`
	Height       *int    `json:"height,omitempty"`
	Width        *int    `json:"width,omitempty"`
	X            *int    `json:"y,omitempty"`
	Y            *int    `json:"x,omitempty"`
	AlertId      *int    `json:"alert_id,omitempty"`
	Timeframe    *string `json:"timeframe,omitempty"`
	Type         *string `json:"type,omitempty"`
	AddTimeframe *bool   `json:"add_timeframe,omitempty"`
}

type HostMapWidget struct {
	TitleSize  *int     `json:"title_size,omitempty"`
	Title      *bool    `json:"title,omitempty"`
	TitleAlign *string  `json:"title_align,omitempty"`
	TitleText  *string  `json:"title_text,omitempty"`
	Height     *int     `json:"height,omitempty"`
	Width      *int     `json:"width,omitempty"`
	X          *int     `json:"y,omitempty"`
	Y          *int     `json:"x,omitempty"`
	Query      *string  `json:"query,omitempty"`
	Timeframe  *string  `json:"timeframe,omitempty"`
	LegendSize *int     `json:"legend_size,omitempty"`
	Type       *string  `json:"type,omitempty"`
	Legend     *bool    `json:"legend,omitempty"`
	TileDef    *TileDef `json:"tile_def,omitempty"`
}

type CheckStatusWidget struct {
	TitleSize  *int    `json:"title_size,omitempty"`
	Title      *bool   `json:"title,omitempty"`
	TitleAlign *string `json:"title_align,omitempty"`
	TextAlign  *string `json:"text_align,omitempty"`
	TitleText  *string `json:"title_text,omitempty"`
	Height     *int    `json:"height,omitempty"`
	Width      *int    `json:"width,omitempty"`
	X          *int    `json:"y,omitempty"`
	Y          *int    `json:"x,omitempty"`
	Tags       *string `json:"tags,omitempty"`
	Timeframe  *string `json:"timeframe,omitempty"`
	TextSize   *string `json:"text_size,omitempty"`
	Type       *string `json:"type,omitempty"`
	Check      *string `json:"check,omitempty"`
	Group      *string `json:"group,omitempty"`
	Grouping   *string `json:"grouping,omitempty"`
}

type IFrameWidget struct {
	TitleSize  *int    `json:"title_size,omitempty"`
	Title      *bool   `json:"title,omitempty"`
	Url        *string `json:"url,omitempty"`
	TitleAlign *string `json:"title_align,omitempty"`
	TitleText  *string `json:"title_text,omitempty"`
	Height     *int    `json:"height,omitempty"`
	Width      *int    `json:"width,omitempty"`
	X          *int    `json:"y,omitempty"`
	Y          *int    `json:"x,omitempty"`
	Type       *string `json:"type,omitempty"`
}

type NoteWidget struct {
	TitleSize    *int    `json:"title_size,omitempty"`
	Title        *bool   `json:"title,omitempty"`
	RefreshEvery *int    `json:"refresh_every,omitempty"`
	TickPos      *string `json:"tick_pos,omitempty"`
	TitleAlign   *string `json:"title_align,omitempty"`
	TickEdge     *string `json:"tick_edge,omitempty"`
	TextAlign    *string `json:"text_align,omitempty"`
	TitleText    *string `json:"title_text,omitempty"`
	Height       *int    `json:"height,omitempty"`
	Color        *string `json:"bgcolor,omitempty"`
	Html         *string `json:"html,omitempty"`
	Y            *int    `json:"y,omitempty"`
	X            *int    `json:"x,omitempty"`
	FontSize     *int    `json:"font_size,omitempty"`
	Tick         *bool   `json:"tick,omitempty"`
	Note         *string `json:"type,omitempty"`
	Width        *int    `json:"width,omitempty"`
	AutoRefresh  *bool   `json:"auto_refresh,omitempty"`
}

type TimeseriesWidget struct {
	Height     *int      `json:"height,omitempty"`
	Legend     *bool     `json:"legend,omitempty"`
	TileDef    *TileDef  `json:"tile_def,omitempty"`
	Timeframe  *string   `json:"timeframe,omitempty"`
	Title      *bool     `json:"title,omitempty"`
	TitleAlign *string   `json:"title_align,omitempty"`
	TitleSize  *TextSize `json:"title_size,omitempty"`
	TitleText  *string   `json:"title_text,omitempty"`
	Type       *string   `json:"type,omitempty"`
	Width      *int      `json:"width,omitempty"`
	X          *int      `json:"x,omitempty"`
	Y          *int      `json:"y,omitempty"`
}

type QueryValueWidget struct {
	Timeframe           *string             `json:"timeframe,omitempty"`
	TimeframeAggregator *string             `json:"aggr,omitempty"`
	Aggregator          *string             `json:"aggregator,omitempty"`
	CalcFunc            *string             `json:"calc_func,omitempty"`
	ConditionalFormats  []ConditionalFormat `json:"conditional_formats,omitempty"`
	Height              *int                `json:"height,omitempty"`
	IsValidQuery        *bool               `json:"is_valid_query,omitempty,omitempty"`
	Metric              *string             `json:"metric,omitempty"`
	MetricType          *string             `json:"metric_type,omitempty"`
	Precision           *int                `json:"precision,omitempty"`
	Query               *string             `json:"query,omitempty"`
	ResultCalcFunc      *string             `json:"res_calc_func,omitempty"`
	Tags                []string            `json:"tags,omitempty"`
	TextAlign           *string             `json:"text_align,omitempty"`
	TextSize            *TextSize           `json:"text_size,omitempty"`
	Title               *bool               `json:"title,omitempty"`
	TitleAlign          *string             `json:"title_align,omitempty"`
	TitleSize           *TextSize           `json:"title_size,omitempty"`
	TitleText           *string             `json:"title_text,omitempty"`
	Type                *string             `json:"type,omitempty"`
	Unit                *string             `json:"auto,omitempty"`
	Width               *int                `json:"width,omitempty"`
	X                   *int                `json:"x,omitempty"`
	Y                   *int                `json:"y,omitempty"`
}
type ConditionalFormat struct {
	Color      *string `json:"color,omitempty"`
	Comparator *string `json:"comparator,omitempty"`
	Inverted   *bool   `json:"invert,omitempty"`
	Value      *int    `json:"value,omitempty"`
}

type ToplistWidget struct {
	Height     *int      `json:"height,omitempty"`
	Legend     *bool     `json:"legend,omitempty"`
	LegendSize *int      `json:"legend_size,omitempty"`
	TileDef    *TileDef  `json:"tile_def,omitempty"`
	Timeframe  *string   `json:"timeframe,omitempty"`
	Title      *bool     `json:"title,omitempty"`
	TitleAlign *string   `json:"title_align,omitempty"`
	TitleSize  *TextSize `json:"title_size,omitempty"`
	TitleText  *string   `json:"title_text,omitempty"`
	Type       *string   `json:"type,omitempty"`
	Width      *int      `json:"width,omitempty"`
	X          *int      `json:"x,omitempty"`
	Y          *int      `json:"y,omitempty"`
}

type EventStreamWidget struct {
	EventSize  *string   `json:"event_size,omitempty"`
	Height     *int      `json:"height,omitempty"`
	Query      *string   `json:"query,omitempty"`
	Timeframe  *string   `json:"timeframe,omitempty"`
	Title      *bool     `json:"title,omitempty"`
	TitleAlign *string   `json:"title_align,omitempty"`
	TitleSize  *TextSize `json:"title_size,omitempty"`
	TitleText  *string   `json:"title_text,omitempty"`
	Type       *string   `json:"type,omitempty"`
	Width      *int      `json:"width,omitempty"`
	X          *int      `json:"x,omitempty"`
	Y          *int      `json:"y,omitempty"`
}

type FreeTextWidget struct {
	Color     *string `json:"color,omitempty"`
	FontSize  *string `json:"font_size,omitempty"`
	Height    *int    `json:"height,omitempty"`
	Text      *string `json:"text,omitempty"`
	TextAlign *string `json:"text_align,omitempty"`
	Type      *string `json:"type,omitempty"`
	Width     *int    `json:"width,omitempty"`
	X         *int    `json:"x,omitempty"`
	Y         *int    `json:"y,omitempty"`
}

type ImageWidget struct {
	Height     *int      `json:"height,omitempty"`
	Sizing     *string   `json:"sizing,omitempty"`
	Title      *bool     `json:"title,omitempty"`
	TitleAlign *string   `json:"title_align,omitempty"`
	TitleSize  *TextSize `json:"title_size,omitempty"`
	TitleText  *string   `json:"title_text,omitempty"`
	Type       *string   `json:"type,omitempty"`
	Url        *string   `json:"url,omitempty"`
	Width      *int      `json:"width,omitempty"`
	X          *int      `json:"x,omitempty"`
	Y          *int      `json:"y,omitempty"`
}


text:
package com.studio4plus.homerplayer.ui;

import android.app.Activity;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import com.studio4plus.homerplayer.GlobalSettings;

public class BaseActivity
        extends Activity
        implements SharedPreferences.OnSharedPreferenceChangeListener {

    @Override
    protected void onStart() {
        super.onStart();
        updateOrientation();
        SharedPreferences sharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        SharedPreferences sharedPreferences =
                PreferenceManager.getDefaultSharedPreferences(this);
        sharedPreferences.unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        updateOrientation();
    }

    private void updateOrientation() {
        //noinspection ResourceType
        setRequestedOrientation(GlobalSettings.getScreenOrientation(this));
    }
}


text:
[jvm]
Content
val [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html)<*>.[typeWithParams](type-with-params.md): [GenericType](../com.github.jonathanxd.kores.type/-generic-type/index.md)
More info

Returns the [GenericType](../com.github.jonathanxd.kores.type/-generic-type/index.md) of [Class](https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html) with its parameters.


text:
Background sound player service.

	@author Andras Belicza


text:
package org.openmrs.module.fhir.mapper.emr;

import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.ProcedureRequest;
import org.hl7.fhir.dstu3.model.Resource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openmrs.Encounter;
import org.openmrs.Order;
import org.openmrs.api.EncounterService;
import org.openmrs.api.OrderService;
import org.openmrs.api.ProviderService;
import org.openmrs.module.fhir.MapperTestHelper;
import org.openmrs.module.fhir.mapper.model.EmrEncounter;
import org.openmrs.module.fhir.mapper.model.ShrEncounterBundle;
import org.openmrs.module.shrclient.dao.IdMappingRepository;
import org.openmrs.module.shrclient.model.IdMapping;
import org.openmrs.module.shrclient.model.IdMappingType;
import org.openmrs.web.test.BaseModuleWebContextSensitiveTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;

import java.util.Date;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.*;
import static org.openmrs.Order.Action.DISCONTINUE;
import static org.openmrs.Order.Action.NEW;
import static org.openmrs.module.fhir.MapperTestHelper.getSystemProperties;
import static org.openmrs.module.fhir.utils.DateUtil.parseDate;
import static org.openmrs.module.fhir.utils.FHIRBundleHelper.identifyFirstResourceWithName;
import static org.openmrs.module.fhir.utils.FHIRBundleHelper.identifyResourcesByName;

@ContextConfiguration(locations = {"classpath:TestingApplicationContext.xml"}, inheritLocations = true)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class FHIRProcedureRequestMapperIT extends BaseModuleWebContextSensitiveTest {
    private final String PATIENT_HEALTH_ID = "HIDA764177";
    private final String SHR_ENC_ID = "shr-enc-id-1";
    @Autowired
    private FHIRProcedureRequestToProcedureOrderMapper procedureRequestMapper;
    @Autowired
    private ProviderService providerService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private EncounterService encounterService;
    @Autowired
    private IdMappingRepository idMappingRepository;

    @Before
    public void setUp() throws Exception {
        executeDataSet("testDataSets/procedureOrderDS.xml");
    }

    @Test
    public void shouldHandleAProcedureRequest() throws Exception {
        Bundle bundle = loadSampleFHIREncounter("encounterBundles/stu3/encounterWithProcedureRequest.xml");
        Resource resource = identifyFirstResourceWithName(bundle, new ProcedureRequest().getResourceType().name());
        assertTrue(procedureRequestMapper.canHandle(resource));
    }

    @Test
    public void shouldMapAProcedureRequest() throws Exception {
        EmrEncounter emrEncounter = mapOrder("encounterBundles/stu3/encounterWithProcedureRequest.xml", ProcedureRequest.ProcedureRequestStatus.ACTIVE);

        Set<Order> orders = emrEncounter.getOrders();
        assertFalse(orders.isEmpty());
        assertEquals(1, orders.size());
        Order order = orders.iterator().next();
        assertEquals("Colposcopy", order.getConcept().getName().getName());
        assertEquals(NEW, order.getAction());
        assertEquals(providerService.getProvider(22), order.getOrderer());
        assertEquals(orderService.getOrderType(16), order.getOrderType());
        assertEquals(orderService.getCareSetting(1), order.getCareSetting());
        assertEquals(parseDate("2016-02-03T15:30:20+05:30"), order.getDateActivated());
        assertEquals(parseDate("2016-02-04T15:30:20+05:30"), order.getAutoExpireDate());
        assertEquals("Some Notes", order.getCommentToFulfiller());

        IdMapping mapping = idMappingRepository.findByInternalId(order.getUuid(), IdMappingType.PROCEDURE_REQUEST);
        assertNotNull(mapping);
        assertEquals(SHR_ENC_ID + ":f3703dad-7e1e-47b6-9152-4aa5774fb361", mapping.getExternalId());
        String expected = String.format("http://shr.com/patients/%s/encounters/%s#ProcedureRequest/f3703dad-7e1e-47b6-9152-4aa5774fb361", PATIENT_HEALTH_ID, SHR_ENC_ID);
        assertEquals(expected, mapping.getUri());
    }

    @Test
    public void shouldNotMapAProcedureRequestWhenConceptIsNotFound() throws Exception {
        EmrEncounter emrEncounter = mapOrder("encounterBundles/stu3/encounterWithProcedureRequestWithNotSyncedConcept.xml", ProcedureRequest.ProcedureRequestStatus.ACTIVE);

        Set<Order> orders = emrEncounter.getOrders();
        assertTrue(orders.isEmpty());
    }

    @Test
    public void shouldNotMapARequestIfAlreadyPresent() throws Exception {
        Encounter existingEncounter = encounterService.getEncounter(38);
        Set<Order> existingOrders = existingEncounter.getOrders();
        assertEquals(1, existingOrders.size());
        Order existingOrder = existingOrders.iterator().next();
        assertEquals("Colposcopy", existingOrder.getConcept().getName().getName());
        assertEquals(NEW, existingOrder.getAction());

        EmrEncounter emrEncounter = mapOrder("encounterBundles/stu3/encounterWithExistingProcedureRequestForProcedureOrder.xml", existingEncounter, ProcedureRequest.ProcedureRequestStatus.ACTIVE);

        Set<Order> orders = emrEncounter.getOrders();
        assertTrue(orders.isEmpty());
    }

    @Test
    public void shouldDiscontinueAnExistingOrderIfUpdatedAsSuspended() throws Exception {
        Encounter existingEncounter = encounterService.getEncounter(38);
        Set<Order> existingOrders = existingEncounter.getOrders();
        assertEquals(1, existingOrders.size());
        Order existingOrder = existingOrders.iterator().next();
        assertEquals("Colposcopy", existingOrder.getConcept().getName().getName());
        assertEquals(NEW, existingOrder.getAction());

        EmrEncounter emrEncounter = mapOrder("encounterBundles/stu3/encounterWithSuspendedProcedureRequest.xml", existingEncounter, ProcedureRequest.ProcedureRequestStatus.CANCELLED);

        Set<Order> orders = emrEncounter.getOrders();
        assertFalse(orders.isEmpty());
        assertEquals(1, orders.size());
        Order order = orders.iterator().next();
        assertEquals("Colposcopy", order.getConcept().getName().getName());
        assertEquals(DISCONTINUE, order.getAction());
        assertEquals(existingOrder, order.getPreviousOrder());
        assertEquals(providerService.getProvider(22), order.getOrderer());
        assertEquals(orderService.getOrderType(16), order.getOrderType());
        assertEquals(orderService.getCareSetting(1), order.getCareSetting());
        assertEquals(parseDate("2016-02-03T15:32:39+05:30"), order.getDateActivated());
        assertEquals(parseDate("2016-02-04T15:32:39+05:30"), order.getAutoExpireDate());
    }

    @Test
    public void shouldNotDownloadIfProcedureRequestWasNotDownloadedAndUpdatedAsSuspended() throws Exception {
        EmrEncounter emrEncounter = mapOrder("encounterBundles/stu3/encounterWithSuspendedProcedureRequestWIthNotDownloadedOrder.xml", ProcedureRequest.ProcedureRequestStatus.CANCELLED);

        Set<Order> orders = emrEncounter.getOrders();
        assertTrue(orders.isEmpty());
    }

    private EmrEncounter mapOrder(String filePath, ProcedureRequest.ProcedureRequestStatus requestStatus) throws Exception {
        Encounter encounter = new Encounter();
        encounter.setEncounterDatetime(new Date());
        return mapOrder(filePath, encounter, requestStatus);
    }

    private EmrEncounter mapOrder(String filePath, Encounter encounter, ProcedureRequest.ProcedureRequestStatus requestStatus) throws Exception {
        Bundle bundle = loadSampleFHIREncounter(filePath);
        ProcedureRequest procedureRequest = getProcedureRequestByStatus(bundle, requestStatus);
        ShrEncounterBundle encounterComposition = new ShrEncounterBundle(bundle, PATIENT_HEALTH_ID, SHR_ENC_ID);
        EmrEncounter emrEncounter = new EmrEncounter(encounter);
        procedureRequestMapper.map(procedureRequest, emrEncounter, encounterComposition, getSystemProperties("1"));
        return emrEncounter;
    }

    private ProcedureRequest getProcedureRequestByStatus(Bundle bundle, ProcedureRequest.ProcedureRequestStatus requestStatus) {
        List<Resource> resources = identifyResourcesByName(bundle, new ProcedureRequest().getResourceType().name());
        for (Resource resource : resources) {
            ProcedureRequest request = (ProcedureRequest) resource;
            if (requestStatus.equals(request.getStatus())) {
                return request;
            }
        }
        return null;
    }

    private Bundle loadSampleFHIREncounter(String filePath) throws Exception {
        return (Bundle) new MapperTestHelper().loadSampleFHIREncounter(filePath, applicationContext);
    }

    @After
    public void tearDown() throws Exception {
        deleteAllData();
    }
}


text:
package org.wso2.andes.kernel;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.andes.amqp.AMQPUtils;
import org.wso2.andes.configuration.AndesConfigurationManager;
import org.wso2.andes.configuration.StoreConfiguration;
import org.wso2.andes.configuration.enums.AndesConfiguration;
import org.wso2.andes.kernel.disruptor.inbound.InboundEventManager;
import org.wso2.andes.kernel.disruptor.inbound.InboundExchangeEvent;
import org.wso2.andes.kernel.dtx.DtxRegistry;
import org.wso2.andes.kernel.registry.MessageRouterRegistry;
import org.wso2.andes.kernel.registry.StorageQueueRegistry;
import org.wso2.andes.kernel.registry.SubscriptionRegistry;
import org.wso2.andes.kernel.slot.SlotCreator;
import org.wso2.andes.kernel.slot.SlotDeletionExecutor;
import org.wso2.andes.kernel.slot.SlotManagerClusterMode;
import org.wso2.andes.kernel.subscription.AndesSubscriptionManager;
import org.wso2.andes.kernel.subscription.StorageQueue;
import org.wso2.andes.mqtt.utils.MQTTUtils;
import org.wso2.andes.server.ClusterResourceHolder;
import org.wso2.andes.server.cluster.ClusterAgent;
import org.wso2.andes.server.cluster.ClusterManagementInformationMBean;
import org.wso2.andes.server.cluster.ClusterManager;
import org.wso2.andes.server.cluster.coordination.ClusterNotificationListenerManager;
import org.wso2.andes.server.cluster.coordination.CoordinationComponentFactory;
import org.wso2.andes.server.information.management.MessageStatusInformationMBean;
import org.wso2.andes.server.information.management.SubscriptionManagementInformationMBean;
import org.wso2.andes.server.queue.DLCQueueUtils;
import org.wso2.andes.server.virtualhost.VirtualHost;
import org.wso2.andes.server.virtualhost.VirtualHostConfigSynchronizer;
import org.wso2.andes.store.FailureObservingAndesContextStore;
import org.wso2.andes.store.FailureObservingMessageStore;
import org.wso2.andes.store.FailureObservingStoreManager;
import org.wso2.andes.thrift.MBThriftServer;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.user.api.UserStoreException;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.management.JMException;

/**
 * Andes kernel startup/shutdown related work is done through this class.
 */
public class AndesKernelBoot {

    private static Log log = LogFactory.getLog(AndesKernelBoot.class);

    /**
     * Store for keeping messages (i.e persistent store)
     */
    private static MessageStore messageStore;

    /**
     * Store for keeping AMQP based artifacts
     */
    private static AMQPConstructStore amqpConstructStore;

    /**
     * In-memory store for keeping subscription entries
     */
    private static SubscriptionRegistry subscriptionRegistry;

    /**
     * Scheduled thread pool executor to run periodic andes recovery task
     */
    private static ScheduledExecutorService andesRecoveryTaskScheduler;

    /**
     * Scheduled thread pool executor to run periodic expiry message deletion task
     */
    private static ScheduledExecutorService expiryMessageDeletionTaskScheduler;

    /**
     * Used to get information from context store
     */
    private static AndesContextStore contextStore;

    /**
     * This is used by independent worker threads to identify if the kernel is performing shutdown operations.
     */
    private static boolean isKernelShuttingDown = false;

    /**
     * Used to initialize cluster notifications listners.
     */
    private static ClusterNotificationListenerManager clusterNotificationListenerManager;

    /**
     * This will boot up all the components in Andes kernel and bring the server to working state
     */
    public static void initializeComponents() throws AndesException {
        isKernelShuttingDown = false;
        //loadConfigurations - done from outside
        //startAndesStores - done from outside
        int threadPoolCount = 1;
        andesRecoveryTaskScheduler = Executors.newScheduledThreadPool(threadPoolCount);
        expiryMessageDeletionTaskScheduler = Executors.newScheduledThreadPool(threadPoolCount);
        startHouseKeepingThreads();
        createDefinedProtocolArtifacts();
        syncNodeWithClusterState();
        registerMBeans();
        startThriftServer();
        Andes.getInstance().startSafeZoneUpdateWorkers();
        int slotDeletingWorkerCount = AndesConfigurationManager.readValue
                (AndesConfiguration.PERFORMANCE_TUNING_SLOT_DELETE_WORKER_COUNT);
        int maxNumberOfPendingSlotsToDelete = AndesConfigurationManager.readValue
                (AndesConfiguration.PERFORMANCE_TUNING_SLOT_DELETE_QUEUE_DEPTH_WARNING_THRESHOLD);
        SlotDeletionExecutor.getInstance().init(slotDeletingWorkerCount, maxNumberOfPendingSlotsToDelete);
    }

    /**
     * This will recreate slot mapping for queues which have messages left in the message store.
     * The slot mapping is required only for the cluster implementation.
     *
     * First we acquire the slot initialization lock and check if the cluster is already
     * initialized using a distributed variable. Then if the cluster is not initialized, the
     * server will reset slot storage and iterate through all the queues available in the
     * context store and inform the the slot mapping. Finally the distribute variable is updated to
     * indicate the success and the lock is released.
     *
     * @throws AndesException
     */
    public static void clearMembershipEventsAndRecoverDistributedSlotMap() throws AndesException {
        if (!AndesContext.getInstance().isClusteringEnabled()) {
            removeNonDurableQueues();
            removeAllSubscriptions();
            recoverMapsForEachQueue();
        }
    }

    private static void removeNonDurableQueues() throws AndesException {
        List<StorageQueue> queueList = contextStore.getAllQueuesStored();
        for (StorageQueue storageQueue : queueList) {
            String queueName = storageQueue.getName();
            if (!storageQueue.isDurable() && queueName.startsWith(AndesUtils.AMQP_TOPIC_STORAGE_QUEUE_PREFIX)) {
                messageStore.deleteAllMessageMetadata(queueName);
                contextStore.deleteBindingInformation(AMQPUtils.TOPIC_EXCHANGE_NAME, queueName);
                contextStore.deleteQueueInformation(queueName);
                messageStore.removeQueue(queueName);
            }
        }
    }

    private static void removeAllSubscriptions() throws AndesException {
        contextStore.removeAllSubscriptions();
    }

    /**
     * Generate slots for each queue
     * @throws AndesException
     */
    private static void recoverMapsForEachQueue() throws AndesException {
        List<StorageQueue> queueList = contextStore.getAllQueuesStored();
        List<Future> futureSlotRecoveryExecutorList = new ArrayList<>();
        Integer concurrentReads = AndesConfigurationManager.readValue
                (AndesConfiguration.RECOVERY_MESSAGES_CONCURRENT_STORAGE_QUEUE_READS);
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat
                ("SlotRecoveryThread-%d").build();
        ExecutorService executorService = Executors.newFixedThreadPool(concurrentReads,namedThreadFactory);
        for (final StorageQueue queue : queueList) {
            final String queueName = queue.getName();
            // Skip slot creation for Dead letter Channel
            if (DLCQueueUtils.isDeadLetterQueue(queueName)) {
                continue;
            }
            Future submit = executorService.submit(new SlotCreator(messageStore, queueName));
            futureSlotRecoveryExecutorList.add(submit);
        }
        for (Future slotRecoveryExecutor : futureSlotRecoveryExecutorList) {
            try {
                slotRecoveryExecutor.get();
            } catch (InterruptedException e) {
                log.error("Error occurred in slot recovery.", e);
                Thread.currentThread().interrupt();
            } catch (ExecutionException e) {
                log.error("Error occurred in slot recovery.", e);
            }
        }
        executorService.shutdown();
    }

    /**
     * Initialize the VirtualHostConfigSynchronizaer based on the provide virtual host. Andes operates on this virtual
     * host only
     *
     * @param defaultVirtualHost virtual host to set
     */
    public static void initVirtualHostConfigSynchronizer(VirtualHost defaultVirtualHost) {
        // initialize amqp constructs syncing into Qpid
        VirtualHostConfigSynchronizer _VirtualHostConfigSynchronizer = new VirtualHostConfigSynchronizer
                (defaultVirtualHost);
        ClusterResourceHolder.getInstance().setVirtualHostConfigSynchronizer(_VirtualHostConfigSynchronizer);
    }

    /**
     * This will trigger graceful shutdown of andes broker
     *
     * @throws AndesException
     */
    public static void shutDownAndesKernel() throws AndesException {

        // Set flag so independent threads can act accordingly
        isKernelShuttingDown = true;

        // Trigger Shutdown Event
        Andes.getInstance().shutDown();

    }

    /**
     * A factory method (/util) to create user specified
     * {@link AndesContextStore} in broker.xml
     *
     * @return an implementation of {@link AndesContextStore}
     * @throws Exception if an error occures
     */
    private static AndesContextStore createAndesContextStoreFromConfig() throws Exception {
        StoreConfiguration andesConfiguration = AndesContext.getInstance()
                .getStoreConfiguration();
        //create a andes context store and register
        String contextStoreClassName = andesConfiguration.getAndesContextStoreClassName();
        Class<? extends AndesContextStore> contextStoreClass = Class.forName(contextStoreClassName).asSubclass(AndesContextStore.class);
        AndesContextStore contextStoreInstance = contextStoreClass.newInstance();

        contextStoreInstance.init(andesConfiguration.getContextStoreProperties());
        log.info("AndesContextStore initialised with " + contextStoreClassName);

        return contextStoreInstance;
    }

    /**
     * A factory method (/util) to create user specified
     * {@link MessageStore} in broker.xml
     *
     * @return an implementation of {@link MessageStore}
     * @throws Exception if an error occurs
     */
    private static MessageStore createMessageStoreFromConfig(AndesContextStore andesContextStore,
                                                             FailureObservingStoreManager failureObservingStoreManager)
            throws Exception {

        StoreConfiguration andesConfiguration = AndesContext.getInstance().getStoreConfiguration();

     // create a message store and initialise messaging engine
        String messageStoreClassName = andesConfiguration.getMessageStoreClassName();
        Class<? extends MessageStore> messageStoreClass =
                Class.forName(messageStoreClassName).asSubclass(MessageStore.class);

        MessageStore messageStoreInConfig = messageStoreClass.newInstance();

        FailureObservingMessageStore failureObservingMessageStore = new FailureObservingMessageStore(
                messageStoreInConfig, failureObservingStoreManager);

        failureObservingMessageStore.initializeMessageStore(
                andesContextStore, andesConfiguration.getMessageStoreProperties());

        log.info("Andes MessageStore initialised with " + messageStoreClassName);
        return failureObservingMessageStore;
    }

    /**
     * Start all andes stores message store/context store and AMQP construct store
     *
     * @throws Exception
     */
    public static void startAndesStores() throws Exception {

        //Create a andes context store and register
        AndesContextStore contextStoreInConfig = createAndesContextStoreFromConfig();
        FailureObservingStoreManager failureObservingStoreManager = new FailureObservingStoreManager();
        AndesKernelBoot.contextStore = new FailureObservingAndesContextStore(contextStoreInConfig,
                failureObservingStoreManager);
        AndesContext.getInstance().setAndesContextStore(contextStore);

        // directly wire the instance without wrapped instance
        messageStore = createMessageStoreFromConfig(contextStoreInConfig, failureObservingStoreManager);

        // Setting the message store in the context store
        AndesContext.getInstance().setMessageStore(messageStore);

        //create AMQP Constructs store
        amqpConstructStore = new AMQPConstructStore(contextStore);
        AndesContext.getInstance().setAMQPConstructStore(amqpConstructStore);

        //create MessageRouter Registry
        MessageRouterRegistry messageRouterRegistry = new MessageRouterRegistry();
        AndesContext.getInstance().setMessageRouterRegistry(messageRouterRegistry);

        //create Storage Queue Registry
        StorageQueueRegistry storageQueueRegistry = new StorageQueueRegistry();
        AndesContext.getInstance().setStorageQueueRegistry(storageQueueRegistry);

        //create subscription registry and manager
        subscriptionRegistry = new SubscriptionRegistry();
    }

    /**
     * Starts all andes components such as the subscription engine, messaging engine, cluster event sync tasks, etc.
     *
     * @throws Exception
     */
    private static void startAndesComponents() throws Exception {

        //create subscription registry and manager
        AndesSubscriptionManager subscriptionManager = new AndesSubscriptionManager(subscriptionRegistry,
                contextStore);
        AndesContext.getInstance().setAndesSubscriptionManager(subscriptionManager);
        ClusterResourceHolder.getInstance().setSubscriptionManager(subscriptionManager);

        MessagingEngine messagingEngine = MessagingEngine.getInstance();
        messagingEngine.initialise(messageStore, new MessageExpiryManager(messageStore), subscriptionManager);

        // initialise Andes context information related manager class
        AndesContextInformationManager contextInformationManager =
                new AndesContextInformationManager(amqpConstructStore, subscriptionManager,
                        contextStore, messageStore);
        AndesContext.getInstance().setAndesContextInformationManager(contextInformationManager);

        //Create an inbound event manager. This will prepare inbound events to disruptor
        InboundEventManager inboundEventManager =  new InboundEventManager(messagingEngine);
        AndesContext.getInstance().setInboundEventManager(inboundEventManager);

        DtxRegistry dtxRegistry = new DtxRegistry(messageStore.getDtxStore(), messagingEngine, inboundEventManager);

        //Initialize Andes API (used by all inbound transports)
        Andes.getInstance().initialise(messagingEngine, inboundEventManager, contextInformationManager,
                                       subscriptionManager, dtxRegistry);

        //Initialize cluster notification listener (null if standalone)
        if(null != clusterNotificationListenerManager) {
            clusterNotificationListenerManager.initializeListener(inboundEventManager, subscriptionManager,
                    contextInformationManager);
        }
    }

    /**
     * Create Pre-defined exchanges, queues, bindings and subscriptions and other artifacts
     * at the startup
     *
     * @throws AndesException
     */
    private static void createDefinedProtocolArtifacts() throws AndesException {
        //Create MQTT exchange
        InboundExchangeEvent inboundExchangeEvent = new
                InboundExchangeEvent(MQTTUtils.MQTT_EXCHANGE_NAME, "topic", false);
        Andes.getInstance().createExchange(inboundExchangeEvent);
    }

    /**
     * Initialize mode of cluster event synchronization depending on configurations and start listeners.
     */
    private static void initClusterEventListener() throws AndesException {

        CoordinationComponentFactory coordinationComponentFactory = new CoordinationComponentFactory();
        clusterNotificationListenerManager = coordinationComponentFactory.createClusterNotificationListener();
        AndesContext.getInstance().setClusterNotificationListenerManager(clusterNotificationListenerManager);
    }

    /**
     * Starts the andes cluster.
     */
    public static void startAndesCluster() throws Exception {

        // Initialize cluster manager
        initClusterManager();

        // Create the listener for listening for cluster events
        initClusterEventListener();

        // Clear all slots and cluster notifications at a cluster startup
        clearMembershipEventsAndRecoverDistributedSlotMap();

        //Start components such as the subscription manager, subscription engine, messaging engine, etc.
        startAndesComponents();

    }

    /**
     * Stops tasks for cluster event synchronization.
     */
    public static void shutDownAndesClusterEventSynchronization() throws AndesException {
        if (ClusterResourceHolder.getInstance().getClusterManager().isClusteringEnabled()) {
            clusterNotificationListenerManager.stopListener();
        }
    }

    /**
     * Bring the node to the state of the cluster. If this is the coordinator, disconnect all active durable
     * subscriptions.
     *
     * @throws AndesException
     */
    public static void syncNodeWithClusterState() throws AndesException {

        //at the startup reload exchanges/queues/bindings and subscriptions
        log.info("Syncing exchanges, queues, bindings and subscriptions");
        ClusterResourceHolder.getInstance().getAndesRecoveryTask()
                .recoverBrokerArtifacts();

        /**
         * remove all subscriptions registered by the local node ID.
         * During a node crash there can be stale subscriptions hanging around.
         */
        AndesContext.getInstance().getAndesSubscriptionManager().
                closeAllActiveLocalSubscriptions();
    }

    /**
     * start andes house keeping threads for the broker
     *
     * @throws AndesException
     */
    public static void startHouseKeepingThreads() throws AndesException {

        //reload exchanges/queues/bindings and subscriptions
        AndesContextInformationManager contextInformationManager = AndesContext.getInstance()
                .getAndesContextInformationManager();
        AndesSubscriptionManager subscriptionManager = AndesContext.getInstance()
                .getAndesSubscriptionManager();
        InboundEventManager inboundEventManager = AndesContext.getInstance()
                .getInboundEventManager();
        AndesRecoveryTask andesRecoveryTask = new AndesRecoveryTask(contextInformationManager,
                subscriptionManager, inboundEventManager);

        //deleted the expired message from db
        PeriodicExpiryMessageDeletionTask periodicExpiryMessageDeletionTask = null;

        int recoveryTaskScheduledPeriod = AndesConfigurationManager.readValue
                (AndesConfiguration.PERFORMANCE_TUNING_FAILOVER_VHOST_SYNC_TASK_INTERVAL);
        int dbBasedDeletionTaskScheduledPeriod = AndesConfigurationManager.readValue
                (AndesConfiguration.PERFORMANCE_TUNING_PERIODIC_EXPIRY_MESSAGE_DELETION_INTERVAL);
        int safeDeleteRegionSlotCount = AndesConfigurationManager.readValue
                (AndesConfiguration.PERFORMANCE_TUNING_SAFE_DELETE_REGION_SLOT_COUNT);

        periodicExpiryMessageDeletionTask = new PeriodicExpiryMessageDeletionTask();

        andesRecoveryTaskScheduler.scheduleAtFixedRate(andesRecoveryTask, recoveryTaskScheduledPeriod,
                recoveryTaskScheduledPeriod, TimeUnit.SECONDS);
        if (safeDeleteRegionSlotCount >= 1) {
            expiryMessageDeletionTaskScheduler.scheduleAtFixedRate(periodicExpiryMessageDeletionTask,
                    dbBasedDeletionTaskScheduledPeriod, dbBasedDeletionTaskScheduledPeriod, TimeUnit.SECONDS);
        } else {
            log.error("DB based expiry message deletion task is not scheduled due to not providing "
                    + "a valid safe delete region slot count is not given. Given slot count is "
                    + safeDeleteRegionSlotCount);
        }

        ClusterResourceHolder.getInstance().setAndesRecoveryTask(andesRecoveryTask);
    }

    /**
     * Stop andes house keeping threads
     */
    public static void stopHouseKeepingThreads() {
        log.info("Stop syncing exchanges, queues, bindings and subscriptions...");
        int threadTerminationTimePerod = 20; // seconds
        try {
            andesRecoveryTaskScheduler.shutdown();
            expiryMessageDeletionTaskScheduler.shutdown();
            expiryMessageDeletionTaskScheduler.awaitTermination(threadTerminationTimePerod, TimeUnit.SECONDS);
            andesRecoveryTaskScheduler.awaitTermination(threadTerminationTimePerod, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            andesRecoveryTaskScheduler.shutdownNow();
            log.warn("Recovery task scheduler is forcefully shutdown.");
        }

    }

    /**
     * Register Andes MBeans
     *
     */
    public static void registerMBeans() throws AndesException {

        try {
            ClusterManagementInformationMBean clusterManagementMBean = new
                    ClusterManagementInformationMBean(
                    ClusterResourceHolder.getInstance().getClusterManager());
            clusterManagementMBean.register();

            SubscriptionManagementInformationMBean subscriptionManagementInformationMBean = new
                    SubscriptionManagementInformationMBean();
            subscriptionManagementInformationMBean.register();

            MessageStatusInformationMBean messageStatusInformationMBean = new
                    MessageStatusInformationMBean();
            messageStatusInformationMBean.register();
        } catch (JMException ex) {
            throw new AndesException("Unable to register Andes MBeans", ex);
        }
    }

    /**
     * Start manager to join node to the cluster and register
     * node in the cluster
     *
     * @throws AndesException
     */
    private static void initClusterManager() throws AndesException {

        /**
         * initialize cluster manager for managing nodes in MB cluster
         */
        ClusterManager clusterManager = new ClusterManager();
        clusterManager.init();
        ClusterResourceHolder.getInstance().setClusterManager(clusterManager);

        //TODO: remove as submanager starts after cluster manager now
       // AndesContext.getInstance().getAndesSubscriptionManager().
        //        setLocalNodeId(clusterManager.getMyNodeID());
    }

    /**
     * reinitialize message stores after a connection lost
     * to DB
     * @throws Exception
     */
    public static void reInitializeAndesStores() throws Exception {
        log.info("Reinitializing Andes Stores...");
        StoreConfiguration virtualHostsConfiguration =
                AndesContext.getInstance().getStoreConfiguration();
        AndesContextStore andesContextStore = AndesContext.getInstance().getAndesContextStore();
        andesContextStore.init(virtualHostsConfiguration.getContextStoreProperties());
        messageStore.initializeMessageStore(andesContextStore,
                                            virtualHostsConfiguration.getMessageStoreProperties());
    }

    /**
     * Start accepting and delivering messages
     */
    public static void startMessaging() {
        Andes.getInstance().startMessageDelivery();
    }

    /**
     * Stop worker threads, close transports and stop message delivery
     *
     */
    private static void stopMessaging() {
        //this will un-assign all slots currently owned
        Andes.getInstance().stopMessageDelivery();
    }

    /**
     * Start the thrift server
     * @throws AndesException
     */
    private static void startThriftServer() throws AndesException {
        if (AndesContext.getInstance().isClusteringEnabled()) {
            MBThriftServer.getInstance().start(AndesContext.getInstance().getThriftServerHost(),
                    AndesContext.getInstance().getThriftServerPort(), "MB-ThriftServer-main-thread");
        }

    }

    /**
     * Stop the thrift server
     */
    public static void stopThriftServer(){
        MBThriftServer.getInstance().stop();
    }

    /**
     * Create a DEAD_LETTER_CHANNEL for the super tenant.
     */
    public static void createSuperTenantDLC() throws AndesException {
        CarbonContext carbonContext = CarbonContext.getThreadLocalCarbonContext();
        try {
            String adminUserName = carbonContext.getUserRealm().getRealmConfiguration().getAdminUserName();
            DLCQueueUtils.createDLCQueue(carbonContext.getTenantDomain(), adminUserName);
        } catch (UserStoreException e) {
            throw new AndesException("Error getting super tenant username", e);
        }
    }

    public static boolean isKernelShuttingDown() {
        return isKernelShuttingDown;
    }

    /**
     * First node in the cluster clear and reset slot storage
     * This will clear slot related records in database which were created in previous session.
     * @throws AndesException
     */
    private static void clearSlotStorage() throws AndesException {
        SlotManagerClusterMode.getInstance().clearSlotStorage();
        log.info("Slots stored in last session were cleared to avoid duplicates when recovering.");
    }
}


text:
/**
 * Package for testing a simple client-server application.
 *
 * @author Ivan Belyaev (gh0st84@mail.ru)
 * @version $Id$
 * @since 1.0
 */


text:
package jp.fieldnotes.hatunatu.dao.exception;

import jp.fieldnotes.hatunatu.util.exception.SRuntimeException;

public class TokenNotClosedRuntimeException extends SRuntimeException {

    private String token;

    private String sql;

    public TokenNotClosedRuntimeException(String token, String sql) {
        super("EDAO0002", new Object[] { token, sql });
        this.token = token;
        this.sql = sql;
    }

    public String getToken() {
        return token;
    }

    public String getSql() {
        return sql;
    }
}


text:
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.spectrads3;

import com.spectralogic.ds3client.models.BlobStoreTasksInformation;
import com.spectralogic.ds3client.models.ChecksumType;
import com.spectralogic.ds3client.commands.interfaces.AbstractResponse;

public class GetDataPlannerBlobStoreTasksSpectraS3Response extends AbstractResponse {

    private final BlobStoreTasksInformation blobStoreTasksInformationResult;

    public GetDataPlannerBlobStoreTasksSpectraS3Response(final BlobStoreTasksInformation blobStoreTasksInformationResult, final String checksum, final ChecksumType.Type checksumType) {
        super(checksum, checksumType);
        this.blobStoreTasksInformationResult = blobStoreTasksInformationResult;
    }

    public BlobStoreTasksInformation getBlobStoreTasksInformationResult() {
        return this.blobStoreTasksInformationResult;
    }

}