text:
Installation
============

PySAML2 uses `XML Security Library <http://www.aleksey.com/xmlsec/>`_ binary to sign SAML assertions, so you need to install
it either through your operating system package or by compiling the source code. It doesn't matter where the final executable is installed because
you will need to set the full path to it in the configuration stage. XmlSec is available (at least) for Debian, OSX and Alpine Linux.

Now you can install the djangosaml2idp package using pip. This will also install PySAML2 and its dependencies automatically::

    pip install djangosaml2idp

redpajama_set_name: RedPajamaGithub


text:
API Key

        Your API Key is a secret token you give to the Python API to enable access. If you change the key you will need to update your API configuration file.

        <md-button class="md-primary" ng-click="$ctrl.showAPIKey()">{{ $ctrl.showHideButtonText }}</md-button>
        <md-button class="md-warn" ng-click="$ctrl.resetAPIKey()">Reset API Key</md-button>
        {{ $ctrl.apikey }}


text:
@interface LinkDriverWindowController : NSWindowController {
	IBOutlet NSTextView	*linkifyView;
	IBOutlet NSButton	*linkifyButton;
	IBOutlet NSTextView	*otherView;
}

-(IBAction) linkifyTextView:(id)sender;
@end


text:
<?php

class Contactjournal extends AppModel
{
    public $name = 'Contactjournal';
    public $displayField = 'text';

    public $belongsTo = array(
        'Klant' => array(
            'className' => 'Klant',
            'foreignKey' => 'klant_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
        ),
        'Medewerker' => array(
            'className' => 'Medewerker',
            'foreignKey' => 'medewerker_id',
            'conditions' => '',
            'fields' => '',
            'order' => '',
        ),
    );

    public $validate = array(
        'datum' => array(
            'date' => array(
                'rule' => array('date'),
                'message' => 'Datum',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            'notempty' => array(
                'rule' => array('notempty'),
                'message' => 'Dit veld is verplicht',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
    );
}


text:
An Ansible role for Nginx as a reverse proxy.

## Role Variables

- `nginx_site_name` - Site name for the reverse proxy configuration
- `nginx_site_server_name` - Server name for the site configuration
- `nginx_site_proxy_pass_scheme` - Scheme for the `proxy_pass` setting
- `nginx_site_proxy_pass_host` Host for the `proxy_pass` setting
- `nginx_site_proxy_pass_port` Port for the `proxy_pass` setting

## Example Playbook

See the [examples](./examples/) directory.


text:
@interface Error_test : XCTestCase

@end

@implementation Error_test

- (void)testThen1 {
    id ex = [self expectationWithDescription:@""];

    PSPromiseWith(^{
        @throw NSErrorMake(nil, @"Error");
    }).then(^{
        XCTAssert(NO, @"这里不应该执行:%@", @"123");
    }).catch(^(NSError *error){
        XCTAssert([error.localizedDescription isEqualToString:@"Error"]);
    }).catch(^{
        XCTAssert(NO, @"这里不应该执行");
    }).always(^{
        [ex fulfill];
    });

    [self waitForExpectationsWithTimeout:TIME_OUT handler:nil];
}

- (void)testThen2{
    id ex = [self expectationWithDescription:@""];

    PSPromiseWith(^{
        return @"aaa";
    }).thenAsync(^{
        @throw NSErrorMake(nil, @"Error");
    }).then(^{
        XCTAssert(NO, @"这里不应该执行");
        return nil;
    }).catch(^(NSError *error) {
        XCTAssert([error.localizedDescription isEqualToString:@"Error"]);
    }).catch(^(NSError *error){
        XCTAssert(NO, @"这里不应该执行");
    }).always(^{
        [ex fulfill];
    });
    [self waitForExpectationsWithTimeout:TIME_OUT handler:nil];
}

- (void)testThen3{
    id ex = [self expectationWithDescription:@""];

    PSPromiseWith(^{
        return @"aaa";
    }).thenPromise(^(id result, PSResolve resolve){
        @throw NSErrorMake(nil, @"Error");
    }).then(^{
        XCTAssert(NO, @"这里不应该执行");
        return nil;
    }).catch(^(NSError *error) {
        XCTAssert([error.localizedDescription isEqualToString:@"Error"]);
    }).catch(^(NSError *error){
        XCTAssert(NO, @"这里不应该执行");
    }).always(^{
        [ex fulfill];
    });
    [self waitForExpectationsWithTimeout:TIME_OUT handler:nil];
}

- (void)testThen4{
    id ex = [self expectationWithDescription:@""];

    PSPromiseWith(^{
        return @"aaa";
    }).thenOn(dispatch_get_global_queue(0, 0), ^{
        @throw NSErrorMake(nil, @"Error");
    }).then(^{
        XCTAssert(NO, @"这里不应该执行");
        return nil;
    }).catch(^(NSError *error) {
        XCTAssert([error.localizedDescription isEqualToString:@"Error"]);
    }).catch(^(NSError *error){
        XCTAssert(NO, @"这里不应该执行");
    }).always(^{
        [ex fulfill];
    });
    [self waitForExpectationsWithTimeout:TIME_OUT handler:nil];
}

- (void)testCatch1{
    id ex = [self expectationWithDescription:@""];

    PSPromiseWith(^{
        @throw NSErrorMake(nil, @"abc");
    }).catch(^{
        @throw NSErrorMake(nil, @"Error");
    }).then(^{
        XCTAssert(NO, @"这里不应该执行");
        return nil;
    }).catch(^(NSError *error) {
        XCTAssert([error.localizedDescription isEqualToString:@"Error"]);
    }).catch(^(NSError *error){
        XCTAssert(NO, @"这里不应该执行");
    }).always(^{
        [ex fulfill];
    });
    [self waitForExpectationsWithTimeout:TIME_OUT handler:nil];
}

- (void)testCatch2{
    id ex = [self expectationWithDescription:@""];

    PSPromiseWith(^{
        @throw NSErrorMake(nil, @"abc");
    }).catchAsync(^{
        @throw NSErrorMake(nil, @"Error");
    }).then(^{
        XCTAssert(NO, @"这里不应该执行");
        return nil;
    }).catch(^(NSError *error) {
        XCTAssert([error.localizedDescription isEqualToString:@"Error"]);
    }).catch(^(NSError *error){
        XCTAssert(NO, @"这里不应该执行");
    }).always(^{
        [ex fulfill];
    });
    [self waitForExpectationsWithTimeout:TIME_OUT handler:nil];
}

- (void)testCatch3{
    id ex = [self expectationWithDescription:@""];

    PSPromiseWith(^{
        @throw NSErrorMake(nil, @"abc");
    }).catchOn(dispatch_get_global_queue(0, 0), ^{
        @throw NSErrorMake(nil, @"Error");
    }).then(^{
        XCTAssert(NO, @"这里不应该执行");
        return nil;
    }).catch(^(NSError *error) {
        XCTAssert([error.localizedDescription isEqualToString:@"Error"]);
    }).catch(^(NSError *error){
        XCTAssert(NO, @"这里不应该执行");
    }).always(^{
        [ex fulfill];
    });
    [self waitForExpectationsWithTimeout:TIME_OUT handler:nil];
}

- (void)testAlways{
    id ex = [self expectationWithDescription:@""];

    PSPromiseWith(^{
        @throw NSErrorMake(nil, @"abc");
    }).always(^{
        @throw NSErrorMake(nil, @"Error");
    }).then(^{
        XCTAssert(NO, @"这里不应该执行");
        return nil;
    }).catch(^(NSError *error) {
        XCTAssert([error.localizedDescription isEqualToString:@"Error"]);
    }).catch(^(NSError *error){
        XCTAssert(NO, @"这里不应该执行");
    }).always(^{
        [ex fulfill];
    });
    [self waitForExpectationsWithTimeout:TIME_OUT handler:nil];
}

@end


mraa

description: IO library that helps you use I2c, SPI, gpio, uart, pwm, analog inputs (aio) and more on a number of platforms such as the Intel galileo, the Intel edison and others

keywords: gpio edison galileo io mraajs spi i2c minnow intel

license: MIT


text:
# PostCSS Copy Assets [![Build Status][travis-img]][travis] [![Windows Build Status][appveyor-img]][appveyor]

[PostCSS] plugin to copy assets referenced by relative `url()`s into a build directory, while keeping their sub-directory hierarchy.

[PostCSS]: https://github.com/postcss/postcss
[travis-img]:  https://travis-ci.org/shutterstock/postcss-copy-assets.svg
[travis]:      https://travis-ci.org/shutterstock/postcss-copy-assets
[appveyor-img]:  https://ci.appveyor.com/api/projects/status/vmhvh3cwv0v0wcbg/branch/master?svg=true
[appveyor]:      https://ci.appveyor.com/project/alexmchardy/postcss-copy-assets-dgts6/branch/master

## Installation
```shell
$ npm install postcss-copy-assets
```

## Example
### Usage
```js
var copyAssets = require('postcss-copy-assets');
postcss(
    [
        copyAssets({ base: 'dist'})
    ],
    {
        to: 'dist/css/foo.css'
    }
);
```
### Input
```css
/* src/css/page/home.css */
.icon {
    background: url("../../images/icons/icon.jpg");
}
@font-face {
    src: url("../../fonts/sans.woff") format("woff"), url("../../fonts/sans.ttf") format("truetype");
}
```
```
src/
|-- css/
|   `-- page/
|       `-- home.css
|-- images/
|   `-- icons/
|       `-- icon.jpg
`-- fonts/
    |-- sans.woff
    `-- sans.ttf
```

### Output
```css
/* dist/css/home.min.css */
.icon {
    background: url("../images/icons/icon.jpg");
}
@font-face {
    src: url("../fonts/sans.woff") format("woff"), url("../fonts/sans.ttf") format("truetype");
}
```
```
dist/
|-- css/
|   `-- home.min.css
|-- images/
|   `-- icons/
|       `-- icon.jpg
`-- fonts/
    |-- sans.woff
    `-- sans.ttf
```

## Options

### Plugin options

#### `base`
Type: `string`
Default: PostCSS `to` option

Optional base path where the plugin will copy images, fonts, and other assets it finds in CSS `url()` declarations. Only `url()` declarations with relative paths are processed. Each asset's sub-directory hierarchy will be maintained under the base path. Basically, sub-directories after the last `../` in the path will be kept (or the whole path if no `../` exists). For example, if the plugin is called with `{ base: 'dist' }`, the image referred to by `url("../../images/icons/icon.jpg")` will be copied to `dist/images/icons/icon.jpg`.

By using a single `base` path, a build pipeline can output several built CSS files (each with its own PostCSS `to` destination) while organizing all their assets under one directory (e.g. under `dist/` in `dist/images/`, `dist/fonts/`, etc.).

If `base` is not specified assets will be copied by default to the base directory given to the PostCSS `to` option while still maintaining the assets' sub-directory hierarchy.  For example, if PostCSS is told to ouput to `dist/css/foo.css` and `base` is not specified the image referred to by `url("../../images/icons/icon.jpg")` will be copied to `dist/css/images/icons/icon.jpg`.

#### `pathTransform`
Type: `function`
Default: `undefined`

Optional function that returns a transformed absolute filesystem path to an asset file. Useful for adding revision hashes to filenames for cachebusting (e.g. `image-a7f234e8d4.jpg`), or handling special cases. The function is expected to be of the form given below:
```js
/**
 * Transforms the paths to which asset files will be copied
 *
 * @param {string} newPath - Absolute filesystem path to which asset would be copied by default
 * @param {string} origPath - Absolute filesystem path to original asset file
 * @param {object} contents - Buffer containing asset file contents
 * @returns {string} - Transformed absolute filesystem path to which asset will be copied
 */
pathTransform: function(newPath, origPath, contents) {
    // ... transform newPath ...
    return newPath;
}
```

### PostCSS options

#### `to`
This plugin requires the `to` option to be passed to `postcss` itself. This specifies where the transformed CSS will be written to.

```js
var copyAssets = require('postcss-copy-assets');
postcss(
    [
        copyAssets({ base: 'base/dir/to/copy/assets'})
    ],
    {
        to: 'path/to/transformed/file.css'
    }
);
```

See [PostCSS] docs for examples for your environment.

## License

[MIT](LICENSE) © 2015 Alex McHardy <amchardy@shutterstock.com>


text:
/**
 * User: katat
 * Date: 8/29/13
 * Time: 11:56 AM
 */
define(['views/base/append', 'views/menu.modal', 'jquery', 'handlebars', 'text!templates/menu.html', 'bootstrap'],
    function(AppendView, MenuModalView, $, Handlebars, tpl){
    var MenuView = AppendView.extend({
        template: Handlebars.compile(tpl),
        tagName: 'li',
        events: {
            'click a': 'showModal'
        },
        onRender: function(){
            var that = this;
            this.$el.html(this.template(this.model.toJSON()));
            this.linkElm = this.$el.find('a.menu');
            this.modalPlaceholder = this.$el.find('.modal-placeholder');
            this.model.bind('change', function(){
                that.linkElm.text(that.model.get('name'));
                that.linkElm.attr('href', that.model.get('link'));
            });
            this.model.bind('destroy', function(){
                that.remove();
            });
            this.addPartialInnerView(new MenuModalView({model:this.model}), this.modalPlaceholder);
        },
        onRendered: function(){
//            this.$el.find('#menu-modal').modal('show');
        },
        enableEdit: function(){
            var that = this;
            this.toShowModal = true;
//            this.$el.find('a.menu').hallo({
//                plugins: {
//                    'hallolink' : {}
//                },
//                toolbar: 'halloToolbarInstant',
//                editable: true
//            })
//            this.$el.find('a.menu').click(function(e){
//                require(['views/menu.modal'], function(MenuModalView){
//                    var menuView = new MenuModalView({model:that.model});
//                    that.addPartialInnerView(menuView, $(e.target).parent().find('.modal-placeholder'));
//                })
//                e.stopPropagation();
//                e.preventDefault();
//                return false;
//            });
//            this.$el.find('ul.menus li').each(function(index, elm){
//                var removeMenu = $(elm).find('a.remove-menu');
//                removeMenu.show();
//                $(removeMenu).click(function(){
//                    $(elm).remove();
//                })
//            });
            this.$el.addClass('enable-edit');
            AppendView.prototype.enableEdit.apply(this, arguments);
        },
        disableEdit: function(){
            this.toShowModal = false;
            this.$el.removeClass('enable-edit');
            AppendView.prototype.disableEdit.apply(this, arguments);
        },
        showModal: function(e){
            if(!this.toShowModal)
                return;
            this.getInnerView(this.modalPlaceholder).showModal();
            e.preventDefault();
            return false;
        }
    })

    return MenuView;
})


text:
<?php

namespace Xabbuh\BRP\Configuration\Writer;

use Symfony\Component\Console\Output\OutputInterface;
use Xabbuh\BRP\Configuration\ConfigurationInterface;
use Xabbuh\BRP\Configuration\Format\FormatInterface;

/**
 * Write a configuration to a given output stream.
 *
 * @author Christian Flothmann <christian.flothmann@xabbuh.de>
 */
class ConsoleWriter extends AbstractWriter
{
    /**
     * @var OutputInterface
     */
    private $output;

    public function __construct(FormatInterface $format, OutputInterface $output)
    {
        parent::__construct($format);

        $this->output = $output;
    }

    /**
     * {@inheritDoc}
     */
    protected function doFormattedWrite($formattedConfiguration)
    {
        $this->output->writeln($formattedConfiguration);
    }
}


text:
"use strict";

var _prototypeProperties = function (child, staticProps, instanceProps) {
  if (staticProps) Object.defineProperties(child, staticProps);
  if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
};

var _get = function get(object, property, receiver) {
  var desc = Object.getOwnPropertyDescriptor(object, property);

  if (desc === undefined) {
    var parent = Object.getPrototypeOf(object);

    if (parent === null) {
      return undefined;
    } else {
      return get(parent, property, receiver);
    }
  } else if ("value" in desc && desc.writable) {
    return desc.value;
  } else {
    var getter = desc.get;
    if (getter === undefined) {
      return undefined;
    }
    return getter.call(receiver);
  }
};

var _inherits = function (subClass, superClass) {
  if (typeof superClass !== "function" && superClass !== null) {
    throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
  }
  subClass.prototype = Object.create(superClass && superClass.prototype, {
    constructor: {
      value: subClass,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
  if (superClass) subClass.__proto__ = superClass;
};

var Node = require("./node");
var vendor = require("./vendor");

// CSS declaration like "color: black" in rules
var Declaration = (function (Node) {
  function Declaration(defaults) {
    this.type = "decl";
    _get(Object.getPrototypeOf(Declaration.prototype), "constructor", this).call(this, defaults);
  }

  _inherits(Declaration, Node);

  _prototypeProperties(Declaration, null, {
    stringify: {

      // Stringify declaration
      value: function stringify(builder, semicolon) {
        var before = this.style("before");
        if (before) builder(before);

        var between = this.style("between", "colon");
        var string = this.prop + between + this.stringifyRaw("value");

        if (this.important) {
          string += this._important || " !important";
        }

        if (semicolon) string += ";";
        builder(string, this);
      },
      writable: true,
      enumerable: true,
      configurable: true
    }
  });

  return Declaration;
})(Node);

module.exports = Declaration;


text:
.class Landroid/support/v4/view/accessibility/b;
.super Ljava/lang/Object;

# interfaces
.implements Landroid/support/v4/view/accessibility/c;

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public a(Landroid/view/accessibility/AccessibilityEvent;)I
    .locals 1

    const/4 v0, 0x0

    return v0
.end method

.method public a(Landroid/view/accessibility/AccessibilityEvent;I)Ljava/lang/Object;
    .locals 1

    const/4 v0, 0x0

    return-object v0
.end method

.method public a(Landroid/view/accessibility/AccessibilityEvent;Ljava/lang/Object;)V
    .locals 0

    return-void
.end method


text:
@interface ZQLShaderCompiler : NSObject

- (instancetype)initWithVertexShader:(NSString *)vertexShader fragmentShader:(NSString *)fragmentShader;

- (void)prepareToDraw;

- (GLuint)uniformIndex:(NSString *)uniformName;

- (GLuint)attributeIndex:(NSString *)attributeName;

@end


text:
using namespace cetty::shiro::session;
using namespace cetty::shiro::authc;
using namespace cetty::shiro::authz;
using namespace cetty::shiro::util;
using namespace cetty::shiro::crypt;
using namespace cetty::shiro::realm;
using namespace cetty::shiro;
using namespace cetty::config;
using namespace cetty::util;
using namespace testing;
using namespace std;

using namespace cetty::redis;
using namespace cetty::redis::builder;

void LoadConfigTest(){
    bool ret = ConfigCenter::instance().loadFromFile("shiro.conf");
    assert(ret);
    std::cout << "///////LoadConfigTest OK///////" << std::endl;
}

TEST(SessionTest, NewSession){
    SessionPtr session = new Session();
    session->setId("001");
    session->setHost("localhost");
    session->setAttribute("key1", "value1");
    session->setAttribute("now", "1137");
    session->setAttribute("", "");
    session->setAttribute("", "nullkey");
    session->setAttribute("nullvale", "");

    std::string sjson;
    session->toJson(&sjson);

    SessionPtr session2 = new Session();
    session2->fromJson(sjson.c_str());
    std::string sjson2;
    session2->toJson(&sjson2);
    EXPECT_STREQ(sjson.c_str(), sjson2.c_str());

    EXPECT_STREQ("value1", session2->getAttribute("key1").c_str());
    EXPECT_STREQ("1137", session2->getAttribute("now").c_str());
}

////////////////////////////////////////////////////////////////////////////////////////////
void createSessionCb(int ret, SessionPtr session){
    EXPECT_EQ(0, ret);
    EXPECT_STREQ("value1", session->getAttribute("key1").c_str());
    EXPECT_STREQ("123", session->getAttribute("key2").c_str());
}

void getSessionCb(int ret, SessionPtr session){
    EXPECT_EQ(0, ret);
    EXPECT_STREQ("value1", session->getAttribute("key1").c_str());
    EXPECT_STREQ("1234", session->getAttribute("key2").c_str());
}

// todo dao.readSession() looks like having problem
TEST(SessionTest, RedisSessionDAO){
    RedisSessionDAO dao;
    SessionPtr session = new Session();
    session->setAttribute("key1", "value1");
    session->setAttribute("key2", "123");
    dao.create(session, boost::bind(createSessionCb, _1, _2));
    dao.readSession(session->getId(), boost::bind(getSessionCb, _1, _2));
}
////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void logout(const std::string &sessionId){
    SecurityManager::instance().logout(sessionId);
}

void SMGetSession(const SessionPtr &session){
    assert(session);
    session->setAttribute("name2", "chenhl");
    session->setAttribute("num2", "2");
    std::cout << session->getAttribute("name") << std::endl;
    std::cout << session->getAttribute("num") << std::endl;
    session->removeAttribute("name");
    session->removeAttribute("num");
    sleep(200);
    logout(const_cast<std::string &>(session->getId()));
}

void SMStartSession(const SessionPtr &session){
    session->setAttribute("sm1", "test1");
    session->setAttribute("sm2", "test2");
    SecurityManager::instance().getSessionManager()->getSession(session->getId(), boost::bind(SMGetSession, _1));
}

void SecurityManagerTest(){
    std::cout << "\n//////////SecurityManagerTest Begin////////////////" << std::endl;
    SecurityManager::instance().getSessionManager()->start("localhost", boost::bind(SMStartSession, _1));

    std::cout << "//////////SecurityManagerTest End////////////////" << std::endl;
}

////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void getSession(int ret, const StringPiece &str){
    assert(ret == 0);
    assert(std::string("zhang").compare(str.c_str()));
    std::cout << "//////////RedisGetTest OK////////////////" << std::endl;
}
// todo redis->get() looks like having problem
void RedisTest(){
    std::cout << "\n//////////RedisGetTest Begin////////////////" << std::endl;
    RedisClientBuilder builder;
    builder.addConnection("127.0.0.1", 6379);
    RedisClient *redis = new RedisClient(builder.build());
    redis->get("name", boost::bind(getSession, _1, _2));
    std::cout << "//////////RedisGetTest End////////////////" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void WSSETest(){
    std::cout << "\n//////////WSSETest Begin////////////////" << std::endl;
    std::string host = "127.0.0.1";
    std::string principal = "chenhl";
    std::string nonce;
    std::string created;
    WSSE::instance().generatorSecret(principal, host, &nonce, &created);

    bool ret = WSSE::instance().verifySecret(host, principal, nonce, created);
    assert(ret);
    std::cout << "//////////RedisGetTest OK////////////////" << std::endl;
    std::cout << "//////////RedisGetTest End////////////////" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void cryptTest(std::string username, std::string origin, int n){
    std::cout << "\n//////////WSSETest Begin////////////////" << std::endl;
    std::string addUsersInfo =
        "INSERT INTO users(username, password) "
        "VALUES (?, ?)";

    SHA1Engine sh1;
    sh1.reset();
    sh1.update(origin);
    DigestEngine::Digest digest = sh1.digest();

    int iterations = n - 1; //already hashed once above
    //iterate remaining number:
    for (int i = 0; i < iterations; i++) {
        sh1.reset();
        sh1.update((const void*)digest.data(), (int)digest.size());
        digest = sh1.digest();
    }

    std::string msg16 = DigestEngine::digestToHex(digest);
    std::cout << msg16 << std::endl;
    std::string oridg;
    DigestEngine::digestFromHex(msg16, &oridg);
    std::cout << oridg << std::endl;

    soci::session sql;

    try {
        sql.open("sqlite3", "/home/chenhl/dev/db/data/sqlite/test");
        sql << addUsersInfo,
               soci::use(username),
               soci::use(msg16);
            //sql.commit();
    } catch (soci::soci_error const& e) {
        LOG_ERROR << e.what();
        //sql.rollback();
    }
    std::cout << "//////////cryptTest End////////////////" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void authcCB(const AuthenticationInfoPtr& info){
    assert(info);
    std::cout << info->getPrincipals().getPrimaryPrincipal() << std::endl;
    std::cout << info->getCredentials() << std::endl;
}

void authzCB(const AuthorizationInfoPtr & info){
    assert(info);
    std::vector<std::string> roles = info->getRoles();
    int i = 0;
    for(i = 0; i < roles.size(); ++i)
        std::cout << roles.at(i) << std::endl;
    std::vector<std::string> stringPermissions = info->getStringPermissions();
    for(i = 0; i < stringPermissions.size(); ++i)
        std::cout << stringPermissions.at(i) << std::endl;
}

void sqlRealmTest(){
    std::cout << "\n//////////sqlRealmTest Begin////////////////" << std::endl;
    SqlRealm realm;
    AuthenticationToken token("chenhl", "123456");

    //realm.doGetAuthenticationInfo(token, boost::bind(authcCB, _1));
    realm.doGetAuthorizationInfo( PrincipalCollection(token.getPrincipal(), realm.getName()), boost::bind(authzCB, _1));

    std::cout << "//////////sqlRealmTest End////////////////" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void generatorUserToken(std::string &principal, std::string &passwd, AuthenticationToken * token){
    assert(token != NULL);
    std::string host = "127.0.0.1";
    std::string nonce;
    std::string created;
    WSSE::instance().generatorSecret(principal, host, &nonce, &created);

    SHA1Engine sh1;
    sh1.reset();
    sh1.update(passwd);
    DigestEngine::Digest digest = sh1.digest();
    std::string cryptpd1(digest.begin(), digest.end());
    cryptpd1.append(nonce);
    cryptpd1.append(created);
    sh1.reset();
    sh1.update(cryptpd1);
    digest = sh1.digest();
    std::string cryptpd2 = DigestEngine::digestToHex(digest);

    bool ret = WSSE::instance().verifySecret(host, principal, nonce, created);
    token->setPrincipal(principal);
    token->setCredentials(cryptpd2);
    token->setHost(host);

    std::string salt;
    salt.append(nonce);
    salt.append(created);
    token->setSalt(salt);
}

void credentialMatcher(AuthenticationToken &token, const AuthenticationInfoPtr& info){
    HashedCredentialsMatcher matcher;
    assert(matcher.match(token, *info));
    std::cout << "//////////HashedCredentialsMatcherTest OK////////////////" << std::endl;
}

void HashedCredentialsMatcherTest(std::string &principal, std::string &passwd){
    std::cout << "\n//////////HashedCredentialsMatcherTest Begin////////////////" << std::endl;

    AuthenticationToken token;
    generatorUserToken(principal, passwd, &token);

    SqlRealm realm;
    realm.doGetAuthenticationInfo(token, boost::bind(credentialMatcher, token, _1));
    std::cout << "//////////HashedCredentialsMatcherTest End////////////////" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void AuthenticatorCB(const AuthenticationInfoPtr& info){
    std::cout << "Authenticator OK" << std::endl;
}

void AuthenticatorTest(std::string principal, std::string passwd){
    std::cout << "\n//////////AuthenticatorTest Begin////////////////" << std::endl;
    AuthenticationToken token;
    generatorUserToken(principal, passwd, &token);

    Authenticator ator;
    ator.authenticate(token, boost::bind(AuthenticatorCB, _1));

    std::cout << "//////////AuthenticatorTest End////////////////" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void loginCB(int ret,const AuthenticationToken& token, const AuthenticationInfoPtr& info, const SessionPtr& session){
    assert(ret == 0);
    std::cout << "login OK" << std::endl;
    session->setAttribute("name", "chenhl");
    session->setAttribute("num", "1");
    sleep(15);
    logout(session->getId());

    SecurityManager::instance().getSessionManager()->getSession(session->getId(), boost::bind(SMGetSession, _1));
}

void LoginTest(std::string &principal, std::string &passwd){
    std::cout << "\n//////////LoginTest Begin////////////////" << std::endl;
    AuthenticationToken token;
    generatorUserToken(principal, passwd, &token);
    SecurityManager::instance().login(token, boost::bind(loginCB, _1, _2, _3, _4));
    std::cout << "//////////LoginTest End////////////////" << std::endl;
}
////////////////////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////////////////////
void authzCB2(bool ret, const std::string &principal, const std::string &permission){
    if(ret) std::cout << "Pass authorization: ";
    else std::cout << "Not pass authorization: ";
    std::cout << principal << "<---->" << permission << std::endl;
}

void AuthzTest(const std::string &principal, const std::string &permission){
    //PrincipalCollection pc(principal, "sqlRealm");
    SecurityManager::instance().isPermitted(principal, permission, boost::bind(authzCB2, _1, _2, _3));
}
////////////////////////////////////////////////////////////////////////////////////////////

int main(int argc, char **argv){
    LoadConfigTest();
    //SecurityManagerTest();
    //RedisTest();
    //WSSETest();
    //cryptTest("chenhl", "123456", 1);
    //sqlRealmTest();
    //std::string principal("chenhl");
    //std::string passwd("123456");
    //HashedCredentialsMatcherTest(principal, passwd);
    //AuthenticatorTest(principal, passwd);
    //LoginTest(principal, passwd);
    AuthzTest("zhang", "A:B:C");

    int a;
    cin >> a;

    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}


text:
from sqlalchemy.testing import eq_, assert_raises, assert_raises_message
import time
from sqlalchemy import select, MetaData, Integer, String, create_engine, pool
from sqlalchemy.testing.schema import Table, Column
import sqlalchemy as tsa
from sqlalchemy import testing
from sqlalchemy.testing import engines
from sqlalchemy.testing.util import gc_collect
from sqlalchemy import exc, util
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.engines import testing_engine
from sqlalchemy.testing import is_not_
from sqlalchemy.testing.mock import Mock, call

class MockError(Exception):
    pass

class MockDisconnect(MockError):
    pass

def mock_connection():
    def mock_cursor():
        def execute(*args, **kwargs):
            if conn.explode == 'execute':
                raise MockDisconnect("Lost the DB connection on execute")
            elif conn.explode in ('execute_no_disconnect', ):
                raise MockError(
                    "something broke on execute but we didn't lose the connection")
            elif conn.explode in ('rollback', 'rollback_no_disconnect'):
                raise MockError(
                    "something broke on execute but we didn't lose the connection")
            elif args and "SELECT" in args[0]:
                cursor.description = [('foo', None, None, None, None, None)]
            else:
                return

        def close():
            cursor.fetchall = cursor.fetchone = \
                Mock(side_effect=MockError("cursor closed"))
        cursor = Mock(
                    execute=Mock(side_effect=execute),
                    close=Mock(side_effect=close)
                )
        return cursor

    def cursor():
        while True:
            yield mock_cursor()

    def rollback():
        if conn.explode == 'rollback':
            raise MockDisconnect("Lost the DB connection on rollback")
        if conn.explode == 'rollback_no_disconnect':
            raise MockError(
                "something broke on rollback but we didn't lose the connection")
        else:
            return

    conn = Mock(
                rollback=Mock(side_effect=rollback),
                cursor=Mock(side_effect=cursor())
            )
    return conn

def MockDBAPI():
    connections = []
    def connect():
        while True:
            conn = mock_connection()
            connections.append(conn)
            yield conn

    def shutdown(explode='execute'):
        for c in connections:
            c.explode = explode

    def dispose():
        for c in connections:
            c.explode = None
        connections[:] = []

    return Mock(
                connect=Mock(side_effect=connect()),
                shutdown=Mock(side_effect=shutdown),
                dispose=Mock(side_effect=dispose),
                paramstyle='named',
                connections=connections,
                Error=MockError
            )

class MockReconnectTest(fixtures.TestBase):
    def setup(self):
        self.dbapi = MockDBAPI()

        self.db = testing_engine(
                    'postgresql://foo:bar@localhost/test',
                    options=dict(module=self.dbapi, _initialize=False))

        self.mock_connect = call(host='localhost', password='bar',
                                user='foo', database='test')
        # monkeypatch disconnect checker
        self.db.dialect.is_disconnect = lambda e, conn, cursor: isinstance(e, MockDisconnect)

    def teardown(self):
        self.dbapi.dispose()

    def test_reconnect(self):
        """test that an 'is_disconnect' condition will invalidate the
        connection, and additionally dispose the previous connection
        pool and recreate."""

        db_pool = self.db.pool

        # make a connection

        conn = self.db.connect()

        # connection works

        conn.execute(select([1]))

        # create a second connection within the pool, which we'll ensure
        # also goes away

        conn2 = self.db.connect()
        conn2.close()

        # two connections opened total now

        assert len(self.dbapi.connections) == 2

        # set it to fail

        self.dbapi.shutdown()
        assert_raises(
            tsa.exc.DBAPIError,
            conn.execute, select([1])
        )

        # assert was invalidated

        assert not conn.closed
        assert conn.invalidated

        # close shouldnt break

        conn.close()
        is_not_(self.db.pool, db_pool)

        # ensure all connections closed (pool was recycled)

        eq_(
            [c.close.mock_calls for c in self.dbapi.connections],
            [[call()], [call()]]
        )

        conn = self.db.connect()
        conn.execute(select([1]))
        conn.close()

        eq_(
            [c.close.mock_calls for c in self.dbapi.connections],
            [[call()], [call()], []]
        )

    def test_invalidate_trans(self):
        conn = self.db.connect()
        trans = conn.begin()
        self.dbapi.shutdown()

        assert_raises(
            tsa.exc.DBAPIError,
            conn.execute, select([1])
        )

        eq_(
            [c.close.mock_calls for c in self.dbapi.connections],
            [[call()]]
        )
        assert not conn.closed
        assert conn.invalidated
        assert trans.is_active
        assert_raises_message(
            tsa.exc.StatementError,
            "Can't reconnect until invalid transaction is rolled back",
            conn.execute, select([1])
        )
        assert trans.is_active

        assert_raises_message(
            tsa.exc.InvalidRequestError,
            "Can't reconnect until invalid transaction is "
                "rolled back",
            trans.commit
        )

        assert trans.is_active
        trans.rollback()
        assert not trans.is_active
        conn.execute(select([1]))
        assert not conn.invalidated
        eq_(
            [c.close.mock_calls for c in self.dbapi.connections],
            [[call()], []]
        )

    def test_conn_reusable(self):
        conn = self.db.connect()

        conn.execute(select([1]))

        eq_(
            self.dbapi.connect.mock_calls,
            [self.mock_connect]
        )

        self.dbapi.shutdown()

        assert_raises(
            tsa.exc.DBAPIError,
            conn.execute, select([1])
        )

        assert not conn.closed
        assert conn.invalidated

        eq_(
            [c.close.mock_calls for c in self.dbapi.connections],
            [[call()]]
        )

        # test reconnects
        conn.execute(select([1]))
        assert not conn.invalidated

        eq_(
            [c.close.mock_calls for c in self.dbapi.connections],
            [[call()], []]
        )

    def test_invalidated_close(self):
        conn = self.db.connect()

        self.dbapi.shutdown()

        assert_raises(
            tsa.exc.DBAPIError,
            conn.execute, select([1])
        )

        conn.close()
        assert conn.closed
        assert conn.invalidated
        assert_raises_message(
            tsa.exc.StatementError,
            "This Connection is closed",
            conn.execute, select([1])
        )

    def test_noreconnect_execute_plus_closewresult(self):
        conn = self.db.connect(close_with_result=True)

        self.dbapi.shutdown("execute_no_disconnect")

        # raises error
        assert_raises_message(
            tsa.exc.DBAPIError,
            "something broke on execute but we didn't lose the connection",
            conn.execute, select([1])
        )

        assert conn.closed
        assert not conn.invalidated

    def test_noreconnect_rollback_plus_closewresult(self):
        conn = self.db.connect(close_with_result=True)

        self.dbapi.shutdown("rollback_no_disconnect")

        # raises error
        assert_raises_message(
            tsa.exc.DBAPIError,
            "something broke on rollback but we didn't lose the connection",
            conn.execute, select([1])
        )

        assert conn.closed
        assert not conn.invalidated

        assert_raises_message(
            tsa.exc.StatementError,
            "This Connection is closed",
            conn.execute, select([1])
        )

    def test_reconnect_on_reentrant(self):
        conn = self.db.connect()

        conn.execute(select([1]))

        assert len(self.dbapi.connections) == 1

        self.dbapi.shutdown("rollback")

        # raises error
        assert_raises_message(
            tsa.exc.DBAPIError,
            "Lost the DB connection on rollback",
            conn.execute, select([1])
        )

        assert not conn.closed
        assert conn.invalidated

    def test_reconnect_on_reentrant_plus_closewresult(self):
        conn = self.db.connect(close_with_result=True)

        self.dbapi.shutdown("rollback")

        # raises error
        assert_raises_message(
            tsa.exc.DBAPIError,
            "Lost the DB connection on rollback",
            conn.execute, select([1])
        )

        assert conn.closed
        assert conn.invalidated

        assert_raises_message(
            tsa.exc.StatementError,
            "This Connection is closed",
            conn.execute, select([1])
        )

    def test_check_disconnect_no_cursor(self):
        conn = self.db.connect()
        result = conn.execute(select([1]))
        result.cursor.close()
        conn.close()

        assert_raises_message(
            tsa.exc.DBAPIError,
            "cursor closed",
            list, result
        )

    def test_dialect_initialize_once(self):
        from sqlalchemy.engine.base import Engine
        from sqlalchemy.engine.url import URL
        from sqlalchemy.engine.default import DefaultDialect
        from sqlalchemy.pool import QueuePool
        dbapi = self.dbapi

        mock_dialect = Mock()
        class MyURL(URL):
            def get_dialect(self):
                return Dialect
        class Dialect(DefaultDialect):
            initialize = Mock()

        engine = create_engine(MyURL("foo://"), module=dbapi)
        c1 = engine.connect()
        engine.dispose()
        c2 = engine.connect()
        eq_(Dialect.initialize.call_count, 1)

class CursorErrTest(fixtures.TestBase):

    def setup(self):
        def MockDBAPI():
            def cursor():
                while True:
                    yield Mock(
                        description=[],
                        close=Mock(side_effect=Exception("explode")))
            def connect():
                while True:
                    yield Mock(cursor=Mock(side_effect=cursor()))

            return Mock(connect=Mock(side_effect=connect()))

        dbapi = MockDBAPI()
        self.db = testing_engine(
                    'postgresql://foo:bar@localhost/test',
                    options=dict(module=dbapi, _initialize=False))

    def test_cursor_explode(self):
        conn = self.db.connect()
        result = conn.execute("select foo")
        result.close()
        conn.close()

    def teardown(self):
        self.db.dispose()

def _assert_invalidated(fn, *args):
    try:
        fn(*args)
        assert False
    except tsa.exc.DBAPIError as e:
        if not e.connection_invalidated:
            raise

class RealReconnectTest(fixtures.TestBase):
    def setup(self):
        self.engine = engines.reconnecting_engine()

    def teardown(self):
        self.engine.dispose()

    @testing.fails_on('+informixdb',
                      "Wrong error thrown, fix in informixdb?")
    def test_reconnect(self):
        conn = self.engine.connect()

        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.closed

        self.engine.test_shutdown()

        _assert_invalidated(conn.execute, select([1]))

        assert not conn.closed
        assert conn.invalidated

        assert conn.invalidated
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.invalidated

        # one more time
        self.engine.test_shutdown()
        _assert_invalidated(conn.execute, select([1]))

        assert conn.invalidated
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.invalidated

        conn.close()

    def test_multiple_invalidate(self):
        c1 = self.engine.connect()
        c2 = self.engine.connect()

        eq_(c1.execute(select([1])).scalar(), 1)

        p1 = self.engine.pool
        self.engine.test_shutdown()

        _assert_invalidated(c1.execute, select([1]))

        p2 = self.engine.pool

        _assert_invalidated(c2.execute, select([1]))

        # pool isn't replaced
        assert self.engine.pool is p2

    def test_ensure_is_disconnect_gets_connection(self):
        def is_disconnect(e, conn, cursor):
            # connection is still present
            assert conn.connection is not None
            # the error usually occurs on connection.cursor(),
            # though MySQLdb we get a non-working cursor.
            # assert cursor is None

        self.engine.dialect.is_disconnect = is_disconnect
        conn = self.engine.connect()
        self.engine.test_shutdown()
        assert_raises(
            tsa.exc.DBAPIError,
            conn.execute, select([1])
        )

    def test_rollback_on_invalid_plain(self):
        conn = self.engine.connect()
        trans = conn.begin()
        conn.invalidate()
        trans.rollback()

    @testing.requires.two_phase_transactions
    def test_rollback_on_invalid_twophase(self):
        conn = self.engine.connect()
        trans = conn.begin_twophase()
        conn.invalidate()
        trans.rollback()

    @testing.requires.savepoints
    def test_rollback_on_invalid_savepoint(self):
        conn = self.engine.connect()
        trans = conn.begin()
        trans2 = conn.begin_nested()
        conn.invalidate()
        trans2.rollback()

    def test_invalidate_twice(self):
        conn = self.engine.connect()
        conn.invalidate()
        conn.invalidate()

    @testing.skip_if(
        [lambda: util.py3k, "oracle+cx_oracle"],
        "Crashes on py3k+cx_oracle")
    def test_explode_in_initializer(self):
        engine = engines.testing_engine()
        def broken_initialize(connection):
            connection.execute("select fake_stuff from _fake_table")

        engine.dialect.initialize = broken_initialize

        # raises a DBAPIError, not an AttributeError
        assert_raises(exc.DBAPIError, engine.connect)

    @testing.skip_if(
        [lambda: util.py3k, "oracle+cx_oracle"],
        "Crashes on py3k+cx_oracle")
    def test_explode_in_initializer_disconnect(self):
        engine = engines.testing_engine()
        def broken_initialize(connection):
            connection.execute("select fake_stuff from _fake_table")

        engine.dialect.initialize = broken_initialize

        p1 = engine.pool

        def is_disconnect(e, conn, cursor):
            return True

        engine.dialect.is_disconnect = is_disconnect

        # invalidate() also doesn't screw up
        assert_raises(exc.DBAPIError, engine.connect)

        # pool was recreated
        assert engine.pool is not p1

    @testing.fails_on('+informixdb',
                      "Wrong error thrown, fix in informixdb?")
    def test_null_pool(self):
        engine = \
            engines.reconnecting_engine(options=dict(poolclass=pool.NullPool))
        conn = engine.connect()
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.closed
        engine.test_shutdown()
        _assert_invalidated(conn.execute, select([1]))
        assert not conn.closed
        assert conn.invalidated
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.invalidated

    @testing.fails_on('+informixdb',
                      "Wrong error thrown, fix in informixdb?")
    def test_close(self):
        conn = self.engine.connect()
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.closed

        self.engine.test_shutdown()

        _assert_invalidated(conn.execute, select([1]))

        conn.close()
        conn = self.engine.connect()
        eq_(conn.execute(select([1])).scalar(), 1)

    @testing.fails_on('+informixdb',
                      "Wrong error thrown, fix in informixdb?")
    def test_with_transaction(self):
        conn = self.engine.connect()
        trans = conn.begin()
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.closed
        self.engine.test_shutdown()
        _assert_invalidated(conn.execute, select([1]))
        assert not conn.closed
        assert conn.invalidated
        assert trans.is_active
        assert_raises_message(
            tsa.exc.StatementError,
            "Can't reconnect until invalid transaction is "\
                "rolled back",
            conn.execute, select([1])
        )
        assert trans.is_active
        assert_raises_message(
            tsa.exc.InvalidRequestError,
            "Can't reconnect until invalid transaction is rolled back",
            trans.commit
        )
        assert trans.is_active
        trans.rollback()
        assert not trans.is_active
        assert conn.invalidated
        eq_(conn.execute(select([1])).scalar(), 1)
        assert not conn.invalidated

class RecycleTest(fixtures.TestBase):

    def test_basic(self):
        for threadlocal in False, True:
            engine = engines.reconnecting_engine(
                        options={'pool_threadlocal': threadlocal})

            conn = engine.contextual_connect()
            eq_(conn.execute(select([1])).scalar(), 1)
            conn.close()

            # set the pool recycle down to 1.
            # we aren't doing this inline with the
            # engine create since cx_oracle takes way
            # too long to create the 1st connection and don't
            # want to build a huge delay into this test.

            engine.pool._recycle = 1

            # kill the DB connection
            engine.test_shutdown()

            # wait until past the recycle period
            time.sleep(2)

            # can connect, no exception
            conn = engine.contextual_connect()
            eq_(conn.execute(select([1])).scalar(), 1)
            conn.close()

class InvalidateDuringResultTest(fixtures.TestBase):
    def setup(self):
        self.engine = engines.reconnecting_engine()
        self.meta = MetaData(self.engine)
        table = Table('sometable', self.meta,
            Column('id', Integer, primary_key=True),
            Column('name', String(50)))
        self.meta.create_all()
        table.insert().execute(
            [{'id': i, 'name': 'row %d' % i} for i in range(1, 100)]
        )

    def teardown(self):
        self.meta.drop_all()
        self.engine.dispose()

    @testing.fails_if([
                    '+mysqlconnector', '+mysqldb',
                    '+cymysql', '+pymysql', '+pg8000'
                    ], "Buffers the result set and doesn't check for "
                        "connection close")
    @testing.fails_on('+informixdb',
                      "Wrong error thrown, fix in informixdb?")
    def test_invalidate_on_results(self):
        conn = self.engine.connect()
        result = conn.execute('select * from sometable')
        for x in range(20):
            result.fetchone()
        self.engine.test_shutdown()
        _assert_invalidated(result.fetchone)
        assert conn.invalidated


text:
package openpgp

import (
	"crypto"
	"github.com/coreos/rkt/Godeps/_workspace/src/golang.org/x/crypto/openpgp/armor"
	"github.com/coreos/rkt/Godeps/_workspace/src/golang.org/x/crypto/openpgp/errors"
	"github.com/coreos/rkt/Godeps/_workspace/src/golang.org/x/crypto/openpgp/packet"
	"github.com/coreos/rkt/Godeps/_workspace/src/golang.org/x/crypto/openpgp/s2k"
	"hash"
	"io"
	"strconv"
	"time"
)

// DetachSign signs message with the private key from signer (which must
// already have been decrypted) and writes the signature to w.
// If config is nil, sensible defaults will be used.
func DetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
	return detachSign(w, signer, message, packet.SigTypeBinary, config)
}

// ArmoredDetachSign signs message with the private key from signer (which
// must already have been decrypted) and writes an armored signature to w.
// If config is nil, sensible defaults will be used.
func ArmoredDetachSign(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) (err error) {
	return armoredDetachSign(w, signer, message, packet.SigTypeBinary, config)
}

// DetachSignText signs message (after canonicalising the line endings) with
// the private key from signer (which must already have been decrypted) and
// writes the signature to w.
// If config is nil, sensible defaults will be used.
func DetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
	return detachSign(w, signer, message, packet.SigTypeText, config)
}

// ArmoredDetachSignText signs message (after canonicalising the line endings)
// with the private key from signer (which must already have been decrypted)
// and writes an armored signature to w.
// If config is nil, sensible defaults will be used.
func ArmoredDetachSignText(w io.Writer, signer *Entity, message io.Reader, config *packet.Config) error {
	return armoredDetachSign(w, signer, message, packet.SigTypeText, config)
}

func armoredDetachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
	out, err := armor.Encode(w, SignatureType, nil)
	if err != nil {
		return
	}
	err = detachSign(out, signer, message, sigType, config)
	if err != nil {
		return
	}
	return out.Close()
}

func detachSign(w io.Writer, signer *Entity, message io.Reader, sigType packet.SignatureType, config *packet.Config) (err error) {
	if signer.PrivateKey == nil {
		return errors.InvalidArgumentError("signing key doesn't have a private key")
	}
	if signer.PrivateKey.Encrypted {
		return errors.InvalidArgumentError("signing key is encrypted")
	}

	sig := new(packet.Signature)
	sig.SigType = sigType
	sig.PubKeyAlgo = signer.PrivateKey.PubKeyAlgo
	sig.Hash = config.Hash()
	sig.CreationTime = config.Now()
	sig.IssuerKeyId = &signer.PrivateKey.KeyId

	h, wrappedHash, err := hashForSignature(sig.Hash, sig.SigType)
	if err != nil {
		return
	}
	io.Copy(wrappedHash, message)

	err = sig.Sign(h, signer.PrivateKey, config)
	if err != nil {
		return
	}

	return sig.Serialize(w)
}

// FileHints contains metadata about encrypted files. This metadata is, itself,
// encrypted.
type FileHints struct {
	// IsBinary can be set to hint that the contents are binary data.
	IsBinary bool
	// FileName hints at the name of the file that should be written. It's
	// truncated to 255 bytes if longer. It may be empty to suggest that the
	// file should not be written to disk. It may be equal to "_CONSOLE" to
	// suggest the data should not be written to disk.
	FileName string
	// ModTime contains the modification time of the file, or the zero time if not applicable.
	ModTime time.Time
}

// SymmetricallyEncrypt acts like gpg -c: it encrypts a file with a passphrase.
// The resulting WriteCloser must be closed after the contents of the file have
// been written.
// If config is nil, sensible defaults will be used.
func SymmetricallyEncrypt(ciphertext io.Writer, passphrase []byte, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) {
	if hints == nil {
		hints = &FileHints{}
	}

	key, err := packet.SerializeSymmetricKeyEncrypted(ciphertext, passphrase, config)
	if err != nil {
		return
	}
	w, err := packet.SerializeSymmetricallyEncrypted(ciphertext, config.Cipher(), key, config)
	if err != nil {
		return
	}

	literaldata := w
	if algo := config.Compression(); algo != packet.CompressionNone {
		var compConfig *packet.CompressionConfig
		if config != nil {
			compConfig = config.CompressionConfig
		}
		literaldata, err = packet.SerializeCompressed(w, algo, compConfig)
		if err != nil {
			return
		}
	}

	var epochSeconds uint32
	if !hints.ModTime.IsZero() {
		epochSeconds = uint32(hints.ModTime.Unix())
	}
	return packet.SerializeLiteral(literaldata, hints.IsBinary, hints.FileName, epochSeconds)
}

// intersectPreferences mutates and returns a prefix of a that contains only
// the values in the intersection of a and b. The order of a is preserved.
func intersectPreferences(a []uint8, b []uint8) (intersection []uint8) {
	var j int
	for _, v := range a {
		for _, v2 := range b {
			if v == v2 {
				a[j] = v
				j++
				break
			}
		}
	}

	return a[:j]
}

func hashToHashId(h crypto.Hash) uint8 {
	v, ok := s2k.HashToHashId(h)
	if !ok {
		panic("tried to convert unknown hash")
	}
	return v
}

// Encrypt encrypts a message to a number of recipients and, optionally, signs
// it. hints contains optional information, that is also encrypted, that aids
// the recipients in processing the message. The resulting WriteCloser must
// be closed after the contents of the file have been written.
// If config is nil, sensible defaults will be used.
func Encrypt(ciphertext io.Writer, to []*Entity, signed *Entity, hints *FileHints, config *packet.Config) (plaintext io.WriteCloser, err error) {
	var signer *packet.PrivateKey
	if signed != nil {
		signKey, ok := signed.signingKey(config.Now())
		if !ok {
			return nil, errors.InvalidArgumentError("no valid signing keys")
		}
		signer = signKey.PrivateKey
		if signer.Encrypted {
			return nil, errors.InvalidArgumentError("signing key must be decrypted")
		}
	}

	// These are the possible ciphers that we'll use for the message.
	candidateCiphers := []uint8{
		uint8(packet.CipherAES128),
		uint8(packet.CipherAES256),
		uint8(packet.CipherCAST5),
	}
	// These are the possible hash functions that we'll use for the signature.
	candidateHashes := []uint8{
		hashToHashId(crypto.SHA256),
		hashToHashId(crypto.SHA512),
		hashToHashId(crypto.SHA1),
		hashToHashId(crypto.RIPEMD160),
	}
	// In the event that a recipient doesn't specify any supported ciphers
	// or hash functions, these are the ones that we assume that every
	// implementation supports.
	defaultCiphers := candidateCiphers[len(candidateCiphers)-1:]
	defaultHashes := candidateHashes[len(candidateHashes)-1:]

	encryptKeys := make([]Key, len(to))
	for i := range to {
		var ok bool
		encryptKeys[i], ok = to[i].encryptionKey(config.Now())
		if !ok {
			return nil, errors.InvalidArgumentError("cannot encrypt a message to key id " + strconv.FormatUint(to[i].PrimaryKey.KeyId, 16) + " because it has no encryption keys")
		}

		sig := to[i].primaryIdentity().SelfSignature

		preferredSymmetric := sig.PreferredSymmetric
		if len(preferredSymmetric) == 0 {
			preferredSymmetric = defaultCiphers
		}
		preferredHashes := sig.PreferredHash
		if len(preferredHashes) == 0 {
			preferredHashes = defaultHashes
		}
		candidateCiphers = intersectPreferences(candidateCiphers, preferredSymmetric)
		candidateHashes = intersectPreferences(candidateHashes, preferredHashes)
	}

	if len(candidateCiphers) == 0 || len(candidateHashes) == 0 {
		return nil, errors.InvalidArgumentError("cannot encrypt because recipient set shares no common algorithms")
	}

	cipher := packet.CipherFunction(candidateCiphers[0])
	// If the cipher specifed by config is a candidate, we'll use that.
	configuredCipher := config.Cipher()
	for _, c := range candidateCiphers {
		cipherFunc := packet.CipherFunction(c)
		if cipherFunc == configuredCipher {
			cipher = cipherFunc
			break
		}
	}

	var hash crypto.Hash
	for _, hashId := range candidateHashes {
		if h, ok := s2k.HashIdToHash(hashId); ok && h.Available() {
			hash = h
			break
		}
	}

	// If the hash specified by config is a candidate, we'll use that.
	if configuredHash := config.Hash(); configuredHash.Available() {
		for _, hashId := range candidateHashes {
			if h, ok := s2k.HashIdToHash(hashId); ok && h == configuredHash {
				hash = h
				break
			}
		}
	}

	if hash == 0 {
		hashId := candidateHashes[0]
		name, ok := s2k.HashIdToString(hashId)
		if !ok {
			name = "#" + strconv.Itoa(int(hashId))
		}
		return nil, errors.InvalidArgumentError("cannot encrypt because no candidate hash functions are compiled in. (Wanted " + name + " in this case.)")
	}

	symKey := make([]byte, cipher.KeySize())
	if _, err := io.ReadFull(config.Random(), symKey); err != nil {
		return nil, err
	}

	for _, key := range encryptKeys {
		if err := packet.SerializeEncryptedKey(ciphertext, key.PublicKey, cipher, symKey, config); err != nil {
			return nil, err
		}
	}

	encryptedData, err := packet.SerializeSymmetricallyEncrypted(ciphertext, cipher, symKey, config)
	if err != nil {
		return
	}

	if signer != nil {
		ops := &packet.OnePassSignature{
			SigType:    packet.SigTypeBinary,
			Hash:       hash,
			PubKeyAlgo: signer.PubKeyAlgo,
			KeyId:      signer.KeyId,
			IsLast:     true,
		}
		if err := ops.Serialize(encryptedData); err != nil {
			return nil, err
		}
	}

	if hints == nil {
		hints = &FileHints{}
	}

	w := encryptedData
	if signer != nil {
		// If we need to write a signature packet after the literal
		// data then we need to stop literalData from closing
		// encryptedData.
		w = noOpCloser{encryptedData}

	}
	var epochSeconds uint32
	if !hints.ModTime.IsZero() {
		epochSeconds = uint32(hints.ModTime.Unix())
	}
	literalData, err := packet.SerializeLiteral(w, hints.IsBinary, hints.FileName, epochSeconds)
	if err != nil {
		return nil, err
	}

	if signer != nil {
		return signatureWriter{encryptedData, literalData, hash, hash.New(), signer, config}, nil
	}
	return literalData, nil
}

// signatureWriter hashes the contents of a message while passing it along to
// literalData. When closed, it closes literalData, writes a signature packet
// to encryptedData and then also closes encryptedData.
type signatureWriter struct {
	encryptedData io.WriteCloser
	literalData   io.WriteCloser
	hashType      crypto.Hash
	h             hash.Hash
	signer        *packet.PrivateKey
	config        *packet.Config
}

func (s signatureWriter) Write(data []byte) (int, error) {
	s.h.Write(data)
	return s.literalData.Write(data)
}

func (s signatureWriter) Close() error {
	sig := &packet.Signature{
		SigType:      packet.SigTypeBinary,
		PubKeyAlgo:   s.signer.PubKeyAlgo,
		Hash:         s.hashType,
		CreationTime: s.config.Now(),
		IssuerKeyId:  &s.signer.KeyId,
	}

	if err := sig.Sign(s.h, s.signer, s.config); err != nil {
		return err
	}
	if err := s.literalData.Close(); err != nil {
		return err
	}
	if err := sig.Serialize(s.encryptedData); err != nil {
		return err
	}
	return s.encryptedData.Close()
}

// noOpCloser is like an ioutil.NopCloser, but for an io.Writer.
// TODO: we have two of these in OpenPGP packages alone. This probably needs
// to be promoted somewhere more common.
type noOpCloser struct {
	w io.Writer
}

func (c noOpCloser) Write(data []byte) (n int, err error) {
	return c.w.Write(data)
}

func (c noOpCloser) Close() error {
	return nil
}


text:
namespace ph
{

//SamplingFilmSet::SamplingFilmSet() :
//	m_tagToFilm()
//{}
//
//SamplingFilmSet::SamplingFilmSet(SamplingFilmSet&& other) :
//	m_tagToFilm(std::move(other.m_tagToFilm))
//{}
//
//SamplingFilmSet& SamplingFilmSet::operator = (SamplingFilmSet&& rhs)
//{
//	m_tagToFilm = std::move(rhs.m_tagToFilm);
//
//	return *this;
//}

}// end namespace ph


text:
package hpa

import (
	"context"

	autoscalingv2beta1 "k8s.io/client-go/informers/autoscaling/v2beta1"

	"github.com/knative/pkg/controller"
	"github.com/knative/pkg/injection"
	"github.com/knative/pkg/injection/informers/kubeinformers/factory"
	"github.com/knative/pkg/logging"
)

func init() {
	injection.Default.RegisterInformer(withInformer)
}

// Key is used as the key for associating information
// with a context.Context.
type Key struct{}

func withInformer(ctx context.Context) (context.Context, controller.Informer) {
	f := factory.Get(ctx)
	inf := f.Autoscaling().V2beta1().HorizontalPodAutoscalers()
	return context.WithValue(ctx, Key{}, inf), inf.Informer()
}

// Get extracts the Kubernetes Hpa informer from the context.
func Get(ctx context.Context) autoscalingv2beta1.HorizontalPodAutoscalerInformer {
	untyped := ctx.Value(Key{})
	if untyped == nil {
		logging.FromContext(ctx).Panicf(
			"Unable to fetch %T from context.", (autoscalingv2beta1.HorizontalPodAutoscalerInformer)(nil))
	}
	return untyped.(autoscalingv2beta1.HorizontalPodAutoscalerInformer)
}


text:
I've been wanting to do some ARt (Augmented Reality Art) for a while now and struggled with creating animations with transparent background to create AR posters. I've finally figured it out so here's the solution!

First, I create an animation with code using Processing. For example, something like this:

![animation](animation.gif)

I saved the animation as a video and then, I wanted to be able to remove the black background to have a transparent video.

To do so, I used Adobe After Effects.

## Save the video with transparent background

* Open After Effects.
* File > Import > File and select your video.

![after effects](ae-1.png)

* Close the `Render Queue` tab if open and drag the video to the bottom left window.

![after effects](ae-2.png)

* Effect > Channel > Shift channels, then in the `Take Alpha from`, select `Luminance`.
This should remove the black background.

![after effects](ae-3.png)

![after effects](ae-4.png)

* Composition > Add to render queue.
* At the bottom, clik on the option saying `lossless`. The output module settings window should open.
* Change video output channels to be `RGB + Alpha`.
* Click the `format option` button and check that the format is `Animation`.

![after effects](ae-5.png)

* Click ok and `render` on the right.

It should export your animation with transparent background.

* Go to where the video has been exported and open it with Quicktime. It should do some kind of conversion and save that converted version (this is the one we'll use in Unity).

Now go to Unity.

## Using the video in Unity.

* Open Unity, log in and create a new project.
* Delete the Main Camera.
* Add a Vuforia AR camera.
* In the project tab (bottom left), create a new folder and call it `Materials`.
* Add a Vuforia image target.
* Inside that Image target, create a plane game object.
* Drag and drop your video inside the materials folder you created.
* Click on it and make sure to select `Keep alpha` and `transcode` and `apply`.
* For some reason, for the transparency to work, try and also drag an image in the materials folder and then drag it on the plane.
* When you drop an image, a new Materials folder should be created with an actual material inside.
* If you click back on your plane object, you should see at the bottom a `shader` option. Instead of standard, select transparent.
* Drag your video on the plane and delete the image in the materials folder.
* If you click on your plane object in the hierarchy window, you should see a `Video Player` section.
* Click on the play button to try it with your webcam and you should see your animation on your image target with a transparent background! :D

![unity](unity.png)


text:
#pragma once

namespace stm32plus {
  namespace spiflash {
    namespace s25fl208k {

      /**
       * Commands for the S25FL208K that are either different to, or extend
       * the standard set.
       */

      enum {
        CMD_BLOCK_ERASE = 0xd8        // different to the usual command id
      };
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="demo.example.com.customarrayadapter" >
    <meta-data android:name="demo.example.com.customarrayadapter.config.GlideConfiguration"
        android:value="GlideModule"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MovieActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

            </intent-filter>
        </activity>
        <provider
            android:authorities="@string/content_authority"
            android:name=".contentviews.data.FlavorsProvider"
            android:exported="false"
            android:syncable="true"/><!-- ATTENTION: This was auto-generated to add Google Play services to your project for
     App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
    </application>
</manifest>