text:
module Azure::EventGrid::Mgmt::V2020_10_15_preview
  module Models
    #
    # Event Channel.
    #
    class EventChannel < Resource

      include MsRestAzure

      # @return [EventChannelSource] Source of the event channel. This
      # represents a unique resource in the partner's resource model.
      attr_accessor :source

      # @return [EventChannelDestination] Represents the destination of an
      # event channel.
      attr_accessor :destination

      # @return [EventChannelProvisioningState] Provisioning state of the event
      # channel. Possible values include: 'Creating', 'Updating', 'Deleting',
      # 'Succeeded', 'Canceled', 'Failed'
      attr_accessor :provisioning_state

      # @return [PartnerTopicReadinessState] The readiness state of the
      # corresponding partner topic. Possible values include:
      # 'NotActivatedByUserYet', 'ActivatedByUser', 'DeactivatedByUser',
      # 'DeletedByUser'
      attr_accessor :partner_topic_readiness_state

      # @return [DateTime] Expiration time of the event channel. If this timer
      # expires while the corresponding partner topic is never activated,
      # the event channel and corresponding partner topic are deleted.
      attr_accessor :expiration_time_if_not_activated_utc

      # @return [EventChannelFilter] Information about the filter for the event
      # channel.
      attr_accessor :filter

      # @return [String] Friendly description about the topic. This can be set
      # by the publisher/partner to show custom description for the customer
      # partner topic.
      # This will be helpful to remove any ambiguity of the origin of creation
      # of the partner topic for the customer.
      attr_accessor :partner_topic_friendly_description

      # @return [SystemData] The system metadata relating to Event Channel
      # resource.
      attr_accessor :system_data

      #
      # Mapper for EventChannel class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'EventChannel',
          type: {
            name: 'Composite',
            class_name: 'EventChannel',
            model_properties: {
              id: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'id',
                type: {
                  name: 'String'
                }
              },
              name: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'name',
                type: {
                  name: 'String'
                }
              },
              type: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'type',
                type: {
                  name: 'String'
                }
              },
              source: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.source',
                type: {
                  name: 'Composite',
                  class_name: 'EventChannelSource'
                }
              },
              destination: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.destination',
                type: {
                  name: 'Composite',
                  class_name: 'EventChannelDestination'
                }
              },
              provisioning_state: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.provisioningState',
                type: {
                  name: 'String'
                }
              },
              partner_topic_readiness_state: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties.partnerTopicReadinessState',
                type: {
                  name: 'String'
                }
              },
              expiration_time_if_not_activated_utc: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.expirationTimeIfNotActivatedUtc',
                type: {
                  name: 'DateTime'
                }
              },
              filter: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.filter',
                type: {
                  name: 'Composite',
                  class_name: 'EventChannelFilter'
                }
              },
              partner_topic_friendly_description: {
                client_side_validation: true,
                required: false,
                serialized_name: 'properties.partnerTopicFriendlyDescription',
                type: {
                  name: 'String'
                }
              },
              system_data: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'systemData',
                type: {
                  name: 'Composite',
                  class_name: 'SystemData'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
YUI.add('widget-base-ie', function(Y) {

/**
 * IE specific support for the widget-base module.
 *
 * @module widget-base-ie
 */
var BOUNDING_BOX = "boundingBox",
    CONTENT_BOX = "contentBox",
    HEIGHT = "height",
    OFFSET_HEIGHT = "offsetHeight",
    EMPTY_STR = "",
    IE = Y.UA.ie,
    heightReallyMinHeight = IE < 7,
    bbTempExpanding = Y.Widget.getClassName("tmp", "forcesize"),
    contentExpanded = Y.Widget.getClassName("content", "expanded");

// TODO: Ideally we want to re-use the base _uiSizeCB impl
Y.Widget.prototype._uiSizeCB = function(expand) {

    var bb = this.get(BOUNDING_BOX),
        cb = this.get(CONTENT_BOX),
        borderBoxSupported = this._bbs;

    if(borderBoxSupported === undefined) {
        this._bbs = borderBoxSupported = !(IE < 8 && bb.get("ownerDocument").get("compatMode") != "BackCompat");
    }

    if (borderBoxSupported) {
        cb.toggleClass(contentExpanded, expand);
    } else {
        if (expand) {
            if (heightReallyMinHeight) {
                bb.addClass(bbTempExpanding);
            }

            cb.set(OFFSET_HEIGHT, bb.get(OFFSET_HEIGHT));

            if (heightReallyMinHeight) {
                bb.removeClass(bbTempExpanding);
            }
        } else {
            cb.setStyle(HEIGHT, EMPTY_STR);
        }
    }
};

}, '3.4.1' ,{requires:['widget-base']});

redpajama_set_name: RedPajamaGithub


text:
var express = require('express');
var router = express.Router();
var fs = require('fs');
var path = require('path');
var marked = require('marked');

/* GET home page. */
router.get('/', function(req, res, next) {
  var navHtml = null;
  var navmd = null;
  try {
    navmd = fs.readFileSync(navFile, 'utf8');
    navHtml = marked(navmd);
  } catch(e) {
    e.status = 404;
    e.message = "Unable to open navigation markdown"
    throw e;
  }

  var fileslist = fs.readdirSync(filesDir);
  console.log(JSON.stringify(fileslist));

  res.render('files', { title: 'Miki - Settings',
    theme: settings.theme,
    settings: settings,
    navHtml: navHtml,
    files: fileslist
  });
});

router.post('/upload', function(req, res, next) {

  res.redirect('/files');
});

router.post('/delete', function(req, res, next) {

  res.redirect('/files');
});

module.exports = router;


text:
module Roar::Rails
  class Responder < ActionController::Responder
    module VersionStrategy
    end
  end

  module TestCase
    module VersionStrategy
    end
  end
end


text:
//
//  MAMultiPointOverlayRenderer.h
//  MAMapKit
//
//  Created by hanxiaoming on 2017/4/11.
//  Copyright © 2017年 Amap. All rights reserved.
//

#import "MAMultiPointOverlay.h"

@class MAMultiPointOverlayRenderer;

///MAMultiPointOverlayRenderer代理(since 5.1.0)
@protocol MAMultiPointOverlayRendererDelegate <NSObject>
@optional

/**
 @brief 点击海量点图层回调

 @param renderer 海量点图层渲染器
 @param item 被点击的单个点对象
 */
- (void)multiPointOverlayRenderer:(MAMultiPointOverlayRenderer *)renderer didItemTapped:(MAMultiPointItem *)item;

@end

///海量点渲染renderer(since 5.1.0)。 注意:为了保证渲染效率,纹理不受alpha参数影响,如果需要设置透明度,请更换icon。
@interface MAMultiPointOverlayRenderer : MAOverlayRenderer

///MAMultiPointOverlayRendererDelegate代理对象
@property (nonatomic, weak) id<MAMultiPointOverlayRendererDelegate> delegate;

///标注纹理图片
@property (nonatomic, strong) UIImage *icon;

///纹理渲染大小,默认为icon图片大小
@property (nonatomic, assign) CGSize pointSize;

///经纬度对应图片中的位置,默认为(0.5,0.5),范围[0-1] 负值自动取其绝对值 左上角为 (0,0) 右下角为 (1,1)
@property (nonatomic, assign) CGPoint anchor;

///对应的overlay
@property (nonatomic, readonly) MAMultiPointOverlay *multiPointOverlay;

///初始化方法
- (instancetype)initWithMultiPointOverlay:(MAMultiPointOverlay *)multiPointOverlay;

@end


text:
#ifndef YICESSOLVER_H
#define YICESSOLVER_H

#include <iostream>
#include <string>
#include <cstring>
#include <sstream>
#include <list>

extern "C" {
#include "yices_c.h"
}

using namespace std;

class YicesSolver
{
    public:
        YicesSolver();
        void solve (string constraint);
        string getSolution();

    private:
        yices_context context;
        yices_type intType;
        yices_type booleanType;
        list<yices_var_decl> variables;
        string solution;

        void buildConstraint (string constraint);
        void buildExpression (const string& constraint, int& location, yices_expr& expression);
        bool isNumber(const string& myString);
        bool isVariable(const string& myString);
        void solveContext();
};
#endif


text:
#include <cstdlib>
#include <memory>
#include <utility>

#include "tensorflow/lite/c/c_api_types.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/core/shims/c/experimental/acceleration/configuration/delegate_plugin.h"
#include "tensorflow/lite/delegates/utils/experimental/sample_stable_delegate/sample_stable_delegate.h"
#include "tensorflow/lite/delegates/utils/experimental/stable_delegate/stable_delegate_interface.h"
#include "tensorflow/lite/delegates/utils/simple_opaque_delegate.h"
#include "tensorflow/lite/experimental/acceleration/configuration/c/stable_delegate.h"

namespace {

TfLiteDelegate* SampleStableDelegateCreateFunc(const void* tflite_settings) {
  auto delegate = std::make_unique<tflite::example::SampleStableDelegate>();
  return reinterpret_cast<TfLiteDelegate*>(
      tflite::TfLiteOpaqueDelegateFactory::CreateSimpleDelegate(
          std::move(delegate)));
}

void SampleStableDelegateDestroyFunc(TfLiteDelegate* sample_stable_delegate) {
  tflite::TfLiteOpaqueDelegateFactory::DeleteSimpleDelegate(
      reinterpret_cast<TfLiteOpaqueDelegateStruct*>(sample_stable_delegate));
}

int SampleStableDelegateErrnoFunc(TfLiteDelegate* sample_stable_delegate) {
  // no-op
  return 0;
}

const TfLiteOpaqueDelegatePlugin sample_stable_delegate_plugin = {
    SampleStableDelegateCreateFunc, SampleStableDelegateDestroyFunc,
    SampleStableDelegateErrnoFunc};

}  // namespace

/**
 * A super simple test delegate for testing.
 */
extern "C" const TfLiteStableDelegate TFL_TheStableDelegate = {
    TFL_STABLE_DELEGATE_ABI_VERSION, tflite::example::kSampleStableDelegateName,
    tflite::example::kSampleStableDelegateVersion,
    &sample_stable_delegate_plugin};


text:
//  (C) Copyright Edward Diener 2011-2015
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#if !defined(BOOST_VMD_DETAIL_IS_TYPE_TYPE_HPP)
#define BOOST_VMD_DETAIL_IS_TYPE_TYPE_HPP

#include <boost/vmd/detail/type_registration.hpp>
#include <boost/vmd/detail/match_single_identifier.hpp>

/*

    Check to see if the 'id' is BOOST_VMD_TYPE_TYPE

    Returns 1 if it is, else 0

*/

#define BOOST_VMD_DETAIL_IS_TYPE_TYPE(id) \
    BOOST_VMD_DETAIL_MATCH_SINGLE_IDENTIFIER(id,BOOST_VMD_TYPE_TYPE) \
/**/

#endif /* BOOST_VMD_DETAIL_IS_TYPE_TYPE_HPP */


text:
using System;
using Adxstudio.Xrm.Configuration;
using Adxstudio.Xrm.Security;
using Adxstudio.Xrm.Web.UI.CrmEntityListView;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;

namespace Adxstudio.Xrm.Web.UI
{
	/// <summary>
	/// Defines the layout of a view for a subgrid
	/// </summary>
	public class SubgridViewLayout : ViewLayout
	{
		/// <summary>
		/// <see cref="EntityReference"/> of the source entity that the subgrid records are related to.
		/// </summary>
		public EntityReference Source { get; private set; }

		/// <summary>
		/// The <see cref="Relationship"/> between the source entity and the subgrid records.
		/// </summary>
		public Relationship Relationship { get; private set; }

		/// <summary>
		/// Parameterless constructor
		/// </summary>
		public SubgridViewLayout()
		{
		}

		/// <summary>
		/// Constructor
		/// </summary>
		public SubgridViewLayout(ViewConfiguration configuration, EntityReference source, Relationship relationship, string viewEntityLogicalName,
			EntityView view = null, string portalName = null,
			int languageCode = 0, bool addSelectColumn = false, bool addActionsColumn = false, string selectColumnHeaderText = "")
			: base(configuration, view, portalName, languageCode, addSelectColumn, addActionsColumn, selectColumnHeaderText)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}

			if (relationship == null)
			{
				throw new ArgumentNullException("relationship");
			}

			if (string.IsNullOrWhiteSpace(viewEntityLogicalName))
			{
				throw new ArgumentNullException("viewEntityLogicalName");
			}

			Source = source;
			Relationship = relationship;

			if ((configuration.EnableEntityPermissions && AdxstudioCrmConfigurationManager.GetCrmSection().ContentMap.Enabled) &&
				configuration.AssociateActionLink.Enabled)
			{
				var serviceContext = PortalCrmConfigurationManager.CreateServiceContext(configuration.PortalName);
				var crmEntityPermissionProvider = new CrmEntityPermissionProvider(configuration.PortalName);

				configuration.AssociateActionLink.Enabled =
					crmEntityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.AppendTo,
						Retrieve(serviceContext, source)) &&
					crmEntityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Append, viewEntityLogicalName);
			}
		}

		private static Entity Retrieve(OrganizationServiceContext serviceContext, EntityReference target)
		{
			var request = new RetrieveRequest { Target = target, ColumnSet = new ColumnSet(true) };
			var response = serviceContext.Execute(request) as RetrieveResponse;
			return response == null ? null : response.Entity;
		}
	}
}


text:
package com.serenegiant.media;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.util.Log;

import androidx.activity.ComponentActivity;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.annotation.CallSuper;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

/**
 * MediaProjectionManagerでスクリーンキャプチャーするためのヘルパークラス
 * MediaProjectionManager#getMediaProjectionへ引き渡すIntentを取得する
 *
 * 本当はoutの型をMediaProjectionにしてMediaProjectionの取得まで実行したい
 * ところだけど、それだとバックグラウンドで録画や映像伝送する際にバックグラウンド
 * 動作のServiceへ引き渡すのが難しくなるので、
 * MediaProjectionManager#getMediaProjectionへ引き渡すIntentを取得する
 * ところまでの処理とする
 */
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
public class ScreenCaptureUtils {
	private static final boolean DEBUG = false;	// set false on production
	private static final String TAG = ScreenCaptureUtils.class.getSimpleName();

	public interface ScreenCaptureCallback {
		/**
		 * MediaProjectionManager#getMediaProjectionへ引き渡すIntent
		 * このコールバックメソッドが呼ばれたときはActivity.RESULT_OKなので
		 * getMediaProjectionの第1引数はActivity.RESULT_OKにすること
		 * @param data
		 */
		public void onResult(@NonNull final Intent data);

		/**
		 * スクリーンキャプチャーの許可要求をユーザーが拒否したとき
		 */
		public void onFailed();
	}

	@NonNull
	private final ActivityResultLauncher<Void> mLauncher;
	private boolean mRequestProjection;

	/**
	 * コンストラクタ
	 * @param activity
	 * @param callback
	 */
	public ScreenCaptureUtils(
		@NonNull final ComponentActivity activity,
		@NonNull final ScreenCaptureCallback callback) {

		mLauncher = activity.registerForActivityResult(
			new ScreenCapture(),
			result -> {
				if (DEBUG) Log.v(TAG, "onActivityResult:" + result);
				if (result != null) {
					callback.onResult(result);
				} else {
					callback.onFailed();
				}
			});
	}

	/**
	 * コンストラクタ
	 * @param fragment
	 * @param callback
	 */
	public ScreenCaptureUtils(
		@NonNull final Fragment fragment,
		@NonNull final ScreenCaptureCallback callback) {

		mLauncher = fragment.registerForActivityResult(
			new ScreenCapture(),
			result -> {
				if (result != null) {
					callback.onResult(result);
				} else {
					callback.onFailed();
				}
			});
	}

	/**
	 * スクリーンキャプチャーの許可を求める
	 */
	public void requestScreenCapture() {
		if (!mRequestProjection) {
			mRequestProjection = true;
			mLauncher.launch(null);
		}
	}

	/**
	 * MediaProjectionManager/MediaProjectionを利用したスクリーンキャプチャー
	 * 開始要求に使うためのActivityResultContract実装
	 * 本当はoutの型をMediaProjectionにしてparseResultでMediaProjectionの
	 * 取得まで実行したいところだけど、それだとバックグラウンドで録画や映像伝送する際に
	 * バックグラウンド動作のServiceへ引き渡すのが難しくなるので、
	 * MediaProjectionManager#getMediaProjectionへ引き渡すIntentを取得するところまでの
	 * 処理とする
	 */
	private static class ScreenCapture extends ActivityResultContract<Void, Intent> {
		private static final String TAG = ScreenCapture.class.getSimpleName();

		@CallSuper
		@NonNull
		@Override
		public Intent createIntent(@NonNull Context context, final Void unsued) {
			if (DEBUG) Log.v(TAG, "createIntent:");
			final MediaProjectionManager manager =
				(MediaProjectionManager) context.getSystemService(
					Context.MEDIA_PROJECTION_SERVICE);
			return manager.createScreenCaptureIntent();
		}

		@Nullable
		@Override
		public final SynchronousResult<Intent> getSynchronousResult(
			@NonNull Context context,
			@Nullable Void unused) {
			if (DEBUG) Log.v(TAG, "getSynchronousResult:");
			return null;
		}

		@Nullable
		@Override
		public final Intent parseResult(final int resultCode, @Nullable Intent intent) {
			if (DEBUG) Log.v(TAG, "parseResult:resultCode=" + resultCode + "," + intent);
			return ((intent!= null)
				&& (resultCode == Activity.RESULT_OK))
				? intent : null;
		}
	}
}


text:
package com.example.hoperun.myapplication;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MixView extends Activity {

    int[] images = new int[]{R.drawable.java, R.drawable.javaee, R.drawable.swift,
            R.drawable.ajax, R.drawable.html};
    int currentImg = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mix_view);
        LinearLayout main = (LinearLayout) findViewById(R.id.root);
        final ImageView image = new ImageView(this);
        main.addView(image);
        image.setImageResource(images[0]);
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                image.setImageResource(images[++currentImg % images.length]);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_mix_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
from twisted.internet import reactor, error
from twisted.words.protocols.jabber import client, jid
from twisted.python import log
from copy import deepcopy

from twisted.words.xish.domish import ExpatElementStream, SuxElementStream
from twisted.words.protocols.jabber import xmlstream
from punjab.xmpp.ns import XMPP_PREFIXES

INVALID_USER_EVENT = "//event/client/basicauth/invaliduser"
AUTH_FAILED_EVENT = "//event/client/basicauth/authfailed"
REGISTER_FAILED_EVENT = "//event/client/basicauth/registerfailed"

# event funtions

def basic_connect(jabberid, secret, host, port, cb, v=0):
    myJid = jid.JID(jabberid)
    factory = client.basicClientFactory(myJid, secret)
    factory.v = v
    factory.addBootstrap('//event/stream/authd', cb)
    reactor.connectTCP(host, port, factory)
    return factory

def basic_disconnect(f, xmlstream):
    sh = "</stream:stream>"
    xmlstream.send(sh)
    f.stopTrying()
    xmlstream = None

class JabberClientFactory(xmlstream.XmlStreamFactory):
    def __init__(self, host, v=0):
        """ Initialize
        """
        p = self.authenticator = PunjabAuthenticator(host)
        xmlstream.XmlStreamFactory.__init__(self, p)

        self.pending = {}
        self.maxRetries = 2
        self.host = host
        self.jid = ""
        self.raw_buffer = ""

        if v != 0:
            self.v = v
            self.rawDataOutFn = self.rawDataOut
            self.rawDataInFn = self.rawDataIn

    def clientConnectionFailed(self, connector, reason, d=None):
        if self.continueTrying:
            self.connector = connector
            if not reason.check(error.UserError):
                self.retry()
            if self.maxRetries and (self.retries > self.maxRetries):
                if d:
                    d.errback(reason)

    def rawDataIn(self, buf):
        log.msg("RECV: %s" % buf.decode('utf-8'))

    def rawDataOut(self, buf):
        log.msg("SEND: %s" % buf.decode('utf-8'))

class ShallowExpatElementStream(ExpatElementStream):
    """Modification of parser that doesn't build xml tree for stanza payload.

    Make stream parser handle only top level stanza tags. In this way payload
    (all xml elements with depth > 1) will not be parsed into xml tree. This
    optimization would particularly be useful for <iq> stanzas, as they may
    contain large payload (e.g. roster)

    """
    STANZA_TYPES = ['message', 'presence', 'iq']

    def __init__(self, *args, **kwargs):
        ExpatElementStream.__init__(self, *args, **kwargs)
        self._depth = 0
        self._cur_stanza = None

    def _parse_tag_name(self, name):
        qname = name.split(' ')
        # Namespace is not present
        if len(qname) == 1:
            tag_name = qname[0]
        # Take only tag name
        elif len(qname) == 2:
            tag_name = qname[1]
        else:
            tag_name = None

        return tag_name

    def _onStartElement(self, name, attrs):
        self._depth += 1
        if self._cur_stanza is None:
            tag_name = self._parse_tag_name(name)
            if tag_name in self.STANZA_TYPES:
                self._cur_stanza = (tag_name, self._depth)
            ExpatElementStream._onStartElement(self, name, attrs)
        else:
            return

    def _onEndElement(self, name):
        if self._cur_stanza is not None:
            if self._depth == self._cur_stanza[1]:
                self._depth -= 1
                self._cur_stanza = None
                ExpatElementStream._onEndElement(self, name)
            else:
                self._depth -= 1
                return
        else:
            self._depth -= 1
            ExpatElementStream._onEndElement(self, name)

def elementStream(shallow=False):
    """ Preferred method to construct an ElementStream

    Uses regular or 'shallow' Expat-based stream if available,
    and falls back to Sux if necessary.

    """
    try:
        if shallow:
            es = ShallowExpatElementStream()
        else:
            es = ExpatElementStream()
        return es
    except ImportError:
        if SuxElementStream is None:
            raise Exception("No parsers available :(")
        es = SuxElementStream()
        return es

class PunjabAuthenticator(xmlstream.ConnectAuthenticator):
    namespace = "jabber:client"
    version = '1.0'
    useTls = 1

    def connectionMade(self):
        host = self.otherHost
        self.streamHost = host

        self.xmlstream.useTls = self.useTls
        self.xmlstream.namespace = self.namespace
        self.xmlstream.otherHost = self.otherHost
        self.xmlstream.otherEntity = jid.internJID(self.otherHost)
        self.xmlstream.prefixes = deepcopy(XMPP_PREFIXES)
        self.xmlstream.sendHeader()

    def streamStarted(self, rootelem=None):
        xmlstream.ConnectAuthenticator.streamStarted(self, rootelem)
        if rootelem is None:
            self.xversion = 3
            return

        self.xversion = 0
        if rootelem.hasAttribute('version'):
            self.version = rootelem['version']
        else:
            self.version = 0.0

    def associateWithStream(self, xs):
        xmlstream.ConnectAuthenticator.associateWithStream(self, xs)
        inits = [(xmlstream.TLSInitiatingInitializer, False)]

        for initClass, required in inits:
            init = initClass(xs)
            init.required = required
            xs.initializers.append(init)

    def _reset(self, shallow=False):
        # need this to be in xmlstream
        stream = elementStream(shallow)
        stream.DocumentStartEvent = self.xmlstream.onDocumentStart
        stream.ElementEvent = self.xmlstream.onElement
        stream.DocumentEndEvent = self.xmlstream.onDocumentEnd
        self.xmlstream.stream = stream
        self.xmlstream.prefixes = deepcopy(XMPP_PREFIXES)
        # Generate stream header

        if self.version != 0.0:
            sh = ("<stream:stream xmlns='%s' "
                  "xmlns:stream='http://etherx.jabber.org/streams' "
                  "version='%s' to='%s'>") % (self.namespace,
                                              self.version,
                                              self.streamHost)
            self.xmlstream.send(sh)

    def sendAuth(self, jid, passwd, callback, errback=None):
        self.jid = jid
        self.passwd = passwd
        if errback:
            self.xmlstream.addObserver(INVALID_USER_EVENT, errback)
            self.xmlstream.addObserver(AUTH_FAILED_EVENT, errback)
        if self.version != '1.0':
            iq = client.IQ(self.xmlstream, "get")
            iq.addElement(("jabber:iq:auth", "query"))
            iq.query.addElement("username", content=jid.user)
            iq.addCallback(callback)
            iq.send()

    def authQueryResultEvent(self, iq, callback):
        if iq["type"] == "result":
            # Construct auth request
            iq = client.IQ(self.xmlstream, "set")
            iq.addElement(("jabber:iq:auth", "query"))
            iq.query.addElement("username", content=self.jid.user)
            iq.query.addElement("resource", content=self.jid.resource)

            # Prefer digest over plaintext
            if client.DigestAuthQry.matches(iq):
                digest = xmlstream.hashPassword(self.xmlstream.sid,
                                                self.passwd)
                iq.query.addElement("digest", content=digest)
            else:
                iq.query.addElement("password", content=self.passwd)

            iq.addCallback(callback)
            iq.send()
        else:
            # Check for 401 -- Invalid user
            if iq.error["code"] == "401":
                self.xmlstream.dispatch(iq, INVALID_USER_EVENT)
            else:
                self.xmlstream.dispatch(iq, AUTH_FAILED_EVENT)


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

			<title>Docs For Class Apache_Solr_Service</title>
			<link rel="stylesheet" href="../../media/stylesheet.css" />
			<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/>

Class Apache_Solr_Service

Description

					Description |
													Vars (details)
						|											Methods (details)

											Constants (details)

Starting point for the Solr API. Represents a Solr server resource and has  methods for pinging, adding, deleting, committing, optimizing and searching.

Example Usage:

 ...

 $solr = new Apache_Solr_Service(); //or explicitly new Apache_Solr_Service('localhost', 8180, '/solr')

 if ($solr->ping())

 {

         $solr->deleteByQuery('*:*'); //deletes ALL documents - be careful :)

         $document = new Apache_Solr_Document();

         $document->id = uniqid(); //or something else suitably unique

         $document->title = 'Some Title';

         $document->content = 'Some content for this wonderful document. Blah blah blah.';

         $solr->addDocument($document);     //if you're going to be adding documents in bulk using addDocuments

                                         //with an array of documents is faster

         $solr->commit(); //commit to see the deletes and the document

         $solr->optimize(); //merges multiple segments into one

         //and the one we all care about, search!

         //any other common or custom parameters to the request handler can go in the

         //optional 4th array argument.

         $solr->search('content:blah', 0, 10, array('sort' => 'timestamp desc'));

 }

 ...

todo: Investigate using other HTTP clients other than file_get_contents built-in handler. Could provide performance  improvements when dealing with multiple requests by using HTTP's keep alive functionality

			Located in /Service.php (line 86)

Class Constant Summary

			Description |
						Constants (details)
												Vars (details)

				|
										|
									Methods (details)

					EXTRACT_SERVLET = 					 'update/extract'

					METHOD_GET = 					 'GET'

					METHOD_POST = 					 'POST'

					NAMED_LIST_FLAT = 					 'flat'

					NAMED_LIST_MAP = 					 'map'

					PING_SERVLET = 					 'admin/ping'

					SEARCH_SERVLET = 					 'select'

					SOLR_WRITER = 					 'json'

					SVN_ID = 					 '$Id: Service.php 59 2011-02-08 20:38:59Z donovan.jimenez $'

					SVN_REVISION = 					 '$Revision: 59 $'

					THREADS_SERVLET = 					 'admin/threads'

					UPDATE_SERVLET = 					 'update'

Variable Summary

			Description |
						Vars (details)
							|
									Methods (details)

															Constants (details)

					boolean
					$_collapseSingleValueArrays

					boolean
					$_createDocuments

					string
					$_host

					Apache_Solr_HttpTransport_Interface
					$_httpTransport

					string
					$_namedListTreatment

					mixed
					$_path

					string
					$_pingUrl

					mixed
					$_port

					mixed
					$_queryBracketsEscaped

					string
					$_queryDelimiter

					mixed
					$_queryStringDelimiter

					mixed
					$_searchUrl

					mixed
					$_threadsUrl

					mixed
					$_updateUrl

					boolean
					$_urlsInited

Method Summary

			Description |
															Constants (details)

															Vars (details)

				|
						Methods (details)

					static 						string
										escape
											(string $value)

					static 						string
										escapePhrase
											(string $value)

					static 						string
										phrase
											(string $value)

											Apache_Solr_Response
										add
											(string $rawPost)

											Apache_Solr_Response
										addDocument
											(Apache_Solr_Document $document, [boolean $allowDups = false], [boolean $overwritePending = true], [boolean $overwriteCommitted = true], [integer $commitWithin = 0])

											Apache_Solr_Response
										addDocuments
											(array $documents, [boolean $allowDups = false], [boolean $overwritePending = true], [boolean $overwriteCommitted = true], [integer $commitWithin = 0])

											Apache_Solr_Response
										commit
											([boolean $expungeDeletes = false], [boolean $waitFlush = true], [boolean $waitSearcher = true], [float $timeout = 3600])

											Apache_Solr_Response
										delete
											(string $rawPost, [float $timeout = 3600])

											Apache_Solr_Response
										deleteById
											(string $id, [boolean $fromPending = true], [boolean $fromCommitted = true], [float $timeout = 3600])

											Apache_Solr_Response
										deleteByMultipleIds
											(array $ids, [boolean $fromPending = true], [boolean $fromCommitted = true], [float $timeout = 3600])

											Apache_Solr_Response
										deleteByQuery
											(string $rawQuery, [boolean $fromPending = true], [boolean $fromCommitted = true], [float $timeout = 3600])

											Apache_Solr_Response
										extract
											(string $file, [array $params = array()], [Apache_Solr_Document $document = null], [string $mimetype = 'application/octet-stream'])

											Apache_Solr_Response
										extractFromString
											(string $data, [array $params = array()], [Apache_Solr_Document $document = null], [string $mimetype = 'application/octet-stream'])

											Apache_Solr_Response
										extractFromUrl
											(string $url, [array $params = array()], [Apache_Solr_Document $document = null], [string $mimetype = 'application/octet-stream'])

											boolean
										getCollapseSingleValueArrays
										()

											boolean
										getCreateDocuments
										()

											float
										getDefaultTimeout
										()

											string
										getHost
										()

											HttpTransportInterface
										getHttpTransport
										()

											string
										getNamedListTreatment
										()

											string
										getPath
										()

											integer
										getPort
										()

											Apache_Solr_Service
										__construct
											([string $host = 'localhost'], [string $port = 8180], [string $path = '/solr/'], [Apache_Solr_HttpTransport_Interface $httpTransport = false])

											Apache_Solr_Response
										optimize
											([boolean $waitFlush = true], [boolean $waitSearcher = true], [float $timeout = 3600])

											float
										ping
											([float $timeout = 2])

											Apache_Solr_Response
										search
											(string $query, [int $offset = 0], [int $limit = 10], [array $params = array()], [string $method = self::METHOD_GET])

											void
										setCollapseSingleValueArrays
											(boolean $collapseSingleValueArrays)

											void
										setCreateDocuments
											(boolean $createDocuments)

											void
										setDefaultTimeout
											(float $timeout)

											void
										setHost
											(string $host)

											void
										setHttpTransport
											(Apache_Solr_HttpTransport_Interface $httpTransport)

											void
										setNamedListTreatment
											(string $namedListTreatment)

											void
										setPath
											(string $path)

											void
										setPort
											(integer $port)

											void
										setQueryDelimiter
											(string $queryDelimiter)

											void
										setQueryStringDelimiter
											(string $queryStringDelimiter)

											Apache_Solr_Response
										threads
										()

											string
										_constructUrl
											(string $servlet, [ $params = array()])

											string
										_documentToXmlFragment
											(Apache_Solr_Document $document)

											void
										_generateQueryString
											( $params)

											void
										_initUrls
										()

											Apache_Solr_Response
										_sendRawGet
											(string $url, [float $timeout = FALSE])

											Apache_Solr_Response
										_sendRawPost
											(string $url, string $rawPost, [float $timeout = FALSE], [string $contentType = 'text/xml; charset=UTF-8'])

											string
										_stripCtrlChars
											(string $string)

Variables

			Description |
										Vars (details)

												Constants (details)

										|
									Methods (details)

			boolean
			$_collapseSingleValueArrays
			 =  true			(line 145)

Whether Apache_Solr_Response objects should have multivalue fields with only a single value  collapsed to appear as a single value would.

access: protected

			boolean
			$_createDocuments
			 =  true			(line 137)

Whether Apache_Solr_Response objects should create Apache_Solr_Documents in  the returned parsed data

access: protected

			string
			$_host
						(line 129)

Server identification strings

access: protected

			Apache_Solr_HttpTransport_Interface
			$_httpTransport
			 =  false			(line 182)

HTTP Transport implementation (pluggable)

access: protected

			string
			$_namedListTreatment
			 =  self::NAMED_LIST_MAP			(line 153)

How NamedLists should be formatted in the output.  This specifically effects facet counts. Valid values  are Apache_Solr_Service::NAMED_LIST_MAP (default) or Apache_Solr_Service::NAMED_LIST_FLAT.

access: protected

			mixed
			$_path
						(line 129)

access: protected

			string
			$_pingUrl
						(line 168)

Constructed servlet full path URLs

access: protected

			mixed
			$_port
						(line 129)

access: protected

			mixed
			$_queryBracketsEscaped
			 =  true			(line 161)

access: protected

			string
			$_queryDelimiter
			 =  '?'			(line 161)

Query delimiters. Someone might want to be able to change  these (to use &amp; instead of & for example), so I've provided them.

access: protected

			mixed
			$_queryStringDelimiter
			 =  '&'			(line 161)

access: protected

			mixed
			$_searchUrl
						(line 168)

access: protected

			mixed
			$_threadsUrl
						(line 168)

access: protected

			mixed
			$_updateUrl
						(line 168)

access: protected

			boolean
			$_urlsInited
			 =  false			(line 175)

Keep track of whether our URLs have been constructed

access: protected

Methods

			Description |
															Vars (details)
																			Constants (details)

										Methods (details)

		static escape (line 192)

Escape a value for special query characters such as ':', '(', ')', '*', '?', etc.

NOTE: inside a phrase fewer characters need escaped, use Apache_Solr_Service::escapePhrase() instead

access: public

		static string

			escape

					(string $value)

				string
				$value

		static escapePhrase (line 207)

Escape a value meant to be contained in a phrase for special query characters

access: public

		static string

			escapePhrase

					(string $value)

				string
				$value

		static phrase (line 221)

Convenience function for creating phrase syntax from a value

access: public

		static string

			phrase

					(string $value)

				string
				$value

		add (line 667)

Raw Add Method. Takes a raw post body and sends it to the update service.  Post body  should be a complete and well formed "add" xml document.

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			add

					(string $rawPost)

				string
				$rawPost

		addDocument (line 684)

Add a Solr Document to the index

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			addDocument

					(Apache_Solr_Document $document, [boolean $allowDups = false], [boolean $overwritePending = true], [boolean $overwriteCommitted = true], [integer $commitWithin = 0])

				Apache_Solr_Document
				$document

				boolean
				$allowDups

				boolean
				$overwritePending

				boolean
				$overwriteCommitted

				integer
				$commitWithin: The number of milliseconds that a document must be committed within, see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details.  If left empty this property will not be set in the request.

		addDocuments (line 712)

Add an array of Solr Documents to the index all at once

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			addDocuments

					(array $documents, [boolean $allowDups = false], [boolean $overwritePending = true], [boolean $overwriteCommitted = true], [integer $commitWithin = 0])

				array
				$documents: Should be an array of Apache_Solr_Document instances

				boolean
				$allowDups

				boolean
				$overwritePending

				boolean
				$overwriteCommitted

				integer
				$commitWithin: The number of milliseconds that a document must be committed within, see @{link http://wiki.apache.org/solr/UpdateXmlMessages#The_Update_Schema} for details.  If left empty this property will not be set in the request.

		commit (line 821)

Send a commit command.  Will be synchronous unless both wait parameters are set to false.

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			commit

					([boolean $expungeDeletes = false], [boolean $waitFlush = true], [boolean $waitSearcher = true], [float $timeout = 3600])

				boolean
				$expungeDeletes: Defaults to false, merge segments with deletes away

				boolean
				$waitFlush: Defaults to true,  block until index changes are flushed to disk

				boolean
				$waitSearcher: Defaults to true, block until a new searcher is opened and registered as the main query searcher, making the changes visible

				float
				$timeout: Maximum expected duration (in seconds) of the commit operation on the server (otherwise, will throw a communication exception). Defaults to 1 hour

		delete (line 842)

Raw Delete Method. Takes a raw post body and sends it to the update service. Body should be  a complete and well formed "delete" xml document

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			delete

					(string $rawPost, [float $timeout = 3600])

				string
				$rawPost: Expected to be utf-8 encoded xml document

				float
				$timeout: Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)

		deleteById (line 858)

Create a delete document based on document ID

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			deleteById

					(string $id, [boolean $fromPending = true], [boolean $fromCommitted = true], [float $timeout = 3600])

				string
				$id: Expected to be utf-8 encoded

				boolean
				$fromPending

				boolean
				$fromCommitted

				float
				$timeout: Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)

		deleteByMultipleIds (line 882)

Create and post a delete document based on multiple document IDs.

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			deleteByMultipleIds

					(array $ids, [boolean $fromPending = true], [boolean $fromCommitted = true], [float $timeout = 3600])

				array
				$ids: Expected to be utf-8 encoded strings

				boolean
				$fromPending

				boolean
				$fromCommitted

				float
				$timeout: Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)

		deleteByQuery (line 913)

Create a delete document based on a query and submit it

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			deleteByQuery

					(string $rawQuery, [boolean $fromPending = true], [boolean $fromCommitted = true], [float $timeout = 3600])

				string
				$rawQuery: Expected to be utf-8 encoded

				boolean
				$fromPending

				boolean
				$fromCommitted

				float
				$timeout: Maximum expected duration of the delete operation on the server (otherwise, will throw a communication exception)

		extract (line 944)

Use Solr Cell to extract document contents. See http://wiki.apache.org/solr/ExtractingRequestHandler for information on how  to use Solr Cell and what parameters are available.

NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost."  as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value  pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also  pass in a document isntance with an "id" field" - the document's value(s) will take precedence).

throws: Apache_Solr_InvalidArgumentException if $file, $params, or $document are invalid.

access: public

		Apache_Solr_Response

			extract

					(string $file, [array $params = array()], [Apache_Solr_Document $document = null], [string $mimetype = 'application/octet-stream'])

				string
				$file: Path to file to extract data from

				array
				$params: optional array of key value pairs that will be sent with the post (see Solr Cell documentation)

				Apache_Solr_Document
				$document: optional document that will be used to generate post parameters (literal.* and boost.* params)

				string
				$mimetype: optional mimetype specification (for the file being extracted)

		extractFromString (line 1005)

Use Solr Cell to extract document contents. See http://wiki.apache.org/solr/ExtractingRequestHandler for information on how  to use Solr Cell and what parameters are available.

NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost."  as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value  pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also  pass in a document isntance with an "id" field" - the document's value(s) will take precedence).

todo: Should be using multipart/form-data to post parameter values, but I could not get my implementation to work. Needs revisisted.

throws: Apache_Solr_InvalidArgumentException if $file, $params, or $document are invalid.

access: public

		Apache_Solr_Response

			extractFromString

					(string $data, [array $params = array()], [Apache_Solr_Document $document = null], [string $mimetype = 'application/octet-stream'])

				string
				$data: Data that will be passed to Solr Cell

				array
				$params: optional array of key value pairs that will be sent with the post (see Solr Cell documentation)

				Apache_Solr_Document
				$document: optional document that will be used to generate post parameters (literal.* and boost.* params)

				string
				$mimetype: optional mimetype specification (for the file being extracted)

		extractFromUrl (line 1068)

Use Solr Cell to extract document contents. See http://wiki.apache.org/solr/ExtractingRequestHandler for information on how  to use Solr Cell and what parameters are available.

NOTE: when passing an Apache_Solr_Document instance, field names and boosts will automatically be prepended by "literal." and "boost."  as appropriate. Any keys from the $params array will NOT be treated this way. Any mappings from the document will overwrite key / value  pairs in the params array if they have the same name (e.g. you pass a "literal.id" key and value in your $params array but you also  pass in a document isntance with an "id" field" - the document's value(s) will take precedence).

throws: Apache_Solr_InvalidArgumentException if $url, $params, or $document are invalid.

access: public

		Apache_Solr_Response

			extractFromUrl

					(string $url, [array $params = array()], [Apache_Solr_Document $document = null], [string $mimetype = 'application/octet-stream'])

				string
				$url: URL

				array
				$params: optional array of key value pairs that will be sent with the post (see Solr Cell documentation)

				Apache_Solr_Document
				$document: optional document that will be used to generate post parameters (literal.* and boost.* params)

				string
				$mimetype: optional mimetype specification (for the file being extracted)

		getCollapseSingleValueArrays (line 533)

Get the current state of the collapse single value arrays flag.

access: public

		boolean

			getCollapseSingleValueArrays

				()

		getCreateDocuments (line 513)

Get the current state of teh create documents flag.

access: public

		boolean

			getCreateDocuments

				()

		getDefaultTimeout (line 546)

Get the current default timeout setting (initially the default_socket_timeout ini setting)  in seconds

deprecated: Use the getDefaultTimeout method on the HTTP transport implementation

access: public

		float

			getDefaultTimeout

				()

		getHost (line 375)

Returns the set host

access: public

		string

			getHost

				()

		getHttpTransport (line 474)

Get the current configured HTTP Transport

access: public

		HttpTransportInterface

			getHttpTransport

				()

		getNamedListTreatment (line 592)

Get the current setting for named list treatment.

access: public

		string

			getNamedListTreatment

				()

		getPath (line 447)

Get the set path.

access: public

		string

			getPath

				()

		getPort (line 410)

Get the set port

access: public

		integer

			getPort

				()

		Constructor __construct (line 235)

Constructor. All parameters are optional and will take on default values  if not specified.

access: public

		Apache_Solr_Service

			__construct

					([string $host = 'localhost'], [string $port = 8180], [string $path = '/solr/'], [Apache_Solr_HttpTransport_Interface $httpTransport = false])

				string
				$host

				string
				$port

				string
				$path

				Apache_Solr_HttpTransport_Interface
				$httpTransport

		optimize (line 1117)

Send an optimize command.  Will be synchronous unless both wait parameters are set  to false.

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			optimize

					([boolean $waitFlush = true], [boolean $waitSearcher = true], [float $timeout = 3600])

				boolean
				$waitFlush

				boolean
				$waitSearcher

				float
				$timeout: Maximum expected duration of the commit operation on the server (otherwise, will throw a communication exception)

		ping (line 626)

Call the /admin/ping servlet, can be used to quickly tell if a connection to the  server is able to be made.

return: Actual time taken to ping the server, FALSE if timeout or HTTP error status occurs

access: public

		float

			ping

					([float $timeout = 2])

				float
				$timeout: maximum time to wait for ping in seconds, -1 for unlimited (default is 2)

		search (line 1140)

Simple Search interface

throws: Apache_Solr_InvalidArgumentException If an invalid HTTP method is used

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			search

					(string $query, [int $offset = 0], [int $limit = 10], [array $params = array()], [string $method = self::METHOD_GET])

				string
				$query: The raw query string

				int
				$offset: The starting offset for result documents

				int
				$limit: The maximum number of result documents to return

				array
				$params: key / value pairs for other query parameters (see Solr documentation), use arrays for parameter keys used more than once (e.g. facet.field)

				string
				$method: The HTTP method (Apache_Solr_Service::METHOD_GET or Apache_Solr_Service::METHOD::POST)

		setCollapseSingleValueArrays (line 523)

Set the collapse single value arrays flag.

access: public

		void

			setCollapseSingleValueArrays

					(boolean $collapseSingleValueArrays)

				boolean
				$collapseSingleValueArrays

		setCreateDocuments (line 503)

Set the create documents flag. This determines whether Apache_Solr_Response objects will  parse the response and create Apache_Solr_Document instances in place.

access: public

		void

			setCreateDocuments

					(boolean $createDocuments)

				boolean
				$createDocuments

		setDefaultTimeout (line 558)

Set the default timeout for all calls that aren't passed a specific timeout

deprecated: Use the setDefaultTimeout method on the HTTP transport implementation

access: public

		void

			setDefaultTimeout

					(float $timeout)

				float
				$timeout: Timeout value in seconds

		setHost (line 387)

Set the host used. If empty will fallback to constants

throws: Apache_Solr_InvalidArgumentException If the host parameter is empty

access: public

		void

			setHost

					(string $host)

				string
				$host

		setHttpTransport (line 492)

Set the HTTP Transport implemenation that will be used for all HTTP requests

access: public

		void

			setHttpTransport

					(Apache_Solr_HttpTransport_Interface $httpTransport)

				Apache_Solr_HttpTransport_Interface
				$httpTransport

		setNamedListTreatment (line 570)

Set how NamedLists should be formatted in the response data. This mainly effects  the facet counts format.

throws: Apache_Solr_InvalidArgumentException If invalid option is set

access: public

		void

			setNamedListTreatment

					(string $namedListTreatment)

				string
				$namedListTreatment

		setPath (line 457)

Set the path used. If empty will fallback to constants

access: public

		void

			setPath

					(string $path)

				string
				$path

		setPort (line 422)

Set the port used. If empty will fallback to constants

throws: Apache_Solr_InvalidArgumentException If the port parameter is empty

access: public

		void

			setPort

					(integer $port)

				integer
				$port

		setQueryDelimiter (line 603)

Set the string used to separate the path form the query string.

Defaulted to '?'

access: public

		void

			setQueryDelimiter

					(string $queryDelimiter)

				string
				$queryDelimiter

		setQueryStringDelimiter (line 614)

Set the string used to separate the parameters in thequery string  Defaulted to '&'

access: public

		void

			setQueryStringDelimiter

					(string $queryStringDelimiter)

				string
				$queryStringDelimiter

		threads (line 653)

Call the /admin/threads servlet and retrieve information about all threads in the  Solr servlet's thread group. Useful for diagnostics.

throws: Apache_Solr_HttpTransportException If an error occurs during the service call

access: public

		Apache_Solr_Response

			threads

				()

		_constructUrl (line 258)

Return a valid http URL given this server's host, port and path and a provided servlet name

access: protected

		string

			_constructUrl

					(string $servlet, [ $params = array()])

				string
				$servlet

				$params

		_documentToXmlFragment (line 741)

Create an XML fragment from a Apache_Solr_Document instance appropriate for use inside a Solr add call

access: protected

		string

			_documentToXmlFragment

					(Apache_Solr_Document $document)

				Apache_Solr_Document
				$document

		_generateQueryString (line 295)

access: protected

		void

			_generateQueryString

					( $params)

				$params

		_initUrls (line 283)

Construct the Full URLs for the three servlets we reference

access: protected

		void

			_initUrls

				()

		_sendRawGet (line 329)

Central method for making a get operation against this Solr Server

throws: Apache_Solr_HttpTransportException If a non 200 response status is returned

access: protected

		Apache_Solr_Response

			_sendRawGet

					(string $url, [float $timeout = FALSE])

				string
				$url

				float
				$timeout: Read timeout in seconds

		_sendRawPost (line 355)

Central method for making a post operation against this Solr Server

throws: Apache_Solr_HttpTransportException If a non 200 response status is returned

access: protected

		Apache_Solr_Response

			_sendRawPost

					(string $url, string $rawPost, [float $timeout = FALSE], [string $contentType = 'text/xml; charset=UTF-8'])

				string
				$url

				string
				$rawPost

				float
				$timeout: Read timeout in seconds

				string
				$contentType

		_stripCtrlChars (line 803)

Replace control (non-printable) characters from string that are invalid to Solr's XML parser with a space.

access: protected

		string

			_stripCtrlChars

					(string $string)

				string
				$string

Class Constants

			Description |
										Constants (details)

												Vars (details)
														|
									Methods (details)

			EXTRACT_SERVLET
			 =  'update/extract'
			(line 122)

			METHOD_GET
			 =  'GET'
			(line 112)

Search HTTP Methods

			METHOD_POST
			 =  'POST'
			(line 113)

			NAMED_LIST_FLAT
			 =  'flat'
			(line 106)

NamedList Treatment constants

			NAMED_LIST_MAP
			 =  'map'
			(line 107)

			PING_SERVLET
			 =  'admin/ping'
			(line 118)

Servlet mappings

			SEARCH_SERVLET
			 =  'select'
			(line 120)

			SOLR_WRITER
			 =  'json'
			(line 101)

Response writer we'll request - JSON. See http://code.google.com/p/solr-php-client/issues/detail?id=6#c1 for reasoning

			SVN_ID
			 =  '$Id: Service.php 59 2011-02-08 20:38:59Z donovan.jimenez $'
			(line 96)

SVN ID meta data for this class

			SVN_REVISION
			 =  '$Revision: 59 $'
			(line 91)

SVN Revision meta data for this class

			THREADS_SERVLET
			 =  'admin/threads'
			(line 121)

			UPDATE_SERVLET
			 =  'update'
			(line 119)

		Documentation generated on Wed, 04 May 2011 11:01:19 -0400 by phpDocumentor 1.4.3


text:
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#include "trcConfig.h"
#include "trcPagedEventBuffer.h"
#include "trcPagedEventBufferConfig.h"
#include "trcKernelPort.h"

uint32_t DroppedEventCounter = 0;	// Total number of dropped events (failed allocations)
uint32_t TotalBytesRemaining_LowWaterMark = TRC_PAGED_EVENT_BUFFER_PAGE_COUNT * TRC_PAGED_EVENT_BUFFER_PAGE_SIZE;

#if (USE_TRACEALYZER_RECORDER == 1)

#define PAGE_STATUS_FREE 0
#define PAGE_STATUS_WRITE 1
#define PAGE_STATUS_READ 2

uint32_t TotalBytesRemaining = TRC_PAGED_EVENT_BUFFER_PAGE_COUNT * TRC_PAGED_EVENT_BUFFER_PAGE_SIZE;

typedef struct{
	uint8_t Status;
	uint16_t BytesRemaining;
	char* WritePointer;
} PageType;

PageType PageInfo[TRC_PAGED_EVENT_BUFFER_PAGE_COUNT];

char* EventBuffer = NULL;

static void prvPageReadComplete(int pageIndex);
static int prvAllocateBufferPage(int prevPage);

static int prvAllocateBufferPage(int prevPage)
{
	int index;
	int count = 0;

	index = (prevPage + 1) % TRC_PAGED_EVENT_BUFFER_PAGE_COUNT;

	while((PageInfo[index].Status != PAGE_STATUS_FREE) && (count ++ < TRC_PAGED_EVENT_BUFFER_PAGE_COUNT))
	{
		index = (index + 1) % TRC_PAGED_EVENT_BUFFER_PAGE_COUNT;
	}

	if (PageInfo[index].Status == PAGE_STATUS_FREE)
	{
		return index;
	}

	return -1;
}

static void prvPageReadComplete(int pageIndex)
{
  	TRACE_ALLOC_CRITICAL_SECTION();

	TRACE_ENTER_CRITICAL_SECTION();
	PageInfo[pageIndex].BytesRemaining = TRC_PAGED_EVENT_BUFFER_PAGE_SIZE;
	PageInfo[pageIndex].WritePointer = &EventBuffer[pageIndex * TRC_PAGED_EVENT_BUFFER_PAGE_SIZE];
	PageInfo[pageIndex].Status = PAGE_STATUS_FREE;

	TotalBytesRemaining += TRC_PAGED_EVENT_BUFFER_PAGE_SIZE;

	TRACE_EXIT_CRITICAL_SECTION();
}

static int prvGetBufferPage(int32_t* bytesUsed)
{
	static int8_t lastPage = -1;
	int count = 0;
  	int8_t index = (lastPage + 1) % TRC_PAGED_EVENT_BUFFER_PAGE_COUNT;

	while((PageInfo[index].Status != PAGE_STATUS_READ) && (count++ < TRC_PAGED_EVENT_BUFFER_PAGE_COUNT))
	{
		index = (index + 1) % TRC_PAGED_EVENT_BUFFER_PAGE_COUNT;
	}

	if (PageInfo[index].Status == PAGE_STATUS_READ)
	{
		*bytesUsed = TRC_PAGED_EVENT_BUFFER_PAGE_SIZE - PageInfo[index].BytesRemaining;
		lastPage = index;
		return index;
	}

	*bytesUsed = 0;

	return -1;
}

/*******************************************************************************

int32_t vPagedEventBufferTransfer(int32_t (*writeFunc)(void* data,
                                                        uint32_t size),
                                            int32_t* nofBytes)

Transfers one block of trace data, if available for reading. Returns the number
of bytes transfered, or a negative error code. If data was transferred (return
value > 0), it can be good to call this function again until all data available
has been transfered.

This function is intended to be called by a periodic task with a suitable
delay (e.g. 10-100 ms).

Example:

	TickType_t lastWakeTime = xTaskGetTickCount();

	while(1)
	{

		do{
			// Transfer all available data
			status = vPagedEventBufferTransfer(MyWrite, ptrBytes);
		}while(status > 0);

		if (status < 0)
		{
			// A negative return value is an error code...
		}

		vTraceDelayUntil(lastWakeTime, 50); // 50 ms -> 20 times/sec
	}

Return value: returnvalue of writeFunc (0 == OK)

Parameters:

- writeFunc
Function pointer (example: int32_t write(void* data, uint32_t size))
The function passed as writeFunc should write "size" bytes from "data" to the
socket/file/channel, and return a status code where 0 means OK,
and any other non-zero value means an error.

- int32_t* nofBytes
Pointer to an integer assigned the number of bytes that was transfered.

*******************************************************************************/

int32_t vPagedEventBufferTransfer(int32_t (*writeFunc)(void* data, uint32_t size, int32_t* ptrBytesWritten), int32_t* nofBytes)
{
	static int firstTime = 1;
	int8_t pageToTransfer = -1;

	pageToTransfer = prvGetBufferPage(nofBytes);

	if (firstTime)
	{
		firstTime = 0;
	}

	if (pageToTransfer > -1)
	{
		if (writeFunc(&EventBuffer[pageToTransfer * TRC_PAGED_EVENT_BUFFER_PAGE_SIZE], *nofBytes, nofBytes) == 0)
		{
			prvPageReadComplete(pageToTransfer);

            return 0;
		}
        else
        {
            return 1;
        }
	}
	return 0;
}

/*******************************************************************************

void* vPagedEventBufferGetWritePointer(int sizeOfEvent)

Returns a pointer to an available location in the buffer able to store the
requested size.

Return value: The pointer.

Parameters:

- sizeOfEvent
The size of the event that is to be placed in the buffer.

*******************************************************************************/
void* vPagedEventBufferGetWritePointer(int sizeOfEvent)
{
	void* ret;
	static int currentWritePage = -1;

	if (currentWritePage == -1)
	{
	    currentWritePage = prvAllocateBufferPage(currentWritePage);
		if (currentWritePage == -1)
		{
		  	DroppedEventCounter++;
			return NULL;
		}
	}

    if (PageInfo[currentWritePage].BytesRemaining - sizeOfEvent < 0)
	{
		PageInfo[currentWritePage].Status = PAGE_STATUS_READ;

		TotalBytesRemaining -= PageInfo[currentWritePage].BytesRemaining; // Last trailing bytes

		if (TotalBytesRemaining < TotalBytesRemaining_LowWaterMark)
		  TotalBytesRemaining_LowWaterMark = TotalBytesRemaining;

		currentWritePage = prvAllocateBufferPage(currentWritePage);
		if (currentWritePage == -1)
		{
		  DroppedEventCounter++;
		  return NULL;
		}
	}
	ret = PageInfo[currentWritePage].WritePointer;
	PageInfo[currentWritePage].WritePointer += sizeOfEvent;
	PageInfo[currentWritePage].BytesRemaining -= sizeOfEvent;

	TotalBytesRemaining -= sizeOfEvent;

	if (TotalBytesRemaining < TotalBytesRemaining_LowWaterMark)
		TotalBytesRemaining_LowWaterMark = TotalBytesRemaining;

	return ret;
}

/*******************************************************************************

void vPagedEventBufferInit(char* buffer)

Assigns the buffer to use and initializes the PageInfo structure.

Return value: void

Parameters:

- buffer
Pointer to the buffer location that is dynamically or statically allocated by
the caller.

*******************************************************************************/
void vPagedEventBufferInit(char* buffer)
{
  	TRACE_ALLOC_CRITICAL_SECTION();
  	int i;

    EventBuffer = buffer;

	TRACE_ENTER_CRITICAL_SECTION();
	for (i = 0; i < TRC_PAGED_EVENT_BUFFER_PAGE_COUNT; i++)
	{
		PageInfo[i].BytesRemaining = TRC_PAGED_EVENT_BUFFER_PAGE_SIZE;
		PageInfo[i].WritePointer = &EventBuffer[i * TRC_PAGED_EVENT_BUFFER_PAGE_SIZE];
		PageInfo[i].Status = PAGE_STATUS_FREE;
	}
	TRACE_EXIT_CRITICAL_SECTION();
}

#endif


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: iam_role
short_description: Manage AWS IAM roles
description:
  - Manage AWS IAM roles
version_added: "2.3"
author: "Rob White (@wimnat)"
options:
  path:
    description:
      - The path to the role. For more information about paths, see U(https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html).
    default: "/"
  name:
    description:
      - The name of the role to create.
    required: true
  description:
    description:
      - Provide a description of the new role
    version_added: "2.5"
  boundary:
    description:
      - Add the ARN of an IAM managed policy to restrict the permissions this role can pass on to IAM roles/users that it creates.
      - Boundaries cannot be set on Instance Profiles, so if this option is specified then C(create_instance_profile) must be false.
      - This is intended for roles/users that have permissions to create new IAM objects.
      - For more information on boundaries, see U(https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)
    aliases: [boundary_policy_arn]
    version_added: "2.7"
  assume_role_policy_document:
    description:
      - The trust relationship policy document that grants an entity permission to assume the role.
      - "This parameter is required when C(state=present)."
  managed_policy:
    description:
      - A list of managed policy ARNs or, since Ansible 2.4, a list of either managed policy ARNs or friendly names.
        To embed an inline policy, use M(iam_policy). To remove existing policies, use an empty list item.
    aliases: [ managed_policies ]
  purge_policies:
    description:
      - Detaches any managed policies not listed in the "managed_policy" option. Set to false if you want to attach policies elsewhere.
    type: bool
    default: true
    version_added: "2.5"
  state:
    description:
      - Create or remove the IAM role
    default: present
    choices: [ present, absent ]
  create_instance_profile:
    description:
      - Creates an IAM instance profile along with the role
    type: bool
    default: yes
    version_added: "2.5"
requirements: [ botocore, boto3 ]
extends_documentation_fragment:
  - aws
  - ec2
'''

EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.

- name: Create a role with description
  iam_role:
    name: mynewrole
    assume_role_policy_document: "{{ lookup('file','policy.json') }}"
    description: This is My New Role

- name: "Create a role and attach a managed policy called 'PowerUserAccess'"
  iam_role:
    name: mynewrole
    assume_role_policy_document: "{{ lookup('file','policy.json') }}"
    managed_policy:
      - arn:aws:iam::aws:policy/PowerUserAccess

- name: Keep the role created above but remove all managed policies
  iam_role:
    name: mynewrole
    assume_role_policy_document: "{{ lookup('file','policy.json') }}"
    managed_policy: []

- name: Delete the role
  iam_role:
    name: mynewrole
    assume_role_policy_document: "{{ lookup('file', 'policy.json') }}"
    state: absent

'''
RETURN = '''
iam_role:
    description: dictionary containing the IAM Role data
    returned: success
    type: complex
    contains:
        path:
            description: the path to the role
            type: str
            returned: always
            sample: /
        role_name:
            description: the friendly name that identifies the role
            type: str
            returned: always
            sample: myrole
        role_id:
            description: the stable and unique string identifying the role
            type: str
            returned: always
            sample: ABCDEFF4EZ4ABCDEFV4ZC
        arn:
            description: the Amazon Resource Name (ARN) specifying the role
            type: str
            returned: always
            sample: "arn:aws:iam::1234567890:role/mynewrole"
        create_date:
            description: the date and time, in ISO 8601 date-time format, when the role was created
            type: str
            returned: always
            sample: "2016-08-14T04:36:28+00:00"
        assume_role_policy_document:
            description: the policy that grants an entity permission to assume the role
            type: str
            returned: always
            sample: {
                        'statement': [
                            {
                                'action': 'sts:AssumeRole',
                                'effect': 'Allow',
                                'principal': {
                                    'service': 'ec2.amazonaws.com'
                                },
                                'sid': ''
                            }
                        ],
                        'version': '2012-10-17'
                    }
        attached_policies:
            description: a list of dicts containing the name and ARN of the managed IAM policies attached to the role
            type: list
            returned: always
            sample: [
                {
                    'policy_arn': 'arn:aws:iam::aws:policy/PowerUserAccess',
                    'policy_name': 'PowerUserAccess'
                }
            ]
'''

from ansible.module_utils._text import to_native
from ansible.module_utils.aws.core import AnsibleAWSModule
from ansible.module_utils.ec2 import camel_dict_to_snake_dict, ec2_argument_spec, get_aws_connection_info, boto3_conn, compare_policies
from ansible.module_utils.ec2 import AWSRetry

import json
import traceback

try:
    from botocore.exceptions import ClientError, BotoCoreError
except ImportError:
    pass  # caught by AnsibleAWSModule

def compare_assume_role_policy_doc(current_policy_doc, new_policy_doc):
    if not compare_policies(current_policy_doc, json.loads(new_policy_doc)):
        return True
    else:
        return False

def compare_attached_role_policies(current_attached_policies, new_attached_policies):

    # If new_attached_policies is None it means we want to remove all policies
    if len(current_attached_policies) > 0 and new_attached_policies is None:
        return False

    current_attached_policies_arn_list = []
    for policy in current_attached_policies:
        current_attached_policies_arn_list.append(policy['PolicyArn'])

    if set(current_attached_policies_arn_list) == set(new_attached_policies):
        return True
    else:
        return False

def convert_friendly_names_to_arns(connection, module, policy_names):
    if not any([not policy.startswith('arn:') for policy in policy_names]):
        return policy_names
    allpolicies = {}
    paginator = connection.get_paginator('list_policies')
    policies = paginator.paginate().build_full_result()['Policies']

    for policy in policies:
        allpolicies[policy['PolicyName']] = policy['Arn']
        allpolicies[policy['Arn']] = policy['Arn']
    try:
        return [allpolicies[policy] for policy in policy_names]
    except KeyError as e:
        module.fail_json(msg="Couldn't find policy: " + str(e))

def remove_policies(connection, module, policies_to_remove, params):
    for policy in policies_to_remove:
        try:
            if not module.check_mode:
                connection.detach_role_policy(RoleName=params['RoleName'], PolicyArn=policy)
        except ClientError as e:
            module.fail_json(msg="Unable to detach policy {0} from {1}: {2}".format(policy, params['RoleName'], to_native(e)),
                             exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
        except BotoCoreError as e:
            module.fail_json(msg="Unable to detach policy {0} from {1}: {2}".format(policy, params['RoleName'], to_native(e)),
                             exception=traceback.format_exc())
        return True

def create_or_update_role(connection, module):
    params = dict()
    params['Path'] = module.params.get('path')
    params['RoleName'] = module.params.get('name')
    params['AssumeRolePolicyDocument'] = module.params.get('assume_role_policy_document')
    if module.params.get('description') is not None:
        params['Description'] = module.params.get('description')
    if module.params.get('boundary') is not None:
        params['PermissionsBoundary'] = module.params.get('boundary')
    managed_policies = module.params.get('managed_policy')
    create_instance_profile = module.params.get('create_instance_profile')
    if managed_policies:
        managed_policies = convert_friendly_names_to_arns(connection, module, managed_policies)
    changed = False

    # Get role
    role = get_role(connection, module, params['RoleName'])

    # If role is None, create it
    if role is None:
        try:
            if not module.check_mode:
                role = connection.create_role(**params)
                # 'Description' is documented as key of the role returned by create_role
                # but appears to be an AWS bug (the value is not returned using the AWS CLI either).
                # Get the role after creating it.
                role = get_role_with_backoff(connection, module, params['RoleName'])
            else:
                role = {'MadeInCheckMode': True}
                role['AssumeRolePolicyDocument'] = json.loads(params['AssumeRolePolicyDocument'])
            changed = True
        except ClientError as e:
            module.fail_json(msg="Unable to create role: {0}".format(to_native(e)),
                             exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
        except BotoCoreError as e:
            module.fail_json(msg="Unable to create role: {0}".format(to_native(e)),
                             exception=traceback.format_exc())
    else:
        # Check Assumed Policy document
        if not compare_assume_role_policy_doc(role['AssumeRolePolicyDocument'], params['AssumeRolePolicyDocument']):
            try:
                if not module.check_mode:
                    connection.update_assume_role_policy(RoleName=params['RoleName'], PolicyDocument=json.dumps(json.loads(params['AssumeRolePolicyDocument'])))
                changed = True
            except ClientError as e:
                module.fail_json(msg="Unable to update assume role policy for role {0}: {1}".format(params['RoleName'], to_native(e)),
                                 exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
            except BotoCoreError as e:
                module.fail_json(msg="Unable to update assume role policy for role {0}: {1}".format(params['RoleName'], to_native(e)),
                                 exception=traceback.format_exc())

    if managed_policies is not None:
        # Get list of current attached managed policies
        current_attached_policies = get_attached_policy_list(connection, module, params['RoleName'])
        current_attached_policies_arn_list = [policy['PolicyArn'] for policy in current_attached_policies]

        # If a single empty list item then all managed policies to be removed
        if len(managed_policies) == 1 and not managed_policies[0] and module.params.get('purge_policies'):

            # Detach policies not present
            if remove_policies(connection, module, set(current_attached_policies_arn_list) - set(managed_policies), params):
                changed = True
        else:
            # Make a list of the ARNs from the attached policies

            # Detach roles not defined in task
            if module.params.get('purge_policies'):
                if remove_policies(connection, module, set(current_attached_policies_arn_list) - set(managed_policies), params):
                    changed = True

            # Attach roles not already attached
            for policy_arn in set(managed_policies) - set(current_attached_policies_arn_list):
                try:
                    if not module.check_mode:
                        connection.attach_role_policy(RoleName=params['RoleName'], PolicyArn=policy_arn)
                except ClientError as e:
                    module.fail_json(msg="Unable to attach policy {0} to role {1}: {2}".format(policy_arn, params['RoleName'], to_native(e)),
                                     exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
                except BotoCoreError as e:
                    module.fail_json(msg="Unable to attach policy {0} to role {1}: {2}".format(policy_arn, params['RoleName'], to_native(e)),
                                     exception=traceback.format_exc())
                changed = True

    # Instance profile
    if create_instance_profile and not role.get('MadeInCheckMode', False):
        try:
            instance_profiles = connection.list_instance_profiles_for_role(RoleName=params['RoleName'])['InstanceProfiles']
        except ClientError as e:
            module.fail_json(msg="Unable to list instance profiles for role {0}: {1}".format(params['RoleName'], to_native(e)),
                             exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
        except BotoCoreError as e:
            module.fail_json(msg="Unable to list instance profiles for role {0}: {1}".format(params['RoleName'], to_native(e)),
                             exception=traceback.format_exc())
        if not any(p['InstanceProfileName'] == params['RoleName'] for p in instance_profiles):
            # Make sure an instance profile is attached
            try:
                if not module.check_mode:
                    connection.create_instance_profile(InstanceProfileName=params['RoleName'], Path=params['Path'])
                changed = True
            except ClientError as e:
                # If the profile already exists, no problem, move on
                if e.response['Error']['Code'] == 'EntityAlreadyExists':
                    pass
                else:
                    module.fail_json(msg="Unable to create instance profile for role {0}: {1}".format(params['RoleName'], to_native(e)),
                                     exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
            except BotoCoreError as e:
                module.fail_json(msg="Unable to create instance profile for role {0}: {1}".format(params['RoleName'], to_native(e)),
                                 exception=traceback.format_exc())
            if not module.check_mode:
                connection.add_role_to_instance_profile(InstanceProfileName=params['RoleName'], RoleName=params['RoleName'])

    # Check Description update
    if not role.get('MadeInCheckMode') and params.get('Description') and role['Description'] != params['Description']:
        try:
            if not module.check_mode:
                connection.update_role_description(RoleName=params['RoleName'], Description=params['Description'])

            changed = True
        except (BotoCoreError, ClientError) as e:
            module.fail_json(msg="Unable to update description for role {0}: {1}".format(params['RoleName'], to_native(e)),
                             exception=traceback.format_exc())

    # Check if permission boundary needs update
    if not role.get('MadeInCheckMode') and (
            (role.get('PermissionsBoundary') or {}).get('PermissionsBoundaryArn') or
            params.get('PermissionsBoundary') is not None):
        # the existing role has a boundary
        if module.params.get('boundary') is None:
            pass
        elif module.params.get('boundary') == '':
            if (role.get('PermissionsBoundary') or {}).get('PermissionsBoundaryArn'):
                try:
                    if not module.check_mode:
                        connection.delete_role_permissions_boundary(RoleName=params['RoleName'])
                    changed = True
                except (BotoCoreError, ClientError) as e:
                    module.fail_json_aws(e, msg="Unable to remove permission boundary for role {0}: {1}".format(params['RoleName'], to_native(e)))
        elif (role.get('PermissionsBoundary') or {}).get('PermissionsBoundaryArn') != params['PermissionsBoundary']:
            try:
                if not module.check_mode:
                    connection.put_role_permissions_boundary(RoleName=params['RoleName'], PermissionsBoundary=params['PermissionsBoundary'])
                changed = True
            except (BotoCoreError, ClientError) as e:
                module.fail_json_aws(e, msg="Unable to update permission boundary for role {0}: {1}".format(params['RoleName'], to_native(e)))

    # Get the role again
    if not role.get('MadeInCheckMode', False):
        role = get_role(connection, module, params['RoleName'])
        role['attached_policies'] = get_attached_policy_list(connection, module, params['RoleName'])

    module.exit_json(changed=changed, iam_role=camel_dict_to_snake_dict(role), **camel_dict_to_snake_dict(role))

def destroy_role(connection, module):

    params = dict()
    params['RoleName'] = module.params.get('name')

    role = get_role(connection, module, params['RoleName'])

    if role:

        # We need to remove any instance profiles from the role before we delete it
        try:
            instance_profiles = connection.list_instance_profiles_for_role(RoleName=params['RoleName'])['InstanceProfiles']
        except ClientError as e:
            module.fail_json(msg="Unable to list instance profiles for role {0}: {1}".format(params['RoleName'], to_native(e)),
                             exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
        except BotoCoreError as e:
            module.fail_json(msg="Unable to list instance profiles for role {0}: {1}".format(params['RoleName'], to_native(e)),
                             exception=traceback.format_exc())

        if role.get('PermissionsBoundary') is not None:
            try:
                connection.delete_role_permissions_boundary(RoleName=params['RoleName'])
            except (ClientError, BotoCoreError) as e:
                module.fail_json_aws(e, msg="Could not delete role permission boundary on role {0}: {1}".format(params['RoleName'], e))

        # Now remove the role from the instance profile(s)
        for profile in instance_profiles:
            try:
                if not module.check_mode:
                    connection.remove_role_from_instance_profile(InstanceProfileName=profile['InstanceProfileName'], RoleName=params['RoleName'])
            except ClientError as e:
                module.fail_json(msg="Unable to remove role {0} from instance profile {1}: {2}".format(
                                 params['RoleName'], profile['InstanceProfileName'], to_native(e)),
                                 exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
            except BotoCoreError as e:
                module.fail_json(msg="Unable to remove role {0} from instance profile {1}: {2}".format(
                                 params['RoleName'], profile['InstanceProfileName'], to_native(e)),
                                 exception=traceback.format_exc())

        # Now remove any attached policies otherwise deletion fails
        try:
            for policy in get_attached_policy_list(connection, module, params['RoleName']):
                if not module.check_mode:
                    connection.detach_role_policy(RoleName=params['RoleName'], PolicyArn=policy['PolicyArn'])
        except ClientError as e:
            module.fail_json(msg="Unable to detach policy {0} from role {1}: {2}".format(policy['PolicyArn'], params['RoleName'], to_native(e)),
                             exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
        except BotoCoreError as e:
            module.fail_json(msg="Unable to detach policy {0} from role {1}: {2}".format(policy['PolicyArn'], params['RoleName'], to_native(e)),
                             exception=traceback.format_exc())

        try:
            if not module.check_mode:
                connection.delete_role(**params)
        except ClientError as e:
            module.fail_json(msg="Unable to delete role: {0}".format(to_native(e)),
                             exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
        except BotoCoreError as e:
            module.fail_json(msg="Unable to delete role: {0}".format(to_native(e)), exception=traceback.format_exc())
    else:
        module.exit_json(changed=False)

    module.exit_json(changed=True)

def get_role_with_backoff(connection, module, name):
    try:
        return AWSRetry.jittered_backoff(catch_extra_error_codes=['NoSuchEntity'])(connection.get_role)(RoleName=name)['Role']
    except (BotoCoreError, ClientError) as e:
        module.fail_json(msg="Unable to get role {0}: {1}".format(name, to_native(e)), exception=traceback.format_exc())

def get_role(connection, module, name):
    try:
        return connection.get_role(RoleName=name)['Role']
    except ClientError as e:
        if e.response['Error']['Code'] == 'NoSuchEntity':
            return None
        else:
            module.fail_json(msg="Unable to get role {0}: {1}".format(name, to_native(e)),
                             exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
    except BotoCoreError as e:
        module.fail_json(msg="Unable to get role {0}: {1}".format(name, to_native(e)), exception=traceback.format_exc())

def get_attached_policy_list(connection, module, name):

    try:
        return connection.list_attached_role_policies(RoleName=name)['AttachedPolicies']
    except ClientError as e:
        if e.response['Error']['Code'] == 'NoSuchEntity':
            return []
        else:
            module.fail_json(msg="Unable to list attached policies for role {0}: {1}".format(name, to_native(e)),
                             exception=traceback.format_exc(), **camel_dict_to_snake_dict(e.response))
    except BotoCoreError as e:
        module.fail_json(msg="Unable to list attached policies for role {0}: {1}".format(name, to_native(e)),
                         exception=traceback.format_exc())

def main():

    argument_spec = dict(
        name=dict(type='str', required=True),
        path=dict(type='str', default="/"),
        assume_role_policy_document=dict(type='json'),
        managed_policy=dict(type='list', aliases=['managed_policies']),
        state=dict(type='str', choices=['present', 'absent'], default='present'),
        description=dict(type='str'),
        boundary=dict(type='str', aliases=['boundary_policy_arn']),
        create_instance_profile=dict(type='bool', default=True),
        purge_policies=dict(type='bool', default=True),
    )
    module = AnsibleAWSModule(argument_spec=argument_spec,
                              required_if=[('state', 'present', ['assume_role_policy_document'])],
                              supports_check_mode=True)

    if module.params.get('boundary') and module.params.get('create_instance_profile'):
        module.fail_json(msg="When using a boundary policy, `create_instance_profile` must be set to `false`.")
    if module.params.get('boundary') is not None and not module.botocore_at_least('1.10.57'):
        module.fail_json(msg="When using a boundary policy, botocore must be at least v1.10.57. "
                         "Current versions: boto3-{boto3_version} botocore-{botocore_version}".format(**module._gather_versions()))

    connection = module.client('iam')

    state = module.params.get("state")

    if state == 'present':
        create_or_update_role(connection, module)
    else:
        destroy_role(connection, module)

if __name__ == '__main__':
    main()


text:
#pragma once
//------------------------------------------------------------------------------
/**
    @class Oryol::IOQueue
    @ingroup IO
    @brief simplify asynchronous loading of multiple files

    IOQueues are used to load one or more files asynchronously, and associate
    a success (and optional failure) callback with an IO request.

    See the IOQueue sample application to see how it works :)
*/
#include "Core/Types.h"
#include "Core/String/StringAtom.h"
#include "IO/IOProtocol.h"
#include "Core/Containers/Array.h"
#include <functional>

namespace Oryol {

class IOQueue {
public:
    /// constructor
    IOQueue();
    /// destructor
    ~IOQueue();

    /// callback function signature for success
    typedef std::function<void(const Ptr<Stream>&)> SuccessFunc;
    /// callback function signature for success when loading URL groups
    typedef std::function<void(const Array<Ptr<Stream>>&)> GroupSuccessFunc;
    /// callback function signature for failure
    typedef std::function<void(const URL& url, IOStatus::Code ioStatus)> FailFunc;

    /// start queue processing
    void Start();
    /// stop queue processing
    void Stop();
    /// return true if queue is in started state
    bool IsStarted() const;

    /// add a file load request to the queue
    void Add(const URL& url, SuccessFunc onSuccess, FailFunc onFail=FailFunc());
    /// add a file group request to the queue
    void AddGroup(const Array<URL>& urls, GroupSuccessFunc onSuccess, FailFunc onFail=FailFunc());
    /// return true if queue is empty
    bool Empty() const;

private:
    /// update the queue, called per frame from runloop
    void update();

    bool isStarted;
    int32 runLoopId;
    struct item {
        Ptr<IOProtocol::Request> ioRequest;
        SuccessFunc successFunc;
        FailFunc failFunc;
    };
    Array<item> items;
    struct groupItem {
        Array<Ptr<IOProtocol::Request>> ioRequests;
        GroupSuccessFunc successFunc;
        FailFunc failFunc;
    };
    Array<groupItem> groupItems;
};

} // namespace Oryol


text:
{% extends "blogs/blog.html" %}
{% load thumbnail i18n compress calculate_age %}
{% load i18n thumbnail punn_tags humanize %}
{% load url from future %}
{% load markup %}
{% load blog_tags %}

    {% block open-graphs %}
    <title>{% block title %}{{ blog.title }} - {{ tag.name }}{% endblock %}</title>

    <meta property="og:title" content="{{ blog.title }} - {{ tag.name }}" />
    <meta property="og:url" content="{% if blog.custom_domain %}http://{{ blog.custom_domain }}/cat/{{ tag.slug }}{% else %}http://{{ blog.slug }}.blobon.com/cat/{{ tag.slug }}{% endif %}" />
    <meta property="og:image" content="{{ MEDIA_URL }}{{ blog.main_image }}" />

    <meta name="twitter:card" content="photo">
    <meta name="twitter:url" content="{% if blog.custom_domain %}http://{{ blog.custom_domain }}/cat/{{ tag.slug }}{% else %}http://{{ blog.slug }}.blobon.com/cat/{{ tag.slug }}{% endif %}">
    <meta name="twitter:title" content="{{ blog.title }} - {{ category.name }}">
    <meta name="twitter:image" content="{{ MEDIA_URL }}{{ blog.main_image }}">

    <link rel="canonical" href="{% if blog.custom_domain %}http://{{ blog.custom_domain }}/cat/{{ tag.slug }}{% else %}http://{{ blog.slug }}.blobon.com/cat/{{ tag.slug }}{% endif %}" />
    {% endblock %}

    {% block breadcrumbs %}

      {{ posts|length }}
      {{ tag.name }}

    {% endblock %}


text:
Updated factis-hexastore. Now import and export functions are available with:

    var factis = new require('factis');
    var myExport = factis.hexastore.exportString();
    var copyOfFactis = new require('factis');
    factis.hexastore.importString(myExport);

# 1.0.3

Update Readme

# 1.0.2

Update Readme

# 1.0.1

Add throw errors when adding or removing wrong things to hexastore

# 1.0.0

Initial version