text:
module Spree
  module Admin
    class PaymentsController < Spree::Admin::BaseController
      include Spree::Backend::Callbacks

      before_action :load_order, only: [:create, :new, :index, :fire]
      before_action :load_payment, except: [:create, :new, :index]
      before_action :load_data
      before_action :can_not_transition_without_customer_info

      respond_to :html

      def index
        @payments = @order.payments.includes(:refunds => :reason)
        @refunds = @payments.flat_map(&:refunds)
        redirect_to new_admin_order_payment_url(@order) if @payments.empty?
      end

      def new
        @payment = @order.payments.build
      end

      def create
        invoke_callbacks(:create, :before)
        @payment ||= @order.payments.build(object_params)
        if params[:card].present? and params[:card] != 'new'
          @payment.source = @payment.payment_method.payment_source_class.find_by_id(params[:card])
        end

        begin
          if @payment.save
            invoke_callbacks(:create, :after)
            # Transition order as far as it will go.
            while @order.next; end
            # If "@order.next" didn't trigger payment processing already (e.g. if the order was
            # already complete) then trigger it manually now
            @payment.process! if @order.completed? && @payment.checkout?
            flash[:success] = flash_message_for(@payment, :successfully_created)
            redirect_to admin_order_payments_path(@order)
          else
            invoke_callbacks(:create, :fails)
            flash[:error] = Spree.t(:payment_could_not_be_created)
            render :new
          end
        rescue Spree::Core::GatewayError => e
          invoke_callbacks(:create, :fails)
          flash[:error] = "#{e.message}"
          redirect_to new_admin_order_payment_path(@order)
        end
      end

      def fire
        return unless event = params[:e] and @payment.payment_source

        # Because we have a transition method also called void, we do this to avoid conflicts.
        event = "void_transaction" if event == "void"
        if @payment.send("#{event}!")
          flash[:success] = Spree.t(:payment_updated)
        else
          flash[:error] = Spree.t(:cannot_perform_operation)
        end
      rescue Spree::Core::GatewayError => ge
        flash[:error] = "#{ge.message}"
      ensure
        redirect_to admin_order_payments_path(@order)
      end

      private

      def object_params
        if params[:payment] and params[:payment_source] and source_params = params.delete(:payment_source)[params[:payment][:payment_method_id]]
          params[:payment][:source_attributes] = source_params
        end

        params.require(:payment).permit(permitted_payment_attributes)
      end

      def load_data
        @amount = params[:amount] || load_order.total
        @payment_methods = PaymentMethod.available(:back_end)
        if @payment and @payment.payment_method
          @payment_method = @payment.payment_method
        else
          @payment_method = @payment_methods.first
        end
      end

      def load_order
        @order = Order.find_by_number!(params[:order_id])
        authorize! action, @order
        @order
      end

      def load_payment
        @payment = Payment.find(params[:id])
      end

      def model_class
        Spree::Payment
      end
    end
  end
end


text:
<?php

declare(strict_types=1);

namespace Doctrine\DBAL\Schema\Synchronizer;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Schema\Comparator;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\DBAL\Schema\Visitor\DropSchemaSqlCollector;
use function count;

/**
 * Schema Synchronizer for Default DBAL Connection.
 */
class SingleDatabaseSynchronizer extends AbstractSchemaSynchronizer
{
    /** @var AbstractPlatform */
    private $platform;

    public function __construct(Connection $conn)
    {
        parent::__construct($conn);
        $this->platform = $conn->getDatabasePlatform();
    }

    /**
     * {@inheritdoc}
     */
    public function getCreateSchema(Schema $createSchema) : array
    {
        return $createSchema->toSql($this->platform);
    }

    /**
     * {@inheritdoc}
     */
    public function getUpdateSchema(Schema $toSchema, bool $noDrops = false) : array
    {
        $comparator = new Comparator();
        $sm         = $this->conn->getSchemaManager();

        $fromSchema = $sm->createSchema();
        $schemaDiff = $comparator->compare($fromSchema, $toSchema);

        if ($noDrops) {
            return $schemaDiff->toSaveSql($this->platform);
        }

        return $schemaDiff->toSql($this->platform);
    }

    /**
     * {@inheritdoc}
     */
    public function getDropSchema(Schema $dropSchema) : array
    {
        $visitor = new DropSchemaSqlCollector($this->platform);
        $sm      = $this->conn->getSchemaManager();

        $fullSchema = $sm->createSchema();

        foreach ($fullSchema->getTables() as $table) {
            if ($dropSchema->hasTable($table->getName())) {
                $visitor->acceptTable($table);
            }

            foreach ($table->getForeignKeys() as $foreignKey) {
                if (! $dropSchema->hasTable($table->getName())) {
                    continue;
                }

                if (! $dropSchema->hasTable($foreignKey->getForeignTableName())) {
                    continue;
                }

                $visitor->acceptForeignKey($table, $foreignKey);
            }
        }

        if (! $this->platform->supportsSequences()) {
            return $visitor->getQueries();
        }

        foreach ($dropSchema->getSequences() as $sequence) {
            $visitor->acceptSequence($sequence);
        }

        foreach ($dropSchema->getTables() as $table) {
            $primaryKey = $table->getPrimaryKey();

            if ($primaryKey === null) {
                continue;
            }

            $columns = $primaryKey->getColumns();

            if (count($columns) > 1) {
                continue;
            }

            $checkSequence = $table->getName() . '_' . $columns[0] . '_seq';
            if (! $fullSchema->hasSequence($checkSequence)) {
                continue;
            }

            $visitor->acceptSequence($fullSchema->getSequence($checkSequence));
        }

        return $visitor->getQueries();
    }

    /**
     * {@inheritdoc}
     */
    public function getDropAllSchema() : array
    {
        $sm      = $this->conn->getSchemaManager();
        $visitor = new DropSchemaSqlCollector($this->platform);

        $schema = $sm->createSchema();
        $schema->visit($visitor);

        return $visitor->getQueries();
    }

    /**
     * {@inheritdoc}
     */
    public function createSchema(Schema $createSchema) : void
    {
        $this->processSql($this->getCreateSchema($createSchema));
    }

    /**
     * {@inheritdoc}
     */
    public function updateSchema(Schema $toSchema, bool $noDrops = false) : void
    {
        $this->processSql($this->getUpdateSchema($toSchema, $noDrops));
    }

    /**
     * {@inheritdoc}
     */
    public function dropSchema(Schema $dropSchema) : void
    {
        $this->processSqlSafely($this->getDropSchema($dropSchema));
    }

    /**
     * {@inheritdoc}
     */
    public function dropAllSchema() : void
    {
        $this->processSql($this->getDropAllSchema());
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_apply"
        android:icon="@drawable/ic_ok"
        android:title="@android:string/ok"
        app:showAsAction="ifRoom" />
</menu>


text:
(function() {
	var eventStore = require('../helpers/eventStoreClient');
	var _ = require('underscore');

	module.exports = function(req, res) {

		eventStore
		.projections
		.getAsync()
		.then(function(response) {
			var eventStoreResponse = JSON.parse(response.body);

			var runningStatus = 'Running';

			var nonRunningProjections = _.filter(eventStoreResponse.projections, function(projection) {
				return projection.status !== runningStatus;
			});

			var projectionsStatus = {'status': 'healthy'};

			if(nonRunningProjections.length > 0) {
				projectionsStatus.status = 'errors';
				projectionsStatus = _.extend(projectionsStatus, {'projections': nonRunningProjections});
			}

			res.json(projectionsStatus);
		});

	};
}());


text:
package org.duracloud.glaciertask;

import com.amazonaws.services.s3.AmazonS3;
import org.duracloud.glacierstorage.GlacierStorageProvider;
import org.duracloud.storage.provider.StorageProvider;
import org.duracloud.storage.provider.TaskProviderBase;
import org.slf4j.LoggerFactory;

/**
 * @author: Bill Branan
 * Date: 2/1/13
 */
public class GlacierTaskProvider extends TaskProviderBase {

    public GlacierTaskProvider(StorageProvider glacierProvider,
                               GlacierStorageProvider unwrappedGlacierProvider,
                               AmazonS3 s3Client,
                               String storeId) {
        super(storeId);
        log = LoggerFactory.getLogger(GlacierTaskProvider.class);

        taskList.add(new RestoreContentTaskRunner(glacierProvider,
                                                  unwrappedGlacierProvider,
                                                  s3Client));
    }

}


text: {{content}}


text:
package thereisnospon.com.blogreader.test_mvp_test.model;

import java.util.List;

import thereisnospon.com.blogreader.data.database.ArticleItemCache;
import thereisnospon.com.blogreader.data.database.ArticleType;

/**
 * Created by yzr on 16-2-28.
 */
public interface IArticleCollecModel {

    List<ArticleType>getTypes();
    List<ArticleItemCache>getArticleCaches(ArticleType type);

}


text:
module.exports = {
	INFO_RETRIEVING_STAGES: "- Identifying orphaned stages of REST API id %s...",
	INFO_DELETING_STAGES: "- Deleting orphaned stages...",
	INFO_STAGES_DELETED: "- Orphaned stages deleted.",

	INFO_RETRIEVING_DEPLOYMENTS: "- Identifying orphaned deployments of REST API id %s",
	INFO_DELETING_DEPLOYMENTS: "- Deleting orphaned deployments...",
	INFO_DEPLOYMENTS_DELETED: "- Orphaned deployments deleted.",

	INFO_CLEANUP_START: "Beginning the cleanup of REST API id %s.",
	INFO_CLEANUP_COMPLETE: "Cleanup of REST API id %s complete."
};


text:
import {OnDestroy, OnInit} from '@angular/core';

import {FormGroup} from '../model';

import {ControlContainer} from './control_container';
import {Form} from './form_interface';
import {composeAsyncValidators, composeValidators, controlPath} from './shared';
import {AsyncValidatorFn, ValidatorFn} from './validators';

/**
 * This is a base class for code shared between {@link NgModelGroup} and {@link FormGroupName}.
 *
 * @stable
 */
export class AbstractFormGroupDirective extends ControlContainer implements OnInit, OnDestroy {
  /** @internal */
  _parent: ControlContainer;

  /** @internal */
  _validators: any[];

  /** @internal */
  _asyncValidators: any[];

  ngOnInit(): void {
    this._checkParentType();
    this.formDirective !.addFormGroup(this);
  }

  ngOnDestroy(): void {
    if (this.formDirective) {
      this.formDirective.removeFormGroup(this);
    }
  }

  /**
   * Get the {@link FormGroup} backing this binding.
   */
  get control(): FormGroup { return this.formDirective !.getFormGroup(this); }

  /**
   * Get the path to this control group.
   */
  get path(): string[] { return controlPath(this.name, this._parent); }

  /**
   * Get the {@link Form} to which this group belongs.
   */
  get formDirective(): Form|null { return this._parent ? this._parent.formDirective : null; }

  get validator(): ValidatorFn|null { return composeValidators(this._validators); }

  get asyncValidator(): AsyncValidatorFn|null {
    return composeAsyncValidators(this._asyncValidators);
  }

  /** @internal */
  _checkParentType(): void {}
}


text:
package org.springframework.hateoas.core;

import static org.springframework.core.annotation.AnnotatedElementUtils.*;
import static org.springframework.core.annotation.AnnotationUtils.*;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.regex.Pattern;

import org.springframework.util.Assert;

/**
 * {@link MappingDiscoverer} implementation that inspects mappings from a particular annotation.
 *
 * @author Oliver Gierke
 * @author Mark Paluch
 */
public class AnnotationMappingDiscoverer implements MappingDiscoverer {

	private static final Pattern MULTIPLE_SLASHES = Pattern.compile("\\/{2,}");

	private final Class<? extends Annotation> annotationType;
	private final String mappingAttributeName;

	/**
	 * Creates an {@link AnnotationMappingDiscoverer} for the given annotation type. Will lookup the {@code value}
	 * attribute by default.
	 *
	 * @param annotation must not be {@literal null}.
	 */
	public AnnotationMappingDiscoverer(Class<? extends Annotation> annotation) {
		this(annotation, null);
	}

	/**
	 * Creates an {@link AnnotationMappingDiscoverer} for the given annotation type and attribute name.
	 *
	 * @param annotation must not be {@literal null}.
	 * @param mappingAttributeName if {@literal null}, it defaults to {@code value}.
	 */
	public AnnotationMappingDiscoverer(Class<? extends Annotation> annotation, String mappingAttributeName) {

		Assert.notNull(annotation, "Annotation must not be null!");

		this.annotationType = annotation;
		this.mappingAttributeName = mappingAttributeName;
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.hateoas.core.MappingDiscoverer#getMapping(java.lang.Class)
	 */
	@Override
	public String getMapping(Class<?> type) {

		Assert.notNull(type, "Type must not be null!");

		String[] mapping = getMappingFrom(findMergedAnnotation(type, annotationType));

		return mapping.length == 0 ? null : mapping[0];
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.hateoas.core.MappingDiscoverer#getMapping(java.lang.reflect.Method)
	 */
	@Override
	public String getMapping(Method method) {

		Assert.notNull(method, "Method must not be null!");
		return getMapping(method.getDeclaringClass(), method);
	}

	/*
	 * (non-Javadoc)
	 * @see org.springframework.hateoas.core.MappingDiscoverer#getMapping(java.lang.Class, java.lang.reflect.Method)
	 */
	@Override
	public String getMapping(Class<?> type, Method method) {

		Assert.notNull(type, "Type must not be null!");
		Assert.notNull(method, "Method must not be null!");

		String[] mapping = getMappingFrom(findMergedAnnotation(method, annotationType));
		String typeMapping = getMapping(type);

		if (mapping == null || mapping.length == 0) {
			return typeMapping;
		}

		return typeMapping == null || "/".equals(typeMapping) ? mapping[0] : join(typeMapping, mapping[0]);
	}

	private String[] getMappingFrom(Annotation annotation) {

		Object value = mappingAttributeName == null ? getValue(annotation) : getValue(annotation, mappingAttributeName);

		if (value instanceof String) {
			return new String[] { (String) value };
		} else if (value instanceof String[]) {
			return (String[]) value;
		} else if (value == null) {
			return new String[0];
		}

		throw new IllegalStateException(String.format(
				"Unsupported type for the mapping attribute! Support String and String[] but got %s!", value.getClass()));
	}

	/**
	 * Joins the given mappings making sure exactly one slash.
	 *
	 * @param typeMapping must not be {@literal null} or empty.
	 * @param mapping must not be {@literal null} or empty.
	 * @return
	 */
	private static String join(String typeMapping, String mapping) {
		return MULTIPLE_SLASHES.matcher(typeMapping.concat("/").concat(mapping)).replaceAll("/");
	}
}


text:
from unittest import mock

from oslo_utils import uuidutils

from magnum.common import context
from magnum.common import exception
from magnum.common.rpc_service import CONF
from magnum.db.sqlalchemy import api as dbapi
from magnum.drivers.common import driver
from magnum.drivers.common import k8s_monitor
from magnum import objects
from magnum.objects.fields import ClusterHealthStatus as cluster_health_status
from magnum.objects.fields import ClusterStatus as cluster_status
from magnum.service import periodic
from magnum.tests import base
from magnum.tests import fake_notifier
from magnum.tests import fakes
from magnum.tests.unit.db import utils

class fake_stack(object):
    def __init__(self, **kw):
        for key, val in kw.items():
            setattr(self, key, val)

# This dictionary will be populated by setUp to help mock
# the nodegroup list magnum.db.api.get_cluster_nodergoups.
cluster_ngs = {}

def mock_nodegroup_list(cls, dummy_context, cluster_id, **kwargs):
    try:
        return cluster_ngs[cluster_id]
    except KeyError:
        return []

class PeriodicTestCase(base.TestCase):

    def setUp(self):
        super(PeriodicTestCase, self).setUp()

        self.context = context.make_admin_context()

        # Can be identical for all clusters.
        trust_attrs = {
            'trustee_username': '5d12f6fd-a196-4bf0-ae4c-1f639a523a52',
            'trustee_password': 'ain7einaebooVaig6d',
            'trust_id': '39d920ca-67c6-4047-b57a-01e9e16bb96f',
            }

        uuid = uuidutils.generate_uuid()
        trust_attrs.update({'id': 1, 'stack_id': '11', 'uuid': uuid,
                            'status': cluster_status.CREATE_IN_PROGRESS,
                            'status_reason': 'no change',
                            'keypair': 'keipair1', 'health_status': None})
        cluster1 = utils.get_test_cluster(**trust_attrs)
        ngs1 = utils.get_nodegroups_for_cluster()
        uuid = uuidutils.generate_uuid()
        trust_attrs.update({'id': 2, 'stack_id': '22', 'uuid': uuid,
                            'status': cluster_status.DELETE_IN_PROGRESS,
                            'status_reason': 'no change',
                            'keypair': 'keipair1', 'health_status': None})
        cluster2 = utils.get_test_cluster(**trust_attrs)
        ngs2 = utils.get_nodegroups_for_cluster()
        uuid = uuidutils.generate_uuid()
        trust_attrs.update({'id': 3, 'stack_id': '33', 'uuid': uuid,
                            'status': cluster_status.UPDATE_IN_PROGRESS,
                            'status_reason': 'no change',
                            'keypair': 'keipair1', 'health_status': None})
        cluster3 = utils.get_test_cluster(**trust_attrs)
        ngs3 = utils.get_nodegroups_for_cluster()
        uuid = uuidutils.generate_uuid()
        trust_attrs.update({'id': 4, 'stack_id': '44', 'uuid': uuid,
                            'status': cluster_status.DELETE_IN_PROGRESS,
                            'status_reason': 'no change',
                            'keypair': 'keipair1', 'health_status': None})
        cluster4 = utils.get_test_cluster(**trust_attrs)
        ngs4 = utils.get_nodegroups_for_cluster()
        uuid = uuidutils.generate_uuid()
        trust_attrs.update({'id': 5, 'stack_id': '55', 'uuid': uuid,
                            'status': cluster_status.ROLLBACK_IN_PROGRESS,
                            'status_reason': 'no change',
                            'keypair': 'keipair1', 'health_status': None})
        cluster5 = utils.get_test_cluster(**trust_attrs)
        ngs5 = utils.get_nodegroups_for_cluster()

        self.nodegroups1 = [
            objects.NodeGroup(self.context, **ngs1['master']),
            objects.NodeGroup(self.context, **ngs1['worker'])
        ]
        self.nodegroups2 = [
            objects.NodeGroup(self.context, **ngs2['master']),
            objects.NodeGroup(self.context, **ngs2['worker'])
        ]
        self.nodegroups3 = [
            objects.NodeGroup(self.context, **ngs3['master']),
            objects.NodeGroup(self.context, **ngs3['worker'])
        ]
        self.nodegroups4 = [
            objects.NodeGroup(self.context, **ngs4['master']),
            objects.NodeGroup(self.context, **ngs4['worker'])
        ]
        self.nodegroups5 = [
            objects.NodeGroup(self.context, **ngs5['master']),
            objects.NodeGroup(self.context, **ngs5['worker'])
        ]

        self.cluster1 = objects.Cluster(self.context, **cluster1)
        self.cluster2 = objects.Cluster(self.context, **cluster2)
        self.cluster3 = objects.Cluster(self.context, **cluster3)
        self.cluster4 = objects.Cluster(self.context, **cluster4)
        self.cluster5 = objects.Cluster(self.context, **cluster5)

        # This is used to mock the get_cluster_nodegroups from magnum.db.api.
        # It's not the greatest way to do it, But we have to populate the
        # dictionary in the runtime (or have statically defined uuids per NG).
        global cluster_ngs
        cluster_ngs = {
            self.cluster1.uuid: self.nodegroups1,
            self.cluster2.uuid: self.nodegroups2,
            self.cluster3.uuid: self.nodegroups3,
            self.cluster4.uuid: self.nodegroups4,
            self.cluster5.uuid: self.nodegroups5
        }

        # these tests are based on the basic behavior of our standard
        # Heat-based drivers, but drivers based on other orchestration
        # methods should generally behave in a similar fashion as far
        # as the actual calls go. It is up to the driver implementor
        # to ensure their implementation of update_cluster_status behaves
        # as expected regardless of how the periodic updater task works
        self.mock_heat_client = mock.MagicMock()
        self.stack1 = fake_stack(
            id='11', stack_status=cluster_status.CREATE_COMPLETE,
            stack_status_reason='fake_reason_11')
        self.stack2 = fake_stack(
            id='22', stack_status=cluster_status.DELETE_IN_PROGRESS,
            stack_status_reason='fake_reason_11')
        self.stack3 = fake_stack(
            id='33', stack_status=cluster_status.UPDATE_COMPLETE,
            stack_status_reason='fake_reason_33')
        self.stack5 = fake_stack(
            id='55', stack_status=cluster_status.ROLLBACK_COMPLETE,
            stack_status_reason='fake_reason_55')
        self.mock_heat_client.stacks.list.return_value = [
            self.stack1, self.stack2, self.stack3, self.stack5]

        self.get_stacks = {
            '11': self.stack1,
            '22': self.stack2,
            '33': self.stack3,
            '55': self.stack5
        }

        self.mock_driver = mock.MagicMock(spec=driver.Driver)

        def _mock_update_status(context, cluster):
            try:
                stack = self.get_stacks[cluster.stack_id]
            except KeyError:
                cluster.status_reason = "Stack %s not found" % cluster.stack_id
                if cluster.status == "DELETE_IN_PROGRESS":
                    cluster.status = cluster_status.DELETE_COMPLETE
                else:
                    cluster.status = cluster.status.replace("IN_PROGRESS",
                                                            "FAILED")
                    cluster.status = cluster.status.replace("COMPLETE",
                                                            "FAILED")
            else:
                if cluster.status != stack.stack_status:
                    cluster.status = stack.stack_status
                    cluster.status_reason = stack.stack_status_reason

        self.mock_driver.update_cluster_status.side_effect = (
            _mock_update_status)

    @mock.patch('magnum.drivers.common.driver.Driver.get_driver_for_cluster')
    def test_update_status_non_trusts_error(self, mock_get_driver):
        mock_get_driver.return_value = self.mock_driver
        trust_ex = ("Unknown Keystone error")
        self.mock_driver.update_cluster_status.side_effect = \
            exception.AuthorizationFailure(client='keystone', message=trust_ex)
        self.assertRaises(
            exception.AuthorizationFailure,
            periodic.ClusterUpdateJob(
                self.context, self.cluster1).update_status
        )
        self.assertEqual(1, self.mock_driver.update_cluster_status.call_count)

    @mock.patch('magnum.drivers.common.driver.Driver.get_driver_for_cluster')
    def test_update_status_trusts_not_found(self, mock_get_driver):
        mock_get_driver.return_value = self.mock_driver
        trust_ex = ("Could not find trust: %s" % self.cluster1.trust_id)
        self.mock_driver.update_cluster_status.side_effect = \
            exception.AuthorizationFailure(client='keystone', message=trust_ex)
        self.assertRaises(
            exception.AuthorizationFailure,
            periodic.ClusterUpdateJob(
                self.context, self.cluster1).update_status
        )
        self.assertEqual(2, self.mock_driver.update_cluster_status.call_count)

    @mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall',
                new=fakes.FakeLoopingCall)
    @mock.patch('magnum.drivers.common.driver.Driver.get_driver_for_cluster')
    @mock.patch('magnum.objects.Cluster.list')
    @mock.patch.object(dbapi.Connection, 'destroy_nodegroup')
    @mock.patch.object(dbapi.Connection, 'destroy_cluster')
    def test_sync_cluster_status_changes(self, mock_db_destroy,
                                         mock_ng_destroy,
                                         mock_cluster_list,
                                         mock_get_driver):

        mock_cluster_list.return_value = [self.cluster1, self.cluster2,
                                          self.cluster3, self.cluster4,
                                          self.cluster5]
        mock_get_driver.return_value = self.mock_driver

        with mock.patch.object(dbapi.Connection, 'list_cluster_nodegroups',
                               mock_nodegroup_list):
            periodic.MagnumPeriodicTasks(CONF).sync_cluster_status(None)

            self.assertEqual(cluster_status.CREATE_COMPLETE,
                             self.cluster1.status)
            self.assertEqual('fake_reason_11', self.cluster1.status_reason)
            # make sure cluster 2 didn't change
            self.assertEqual(cluster_status.DELETE_IN_PROGRESS,
                             self.cluster2.status)
            self.assertEqual('no change', self.cluster2.status_reason)
            self.assertEqual(cluster_status.UPDATE_COMPLETE,
                             self.cluster3.status)
            self.assertEqual('fake_reason_33', self.cluster3.status_reason)
            self.assertEqual(2, mock_ng_destroy.call_count)
            mock_db_destroy.assert_called_once_with(self.cluster4.uuid)
            self.assertEqual(cluster_status.ROLLBACK_COMPLETE,
                             self.cluster5.status)
            self.assertEqual('fake_reason_55', self.cluster5.status_reason)
            notifications = fake_notifier.NOTIFICATIONS
            self.assertEqual(4, len(notifications))

    @mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall',
                new=fakes.FakeLoopingCall)
    @mock.patch('magnum.drivers.common.driver.Driver.get_driver_for_cluster')
    @mock.patch('magnum.objects.Cluster.list')
    def test_sync_cluster_status_not_changes(self, mock_cluster_list,
                                             mock_get_driver):

        self.stack1.stack_status = self.cluster1.status
        self.stack2.stack_status = self.cluster2.status
        self.stack3.stack_status = self.cluster3.status
        self.stack5.stack_status = self.cluster5.status
        mock_cluster_list.return_value = [self.cluster1, self.cluster2,
                                          self.cluster3, self.cluster5]
        mock_get_driver.return_value = self.mock_driver

        periodic.MagnumPeriodicTasks(CONF).sync_cluster_status(None)

        self.assertEqual(cluster_status.CREATE_IN_PROGRESS,
                         self.cluster1.status)
        self.assertEqual('no change', self.cluster1.status_reason)
        self.assertEqual(cluster_status.DELETE_IN_PROGRESS,
                         self.cluster2.status)
        self.assertEqual('no change', self.cluster2.status_reason)
        self.assertEqual(cluster_status.UPDATE_IN_PROGRESS,
                         self.cluster3.status)
        self.assertEqual('no change', self.cluster3.status_reason)
        self.assertEqual(cluster_status.ROLLBACK_IN_PROGRESS,
                         self.cluster5.status)
        self.assertEqual('no change', self.cluster5.status_reason)
        notifications = fake_notifier.NOTIFICATIONS
        self.assertEqual(0, len(notifications))

    @mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall',
                new=fakes.FakeLoopingCall)
    @mock.patch('magnum.drivers.common.driver.Driver.get_driver_for_cluster')
    @mock.patch('magnum.objects.Cluster.list')
    @mock.patch.object(dbapi.Connection, 'destroy_cluster')
    @mock.patch.object(dbapi.Connection, 'destroy_nodegroup')
    def test_sync_cluster_status_heat_not_found(self, mock_ng_destroy,
                                                mock_db_destroy,
                                                mock_cluster_list,
                                                mock_get_driver):
        self.get_stacks.clear()
        mock_get_driver.return_value = self.mock_driver
        mock_cluster_list.return_value = [self.cluster1, self.cluster2,
                                          self.cluster3, self.cluster4,
                                          self.cluster5]

        with mock.patch.object(dbapi.Connection, 'list_cluster_nodegroups',
                               mock_nodegroup_list):
            periodic.MagnumPeriodicTasks(CONF).sync_cluster_status(None)

            self.assertEqual(cluster_status.CREATE_FAILED,
                             self.cluster1.status)
            self.assertEqual('Stack 11 not found', self.cluster1.status_reason)
            self.assertEqual(cluster_status.UPDATE_FAILED,
                             self.cluster3.status)
            self.assertEqual('Stack 33 not found', self.cluster3.status_reason)
            self.assertEqual(cluster_status.ROLLBACK_FAILED,
                             self.cluster5.status)
            self.assertEqual('Stack 55 not found', self.cluster5.status_reason)
            mock_db_destroy.assert_has_calls([
                mock.call(self.cluster2.uuid),
                mock.call(self.cluster4.uuid)
            ])
            self.assertEqual(2, mock_db_destroy.call_count)
            notifications = fake_notifier.NOTIFICATIONS
            self.assertEqual(5, len(notifications))

    @mock.patch('magnum.conductor.monitors.create_monitor')
    @mock.patch('magnum.objects.Cluster.list')
    @mock.patch('magnum.common.rpc.get_notifier')
    @mock.patch('magnum.common.context.make_admin_context')
    def test_send_cluster_metrics(self, mock_make_admin_context,
                                  mock_get_notifier, mock_cluster_list,
                                  mock_create_monitor):
        """Test if RPC notifier receives the expected message"""
        CONF.set_override('send_cluster_metrics', True, group='drivers')
        mock_make_admin_context.return_value = self.context
        notifier = mock.MagicMock()
        mock_get_notifier.return_value = notifier
        mock_cluster_list.return_value = [self.cluster1, self.cluster2,
                                          self.cluster3, self.cluster4]
        self.cluster4.status = cluster_status.CREATE_COMPLETE
        monitor = mock.MagicMock()
        monitor.get_metric_names.return_value = ['metric1', 'metric2']
        monitor.compute_metric_value.return_value = 30
        monitor.get_metric_unit.return_value = '%'
        mock_create_monitor.return_value = monitor

        periodic.MagnumPeriodicTasks(CONF)._send_cluster_metrics(self.context)

        expected_event_type = 'magnum.cluster.metrics.update'
        expected_metrics = [
            {
                'name': 'metric1',
                'value': 30,
                'unit': '%',
            },
            {
                'name': 'metric2',
                'value': 30,
                'unit': '%',
            },
        ]
        expected_msg = {
            'user_id': self.cluster4.user_id,
            'project_id': self.cluster4.project_id,
            'resource_id': self.cluster4.uuid,
            'metrics': expected_metrics
        }

        self.assertEqual(1, mock_create_monitor.call_count)
        notifier.info.assert_called_once_with(
            self.context, expected_event_type, expected_msg)

    @mock.patch('magnum.conductor.monitors.create_monitor')
    @mock.patch('magnum.objects.Cluster.list')
    @mock.patch('magnum.common.rpc.get_notifier')
    @mock.patch('magnum.common.context.make_admin_context')
    def test_send_cluster_metrics_compute_metric_raise(
            self, mock_make_admin_context, mock_get_notifier,
            mock_cluster_list, mock_create_monitor):
        CONF.set_override('send_cluster_metrics', True, group='drivers')
        mock_make_admin_context.return_value = self.context
        notifier = mock.MagicMock()
        mock_get_notifier.return_value = notifier
        mock_cluster_list.return_value = [self.cluster4]
        self.cluster4.status = cluster_status.CREATE_COMPLETE
        monitor = mock.MagicMock()
        monitor.get_metric_names.return_value = ['metric1', 'metric2']
        monitor.compute_metric_value.side_effect = Exception(
            "error on computing metric")
        mock_create_monitor.return_value = monitor

        periodic.MagnumPeriodicTasks(CONF)._send_cluster_metrics(self.context)

        expected_event_type = 'magnum.cluster.metrics.update'
        expected_msg = {
            'user_id': self.cluster4.user_id,
            'project_id': self.cluster4.project_id,
            'resource_id': self.cluster4.uuid,
            'metrics': []
        }
        self.assertEqual(1, mock_create_monitor.call_count)
        notifier.info.assert_called_once_with(
            self.context, expected_event_type, expected_msg)

    @mock.patch('magnum.conductor.monitors.create_monitor')
    @mock.patch('magnum.objects.Cluster.list')
    @mock.patch('magnum.common.rpc.get_notifier')
    @mock.patch('magnum.common.context.make_admin_context')
    def test_send_cluster_metrics_pull_data_raise(
            self, mock_make_admin_context, mock_get_notifier,
            mock_cluster_list, mock_create_monitor):
        CONF.set_override('send_cluster_metrics', True, group='drivers')
        mock_make_admin_context.return_value = self.context
        notifier = mock.MagicMock()
        mock_get_notifier.return_value = notifier
        mock_cluster_list.return_value = [self.cluster4]
        self.cluster4.status = cluster_status.CREATE_COMPLETE
        monitor = mock.MagicMock()
        monitor.pull_data.side_effect = Exception("error on pulling data")
        mock_create_monitor.return_value = monitor

        periodic.MagnumPeriodicTasks(CONF)._send_cluster_metrics(self.context)

        self.assertEqual(1, mock_create_monitor.call_count)
        self.assertEqual(0, notifier.info.call_count)

    @mock.patch('magnum.conductor.monitors.create_monitor')
    @mock.patch('magnum.objects.Cluster.list')
    @mock.patch('magnum.common.rpc.get_notifier')
    @mock.patch('magnum.common.context.make_admin_context')
    def test_send_cluster_metrics_monitor_none(
            self, mock_make_admin_context, mock_get_notifier,
            mock_cluster_list, mock_create_monitor):
        CONF.set_override('send_cluster_metrics', True, group='drivers')
        mock_make_admin_context.return_value = self.context
        notifier = mock.MagicMock()
        mock_get_notifier.return_value = notifier
        mock_cluster_list.return_value = [self.cluster4]
        self.cluster4.status = cluster_status.CREATE_COMPLETE
        mock_create_monitor.return_value = None

        periodic.MagnumPeriodicTasks(CONF)._send_cluster_metrics(self.context)

        self.assertEqual(1, mock_create_monitor.call_count)
        self.assertEqual(0, notifier.info.call_count)

    @mock.patch('magnum.conductor.monitors.create_monitor')
    @mock.patch('magnum.objects.Cluster.list')
    @mock.patch('magnum.common.rpc.get_notifier')
    @mock.patch('magnum.common.context.make_admin_context')
    def test_send_cluster_metrics_disable_pull_data(
            self, mock_make_admin_context, mock_get_notifier,
            mock_cluster_list, mock_create_monitor):

        mock_make_admin_context.return_value = self.context
        notifier = mock.MagicMock()
        mock_get_notifier.return_value = notifier
        mock_cluster_list.return_value = [self.cluster1, self.cluster2,
                                          self.cluster3, self.cluster4]
        self.cluster4.status = cluster_status.CREATE_COMPLETE
        monitor = mock.MagicMock()
        monitor.get_metric_names.return_value = ['metric1', 'metric2']
        monitor.compute_metric_value.return_value = 30
        monitor.get_metric_unit.return_value = '%'
        mock_create_monitor.return_value = monitor

        periodic.MagnumPeriodicTasks(CONF)._send_cluster_metrics(self.context)

        self.assertEqual(0, mock_create_monitor.call_count)
        self.assertEqual(0, notifier.info.call_count)

    @mock.patch('oslo_service.loopingcall.FixedIntervalLoopingCall',
                new=fakes.FakeLoopingCall)
    @mock.patch('magnum.conductor.monitors.create_monitor')
    @mock.patch('magnum.objects.Cluster.list')
    @mock.patch('magnum.common.rpc.get_notifier')
    @mock.patch('magnum.common.context.make_admin_context')
    def test_sync_cluster_health_status(self, mock_make_admin_context,
                                        mock_get_notifier, mock_cluster_list,
                                        mock_create_monitor):
        """Test sync cluster health status"""
        mock_make_admin_context.return_value = self.context
        notifier = mock.MagicMock()
        mock_get_notifier.return_value = notifier
        mock_cluster_list.return_value = [self.cluster4]
        self.cluster4.status = cluster_status.CREATE_COMPLETE
        health = {'health_status': cluster_health_status.UNHEALTHY,
                  'health_status_reason': {'api': 'ok', 'node-0.Ready': False}}
        monitor = mock.MagicMock(spec=k8s_monitor.K8sMonitor, name='test',
                                 data=health)
        mock_create_monitor.return_value = monitor
        periodic.MagnumPeriodicTasks(CONF).sync_cluster_health_status(
            self.context)

        self.assertEqual(cluster_health_status.UNHEALTHY,
                         self.cluster4.health_status)
        self.assertEqual({'api': 'ok', 'node-0.Ready': 'False'},
                         self.cluster4.health_status_reason)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>lang property - SpeechSynthesisUtterance class - polymer_app_layout.behaviors library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the lang property from the SpeechSynthesisUtterance class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

polymer_app_layout_template

polymer_app_layout.behaviors

SpeechSynthesisUtterance

lang

lang

polymer_app_layout_template

polymer_app_layout.behaviors

SpeechSynthesisUtterance

lang

property
 lang

polymer_app_layout_template

polymer_app_layout.behaviors

SpeechSynthesisUtterance

Constants

boundaryEvent

endEvent

errorEvent

markEvent

pauseEvent

resumeEvent

startEvent

Properties

lang

on

onBoundary

onEnd

onError

onMark

onPause

onResume

onStart

pitch

rate

text

voice

volume

Constructors

SpeechSynthesisUtterance

Methods

addEventListener

dispatchEvent

removeEventListener

        String
        lang

            read / write

Not documented.

                  polymer_app_layout_template 0.1.0 api docs

                •

                •

                  cc license


text:
import sys
import os
from optparse import OptionParser

def extract_dict_features(pair_file, feature_file, src_dict_file,
                          tgt_dict_file):
    src_dict = set()
    tgt_dict = set()

    with open(pair_file) as fin, open(feature_file, 'w') as feature_out, open(
            src_dict_file, 'w') as src_dict_out, open(tgt_dict_file,
                                                      'w') as tgt_dict_out:
        for line in fin:
            sentence, labels = line.strip().split('\t')
            sentence_list = sentence.split()
            labels_list = labels.split()

            src_dict.update(sentence_list)
            tgt_dict.update(labels_list)

            verb_index = labels_list.index('B-V')
            verb_feature = sentence_list[verb_index]

            mark = [0] * len(labels_list)
            if verb_index > 0:
                mark[verb_index - 1] = 1
                ctx_n1 = sentence_list[verb_index - 1]
            else:
                ctx_n1 = 'bos'
            ctx_n1_feature = ctx_n1

            mark[verb_index] = 1
            ctx_0_feature = sentence_list[verb_index]

            if verb_index < len(labels_list) - 2:
                mark[verb_index + 1] = 1
                ctx_p1 = sentence_list[verb_index + 1]
            else:
                ctx_p1 = 'eos'
            ctx_p1_feature = ctx_p1

            feature_str  = sentence + '\t' \
                           + verb_feature + '\t' \
                           + ctx_n1_feature + '\t' \
                           + ctx_0_feature + '\t' \
                           + ctx_p1_feature + '\t' \
                           + ' '.join([str(i) for i in mark]) + '\t' \
                           + labels

            feature_out.write(feature_str + '\n')

        src_dict_out.write('<unk>\n')
        src_dict_out.write('\n'.join(list(src_dict)))

        tgt_dict_out.write('\n'.join(list(tgt_dict)))

if __name__ == '__main__':

    usage = '-p pair_file -f feature_file -s source dictionary -t target dictionary '
    parser = OptionParser(usage)
    parser.add_option('-p', dest='pair_file', help='the pair file')
    parser.add_option(
        '-f', dest='feature_file', help='the file to store feature')
    parser.add_option(
        '-s', dest='src_dict', help='the file to store source dictionary')
    parser.add_option(
        '-t', dest='tgt_dict', help='the file to store target dictionary')

    (options, args) = parser.parse_args()

    extract_dict_features(options.pair_file, options.feature_file,
                          options.src_dict, options.tgt_dict)


text:
require 'gcal_mapper/authentification/base'
require 'yaml'

module GcalMapper
  class Authentification
    #
    # make the authentification with Oauth2 and request data from google calendar.
    #
    class Oauth2 < Authentification::Base

      # intialize client info needed for connection to Oauth2.
      #
      # @param [String] yaml_file path to the yaml file which contains acess token, ...
      def initialize (yaml_file)
        begin
          oauth_yaml = YAML.load_file(yaml_file)
          @client_id = oauth_yaml["client_id"]
          @client_secret = oauth_yaml["client_secret"]
          @scope = oauth_yaml["scope"]
          @refresh_token = oauth_yaml["refresh_token"]
          @access_token = oauth_yaml["access_token"]
          @validity = Time.now.getutc.to_i
        rescue
          raise GcalMapper::AuthFileError
        end
      end

      # give the acess token for th application and refresh if it is outdated
      #
      # @return [String] access token
      def access_token
        if (Time.now.getutc.to_i - @validity) > 3600
          refresh_token
        end

        @access_token
      end

      # refresh the token by using refresh token
      #
      # @return [String] access token
      def refresh_token
        data = {
          'client_id' => @client_id,
          'client_secret' => @client_secret,
          'refresh_token' => @refresh_token,
          'grant_type' => 'refresh_token'
        }
        options = {
          :method => :post,
          :headers => {'Content-Type' => 'application/x-www-form-urlencoded'},
          :parameters => data
        }
        req = GcalMapper::RestRequest.new(Authentification::REQUEST_URL, options)
        begin
          response = req.execute
        rescue
          raise GcalMapper::AuthentificationError
        end
        @validity = Time.now.getutc.to_i

        @access_token = response['access_token']
        response
      end

    end
  end
end


text:
A popular option for organizations that have an existing endpoint management solution like LANDesk Management Suite ®, Microsoft System Center, or Novell ZENworks is to deploy containerized applications as standalone executables. These executables are built on the SVM architecture and work just like a container.

Deploying applications within containers is convenient for running different versions of applications like Internet Explorer 8 and 11 side-by-side on the same system.

To produce an executable output, set the **Project Type** to **ISV Application** in Turbo Studio. Executables can be deployed directly to the users device or to a network share and do not have any dependency requirements.

An enterprise license for Turbo Studio is required to enable executable outputs. Contact our [sales team](mailto:sales@turbo.net) for more information.

#### Command Line Options

Standalone executables have many command line options to change settings at runtime. The following is a list of available options. Note that these are case sensitive and must be specified before any command line options to the application itself.

		Setting
		Description

		/XEnv=VariableName=Value
		Specifies additional environment variables. Multiple /XEnv arguments can add additional environment variables.

		/XLayerPath=LayerPath
		Adds the given SVM into the virtual environment. Multiple /XLayerPath arguments can add additional virtual layers. Refer to 'Specify Additional SVMs for a Container' for more information.

		/XSandboxPath=SandboxPath
		Specifies the path for the application sandbox.

		/XShellEx=Command
		Specifies a shell execute command to launch from within the virtual application environment. This option overrides any startup files specified in the virtual application configuration. Only one /XShellEx argument can be specified.

		/XShellExVerb=CommandVerb
		Specifies the verb to use in conjunction with the XShellEx command. The default verb is OPEN.

		/XLogPath=LogPath
		Specifies the destination path for generated log files (only applies to executables running in diagnostic-mode). This path can include a custom file name pattern (ie. "/XLogPath=c:\logs\mylog*.log"). The output directory must exist for the logs to be written.

		/XSpawnVmExceptions=ProcessExceptions
		Accepts a semi-colon delimited list of processes add to the child process exception list.

		/XRegRoot=RegistryCacheRoot
		Specifies an override to the runtime-registry-cache portion of the sandbox.

		/XEnable=Setting and /XDisable=Setting
		Enables or disables specific process configuration options. These options include:
ChildProcAsUser
DeleteSandbox
DEPCompat
Diagnostics
DRMCompat
ExeOptimization
IndicateElevated
IndicateVirtualization
IsolateWindowClasses
NotifyProcStarts
ReadOnly
ReadShare
ShutdownProctree
SpawnComServers
SpawnVM
SuppressCollisionCheck

See [VM Settings](/docs/reference/vm-settings-and-variables#command-line-settings) for details on the available settings.

		/XCollisionCheck=FALSE
		Disables detection of multiple apps attempting to use the same sandbox at the same time. This should only be used to support legacy behavior.

#### Specify Additional SVMs for a Container

When you have updates or patches you can use Turbo Studio to specify additional SVMs for applications. Studio provides two mechanisms to accomplish this. Both methods support path tokens (ie. @APPDIR@) and must specify the full path to SVM dependencies.

##### Using Studio

One mechanism is to specify the SVM dependencies in Turbo Studio.

![](/docs/studio/working_with_turbo_studio/svms1.png)

The SVMs dependency editor can be accessed by clicking on 'Settings' button, then 'Process Configuration' tab, then 'SVMs' button.

![](/docs/studio/working_with_turbo_studio/svms2.png)

The first field is the **SVM Search Pattern** field. Here users can enter the complete path to where multiple SVMs are located using a wildcard. An example of using a wildcard in the search field is `@APPDIR@\patches\*.svm`.

Multiple SVMs may be specified for the **SVM Search Pattern** field in a semi-colon delimited list. SVMs specified first in the list will take precedence over SVMs specified later in the list. If multiple SVMs match a search pattern through the use of the '*' wildcard, the SVMs are applied in reverse-alphabetical priority (ie items in `patch_002.svm` would have higher priority than items in `patch_001.svm`).

The second field allows required SVMs to be specified. Wildcard characters are not valid for this and a specific path must be used. If the file is not found during application launch, an error will be reported and the launch will be aborted.

##### Using Command Line

Another mechanism is by using the `/XLayerPath=` command line option. This parameter takes a path to additional SVMs to load. This can be useful for dynamically creating container environments depending on other user settings. These runtime settings augment any which are built into the SVM.

An example of a specified SVM path using full path:
```
# look for 'patches.svm' in the same directory as 'virtual-app.exe'
> virtual-app.exe /XLayerPath=@APPDIR@\patches.svm

# look for 'patches.svm' in a specific location on the local machine
> virtual-app.exe /XLayerPath=c:\path\to\patches.svm

# look for 'patches.svm' on a unc share
> virtual-app.exe /XLayerPath=\\server\dir\patches.svm
```

An example of specifying SVMs from multiple locations:
```
> virtual-app.exe /XLayerPath=@APPDIR@\patches.svm /XLayerPath=@APPDIR@\officepatches.svm
```

An example using a path with wildcard:
```
> virtual-app.exe /XLayerPath=c:\path\to\patches\*.svm
```
This performs a wildcard match finding any files that match the pattern, such as 'c:\path\to\patches\patch_001.svm'.

Note: SVMs that are discovered by wildcard are applied in reverse-alphabetical priority. For example, items in 'patch_002.svm' have higher priority than items in 'patch_001.svm'.

#### Startup File Triggers

A container package can define several startup files. These can all be activated on launch or they can be configured to only be launched given a specified trigger. This is useful for suite applications (like Microsoft Office) where most of the container package is shared.

In Turbo Studio, the startup file triggers are managed in the 'Startup Files' dialog.

![](/docs/studio/working_with_turbo_studio/triggers1.png)

In this example, an application package is defined with three startup files; word, excel, and access. Any startup files that don't have a specific trigger or have Auto Start enabled will be launched by default. Any startup file that has a trigger (but not 'auto start') will not be launched unless the trigger is specified. Multiple startup files can have the same trigger to enable grouped launching.

To launch a startup file by its trigger, specify its trigger as the first parameter to the container .exe:
```
# to launch word
> virtual-app.exe WORD

# to launch access
> virtual-app.exe ACCESS

# to launch excel
> virtual-app.exe EXCEL

# to launch excel as the default
> virtual-app.exe
```

To create an easy-to-access shortcut for a trigger, right-click on your packaged executable and select **Create shortcut**. Then, right-click on the newly created shortcut and append the trigger to the **Target** field. Change the shortcut name and icon to differentiate the application entry point that will be launched when the user runs the shortcut.

![](/docs/studio/working_with_turbo_studio/triggers2.png)


text:
Denouncer allows you to send notifications for occuring errors within your ruby applications.
Right now it supports SMTP to send mail notifications with error details.
The gem is designed to be extendable and provides a simple interface to implement other notification
methods.

## Build status

[![Build Status](https://travis-ci.org/julweber/denouncer.svg)](https://travis-ci.org/julweber/denouncer)

## Current gem version

[![Gem Version](https://badge.fury.io/rb/denouncer.svg)](http://badge.fury.io/rb/denouncer)

## Installation

Add this line to your application's Gemfile:

    gem 'denouncer'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install denouncer

## Configuration

The configuration options depend on the chosen Notifier.
Basic configuration variables are:
* application_name - the name of your application (required)

### Console Notifier

The ConsoleNotifier is just for testing and demo purposes. It prints out exception details on the command line.

### SmtpNotifier

The STMP notifier sends email messages using the SMTP protocol.
Set the notifier configuration setting to :smtp to use the SmtpNotifier.

Configuration variables are:
* application_name - the name of your application (required)
* server - the smtp server address to use (default: localhost)
* port - the port to use for smtp connections (default: 25)
* domain - the from domain to use (default: localhost)
* username - the username for the smtp connection (default: nil)
* password - the password for the smtp connection (default: nil)
* authtype - the smtp auth type to use (default: :cram_md5) (:plain, :login or :cram_md5)
* sender - the sender (from) address to use (required)
* recipients - an array of recipients for the notifications (required)

#### External SMTP server

Denouncer uses the Net::SMTP class to send mail. Additional configuration options are described [here](http://ruby-doc.org/stdlib-2.0/libdoc/net/smtp/rdoc/Net/SMTP.html).
    require 'denouncer'

    Denouncer.configure(
      application_name: 'my_app',
      notifier: :smtp,
      port: 25,
      server: 'mail.example.com',
      sender: 'noreply@example.com',
      username: 'noreply@example.com',
      password: 'your_password',
      recipients: ['usera@example.com', 'userb@example.com'],
      authtype: :plain,
      domain: 'mail.example.com'
    )

#### mailcatcher configuration

For more information in mailcatcher please refer to their [github repo](https://github.com/sj26/mailcatcher).

    require 'denouncer'

    Denouncer.configure(
      application_name: "my_app",
      notifier: :smtp,
      port: 1025,
      server: "localhost",
      sender: "noreply@example.com",
      recipients: ['usera@example.com', 'userb@example.com']
    )

### AmqpNotifier

Denouncer uses the bunny gem to send mail. Additional configuration options are described [here](http://reference.rubybunny.info/).

#### !!!ATTENTION

The bunny gem is required for the AmqpNotifier. Please add the bunny gem to your Gemfile as follows:

    gem 'bunny'

Configuration variables are:
* application_name - the name of your application (required)
* server - the amqp server address to use (default: localhost)
* port - the port to use for amqp connections (default: 5672)
* username - the username for the amqp connection (default: 'guest')
* password - the password for the amqp connection (default: 'guest')
* vhost - the virtual host to use for the amqp connection (default: '/')
* message_queue - the message queue to use (default: "#{application_name}.errors", e.g. "myapp.errors")

#### AMQP Configuration

    require 'denouncer'

    Denouncer.configure(
      application_name: "my_app",
      notifier: :amqp,
      port: 5672,
      server: "localhost",
      vhost: "/",
      username: "guest",
      password: "guest",
      message_queue: "my_app.errors"
    )

#### HoneybadgerNotifier

For more information on honeybadger please refer to their [github repo](https://github.com/honeybadger-io/honeybadger-ruby).

#### !!!ATTENTION

The honeybadger and rack gems are required for the HoneybadgerNotifier. Please add the gems to your Gemfile as follows:

    gem 'honeybadger'
    gem 'rack'

Honeybadger is automatically configured using environment variables (e.g. HONEYBADGER_API_KEY). For a more detailed documentation please have a look at [their instructions](http://docs.honeybadger.io/collection/7-getting-started).

    require 'denouncer'

    Denouncer.configure(
      application_name: "my_app",
      notifier: :honeybadger
    )

#### AirbrakeNotifier

For more information on airbrake please refer to their [github repo](https://github.com/airbrake/airbrake).

#### !!!ATTENTION

The airbrake gem is required for the AirbrakeNotifier. Please add the gem to your Gemfile as follows:

    gem 'airbrake'

##### Airbrake Usage

    require 'denouncer'

    Denouncer.configure(
      application_name: "my_app",
      notifier: :airbrake,
      api_key: 'my_key'
    )

#### Multiple notifier configuration

Since version 0.4.0 denouncer supports parallel usage of multiple notifiers.
All exception notifications will be send to all configured notifiers.
The example below configures the amqp and smtp notifiers in parallel.

    require 'denouncer'

    Denouncer.configure(
      {
        application_name: "my_app",
        notifiers: [:smtp, :amqp],
        configurations: {
          smtp: {
            port: 1025,
            server: "localhost",
            sender: "noreply@example.com",
            recipients: ['usera@example.com', 'userb@example.com']
          },
          amqp: {
            port: 5672,
            server: "localhost",
            vhost: "/",
            username: "guest",
            password: "guest",
            message_queue: "my_app.errors"
          }
        }
      }
    )

## Usage

### Error notification

The example below shows a basic usage pattern for denouncer notifications.
Catch exceptions, then use denouncer's notify function and then re-raise the error again.

    begin
      1/0
    rescue => err
      Denouncer.notify err, { test: "my metadata 1", test2: "my metadata 2" }
      raise err
    end

or

    begin
      1/0
    rescue => err
      Denouncer.notify! err, { test: "my metadata 1", test2: "my metadata 2" }
    end

The metadata is optional and defaults to nil.

### Information notification

    Denouncer.info 'This contains lots of valuable information :)', { t1: "metadata 1", t2: "metadata 2" }

## Test Suite

    bundle exec rspec

## Architecture overview

[This](https://docs.google.com/drawings/d/16DaQhsAwcr-5zlguhKGwigpdNpOgO4-IXssLst7zlUM/edit?usp=sharing) illustration shows the basic architecture of the denouncer gem.

## TODOs

* Implement better test coverage

## Contributing

1. Fork it ( https://github.com/[my-github-username]/denouncer/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request

## How to add a new notfier?

    # Copy the console notifier as base
    cp lib/denouncer/notifiers/console_notifier.rb lib/denouncer/notifiers/<name>_notifier.rb

    # add your notifier to the module
    vim lib/denouncer/notifiers.rb

    # adjust the notifier as needed
    # implement name, set_configuration! and notify methods
    vim lib/denouncer/notifiers/<name>_notifier.rb

    # add a section for the notifier to the documentation
    vim README.md

    # follow the instructions above (Contributing)


text:
package com.navercorp.pinpoint.web.cluster;

import com.navercorp.pinpoint.common.server.cluster.zookeeper.ZookeeperConstants;
import com.navercorp.pinpoint.common.util.NetUtils;
import com.navercorp.pinpoint.rpc.client.SimpleMessageListener;
import com.navercorp.pinpoint.test.client.TestPinpointClient;
import com.navercorp.pinpoint.web.cluster.connection.ClusterConnectionManager;
import com.navercorp.pinpoint.web.cluster.zookeeper.ZookeeperClusterDataManager;
import com.navercorp.pinpoint.web.config.WebClusterConfig;

import org.apache.curator.test.TestingServer;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.awaitility.Awaitility;
import org.awaitility.core.ConditionFactory;
import org.hamcrest.collection.IsEmptyCollection;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.util.SocketUtils;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * @author Taejin Koo
 */
public class ClusterTest {

    private static final Logger LOGGER = LogManager.getLogger(ClusterTest.class);

    private static final Charset UTF_8_CHARSET = StandardCharsets.UTF_8;

    // some tests may fail when executed in local environment
    // when failures happen, you have to copy pinpoint-web-root.properties of resource-test to resource-local. Tests will succeed.

    private ConditionFactory awaitility() {
        ConditionFactory conditionFactory = Awaitility.await()
                .pollDelay(100, TimeUnit.MILLISECONDS)
                .timeout(10000, TimeUnit.MILLISECONDS);
        return conditionFactory;
    }

    private static final String DEFAULT_IP = NetUtils.LOOPBACK_ADDRESS_V4;
    static ClusterConnectionManager clusterConnectionManager;
    static ZookeeperClusterDataManager clusterDataManager;

    private static int zookeeperPort;
    private static String zookeeperAddress;

    private static int acceptorPort;
    private static String acceptorAddress;
    private static String CLUSTER_NODE_PATH;

    private static TestingServer ts = null;

    @BeforeClass
    public static void setUp() throws Exception {
        zookeeperPort = SocketUtils.findAvailableTcpPort(28000);
        zookeeperAddress = DEFAULT_IP + ":" + zookeeperPort;
        ts = createZookeeperServer(zookeeperPort);

        WebClusterConfig config = mock(WebClusterConfig.class);
        when(config.isClusterEnable()).thenReturn(true);
        when(config.getHostAddress()).thenReturn(DEFAULT_IP);
        when(config.getClusterZookeeperAddress()).thenReturn(zookeeperAddress);
        when(config.getClusterZookeeperRetryInterval()).thenReturn(60000);
        when(config.getClusterZookeeperSessionTimeout()).thenReturn(3000);
        when(config.getWebZNodePath()).
                thenReturn(ZKPaths.makePath(ZookeeperConstants.DEFAULT_CLUSTER_ZNODE_ROOT_PATH, ZookeeperConstants.WEB_LEAF_PATH));
        when(config.getCollectorZNodePath()).
                thenReturn(ZKPaths.makePath(ZookeeperConstants.DEFAULT_CLUSTER_ZNODE_ROOT_PATH, ZookeeperConstants.COLLECTOR_LEAF_PATH));

        acceptorPort = SocketUtils.findAvailableTcpPort(zookeeperPort);
        acceptorAddress = DEFAULT_IP + ":" + acceptorPort;
        when(config.getClusterTcpPort()).thenReturn(acceptorPort);

        CLUSTER_NODE_PATH
                = ZKPaths.makePath(ZookeeperConstants.DEFAULT_CLUSTER_ZNODE_ROOT_PATH, ZookeeperConstants.WEB_LEAF_PATH, acceptorAddress);
        LOGGER.debug("CLUSTER_NODE_PATH:{}", CLUSTER_NODE_PATH);

        clusterConnectionManager = new ClusterConnectionManager(config);
        clusterConnectionManager.start();

        clusterDataManager = new ZookeeperClusterDataManager(config);
        clusterDataManager.start();

        List<String> localV4IpList = NetUtils.getLocalV4IpList();
        clusterDataManager.registerWebCluster(acceptorAddress, convertIpListToBytes(localV4IpList, "\r\n"));
    }

    @AfterClass
    public static void tearDown() throws Exception {
        closeZookeeperServer(ts);

        try {
            clusterDataManager.stop();
        } catch (Exception ignore) {
        }

        try {
            clusterConnectionManager.stop();
        } catch (Exception ignore) {
        }
    }

    private static TestingServer createZookeeperServer(int port) throws Exception {
        TestingServer mockZookeeperServer = new TestingServer(port);
        mockZookeeperServer.start();

        return mockZookeeperServer;
    }

    private static void closeZookeeperServer(TestingServer mockZookeeperServer) throws Exception {
        try {
            if (mockZookeeperServer != null) {
                mockZookeeperServer.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static byte[] convertIpListToBytes(List<String> ipList, String delimiter) {
        StringBuilder stringBuilder = new StringBuilder();

        Iterator<String> ipIterator = ipList.iterator();
        while (ipIterator.hasNext()) {
            String eachIp = ipIterator.next();
            stringBuilder.append(eachIp);

            if (ipIterator.hasNext()) {
                stringBuilder.append(delimiter);
            }
        }

        return stringBuilder.toString().getBytes(UTF_8_CHARSET);
    }

    @After
    public void after() throws Exception {
        ts.restart();
    }

    @Test
    public void clusterTest1() throws Exception {
        ZooKeeper zookeeper = new ZooKeeper(zookeeperAddress, 5000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                LOGGER.info("process:{}", watchedEvent);
            }
        });
        awaitZookeeperConnected(zookeeper);

        if (zookeeper != null) {
            zookeeper.close();
        }
    }

    @Test
    public void clusterTest2() throws Exception {
        ZooKeeper zookeeper = new ZooKeeper(zookeeperAddress, 5000, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                LOGGER.info("process:{}", watchedEvent);
            }
        });
        awaitZookeeperConnected(zookeeper);

        ts.stop();

        awaitZookeeperDisconnected(zookeeper);
        try {
            zookeeper.getData(CLUSTER_NODE_PATH, null, null);
            Assert.fail();
        } catch (KeeperException e) {
            Assert.assertEquals(KeeperException.Code.CONNECTIONLOSS, e.code());
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ts.restart();
        getNodeAndCompareContents(zookeeper);

        if (zookeeper != null) {
            zookeeper.close();
        }
    }

    @Test
    public void clusterTest3() throws Exception {
        ZooKeeper zookeeper = null;
        TestPinpointClient testPinpointClient = new TestPinpointClient(SimpleMessageListener.INSTANCE);
        try {
            zookeeper = new ZooKeeper(zookeeperAddress, 5000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    LOGGER.info("process:{}", watchedEvent);
                }
            });
            awaitZookeeperConnected(zookeeper);

            Assert.assertEquals(0, clusterConnectionManager.getClusterList().size());

            testPinpointClient.connect(DEFAULT_IP, acceptorPort);
            awaitPinpointClientConnected(clusterConnectionManager);

            Assert.assertEquals(1, clusterConnectionManager.getClusterList().size());
        } finally {
            testPinpointClient.closeAll();
            if (zookeeper != null) {
                zookeeper.close();
            }
        }
    }

    private void awaitZookeeperConnected(final ZooKeeper zookeeper) {
        awaitility().until(() -> getNodeAndCompareContents0(zookeeper));
    }

    private void awaitZookeeperDisconnected(final ZooKeeper zookeeper) {
        awaitility().until(() -> getNodeAndCompareContents0(zookeeper), is(false));
    }

    private void awaitPinpointClientConnected(final ClusterConnectionManager connectionManager) {
        awaitility().until(connectionManager::getClusterList, not(IsEmptyCollection.empty()));
    }

    private void getNodeAndCompareContents(ZooKeeper zookeeper) throws KeeperException, InterruptedException {
        LOGGER.debug("getNodeAndCompareContents() {}", CLUSTER_NODE_PATH);

        byte[] contents = zookeeper.getData(CLUSTER_NODE_PATH, null, null);

        String[] registeredIpList = new String(contents).split("\r\n");

        List<String> ipList = NetUtils.getLocalV4IpList();

        Assert.assertEquals(registeredIpList.length, ipList.size());

        for (String ip : registeredIpList) {
            Assert.assertTrue(ipList.contains(ip));
        }
    }

    private boolean getNodeAndCompareContents0(ZooKeeper zookeeper) {
        try {
            LOGGER.debug("getNodeAndCompareContents() {}", CLUSTER_NODE_PATH);

            byte[] contents = zookeeper.getData(CLUSTER_NODE_PATH, null, null);
            if (contents == null) {
                contents = new byte[0];
            }

            String[] registeredIplist = new String(contents).split("\r\n");

            List<String> ipList = NetUtils.getLocalV4IpList();

            if (registeredIplist.length != ipList.size()) {
                return false;
            }

            for (String ip : registeredIplist) {
                if (!ipList.contains(ip)) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            LOGGER.warn(e.getMessage(), e);
        }
        return false;
    }

}


text:
title: 'New bread recipe: rye sourdough'
published: true
date: '12-02-2016 17:00'
metadata:
    Keywords: sourdough
header_image: '0'
summary:
    enabled: '1'
    format: short
taxonomy:
    tag:
        - Food
    category:
        - blog
---

It took me four days to make a Swedish rye sourdough loaf, and half a day to write it up, but it was well worth it. My conclusion:

> This is a seriously good loaf. I sliced it upside down, as the top crust was a little brittle and I feared it would break up if I attempted to slice it normally. The crumb was dense but not heavy, moist and chewy, with enough rye bitterness and enough sourness too. Great with sweet jam and savoury cheese alike. A keeper.

For full details, pop over to fornacalia.com and read about [Baking that dark, sour bread](http://www.fornacalia.com/2016/baking-that-dark-sour-bread/).

If you try it, let me know how you get on.


text:
package org.moparscape.elysium.net.codec.decoder.message;

import org.moparscape.elysium.net.codec.AbstractMessage;

/**
 * Created by IntelliJ IDEA.
 *
 * @author lothy
 */
public final class AttackPlayerMessage extends AbstractMessage {

    private final int playerIndex;

    public AttackPlayerMessage(int playerIndex) {
        this.playerIndex = playerIndex;
    }

    public int getPlayerIndex() {
        return playerIndex;
    }
}


text:
from rest_framework import viewsets, permissions

from email2sms.models import Provider
from email2sms.serializers import ProviderSerializer

class ProviderViewSet(viewsets.ModelViewSet):
    """ViewSet for the Provider class"""

    queryset = Provider.objects.all()
    serializer_class = ProviderSerializer
    permission_classes = [permissions.IsAuthenticated]


text:
class Asteroid : public GameObject
{
public:
	Asteroid(BaseScene* scene) :
		GameObject::GameObject(scene),
		moveSpeed(200),
		rotationSpeed(5),
		hitPoints(1)
	{}

	~Asteroid(){}

	virtual void Initialize();
	void Update(float dt);
	void Draw(float dt);

	void GetHit();

protected:
	float moveSpeed;
	float rotationSpeed;
	int hitPoints;
};


text:
Minimalist theme for [Ghost](https://ghost.org/) Blogging platform.

Based off of Casper theme.

Using [Skeleton](http://getskeleton.com/) grid system


text:
package vtk.repository;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import vtk.repository.resourcetype.PropertyType;
import vtk.repository.resourcetype.PropertyTypeDefinitionImpl;
import vtk.repository.resourcetype.Value;

/**
 *
 */
public class PropertySetImplTest {

    protected Set<Property> collector;
    protected Property title;
    protected Property modifiedBy;
    protected Property custom;
    protected PropertySetImpl ps;

    @Before
    public void setup() {
        ps = new PropertySetImpl();
        ps.setUri(Path.ROOT);
        ps.setResourceType("collection");

        collector = new HashSet<Property>();

        title = newStringProperty(Namespace.DEFAULT_NAMESPACE, "title", "Root resource");
        modifiedBy = newStringProperty(Namespace.DEFAULT_NAMESPACE, "modifiedBy", "vortex@localhost");
        custom = newStringProperty(new Namespace("cust", "http://custom/"), "foo", "bar");
    }

    @Test
    public void testIterationEmpty() {
        Iterator<Property> it = ps.iterator();
        assertFalse(it.hasNext());
        try {
            it.next();
            fail("Expected no such element exception");
        } catch (NoSuchElementException e) {
            // OK
        }
    }

    @Test
    public void testPropIterationPerfomance() {
        ps.addProperty(title);
        ps.propertyMap.put(new Namespace("foo", "bar"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("baz", "boz"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("bing", "bing"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("1", "2"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("3", "4"), new HashMap<String,Property>());
        ps.addProperty(modifiedBy);
        ps.addProperty(custom);
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop1", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop2", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop3", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop4", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop5", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop6", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop7", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop8", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop9", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop10", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop11", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop12", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop13", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop14", "value1"));
        ps.addProperty(newStringProperty(Namespace.DEFAULT_NAMESPACE, "prop15", "value1"));

        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop1", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop2", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop3", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop4", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop5", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop6", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop7", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop8", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop9", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop10", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop11", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop12", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop13", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop14", "value1"));
        ps.addProperty(newStringProperty(Namespace.CUSTOM_NAMESPACE, "prop15", "value1"));

        long count = 0;
        long start = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            for (Property p : ps.getProperties()) {
                Value v = p.getValue();
                count++;
            }
        }
        System.out.println("Time usage with getProperties(): "
                + (System.currentTimeMillis() - start) + "ms, count = " + count);

        count = 0;
        start = System.currentTimeMillis();
        for (int i = 0; i < 20000; i++) {
            for (Property p : ps) {
                Value v = p.getValue();
                count++;
            }
        }
        System.out.println("Time usage with Iterable<Property>: "
                + (System.currentTimeMillis() - start) + "ms, count = " + count);
    }

    @Test
    public void testIterationOneProp() {
        ps.addProperty(title);
        Iterator<Property> it = ps.iterator();
        assertTrue(it.hasNext());
        assertEquals(title, it.next());
        assertFalse(it.hasNext());
        try {
            it.next();
            fail("Expected no such element exception");
        } catch (NoSuchElementException e) {
            // OK
        }
    }

    @Test
    public void testIterationTwoProps() {
        ps.addProperty(title);
        ps.addProperty(modifiedBy);
        for (Property p: ps) {
            collector.add(p);
        }
        assertTrue(collector.contains(title));
        assertTrue(collector.contains(modifiedBy));
        assertEquals(2, collector.size());
    }

    @Test
    public void testIterationMultipleNamespaces() {
        ps.addProperty(title);
        ps.addProperty(modifiedBy);
        ps.addProperty(custom);
        for (Property p: ps) {
            collector.add(p);
        }
        assertTrue(collector.contains(title));
        assertTrue(collector.contains(modifiedBy));
        assertTrue(collector.contains(custom));
        assertEquals(3, collector.size());
    }

    @Test
    public void testIterationEmptyNamespaceMap() {
        ps.addProperty(title);
        ps.propertyMap.put(new Namespace("foo", "bar"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("baz", "boz"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("bing", "bing"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("1", "2"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("3", "4"), new HashMap<String,Property>());
        ps.addProperty(modifiedBy);
        ps.addProperty(custom);

        for (Property p: ps) {
            collector.add(p);
        }
        assertTrue(collector.contains(title));
        assertTrue(collector.contains(modifiedBy));
        assertTrue(collector.contains(custom));
        assertEquals(3, collector.size());
    }

    @Test
    public void testIterationOnlyEmptyNamespaceMap() {
        ps.propertyMap.put(new Namespace("foo", "bar"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("baz", "boz"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("bing", "bing"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("1", "2"), new HashMap<String,Property>());
        ps.propertyMap.put(new Namespace("3", "4"), new HashMap<String,Property>());
        Iterator<Property> it = ps.iterator();
        assertFalse(it.hasNext());
        try {
            it.next();
            fail("Expected no such element exception");
        } catch (NoSuchElementException e) {
            // OK
        }
    }

    @Test
    public void testIterationRemoveNotAllowed() {
        // Removing property is not part of PropertySet interface API, so
        // iterator should not allow it either.
        ps.addProperty(title);
        Iterator<Property> it = ps.iterator();
        assertEquals(title, it.next());
        try {
            it.remove();
            fail("Expected IllegalStateException");
        } catch (UnsupportedOperationException e) {
            // OK
        }
    }

    private Property newStringProperty(Namespace namespace, String name, String value) {
        return PropertyTypeDefinitionImpl.createDefault(namespace, name, false)
                                         .createProperty(value);
    }
}


text:
require('./localenv.js');
var app = require('./app').create();


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

import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.*;

import ghidra.app.util.bin.BinaryReader;
import ghidra.app.util.importer.MessageLog;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressSpace;
import ghidra.program.model.data.*;
import ghidra.program.model.listing.Program;
import ghidra.program.model.util.CodeUnitInsertionException;
import ghidra.util.DataConverter;
import ghidra.util.Msg;
import ghidra.util.exception.DuplicateNameException;
import ghidra.util.task.TaskMonitor;

/**
 * Points to an array of IMAGE_BOUND_IMPORT_DESCRIPTORs.
 */
public class BoundImportDataDirectory extends DataDirectory {
    private final static String NAME = "IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT";

    private BoundImportDescriptor [] descriptors;
    private LinkedHashMap<String,Short> nameHash;

	BoundImportDataDirectory(NTHeader ntHeader, BinaryReader reader) throws IOException {
		processDataDirectory(ntHeader, reader);

        if (descriptors == null) descriptors = new BoundImportDescriptor[0];
	}

    /**
     * @see ghidra.app.util.bin.StructConverter#toDataType()
     */
    @Override
    public DataType toDataType() throws DuplicateNameException, IOException {
        StructureDataType struct = new StructureDataType(NAME, 0);
        for (BoundImportDescriptor descriptor : descriptors) {
            struct.add(descriptor.toDataType());
        }
        struct.setCategoryPath(new CategoryPath("/PE"));
        return struct;
    }

	/**
	 * Returns the array of bound import descriptors defined in this bound import data directory.
	 * @return the array of bound import descriptors defined in this bound import data directory
	 */
    public BoundImportDescriptor [] getBoundImportDescriptors() {
        return descriptors;
    }

    @Override
	public void markup(Program program, boolean isBinary, TaskMonitor monitor, MessageLog log,
			NTHeader ntHeader) throws DuplicateNameException, CodeUnitInsertionException {

    	monitor.setMessage(program.getName()+": bound import(s)...");
		Address addr = PeUtils.getMarkupAddress(program, isBinary, ntHeader, virtualAddress);
		if (!program.getMemory().contains(addr)) {
			return;
		}
		createDirectoryBookmark(program, addr);

		AddressSpace space = program.getAddressFactory().getDefaultAddressSpace();

		for (BoundImportDescriptor descriptor : descriptors) {
            if (monitor.isCancelled()) {
                return;
            }
            DataType dt = descriptor.toDataType();
			PeUtils.createData(program, addr, dt, log);
            addr = addr.add(dt.getLength());

            long namePtr = descriptor.getOffsetModuleName()+virtualAddress;
            Address nameAddr = space.getAddress(va(namePtr, isBinary));
            createTerminatedString(program, nameAddr, false, log);
        }

		BoundImportDescriptor terminator = new BoundImportDescriptor();
		PeUtils.createData(program, addr, terminator.toDataType(), log);
    }

    @Override
    public String getDirectoryName() {
    	return NAME;
    }

    @Override
	public boolean parse() throws IOException {
    	nameHash = new LinkedHashMap<String,Short>();

        int rva = getVirtualAddress();
        int ptr = getVirtualAddress();
        if (rva <= 0) {
        	if (rva < 0) {
        		Msg.error(this, "Invalid RVA "+rva);
        	}
        	return false;
        }

        List<BoundImportDescriptor> descriptorsList = new ArrayList<BoundImportDescriptor>();
        while (true) {
        	if (ptr < 0) {
            	Msg.error(this, "Invalid file index "+ptr);
            	break;
        	}
            BoundImportDescriptor bid = new BoundImportDescriptor(reader, ptr, rva);

            if (bid.getTimeDateStamp() == 0) break;
            if (bid.getNumberOfModuleForwarderRefs() < 0) break;

            descriptorsList.add(bid);

            // increment ptr by 1 BoundImportDescriptor and
            // the number of forwards refs located
            //
            ptr += BoundImportDescriptor.IMAGE_SIZEOF_BOUND_IMPORT_DESCRIPTOR;
            ptr += (bid.getNumberOfModuleForwarderRefs() * BoundImportForwarderRef.IMAGE_SIZEOF_BOUND_IMPORT_FORWARDER_REF);
        }

        descriptors = new BoundImportDescriptor[descriptorsList.size()];
        descriptorsList.toArray(descriptors);

		buildNameHash();
		return true;
    }

	@Override
    int rvaToPointer() {
		return virtualAddress;
	}

	@Override
    public void writeBytes(RandomAccessFile raf, DataConverter dc, PortableExecutable template) throws IOException {
		if (size == 0) {
			return;
		}

		//this is the actual byte position in the file
		raf.seek(rvaToPointer());

		//write the descriptors...
		for (BoundImportDescriptor descriptor : descriptors) {
			raf.write(dc.getBytes(descriptor.getTimeDateStamp()));
			raf.write(dc.getBytes(descriptor.getOffsetModuleName()));
			raf.write(dc.getBytes(descriptor.getNumberOfModuleForwarderRefs()));
			for (int j = 0 ; j < descriptor.getNumberOfModuleForwarderRefs() ; ++j) {
				BoundImportForwarderRef forwarder = descriptor.getBoundImportForwarderRef(j);
				raf.write(dc.getBytes(forwarder.getTimeDateStamp()));
				raf.write(dc.getBytes(forwarder.getOffsetModuleName()));
				raf.write(dc.getBytes(forwarder.getReserved()));
			}
		}

		int zeroInt = 0;
		short zeroShort = 0;

		//write a terminating descriptor...
		raf.write(dc.getBytes(zeroInt));
		raf.write(dc.getBytes(zeroShort));
		raf.write(dc.getBytes(zeroShort));

		//write the dll names...
		Iterator<String> iter = nameHash.keySet().iterator();
		short prevOffset = 0;
		while (iter.hasNext()) {
			String name = iter.next();
			Short currOffset = nameHash.get(name);
			if (currOffset.shortValue() < prevOffset) {
				throw new IllegalArgumentException();
			}
			prevOffset = currOffset.shortValue();

			raf.write(name.getBytes());
			raf.write((byte)0);//null-terminator
		}
	}

	void updatePointers(int offset) {
		virtualAddress += offset;
	}

	public void addDescriptor(BoundImportDescriptor bid) {
		BoundImportDescriptor [] tmp = new BoundImportDescriptor[descriptors.length+1];
		System.arraycopy(descriptors, 0, tmp, 0, descriptors.length);
		tmp[tmp.length-1] = bid;
		descriptors = tmp;

		size +=  BoundImportDescriptor.IMAGE_SIZEOF_BOUND_IMPORT_DESCRIPTOR;
		size += (bid.getNumberOfModuleForwarderRefs() * BoundImportForwarderRef.IMAGE_SIZEOF_BOUND_IMPORT_FORWARDER_REF);
		size += (bid.getModuleName().length() + 1);

		buildNameHash();
	}

	private void buildNameHash() {
		nameHash.clear();

		int pos = (descriptors.length + 1) * BoundImportDescriptor.IMAGE_SIZEOF_BOUND_IMPORT_DESCRIPTOR;
		for (BoundImportDescriptor descriptor : descriptors) {
			pos += (descriptor.getNumberOfModuleForwarderRefs() * BoundImportForwarderRef.IMAGE_SIZEOF_BOUND_IMPORT_FORWARDER_REF);
		}

		for (BoundImportDescriptor descriptor : descriptors) {
			Short offset = nameHash.get(descriptor.getModuleName());
			if (offset != null) {
				descriptor.setOffsetModuleName(offset.shortValue());
			}
			else {
				String moduleName = descriptor.getModuleName();
				if (moduleName != null && moduleName.length() > 0) {
					nameHash.put(moduleName, new Short((short)pos));
					descriptor.setOffsetModuleName((short)pos);
					pos += (descriptor.getModuleName().length() + 1);
				}
			}

			for (int j = 0 ; j < descriptor.getNumberOfModuleForwarderRefs() ; ++j) {
				BoundImportForwarderRef forwarder = descriptor.getBoundImportForwarderRef(j);
				if (forwarder == null) {
					continue;
				}
				offset = nameHash.get(forwarder.getModuleName());
				if (offset != null) {
					forwarder.setOffsetModuleName(offset.shortValue());
				}
				else {
					String moduleName = forwarder.getModuleName();
					if (moduleName != null && moduleName.length() > 0) {
						nameHash.put(moduleName, new Short((short)pos));
						forwarder.setOffsetModuleName((short)pos);
						pos += (forwarder.getModuleName().length() + 1);
					}
				}
			}
		}
	}
}


text:
namespace relevanced {
namespace stemmer {

class ThreadSafeStemmerManager: public StemmerManagerIf {
protected:
  folly::ThreadLocal<std::map<thrift_protocol::Language, std::shared_ptr<StemmerIf>>> stemmers_;
public:
  std::shared_ptr<StemmerIf> getStemmer(thrift_protocol::Language lang) override;
};

}
}


text:
#!/usr/bin/env node

//
// Detects triangles and quadrilaterals
//

// sourced from: https://github.com/peterbraden/node-opencv/tree/master/examples

var cv = require('opencv'),
  fs = require("fs"),
  PNG = require("png").Png,
  PNGdecoder = require('png-js');

var image_path = "./";
/*
var image = new PNGdecoder("test.png");

image.decode(function (pixels) {
    console.log(pixels);
});

*/

fs.readFile(image_path + "test.png", function(err, data) {
  console.log(data);

  var base64data = data.toString('base64');
  console.log('1. sending base 64 with length' + base64data.length);

  var b64_buf = new Buffer(base64data, 'base64').toString('binary');
  var buf = new Buffer(b64_buf, 'binary');
  console.log('2. base64 buffer created');
  console.log(buf);

  //var png = new PNG(buf, 640, 480, 'rgb');
  //console.log('3. png created');

  //var png_image = png.encodeSync();
  //console.log('4. png_image created from encode');

  //fs.writeFileSync('./copy.png', png_image.toString('binary'), 'binary');

  fs.writeFileSync('./copy.png', buf, 'binary');

  console.log('5. file written');

});

var lowThresh = 0;
var highThresh = 100;
var nIters = 2;
var minArea = 2000;

var BLUE = [0, 255, 0]; //B, G, R
var RED   = [0, 0, 255]; //B, G, R
var GREEN = [0, 255, 0]; //B, G, R
var WHITE = [255, 255, 255]; //B, G, R

/*
cv.readImage('../test/square2.jpg', function(err, im) {

  var out = new cv.Matrix(im.height(), im.width());

  // convert the image to grey scale
  im.convertGrayscale();

  //make a copy of the image called im_canny (not sure why?)
  im_canny = im.copy();

  im_canny.canny(lowThresh, highThresh);
  im_canny.dilate(nIters);

//uses a for loop to find number of contours
  contours = im_canny.findContours();

  for(i = 0; i < contours.size(); i++) {

    if(contours.area(i) < minArea) continue;

    // arcLength tells you how long each face is, so that you can cut out any small shape
    var arcLength = contours.arcLength(i, true);
    contours.approxPolyDP(i, 0.01 * arcLength, true);

    // chooses a drawing color based on number of contours
    switch(contours.cornerCount(i)) {
    case 3:
      out.drawContour(contours, i, GREEN);
      break;
    case 4:
      out.drawContour(contours, i, RED);
      break;
    case 5:
    out.drawContour(contours,i, BLUE);
    break;
    default:
      out.drawContour(contours, i, WHITE);

    }
  }

//saves image
  out.save('../test/out.png');
});
*/


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Eremostachys fulgens Bunge

### Remarks
null


text:
module RuboCop
  module Cop
    module Style
      # Checks that operators have space around them, except for **
      # which should not have surrounding space.
      class SpaceAroundOperators < Cop
        include PrecedingFollowingAlignment
        include HashNode # any_pairs_on_the_same_line?

        def on_pair(node)
          return unless node.loc.operator.is?('=>')

          align_hash_config = config.for_cop('Style/AlignHash')
          return if align_hash_config['EnforcedHashRocketStyle'] == 'table' &&
                    !any_pairs_on_the_same_line?(node.parent)

          _, right = *node
          check_operator(node.loc.operator, right.source_range)
        end

        def on_if(node)
          return unless node.loc.respond_to?(:question)
          _, if_branch, else_branch = *node

          check_operator(node.loc.question, if_branch.source_range)
          check_operator(node.loc.colon, else_branch.source_range)
        end

        def on_resbody(node)
          if node.loc.assoc
            _, variable, = *node
            check_operator(node.loc.assoc, variable.source_range)
          end
        end

        def on_send(node)
          if node.loc.operator # aref assignment, attribute assignment
            on_special_asgn(node)
          elsif !node.unary_operation? && !called_with_dot?(node)
            op = node.method_name
            if op != :[] && op != :! && op != :[]= && operator?(op)
              _, _, right, = *node
              check_operator(node.loc.selector, right.source_range)
            end
          end
        end

        def on_binary(node)
          _, right, = *node
          return if right.nil?
          check_operator(node.loc.operator, right.source_range)
        end

        def on_special_asgn(node)
          return unless node.loc.operator
          _, _, right, = *node
          check_operator(node.loc.operator, right.source_range)
        end

        alias on_or       on_binary
        alias on_and      on_binary
        alias on_lvasgn   on_binary
        alias on_masgn    on_binary
        alias on_casgn    on_special_asgn
        alias on_ivasgn   on_binary
        alias on_cvasgn   on_binary
        alias on_gvasgn   on_binary
        alias on_class    on_binary
        alias on_or_asgn  on_binary
        alias on_and_asgn on_binary
        alias on_op_asgn  on_special_asgn

        private

        def called_with_dot?(node)
          node.loc.dot
        end

        def check_operator(op, right_operand)
          with_space = range_with_surrounding_space(op)
          return if with_space.source.start_with?("\n")

          if op.is?('**')
            unless with_space.is?('**')
              add_offense(with_space, op,
                          'Space around operator `**` detected.')
            end
          elsif with_space.source !~ /^\s.*\s$/
            add_offense(with_space, op, 'Surrounding space missing for ' \
                                        "operator `#{op.source}`.")
          elsif excess_leading_space?(op, with_space)
            add_offense(with_space, op, "Operator `#{op.source}` should be " \
                                        'surrounded by a single space.')
          elsif excess_trailing_space?(right_operand, with_space)
            add_offense(with_space, op, "Operator `#{op.source}` should be " \
                                        'surrounded by a single space.')
          end
        end

        def excess_leading_space?(op, with_space)
          with_space.source =~ /^  / &&
            (!allow_for_alignment? || !aligned_with_operator?(op))
        end

        def excess_trailing_space?(right_operand, with_space)
          with_space.source =~ /  $/ &&
            (!allow_for_alignment? || !aligned_with_something?(right_operand))
        end

        def autocorrect(range)
          lambda do |corrector|
            if range.source =~ /\*\*/
              corrector.replace(range, '**')
            elsif range.source.end_with?("\n")
              corrector.replace(range, " #{range.source.strip}\n")
            else
              corrector.replace(range, " #{range.source.strip} ")
            end
          end
        end
      end
    end
  end
end