text:
/*jshint expr:true*/
/*globals before,beforeEach,after,afterEach,describe,it */
"use strict";

var libUrl = require('url');
var expect = require('chai').expect;
var mockery = require('mockery');
var Fetcher;
var fetcher;
var app = require('../../mock/app');
var supertest = require('supertest');
var request = require('request');
var qs = require('qs');
var resource = 'mock_service';
var DEFAULT_XHR_PATH = '/api';

var validateGET;
var validatePOST;
var validateHTTP = function (options) {
    options = options || {};
    validateGET = options.validateGET;
    validatePOST = options.validatePOST;
};
describe('Client Fetcher', function () {
    beforeEach(function () {
        mockery.registerMock('./util/http.client', {
            get: function (url, headers, config, callback) {
                validateGET && validateGET(url, headers, config);
                supertest(app)
                    .get(url)
                    .expect(200)
                    .end(function (err, res) {
                        callback(err, {
                            responseText: res.text
                        });
                    });
            },
            post : function (url, headers, body, config, callback) {
                expect(url).to.not.be.empty;
                expect(callback).to.exist;
                expect(body).to.exist;
                validatePOST && validatePOST(url, headers, body, config);
                supertest(app)
                    .post(url)
                    .send(body)
                    .expect(200)
                    .end(function (err, res) {
                        callback(err, {
                            responseText: res.text
                        });
                    });
            }
        });
        mockery.enable({
            useCleanCache: true,
            warnOnUnregistered: false
        });
        Fetcher = require('../../../libs/fetcher.client');
        validateHTTP(); // Important, reset validate functions
    });
    afterEach(function () {
        mockery.deregisterAll();
        mockery.disable();
    });
    var testCrud = function (it, resource, params, body, config, callback) {
            it('should handle CREATE', function (done) {
                var operation = 'create';
                fetcher
                    [operation](resource)
                    .params(params)
                    .body(body)
                    .clientConfig(config)
                    .end(callback(operation, done));
            });
            it('should handle READ', function (done) {
                var operation = 'read';
                fetcher
                    [operation](resource)
                    .params(params)
                    .clientConfig(config)
                    .end(callback(operation, done));
            });
            it('should handle UPDATE', function (done) {
                var operation = 'update';
                fetcher
                    [operation](resource)
                    .params(params)
                    .body(body)
                    .clientConfig(config)
                    .end(callback(operation, done));
            });
            it('should handle DELETE', function (done) {
                var operation = 'delete';
                fetcher
                    [operation](resource)
                    .params(params)
                    .clientConfig(config)
                    .end(callback(operation, done));
            });
        };

    describe('CRUD Interface', function () {
        beforeEach(function () {
            var context = {_csrf: 'stuff'};
            fetcher = new Fetcher({
                context: context
            });
            validateHTTP({
                validateGET: function (url, headers, config) {
                    expect(url).to.contain(DEFAULT_XHR_PATH + '/' + resource);
                    expect(url).to.contain('?_csrf=' + context._csrf);
                },
                validatePOST: function (url, headers, body, config) {
                    expect(url).to.equal(DEFAULT_XHR_PATH + '?_csrf=' + context._csrf);
                }
            });
        });
        var params = {
                uuids: ['1','2','3','4','5']
            };
        var body = { stuff: 'is'};
        var config = {};
        var callback = function (operation, done) {
                return function (err, data) {
                    if (err){
                        done(err);
                    }
                    expect(data.operation).to.exist;
                    expect(data.operation.name).to.equal(operation);
                    expect(data.operation.success).to.be.true;
                    expect(data.args).to.exist;
                    expect(data.args.resource).to.equal(resource);
                    expect(data.args.params).to.eql(params);
                    done();
                };
            };
        var resolve = function (operation, done) {
            return function (data) {
                try {
                    expect(data).to.exist;
                    expect(data.operation).to.exist;
                    expect(data.operation.name).to.equal(operation);
                    expect(data.operation.success).to.be.true;
                    expect(data.args).to.exist;
                    expect(data.args.resource).to.equal(resource);
                    expect(data.args.params).to.eql(params);
                } catch (e) {
                    done(e);
                    return;
                }
                done();
            };
        };
        var reject = function (operation, done) {
            return function (err) {
                done(err);
            };
        };
        describe('should work superagent style', function (done) {
            describe('with callbacks', function () {
                testCrud(it, resource, params, body, config, callback);
                it('should throw if no resource is given', function () {
                    expect(fetcher.read).to.throw('Resource is required for a fetcher request');
                });
            });
            describe('with Promises', function () {
                it('should handle CREATE', function (done) {
                    var operation = 'create';
                    fetcher
                        [operation](resource)
                        .params(params)
                        .body(body)
                        .clientConfig(config)
                        .end()
                        .then(resolve(operation, done), reject(operation, done));
                });
                it('should handle READ', function (done) {
                    var operation = 'read';
                    fetcher
                        [operation](resource)
                        .params(params)
                        .clientConfig(config)
                        .end()
                        .then(resolve(operation, done), reject(operation, done));
                });
                it('should handle UPDATE', function (done) {
                    var operation = 'update';
                    fetcher
                        [operation](resource)
                        .params(params)
                        .body(body)
                        .clientConfig(config)
                        .end()
                        .then(resolve(operation, done), reject(operation, done));
                });
                it('should handle DELETE', function (done) {
                    var operation = 'delete';
                    fetcher
                        [operation](resource)
                        .params(params)
                        .clientConfig(config)
                        .end()
                        .then(resolve(operation, done), reject(operation, done));
                });
                it('should throw if no resource is given', function () {
                    expect(fetcher.read).to.throw('Resource is required for a fetcher request');
                });
            })
        });
        describe('should be backwards compatible', function (done) {
            // with config
            it('should handle CREATE', function (done) {
                var operation = 'create';
                fetcher[operation](resource, params, body, config, callback(operation, done));
            });
            it('should handle READ', function (done) {
                var operation = 'read';
                fetcher[operation](resource, params, config, callback(operation, done));
            });
            it('should handle UPDATE', function (done) {
                var operation = 'update';
                fetcher[operation](resource, params, body, config, callback(operation, done));
            });
            it('should handle DELETE', function (done) {
                var operation = 'delete';
                fetcher[operation](resource, params, config, callback(operation, done));
            });

            // without config
            it('should handle CREATE w/ no config', function (done) {
                var operation = 'create';
                fetcher[operation](resource, params, body, callback(operation, done));
            });
            it('should handle READ w/ no config', function (done) {
                var operation = 'read';
                fetcher[operation](resource, params, callback(operation, done));
            });
            it('should handle UPDATE w/ no config', function (done) {
                var operation = 'update';
                fetcher[operation](resource, params, body, callback(operation, done));
            });
            it('should handle DELETE w/ no config', function (done) {
                var operation = 'delete';
                fetcher[operation](resource, params, callback(operation, done));
            });
        });

    });
    describe('CORS', function () {
        // start CORS app at localhost:3001
        var corsApp = require('../../mock/corsApp');
        var corsPath = 'http://localhost:3001';
        var params = {
                uuids: ['1','2','3','4','5'],
                corsDomain: 'test1'
            },
            body = { stuff: 'is'},
            context = {
                _csrf: 'stuff'
            },
            callback = function(operation, done) {
                return function(err, data) {
                    if (err){
                        return done(err);
                    }
                    if (data) {
                        expect(data).to.deep.equal(params);
                    }
                    done();
                };
            };
        beforeEach(function() {
            mockery.deregisterAll(); // deregister default http.client mock
            mockery.registerMock('./util/http.client', { // register CORS http.client mock
                get: function (url, headers, config, callback) {
                    expect(url).to.contain(corsPath);
                    var path = url.substr(corsPath.length);
                    // constructGetUri above doesn't implement csrf so we don't check csrf here
                    supertest(corsPath)
                        .get(path)
                        .expect(200)
                        .end(function (err, res) {
                            callback(err, {
                                responseText: res.text
                            });
                        });
                },
                post : function (url, headers, body, config, callback) {
                    expect(url).to.not.be.empty;
                    expect(callback).to.exist;
                    expect(body).to.exist;
                    expect(url).to.equal(corsPath + '?_csrf=' + context._csrf);
                    var path = url.substring(corsPath.length);
                    supertest(corsPath)
                        .post(path)
                        .send(body)
                        .expect(200)
                        .end(function (err, res) {
                            callback(err, {
                                responseText: res.text
                            });
                        });
                }
            });
            mockery.resetCache();
            Fetcher = require('../../../libs/fetcher.client');
            fetcher = new Fetcher({
                context: context,
                corsPath: corsPath
            });
        });
        afterEach(function () {
            mockery.deregisterAll(); // deregister CORS http.client mock
        });

        function constructGetUri (uri, resource, params, config) {
            if (config.cors) {
                return uri + '/' + resource + '?' + qs.stringify(params, { arrayFormat: 'repeat' });
            }
        }

        testCrud(it, resource, params, body, {
            cors: true,
            constructGetUri: constructGetUri
        }, callback);
    });

    describe('xhrTimeout', function () {
        var DEFAULT_XHR_TIMEOUT = 3000;
        var params = {
                uuids: [1,2,3,4,5],
                category: ''
            },
            body = { stuff: 'is'},
            context = {
                _csrf: 'stuff'
            },
            config = {},
            callback = function(operation, done) {
                return function(err, data) {
                    if (err){
                        done(err);
                    }
                    done();
                };
            };

        describe('should be configurable globally', function () {
            beforeEach(function(){
                validateHTTP({
                    validateGET: function (url, headers, config) {
                        expect(config.xhrTimeout).to.equal(4000);
                    },
                    validatePOST: function (url, headers, body, config) {
                        expect(config.xhrTimeout).to.equal(4000);
                    }
                });

                fetcher = new Fetcher({
                    context: context,
                    xhrTimeout: 4000
                });
            });

            testCrud(it, resource, params, body, config, callback);
        });

        describe('should be configurable per each fetchr call', function () {
            config = {timeout: 5000};
            beforeEach(function(){
                validateHTTP({
                    validateGET: function (url, headers, config) {
                        expect(config.xhrTimeout).to.equal(4000);
                        expect(config.timeout).to.equal(5000);
                    },
                    validatePOST: function (url, headers, body, config) {
                        expect(config.xhrTimeout).to.equal(4000);
                        expect(config.timeout).to.equal(5000);
                    }
                });
                fetcher = new Fetcher({
                    context: context,
                    xhrTimeout: 4000
                });
            });

            testCrud(it, resource, params, body, config, callback);
        });

        describe('should default to DEFAULT_XHR_TIMEOUT of 3000', function () {
            beforeEach(function(){
                validateHTTP({
                    validateGET: function (url, headers, config) {
                        expect(config.xhrTimeout).to.equal(DEFAULT_XHR_TIMEOUT);
                    },
                    validatePOST: function (url, headers, body, config) {
                        expect(config.xhrTimeout).to.equal(DEFAULT_XHR_TIMEOUT);
                    }
                });

                fetcher = new Fetcher({
                    context: context
                });
            });

            testCrud(it, resource, params, body, config, callback);
        });
    });

    describe('Context Picker', function () {
        var context = {_csrf: 'stuff', random: 'randomnumber'};
        var params = {};
        var body = {};
        var config = {};
        var callback = function(operation, done) {
                return function(err, data) {
                    if (err){
                        done(err);
                    }
                    done();
                };
            };

        beforeEach(function(){
            fetcher = new Fetcher({
                context: context,
                contextPicker: {
                    GET: function getContextPicker(value, key, object) {
                        if (key === 'random') {
                            return false
                        }
                        return true;
                    }
                }
            });
            validateHTTP({
                validateGET: function (url, headers, config) {
                    expect(url).to.contain(DEFAULT_XHR_PATH + '/' + resource);
                    expect(url).to.contain('?_csrf=' + context._csrf);
                    // for GET, ignore 'random'
                    expect(url).to.not.contain('random=' + context.random);
                },
                validatePOST: function (url, headers, body, config) {
                    expect(url).to.equal(DEFAULT_XHR_PATH + '?_csrf=' + context._csrf + '&random=' + context.random);
                }
            });
        });

        testCrud(it, resource, params, body, config, callback);
    });

    describe('Utils', function () {
        it('should able to update options', function () {
            fetcher = new Fetcher({
                context: {
                    _csrf: 'stuff'
                },
                xhrTimeout: 1000
            });
            fetcher.updateOptions({
                context: {
                    lang : 'en-US',
                },
                xhrTimeout: 1500
            })
            expect(fetcher.options.xhrTimeout).to.equal(1500);
            // new context should be merged
            expect(fetcher.options.context._csrf).to.equal('stuff');
            expect(fetcher.options.context.lang).to.equal('en-US');
        });
    });
});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3(2): 516 (1898)

#### Original name
Hexagonia cookei Sacc.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
layout: page
title: "Publish your Paragraph"
description: ""
group: manual
---

{% include JB/setup %}

# How can you publish your paragraph ?

Apache Zeppelin provides a feature for publishing your notebook paragraph results. Using this feature, you can show Zeppelin notebook paragraph results in your own website.
It's very straightforward. Just use `<iframe>` tag in your page.

## Copy a Paragraph Link
A first step to publish your paragraph result is **Copy a Paragraph Link**.

  * After running a paragraph in your Zeppelin notebook, click a gear button located on the right side. Then, click **Link this Paragraph** menu like below image.

  * Just copy the provided link.

## Embed the Paragraph to Your Website
For publishing the copied paragraph, you may use `<iframe>` tag in your website page.
For example,

```
<iframe src="http://< ip-address >:< port >/#/notebook/2B3QSZTKR/paragraph/...?asIframe" height="" width="" ></iframe>
```

Finally, you can show off your beautiful visualization results in your website.

> **Note**: To embed the paragraph in a website, Apache Zeppelin needs to be reachable by that website. And please use this feature with caution and in a trusted environment only, as Zeppelin entire Webapp could be accessible by whoever visits your website.


text:
Imports bv.common.db
Imports System.Data.Common
Imports bv.common
Imports bv.common.Configuration
Imports bv.common.Enums

Public Class EmNotify_DB
    Inherits BaseDbService

    Protected m_GetNotificationAdapter As DbDataAdapter
    Protected m_NtfyCountCommand As IDbCommand
    Protected m_NtfyProcessedCommand As IDbCommand
    Protected m_CreateNotificationCommand As IDbCommand
    Protected m_SiteID As Long
    Protected m_ClientID As String
    Private ReadOnly m_SiteService As EIDSS_SiteService

    Public Sub New(Optional ByVal credentials As ConnectionCredentials = Nothing, Optional ByVal aClientId As String = Nothing)

        If Not credentials Is Nothing Then
            CreateConnection(credentials.SQLServer, credentials.SQLDatabase, credentials.SQLUser, credentials.SQLPassword, credentials.SQLConnectionString)
        End If
        m_SiteService = New EIDSS_SiteService()
        m_SiteService.SiteConnection = Connection
        m_SiteID = m_SiteService.GetRealSiteID()
        If Utils.IsEmpty(aClientId) Then
            m_ClientID = model.Core.EidssUserContext.ClientID
        Else
            m_ClientID = aClientId
        End If
    End Sub

    Public ReadOnly Property IsValid As Boolean
        Get
            Return m_SiteID > 0
        End Get
    End Property
    Private m_InProcess As Boolean = False
    Public Overridable Function GetNotificationsCount() As Integer
        If m_InProcess Then
            Return 0
        End If
        m_InProcess = True
        Try
            m_Error = Nothing
            If m_NtfyCountCommand Is Nothing Then
                m_NtfyCountCommand = CreateSPCommand("spNotification_GetCount")
                AddParam(m_NtfyCountCommand, "@idfsSite", "")
            End If
            SetParam(m_NtfyCountCommand, "@idfsSite", SiteID)
            Dim tempObjCount As Object = ExecScalar(m_NtfyCountCommand, m_NtfyCountCommand.Connection, m_Error)

            If m_Error Is Nothing Then
                Return CType(tempObjCount, Integer)
            Else
                Dbg.Debug("error during GetNotificationsCount call: {0}", m_Error.DetailError)
                Return -1
            End If
        Catch ex As Exception
            Dbg.Debug("error during GetNotificationsCount call: {0}", ex.Message)
            Return -1
        Finally
            m_InProcess = False
        End Try
    End Function

    Public Overridable Function GetNotifications() As DataSet
        m_Error = Nothing
        If m_GetNotificationAdapter Is Nothing Then
            Dim cmd As IDbCommand = CreateSPCommand("spNotification_SelectUnprocessed")
            AddParam(cmd, "@idfsSite", SiteID)
            m_GetNotificationAdapter = CreateAdapter(cmd)
        End If
        Dim retRes As New DataSet
        Try
            SyncLock (m_GetNotificationAdapter.SelectCommand.Connection)
                m_GetNotificationAdapter.Fill(retRes, "Notification")
            End SyncLock
        Catch ex As Exception
            m_Error = New ErrorMessage(StandardError.PostError, ex)
            Trace.WriteLine(Trace.Kind.Error, "GetNotifications", ex)
            Return Nothing
        End Try
        Return retRes
    End Function

    Public Overridable Function CreateNotification(ByVal ntfType As NotificationType, ByVal objectId As Long, _
                                                   ByVal objectType As Long, ByVal ntfyData As String, _
                                                   sourceSiteID As Object, _
                                                   Optional ByVal targetSiteID As Object = Nothing, _
                                                   Optional ByVal targetSiteType As Object = Nothing, _
                                                   Optional ByVal user As Object = Nothing, _
                                                   Optional ByVal targetUser As Object = Nothing
                                                   ) As Object
        If m_CreateNotificationCommand Is Nothing Then
            m_CreateNotificationCommand = CreateSPCommand("spNotification_Create", Connection)
            StoredProcParamsCache.CreateParameters(m_CreateNotificationCommand)
        End If
        If targetSiteID Is Nothing Then
            targetSiteID = DBNull.Value
        End If
        If targetSiteType Is Nothing Then
            targetSiteType = DBNull.Value
        End If
        SetParam(m_CreateNotificationCommand, "@idfNotification", DBNull.Value)
        If (Not Utils.IsEmpty(sourceSiteID)) Then
            SetParam(m_CreateNotificationCommand, "@idfsSite", sourceSiteID)
        Else
            SetParam(m_CreateNotificationCommand, "@idfsSite", SiteID)
        End If
        SetParam(m_CreateNotificationCommand, "@idfsNotificationType", ntfType)
        SetParam(m_CreateNotificationCommand, "@idfsTargetSite", targetSiteID)
        SetParam(m_CreateNotificationCommand, "@idfsTargetSiteType", targetSiteType)
        If (Not Utils.IsEmpty(user)) Then
            SetParam(m_CreateNotificationCommand, "@idfUserID", user)
        End If
        If (Not Utils.IsEmpty(targetUser)) Then
            SetParam(m_CreateNotificationCommand, "@idfTargetUserID", targetUser)
        End If
        SetParam(m_CreateNotificationCommand, "@strPayload", Utils.Str(ntfyData))
        If objectId > 0 Then
            SetParam(m_CreateNotificationCommand, "@idfNotificationObject", objectId)
        Else
            SetParam(m_CreateNotificationCommand, "@idfNotificationObject", DBNull.Value)
        End If
        If objectType > 0 Then
            SetParam(m_CreateNotificationCommand, "@idfsNotificationObjectType", objectType)
        Else
            SetParam(m_CreateNotificationCommand, "@idfsNotificationObjectType", DBNull.Value)
        End If
        m_Error = Nothing
        Try
            ExecCommand(m_CreateNotificationCommand, Connection, Nothing, True)
            m_ID = GetParamValue(m_CreateNotificationCommand, "@idfNotification")
        Catch ex As Exception
            m_Error = New ErrorMessage(StandardError.PostError, ex)
            Trace.WriteLine(Trace.Kind.Error, "error during notification creation:", ex)
            Return Nothing
        End Try
        Return m_ID
    End Function

    Public Overridable Function MarkProcessed(ByVal notificationID As Long) As Boolean
        m_Error = Nothing
        If m_NtfyProcessedCommand Is Nothing Then
            m_NtfyProcessedCommand = CreateSPCommand("spNotification_Process")
        End If

        Try
            SetParam(m_NtfyProcessedCommand, "@idfNotification", notificationID)
            ExecCommand(m_NtfyProcessedCommand, m_NtfyProcessedCommand.Connection)
        Catch ex As Exception
            m_Error = New ErrorMessage(StandardError.SqlQueryError, ex)
            Trace.WriteLine(Trace.Kind.Error, "MarkProcessed", ex)
            Return False
        End Try
        Return True
    End Function

    Public Overridable Function SubscribeToAllEvents() As Boolean
        m_Error = Nothing
        Dim subscribeToAllCmd As IDbCommand
        subscribeToAllCmd = CreateSPCommand("spEventLog_SubscribeToAllEvents", Connection)
        AddParam(subscribeToAllCmd, "@idfClientID", ClientID)

        m_Error = ExecCommand(subscribeToAllCmd, subscribeToAllCmd.Connection, Nothing)

        If m_Error Is Nothing Then
            Return True
        Else
            Return False
        End If
    End Function
    Public Property ClientID() As String
        Get
            If m_ClientID Is Nothing Then
                m_ClientID = model.Core.EidssUserContext.ClientID
            End If
            Return m_ClientID
        End Get
        Set(ByVal value As String)
            m_ClientID = value
        End Set
    End Property
    Public Property SiteID() As Long
        Get
            If (m_SiteID <= 0) Then
                m_SiteID = m_SiteService.GetSiteID()
            End If
            Return m_SiteID
        End Get
        Set(ByVal value As Long)
            m_SiteID = value
        End Set
    End Property
    Public Shared Function GetTransferedSampleSite(idfTransferOut As Long) As Object
        Dim cmd As IDbCommand = CreateSPCommand("spGetTargetSiteForTransferOut", ConnectionManager.DefaultInstance.Connection)
        AddParam(cmd, "@idfTransferOut", idfTransferOut)
        Dim errMsg As ErrorMessage = Nothing
        Dim res As Object = ExecScalar(cmd, ConnectionManager.DefaultInstance.Connection, errMsg)
        If res Is Nothing Then
            res = DBNull.Value
        End If
        Return res
    End Function
    Public Shared Function GetTestSampleSite(idfTesting As Long) As Object
        Dim cmd As IDbCommand = CreateSPCommand("spGetTargetSiteForRemoteTestResult", ConnectionManager.DefaultInstance.Connection)
        AddParam(cmd, "@idfTesting", idfTesting)
        Dim errMsg As ErrorMessage = Nothing
        Dim res As Object = ExecScalar(cmd, ConnectionManager.DefaultInstance.Connection, errMsg)
        If res Is Nothing Then
            res = DBNull.Value
        End If
        Return res
    End Function

    Public Shared Function GetParentSite(ByVal idfsSite As Long) As Object
        If idfsSite <= 0 Then Return DBNull.Value
        Dim cmd As IDbCommand = CreateSPCommand("spSite_GetParentSite", ConnectionManager.DefaultInstance.Connection)
        AddParam(cmd, "@SiteID", idfsSite)
        Dim errMsg As ErrorMessage = Nothing
        Dim res As Object = ExecScalar(cmd, ConnectionManager.DefaultInstance.Connection, errMsg)
        If Utils.IsEmpty(res) Then
            Return DBNull.Value
        End If
        Return CLng(res)
    End Function
    Public Shared Function GetChildSite(ByVal idfsSite As Long) As Object
        If idfsSite <= 0 Then Return DBNull.Value
        Dim cmd As IDbCommand = CreateSPCommand("spSite_GetChildSites", ConnectionManager.DefaultInstance.Connection)
        AddParam(cmd, "@SiteID", idfsSite)
        Dim errMsg As ErrorMessage = Nothing
        Dim res As Object = ExecScalar(cmd, ConnectionManager.DefaultInstance.Connection, errMsg)
        If Utils.IsEmpty(res) Then
            Return DBNull.Value
        End If
        Return CLng(res)
    End Function
End Class


text:
<?php

namespace BonderTest\Builders;

/**
 * @author hbandura
 */
final class StandardFiltersProviderBuilderTest
  extends \PHPUnit_Framework_TestCase {

  public function testSimple() {
    $builder = new \Bonder\Builders\StandardFiltersProviderBuilder();
    $context = $this->getMock("\Bonder\Context");
    $f1 = $this->getMock("\Bonder\Filters\Filter");
    $f2 = $this->getMock("\Bonder\Filters\ContextAwareFilter");
    $f3 = $this->getMock("\Bonder\Filter");
    $f4 = $this->getMock("\Bonder\Filter");
    $f2->expects($this->once())->method("setContext")
      ->with($context);
    $filters = array(
      "key1.*" => $f1,
      "key2.*" => $f2,
      "key3.*" => $f3,
      "key.*end" => $f4
    );
    $this->assertSame($builder, $builder->setContext($context));
    $this->assertSame($context, $builder->getContext());
    $this->assertSame($builder, $builder->setFilters($filters));
    $this->assertSame($filters, $builder->getFilters());
    $fp = $builder->build();
    $key1aFilters = $fp->getFilters("key1a");
    $this->assertSame($f1, $key1aFilters[0]);
    $this->assertCount(1, $key1aFilters);

    $key2bFilters = $fp->getFilters("key2b");
    $this->assertCount(1, $key2bFilters);
    $this->assertSame($f2, $key2bFilters[0]);

    $key3endFilters = $fp->getFilters("key3end");
    $this->assertCount(2, $key3endFilters);
    $this->assertEquals(array($f3, $f4), $key3endFilters);

    $emptyFilters = $fp->getFilters("nothing");
    $this->assertEmpty($emptyFilters);
  }

  public function testDefaults() {
    $builder = new \Bonder\Builders\StandardFiltersProviderBuilder();
    $this->assertInstanceOf("\Bonder\Context", $builder->getContext());
    $this->assertTrue(is_array($builder->getFilters()));
  }

}


text:
.. _installation:

************
Installation
************

This section documents the process of deploying the GA4GH reference
server in a production setting. The intended audience is therefore
server administrators. If you are looking for a quick demo of the
GA4GH API using a local installation of the reference server
please check out the :ref:`demo`. If you are looking for
instructions to get a development system up and running, then
please go to the :ref:`development` section.

--------------------
Deployment on Apache
--------------------

To deploy on Apache on Debian/Ubuntu platforms, do the following.

First, we install some basic pre-requisite packages:

.. code-block:: bash

  $ sudo apt-get install python-dev python-virtualenv zlib1g-dev libxslt1-dev libffi-dev

Install Apache and mod_wsgi, and enable mod_wsgi:

.. code-block:: bash

  $ sudo apt-get install apache2 libapache2-mod-wsgi
  $ sudo a2enmod wsgi

Create the Python egg cache directory, and make it writable by
the ``www-data`` user:

.. code-block:: bash

  $ sudo mkdir /var/cache/apache2/python-egg-cache
  $ sudo chown www-data:www-data /var/cache/apache2/python-egg-cache/

Create a directory to hold the GA4GH server code, configuration
and data. For convenience, we make this owned by the current user
(but make sure all the files are world-readable).:

.. code-block:: bash

  $ sudo mkdir /srv/ga4gh
  $ sudo chown $USER /srv/ga4gh
  $ cd /srv/ga4gh

Make a virtualenv, and install the ga4gh package:

.. code-block:: bash

  $ virtualenv ga4gh-server-env
  $ source ga4gh-server-env/bin/activate
  (ga4gh-server-env) $ pip install --pre ga4gh  # We need the --pre because ga4gh is pre-release
  (ga4gh-server-env) $ deactivate

Download and unpack the example data:

.. code-block:: bash

  $ wget http://www.well.ox.ac.uk/~jk/ga4gh-example-data-v3.0.tar
  $ tar -xf ga4gh-example-data-v3.0.tar

Create the WSGI file at ``/srv/ga4gh/application.wsgi`` and write the following
contents:

.. code-block:: python

    from ga4gh.frontend import app as application
    import ga4gh.frontend as frontend
    frontend.configure("/srv/ga4gh/config.py")

Create the configuration file at ``/srv/ga4gh/config.py``, and write the
following contents:

.. code-block:: python

    DATA_SOURCE = "/srv/ga4gh/ga4gh-example-data"

(Many more configuration options are available --- see the :ref:`configuration`
section for a detailed discussion on the server configuration and input data.)

Configure Apache. Edit the file ``/etc/apache2/sites-enabled/000-default.conf``
and insert the following contents towards the end of the file
(*within* the ``<VirtualHost:80>...</VirtualHost>`` block):

.. code-block:: apacheconf

    WSGIDaemonProcess ga4gh \
        python-path=/srv/ga4gh/ga4gh-server-env/lib/python2.7/site-packages \
        python-eggs=/var/cache/apache2/python-egg-cache
    WSGIScriptAlias /ga4gh /srv/ga4gh/application.wsgi

    <Directory /srv/ga4gh>
        WSGIProcessGroup ga4gh
        WSGIApplicationGroup %{GLOBAL}
        Require all granted
    </Directory>

Restart Apache:

.. code-block:: bash

  $ sudo service apache2 restart

Test the installation by pointing a web-browser at the root URL; for example,
to test on the installation server use:

.. code-block:: bash

    $ links http://localhost/ga4gh

We can also test the server by running some API commands; the instructions
in the :ref:`demo` can be easily adapted here to test out the server across
the network.

There are any number of different ways in which we can set up a WSGI
application under Apache, which may be preferable in different installations.
(In particular, the Apache configuration here may be specific to
Ubuntu 14.04, where this was tested.)
See the `mod_wsgi documentation <https://code.google.com/p/modwsgi/>`_ for
more details. These instructions are also specific to Debian/Ubuntu and
different commands and directory structures will be required on
different platforms.

The server can be deployed on any WSGI compliant web server. See the
instructions in the `Flask documentation
<http://flask.pocoo.org/docs/0.10/deploying/>`_ for more details on
how to deploy on various other servers.

**TODO**

1. Add more detail on how we can test out the API by making some client
   queries.
2. Add links to the Configuration section to give details on how we
   configure the server.

+++++++++++++++
Troubleshooting
+++++++++++++++

If you are encountering difficulties getting the above to work, it is helpful
to turn on debugging output. Do this by adding the following line to your
config file:

.. code-block:: python

    DEBUG = True

When an error occurs, the details of this will then be printed to the web server's
error log (in Apache on Debian/Ubuntu, for example, this is ``/var/log/apache2/error.log``).

--------------------
Deployment on Docker
--------------------
It is also possible to deploy the server using Docker.

First, you need an environment running the docker daemon. For non-production use, we recommend `boot2docker <http://boot2docker.io/>`_. For production use you should install docker on a stable linux distro.
Please reference the `platform specific Docker installation instructions <https://docs.docker.com/installation/>`_. OSX and Windows are instructions for boot2docker.

**Local Dataset Mounted as Volume**

If you already have a dataset on your machine, you can download and deploy the apache server in one command:

.. code-block:: bash

  $ docker run -e GA4GH_DATA_SOURCE=/data -v /my/ga4gh_data/:/data:ro -d -p 8000:80 --name ga4gh_server afirth/ga4gh-server:latest

Replace ``/my/ga4gh_data/`` with the path to your data.

This will:

* pull the automatically built image from `Dockerhub <https://registry.hub.docker.com/u/afirth/ga4gh-server/>`_
* start an apache server running mod_wsgi on container port 80
* mount your data read-only to the docker container
* assign a name to the container
* forward port 8000 to the container.

For more information on docker run options, see the `run reference <https://docs.docker.com/reference/run/>`_.

**Demo Dataset Inside Container**

If you do not have a dataset yet, you can deploy a container which includes the demo data:

.. code-block:: bash

  $ docker run -d -p 8000:80 --name ga4gh_demo afirth/ga4gh-server:develop-demo

This is identical to the production container, except that a copy of the demo data is included and appropriate defaults are set.

**Developing Client Code: Run a Client Container and a Server**

In this example you run a server as a daemon in one container, and the client as an ephemeral instance in another container.
From the client, the server is accessible at ``http://server/``, and the ``/tmp/mydev`` directory is mounted at ``/app/mydev/``. Any changes you make to scripts in ``mydev`` will be reflected on the host and container and persist even after the container dies.

.. code-block:: bash

  #make a development dir and place the example client script in it
  $ mkdir /tmp/mydev
  $ curl https://raw.githubusercontent.com/ga4gh/server/develop/scripts/demo_example.py > /tmp/mydev/demo_example.py
  $ chmod +x /tmp/mydev/demo_example.py

  # start the server daemon
  # assumes the demo data on host at /my/ga4gh_data
  $ docker run -e GA4GH_DEBUG=True -e GA4GH_DATA_SOURCE=/data -v /my/ga4gh_data/:/data:ro -d --name ga4gh_server afirth/ga4gh-server:latest

  # start the client and drop into a bash shell, with mydev/ mounted read/write
  # --link adds a host entry for server, and --rm destroys the container when you exit
  $ docker run -e GA4GH_DEBUG=True -v /tmp/mydev/:/app/mydev:rw -it --name ga4gh_client --link ga4gh_server:server --entrypoint=/bin/bash --rm afirth/ga4gh-server:latest

  # call the client code script
  root@md5:/app# ./mydev/demo_example.py

  # call the command line client
  root@md5:/app# ga4gh_client variantsets-search http://server/current

  #exit and destroy the client container
  root@md5:/app# exit

**Ports**

The ``-p 8000:80`` argument to ``docker run`` will run the docker container in the background, and translate calls from your host environment
port 8000 to the docker container port 80. At that point you should be able to access it like a normal website, albeit on port 8000.
Running in `boot2docker <http://boot2docker.io/>`_, you will need to forward the port from the boot2docker VM to the host.
From a terminal on the host to forward traffic from localhost:8000 to the VM 8000 on OSX:

.. code-block:: bash

  $ VBoxManage controlvm boot2docker-vm natpf1 "ga4gh,tcp,127.0.0.1,8000,,8000"

For more info on port forwarding see `the VirtualBox manual <https://www.virtualbox.org/manual/ch06.html#natforward>`_ and this `wiki article <https://github.com/CenturyLinkLabs/panamax-ui/wiki/How-To%3A-Port-Forwarding-on-VirtualBox>`_.

++++++++
Advanced
++++++++

If you want to build the images yourself, that is possible. The `afirth/ga4gh-server repo <https://registry.hub.docker.com/u/afirth/ga4gh-server/>`_
builds automatically on new commits, so this is only needed if you want to modify the Dockerfiles, or build from a different source.

The prod and demo builds are based off of `mod_wsgi-docker <https://github.com/GrahamDumpleton/mod_wsgi-docker>`_, a project from the author of mod_wsgi.
Please reference the Dockerfiles and documentation for that project during development on these builds.

**Examples**

Build the code at server/ and run for production, serving a dataset on local host located at ``/my/dataset``

.. code-block:: bash

 $ cd server/
 $ docker build -t my-repo/my-image .
 $ docker run -e GA4GH_DATA_SOURCE=/dataset -v /my/dataset:/dataset:ro -itd -p 8000:80 --name ga4gh_server my-repo/my-image

Build and run the production build from above, with the demo dataset in the container
(you will need to modify the FROM line in ``/deploy/variants/demo/Dockerfile`` if you want to use your image from above as the base):

.. code-block:: bash

 $ cd server/deploy/variants/demo
 $ docker build -t my-repo/my-demo-image .
 $ docker run -itd -p 8000:80 --name ga4gh_demo my-repo/my-demo-image

**Variants**

Other Dockerfile implementations are available in the variants folder which install manually.
To build one of these images:

.. code-block:: bash

 $ cd server/deploy/variants/xxxx
 $ docker build -t my-repo/my-image .
 $ docker run -itd -p 8000:80 --name my_container my-repo/my-image

++++++++++++++++++++++
Troubleshooting Docker
++++++++++++++++++++++

**DNS**

The docker daemon's DNS may be corrupted if you switch networks, especially if run in a VM.
For boot2docker, running udhcpc on the VM usually fixes it.
From a terminal on the host:

.. code-block:: bash

  $ eval "$(boot2docker shellinit)"
  $ boot2docker ssh
  >	sudo udhcpc
  (password is tcuser)

**DEBUG**

To enable DEBUG on your docker server, call docker run with ``-e GA4GH_DEBUG=True``

.. code-block:: bash

  $ docker run -itd -p 8000:80 --name ga4gh_demo -e GA4GH_DEBUG=True afirth/ga4gh-server:develop-demo

This will set the environment variable which is read by config.py

You can then get logs from the docker container by running ``docker logs (container)`` e.g. ``docker logs ga4gh_demo``


text:
import * as React from "react";
import * as LiveSplit from "../livesplit";
import { gradientToCss } from "../util/ColorUtil";

export interface Props { state: LiveSplit.BlankSpaceComponentStateJson }

export default class BlankSpace extends React.Component<Props> {
    public render() {
        return (
            <div
                className="blank-space"
                style={{
                    height: this.props.state.height,
                    background: gradientToCss(this.props.state.background),
                }}
            />
        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _6.Prototype
{
    public abstract class BmwPrototype
    {
        public abstract Bmw Clone();
    }
}


text:
module.exports = function(err, res) {
  console.log(err);
  res.status(500).json({info: 'error'});
};


text:
InsecureBankv2 Readme
==========

This is a major update to one of my previous projects - "InsecureBank". This vulnerable Android application is named "InsecureBankv2" and is made for security enthusiasts and developers to learn the Android insecurities by testing this vulnerable application. Its back-end server component is written in python. The client component i.e. the Android InsecureBank.apk can be downloaded along with the source. The list of vulnerabilities that are currently included in this release are:

* Flawed Broadcast Receivers
* Weak Authorization mechanism
* Local Encryption issues
* Vulnerable Activity Components
* Root Detection and Bypass
* Insecure Content Provider access
* Insecure Webview implementation
* Weak Cryptography implementation
* Application Patching
* Sensitive Information in Memory
* Insecure Logging mechanism
* Android Pasteboard vulnerability
* Application Debuggable
* Android keyboard cache issues
* Android Backup vulnerability
* Runtime Manipulation
* Insecure SDCard storage
* Insecure HTTP connections
* Parameter Manipulation
* Hardcoded secrets
* Username Enumeration issue
* Developer Backdoors
* Weak change password implementation

Below are some of the other vulnerabilities that I am working on currently - and will be added as soon as I make sure that it does not break any of the other existing features:
* Local SQL Injection
* SMS based Denial-Of-Service
* LockScreen Bypass


text:
package pow.backend.action;

import pow.backend.event.GameEvent;

import java.util.*;

public class ActionResult {
    public final List<GameEvent> events;
    public final List<Action> derivedActions;
    public final boolean succeeded;

    private ActionResult(List<GameEvent> events, List<Action> derivedActions, boolean succeeded) {
        this.events = events;
        this.derivedActions = derivedActions;
        this.succeeded = succeeded;
    }

    public static ActionResult succeeded(List<GameEvent> events) {
        return new ActionResult(events, Collections.emptyList(), true);
    }

    public static ActionResult succeeded(GameEvent event) {
        return new ActionResult(Collections.singletonList(event), Collections.emptyList(), true);
    }

    public static ActionResult succeeded() {
        return new ActionResult(Collections.emptyList(), Collections.emptyList(), true);
    }

    public static ActionResult failed(List<Action> derivedActions) {
        return new ActionResult(Collections.emptyList(), derivedActions, false);
    }

    public static ActionResult failed(Action derivedAction) {
        return new ActionResult(Collections.emptyList(), Collections.singletonList(derivedAction), false);
    }

    public static ActionResult failed() {
        return new ActionResult(Collections.emptyList(), Collections.emptyList(), false);
    }
}


text:
#ifndef LD24_LEVEL_HPP
#define LD24_LEVEL_HPP
#include <vector>
#include <stddef.h>
namespace LD24 {
class GameScreen;

class Level {
    const char *const *m_allTips;
    unsigned m_tipflag;

    void setTipFlags(unsigned flags);

public:
    GameScreen &screen;
    std::vector<const char *> levelTips;

    Level(GameScreen &s, const char *const *tips=NULL)
        : m_allTips(tips), m_tipflag(0), screen(s)
    { }

    virtual ~Level();

    /* Advance one frame, 8 milliseconds.  The controls are the FLAG
       constant above, combined to show which buttons the user has
       down.  */
    virtual void advance(unsigned msec, int controls) = 0;

    /* Draw the frame (frac is milliseconds since 'advance') */
    virtual void draw(int frac) = 0;

    void nextLevel();

    void addTip(int index);
    void removeTip(int index);
};

}
#endif


text:
mod block;
mod gpu;
mod handler;
mod virtio_device;

use remain::sorted;
use thiserror::Error as ThisError;
use virtio_device::QueueSizes;
pub use virtio_device::VhostUserVirtioDevice;
use vm_memory::GuestMemoryError;
use vmm_vhost::message::VhostUserProtocolFeatures;
use vmm_vhost::Error as VhostError;

pub use self::block::*;
pub use self::gpu::*;
pub use self::handler::VhostUserHandler;

cfg_if::cfg_if! {
    if #[cfg(unix)] {
        mod console;
        mod fs;
        mod mac80211_hwsim;
        mod net;
        mod snd;
        mod vsock;
        mod wl;
        mod video;

        pub use self::snd::*;
        pub use self::vsock::*;
        pub use self::wl::*;
        pub use self::net::*;
        pub use self::mac80211_hwsim::*;
        pub use self::console::*;
        pub use self::fs::*;
        pub use self::video::*;

        pub type Connection = std::os::unix::net::UnixStream;
    } else if #[cfg(windows)] {
        #[cfg(feature = "slirp")]
        pub mod net;

        #[cfg(feature = "slirp")]
        pub use self::net::*;

        pub type Connection = base::Tube;
    }
}

#[sorted]
#[derive(ThisError, Debug)]
pub enum Error {
    /// Failed to copy config to a buffer.
    #[error("failed to copy config to a buffer: {0}")]
    CopyConfig(std::io::Error),
    /// Failed to create backend request handler
    #[error("could not create backend req handler: {0}")]
    CreateBackendReqHandler(VhostError),
    /// Failed to create `base::Event`.
    #[error("failed to create Event: {0}")]
    CreateEvent(base::Error),
    /// Failed to get config.
    #[error("failed to get config: {0}")]
    GetConfig(VhostError),
    /// Failed to get features.
    #[error("failed to get features: {0}")]
    GetFeatures(VhostError),
    /// Failed to get host address.
    #[error("failed to get host address: {0}")]
    GetHostAddress(GuestMemoryError),
    /// Failed to get protocol features.
    #[error("failed to get protocol features: {0}")]
    GetProtocolFeatures(VhostError),
    /// Failed to get number of queues.
    #[error("failed to get number of queues: {0}")]
    GetQueueNum(VhostError),
    /// Failed to get vring base offset.
    #[error("failed to get vring base offset: {0}")]
    GetVringBase(VhostError),
    /// Invalid config length is given.
    #[error("invalid config length is given: {0}")]
    InvalidConfigLen(usize),
    /// Invalid config offset is given.
    #[error("invalid config offset is given: {0}")]
    InvalidConfigOffset(u64),
    /// MSI-X config is unavailable.
    #[error("MSI-X config is unavailable")]
    MsixConfigUnavailable,
    /// MSI-X irqfd is unavailable.
    #[error("MSI-X irqfd is unavailable")]
    MsixIrqfdUnavailable,
    #[error("protocol feature is not negotiated: {0:?}")]
    ProtocolFeatureNotNegoiated(VhostUserProtocolFeatures),
    /// Failed to reset owner.
    #[error("failed to reset owner: {0}")]
    ResetOwner(VhostError),
    /// Failed to set config.
    #[error("failed to set config: {0}")]
    SetConfig(VhostError),
    /// Failed to set device request channel.
    #[error("failed to set device request channel: {0}")]
    SetDeviceRequestChannel(VhostError),
    /// Failed to set features.
    #[error("failed to set features: {0}")]
    SetFeatures(VhostError),
    /// Failed to set memory map regions.
    #[error("failed to set memory map regions: {0}")]
    SetMemTable(VhostError),
    /// Failed to set owner.
    #[error("failed to set owner: {0}")]
    SetOwner(VhostError),
    /// Failed to set protocol features.
    #[error("failed to set protocol features: {0}")]
    SetProtocolFeatures(VhostError),
    /// Failed to set vring address.
    #[error("failed to set vring address: {0}")]
    SetVringAddr(VhostError),
    /// Failed to set vring base offset.
    #[error("failed to set vring base offset: {0}")]
    SetVringBase(VhostError),
    /// Failed to set eventfd to signal used vring buffers.
    #[error("failed to set eventfd to signal used vring buffers: {0}")]
    SetVringCall(VhostError),
    /// Failed to enable or disable vring.
    #[error("failed to enable or disable vring: {0}")]
    SetVringEnable(VhostError),
    /// Failed to set eventfd for adding buffers to vring.
    #[error("failed to set eventfd for adding buffers to vring: {0}")]
    SetVringKick(VhostError),
    /// Failed to set the size of the queue.
    #[error("failed to set the size of the queue: {0}")]
    SetVringNum(VhostError),
    /// Error getting the shmem regions.
    #[error("failed to enumerate shmem regions {0}")]
    ShmemRegions(VhostError),
    /// Failed to connect socket.
    #[error("failed to connect socket: {0}")]
    SocketConnect(std::io::Error),
    /// Failed to create Master from a UDS path.
    #[error("failed to connect to device socket while creating instance: {0}")]
    SocketConnectOnMasterCreate(VhostError),
    /// Failed to spawn worker thread.
    #[error("failed to spawn worker: {0}")]
    SpawnWorker(std::io::Error),
    /// The tag for the Fs device was too long to fit in the config space.
    #[error("tag is too long: {len} > {max}")]
    TagTooLong { len: usize, max: usize },
    /// Too many shmem regions.
    #[error("too many shmem regions: {0} > 1")]
    TooManyShmemRegions(usize),
}

pub type Result<T> = std::result::Result<T, Error>;


text:
package au.com.dius.pact.consumer;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConsumerClient{
    private String url;

    public ConsumerClient(String url) {
        this.url = url;
    }

    public Map getAsMap(String path) throws IOException {
        return jsonToMap(Request.Get(url + path)
                .addHeader("testreqheader", "testreqheadervalue")
                .execute().returnContent().asString());
    }

	public List getAsList(String path) throws IOException {
		return jsonToList(Request.Get(url + path)
				.addHeader("testreqheader", "testreqheadervalue")
				.execute().returnContent().asString());
	}

    public Map post(String path, String body, ContentType mimeType) throws IOException {
        String respBody = Request.Post(url + path)
                .addHeader("testreqheader", "testreqheadervalue")
                .bodyString(body, mimeType)
                .execute().returnContent().asString();
        return jsonToMap(respBody);
    }

    private HashMap jsonToMap(String respBody) throws IOException {
        return new ObjectMapper().readValue(respBody, HashMap.class);
    }

	private List jsonToList(String respBody) throws IOException {
		return new ObjectMapper().readValue(respBody, ArrayList.class);
	}

    public int options(String path) throws IOException {
        return Request.Options(url + path)
                .addHeader("testreqheader", "testreqheadervalue")
                .execute().returnResponse().getStatusLine().getStatusCode();
    }

    public String postBody(String path, String body, ContentType mimeType) throws IOException {
        return Request.Post(url + path)
            .bodyString(body, mimeType)
            .execute().returnContent().asString();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 Copyright (C) 2014 ZXing authors

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 -->
<resources>
  <string name="app_name">باركد خوان</string>
  <string name="app_picker_name">اپليكيشن</string>
  <string name="bookmark_picker_name">بوك مارك ها</string>
  <string name="button_add_calendar">افزودن به تقويم</string>
  <string name="button_add_contact">افزودن مخاطبان</string>
  <string name="button_book_search">جستجو كتاب</string>
  <string name="button_cancel">لغو</string>
  <string name="button_custom_product_search">جستجوي سفارشي</string>
  <string name="button_dial">شماره گيري تلفن</string>
  <string name="button_email">ارسال ايميل</string>
  <string name="button_get_directions">دريافت جهت</string>
  <string name="button_mms">ارسال MMS</string>
  <string name="button_ok">تاييد</string>
  <string name="button_open_browser">گشودن مرورگر</string>
  <string name="button_product_search">جستجوي محصول</string>
  <string name="button_search_book_contents">جستجو محتوا</string>
  <string name="button_share_app">برنامه</string>
  <string name="button_share_bookmark">بوك مارك</string>
  <string name="button_share_by_email">اشتراك گذاري با ايميل</string>
  <string name="button_share_by_sms">اشتراك گذاري با SMS</string>
  <string name="button_share_clipboard">حافظه موقت</string>
  <string name="button_share_contact">مخاطبان</string>
  <string name="button_show_map">نمايش نقشه</string>
  <string name="button_sms">ارسال SMS</string>
  <string name="button_web_search">جستجوي وب</string>
  <string name="button_wifi">اتصال به شبكه</string>
  <string name="contents_contact">اطلاعات تماس</string>
  <string name="contents_email">آدرس ايميل</string>
  <string name="contents_location">مختصات جغرافيايي</string>
  <string name="contents_phone">شماره تلفن</string>
  <string name="contents_sms">آدرس SMS</string>
  <string name="contents_text">متن خالي</string>
  <string name="history_clear_text">پاك كردن تاريخچه</string>
  <string name="history_clear_one_history_text">پاك كردن</string>
  <string name="history_email_title">تاريخچه باركد خوان</string>
  <string name="history_empty">خالي</string>
  <string name="history_empty_detail">هيچ باركد اسكن شده اي ثبت نشده است</string>
  <string name="history_send">تاريخچه ارسال</string>
  <string name="history_title">تاريخچه</string>
  <string name="menu_encode_mecard">استفاده از MECARD</string>
  <string name="menu_encode_vcard">استفاده از vCard</string>
  <string name="menu_help">راهنما و درباره پرو‍ژه ZXing</string>
  <string name="menu_history">تاريخچه</string>
  <string name="menu_settings">تنظيمات</string>
  <string name="menu_share">اشتراك گذاري</string>
  <string name="msg_bulk_mode_scanned">مد انبوه: باركد اسكن و ذخيره شد</string>
  <string name="msg_camera_framework_bug">دوربين اندرويد با مشكل مواجه شده است. لطفا دستگاه خود را ري ست نماييد</string>
  <string name="msg_default_format">قالب بندي</string>
  <string name="msg_default_meta">متاديتا</string>
  <string name="msg_default_mms_subject">سلام</string>
  <string name="msg_default_status">براي اسكن باركد ، باركد بايستي در داخل كادر مستطيلي قرار بگيرد</string>
  <string name="msg_default_time">زمان</string>
  <string name="msg_default_type">نوع</string>
  <string name="msg_encode_contents_failed">باركد قابل رمزگشايي نيست</string>
  <string name="msg_error">خطا</string>
  <string name="msg_google_books">Google</string>
  <string name="msg_google_product">Google</string>
  <string name="msg_intent_failed">اپليكيشن درخواست شده قابل دسترس نيست. احتمالا محتواي بار كد نامعتبر است</string>
  <string name="msg_invalid_value">مقدار نامعتبر</string>
  <string name="msg_redirect">انتقال</string>
  <string name="msg_sbc_book_not_searchable">كتاب خواسته شده قابل جستجو نيست</string>
  <string name="msg_sbc_failed">جستجو با مشكل مواجه شده است</string>
  <string name="msg_sbc_no_page_returned">صفحه اي دريافت نشد</string>
  <string name="msg_sbc_page">صفحه</string>
  <string name="msg_sbc_results">نتايج</string>
  <string name="msg_sbc_searching_book">جستجوي كتاب\u2026</string>
  <string name="msg_sbc_snippet_unavailable">چيزي در دسترس نيست</string>
  <string name="msg_share_explanation">شما مي توانيد با نمايش باركد در صفحه نمايش خود، و اسكن آن با موبايلي ديگر، اطلاعات را به اشتراك بگذاريد</string>
  <string name="msg_share_text">يا متني را تايپ كنيد و كليد Enter را بفشاريد</string>
  <string name="msg_sure">آيا شما اطمينان داريد؟</string>
  <string name="msg_unmount_usb">كارت SD در دسترس نيست</string>
  <string name="preferences_actions_title">زماني كه باركد يافت مي شود\u2026</string>
  <string name="preferences_auto_focus_title">از فوكوس اتوكاتيك استفاده نماييد</string>
  <string name="preferences_auto_open_web_title">باز كردن صفحات وب بطور اتوماتيك</string>
  <string name="preferences_bulk_mode_summary">تعداد زيادي باركد را به طور متوالي اسكن و ذخيره كن</string>
  <string name="preferences_bulk_mode_title">مد اسكن انبوه</string>
  <string name="preferences_copy_to_clipboard_title">كپي در حافظه موقت</string>
  <string name="preferences_custom_product_search_summary" formatted="false">Substitutions: %s = contents, %f = format, %t = type</string>
  <string name="preferences_custom_product_search_title">جستجوي سفارشي URL</string>
  <string name="preferences_decode_1D_industrial_title">1D صنعتي</string>
  <string name="preferences_decode_1D_product_title">1D كالا</string>
  <string name="preferences_decode_Aztec_title">Aztec</string>
  <string name="preferences_decode_Data_Matrix_title">Data Matrix</string>
  <string name="preferences_decode_PDF417_title">PDF417 (β)</string>
  <string name="preferences_decode_QR_title">كدهاي QR</string>
  <string name="preferences_device_bug_workarounds_title">رفع مشكلات و باگ هاي دستگاه</string>
  <string name="preferences_disable_barcode_scene_mode_title">مد بدون نمايش باركد</string>
  <string name="preferences_disable_continuous_focus_summary">تنها از مد فوكوس استاندارد استفاده نماييد</string>
  <string name="preferences_disable_continuous_focus_title">بدون فوكوس ممتد</string>
  <string name="preferences_disable_exposure_title">بدون exposure</string>
  <string name="preferences_disable_metering_title">بدون metering</string>
  <string name="preferences_front_light_summary">امكان بهبودي در اسكن كردن كدها در نورهاي كم. مي تواند موجب درخشندگي شود. در بعضي از تلفن ها پشتيباني مي شود.</string>
  <string name="preferences_front_light_title">استفاده از نور</string>
  <string name="preferences_front_light_auto">اتوماتيك</string>
  <string name="preferences_front_light_off">خاموش</string>
  <string name="preferences_front_light_on">روشن</string>
  <string name="preferences_general_title">تنظيمات عمومي</string>
  <string name="preferences_history_summary">ذخيره اسكن ها در تاريخچه</string>
  <string name="preferences_history_title">افزودن به تاريخچه</string>
  <string name="preferences_invert_scan_title">معكوس كردن اسكن</string>
  <string name="preferences_invert_scan_summary">اسكن باركد سفيد در پس زمينه مشكي. در بعضي از دستگاه ها پشتيباني نمي شود</string>
  <string name="preferences_name">تنظيمات</string>
  <string name="preferences_orientation_title">بدون دوران اتوماتيك</string>
  <string name="preferences_play_beep_title">بوق</string>
  <string name="preferences_remember_duplicates_summary">چندين اسكن از يك باركد را در تاريخچه ذخيره مي كند.</string>
  <string name="preferences_remember_duplicates_title">به ياد آوري تكرار ها</string>
  <string name="preferences_result_title">تنظيمات نتيجه بدست آمده</string>
  <string name="preferences_scanning_title">كدام نوع باركد قابل خواندن و رمزگشايي باشد\u2026</string>
  <string name="preferences_search_country">جستجوي كشور</string>
  <string name="preferences_supplemental_summary">تلاش در بدست آوردن اطلاعات بيشتر در مورد محتواي باركد</string>
  <string name="preferences_supplemental_title">بازيابي اطلاعات بيشتر</string>
  <string name="preferences_vibrate_title">لرزش</string>
  <string name="result_address_book">اطلاعات تماس يافته شده</string>
  <string name="result_calendar">رويداد تقويمي يافته شده</string>
  <string name="result_email_address">آدرس ايميل يافته شده</string>
  <string name="result_geo">مختصات جغرافيايي يافته شده</string>
  <string name="result_isbn">كتاب يافته شده</string>
  <string name="result_product">محصول يافته شده</string>
  <string name="result_sms">آدرس SMS يافته شده</string>
  <string name="result_tel">شماره تلفن يافته شده</string>
  <string name="result_text">متن يافته شده</string>
  <string name="result_uri">URL يافته شده</string>
  <string name="result_wifi">پيكربندي WLAN يافته شده</string>
  <string name="sbc_name">جستجو در گوگل بوك</string>
  <string name="wifi_changing_network">درخواست اتصال به شبكه\u2026</string>
</resources>


text:
seqan::ArgumentParser::ParseResult
parseCommandLine(MasonFragmentSequencingOptions & options, int argc, char const ** argv)
{
    // Setup ArgumentParser.
    seqan::ArgumentParser parser("mason_frag_sequencing");
    // Set short description, version, and date.
    setShortDescription(parser, "Fragment Sequencing Simulation");
    setVersion(parser, "2.1");
    setDate(parser, "March 2013");
    setCategory(parser, "Simulators");

    // Define usage line and long description.
    addUsageLine(parser, "[\\fIOPTIONS\\fP] \\fB-i\\fP \\fIIN.fa\\fP \\fB-o\\fP \\fIOUT.{fa,fq}\\fP "
                 "[\\fB-or\\fP \\fIOUT2.{fa,fq}\\fP]");
    addDescription(parser,
                   "Given a FASTA file with fragments, simulate sequencing thereof.");
    addDescription(parser,
                   "This program is a more lightweight version of mason_sequencing without support for the "
                   "application of VCF and fragment sampling.  Output of SAM is also not available.  However, "
                   "it uses the same code for the simulation of the reads as the more powerful mason_simulator.");
    addDescription(parser,
                   "You can use mason_frag_sequencing if you want to implement you rown fragmentation behaviour, e.g. "
                   "if you have implemented your own bias models.");

    // Add option and text sections.
    options.addOptions(parser);
    options.addTextSections(parser);

    // Parse command line.
    seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv);

    // Only extract  options if the program will continue after parseCommandLine()
    if (res != seqan::ArgumentParser::PARSE_OK)
        return res;

    options.getOptionValues(parser);

    return seqan::ArgumentParser::PARSE_OK;
}

// --------------------------------------------------------------------------
// Function main()
// --------------------------------------------------------------------------

// Program entry point.

int main(int argc, char const ** argv)
{
    // Parse the command line.
    MasonFragmentSequencingOptions options;
    seqan::ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv);
    if (res != seqan::ArgumentParser::PARSE_OK)
        return res == seqan::ArgumentParser::PARSE_ERROR;

    std::cerr << "MASON SEQUENCING SIMULATOR\n"
              << "==========================\n\n";

    // Print the command line arguments back to the user.
    if (options.verbosity > 0)
    {
        std::cerr << "__OPTIONS____________________________________________________________________\n"
                  << '\n';
        options.print(std::cerr);
    }

    std::cerr << "\n__PREPARATION________________________________________________________________\n"
              << "\n";

    // Open fragments FASTA file.
    std::cerr << "Opening fragments       " << options.inputFileName << " ...";
    seqan::SequenceStream inFragments(toCString(options.inputFileName));
    if (!isGood(inFragments))
    {
        std::cerr << " ERROR\n"
                  << "Could not open " << options.inputFileName << "\n";
        return 1;
    }
    std::cerr << " OK\n";

    // Open reads output file.
    std::cerr << "Opening output file (L) " << options.outFileNameLeft << " ...";
    seqan::SequenceStream outReads(toCString(options.outFileNameLeft), seqan::SequenceStream::WRITE);
    if (!isGood(outReads))
    {
        std::cerr << " ERROR\n"
                  << "Could not open " << options.outFileNameLeft << "\n";
        return 1;
    }
    std::cerr << " OK\n";

    // Open output file for the right reads.
    seqan::SequenceStream outReadsRight;
    if (!empty(options.outFileNameRight))
    {
        std::cerr << "Opening output file (R) " << options.outFileNameRight << " ...";
        open(outReadsRight, toCString(options.outFileNameRight), seqan::SequenceStream::WRITE);
        if (!isGood(outReadsRight))
        {
            std::cerr << " ERROR\n"
                      << "Could not open " << options.outFileNameRight << "\n";
            return 1;
        }
        std::cerr << " OK\n";
    }

    // Configure output streams to write out each sequence in a single line.
    outReads.outputOptions.lineLength = 0;
    outReadsRight.outputOptions.lineLength = 0;

    // Perform genome simulation.
    std::cerr << "\n__SIMULATING READS___________________________________________________________\n"
              << "\n"
              << "Simulating reads ...";

    TRng rng(options.seed);
    TRng ignoredMethRng(0);

    // Create sequencing simulator.
    SequencingSimulatorFactory simFactory(rng, ignoredMethRng, options.seqOptions, options.illuminaOptions,
                                          options.rocheOptions, options.sangerOptions);
    std::SEQAN_AUTO_PTR_NAME<SequencingSimulator> sim = simFactory.make();

    // Buffers for reading in fragments.
    seqan::CharString fragId;
    seqan::Dna5String fragSeq;
    // Buffers for simulated reads.
    seqan::Dna5String seqL, seqR;
    seqan::CharString qualsL, qualsR;
    // The information for storing the simulation info.
    SequencingSimulationInfo simInfoL, simInfoR;

    // We will use these string streams to generate the read identifier strings.
    std::stringstream ssL, ssR;

    for (unsigned readId = 1; !atEnd(inFragments); ++readId)
    {
        // Reset the string streams.
        ssL.str("");
        ssL.clear();
        ssR.str("");
        ssR.clear();

        // Read fragment to simulate from.
        if (readRecord(fragId, fragSeq, inFragments) != 0)
            return 1;

        if (empty(options.outFileNameRight))  // Single-end sequencing.
        {
            sim->simulateSingleEnd(seqL, qualsL, simInfoL, infix(fragSeq, 0, length(fragSeq)));
            ssL << options.seqOptions.readNamePrefix << readId;
            if (options.seqOptions.embedReadInfo)
            {
                ssL << ' ';
                simInfoL.serialize(ssL);
            }
            if (writeRecord(outReads, ssL.str(), seqL, qualsL) != 0)
            {
                std::cerr << "ERROR writing to " << options.outFileNameLeft << "\n";
                return 1;
            }
        }
        else  // Paired sequencing.
        {
            sim->simulatePairedEnd(seqL, qualsL, simInfoL, seqR, qualsR, simInfoR, infix(fragSeq, 0, length(fragSeq)));
            ssL << options.seqOptions.readNamePrefix << readId;
            ssR << options.seqOptions.readNamePrefix << readId;
            if (options.seqOptions.embedReadInfo)
            {
                ssL << ' ';
                simInfoL.serialize(ssL);
                ssR << ' ';
                simInfoR.serialize(ssR);
            }

            // std::cerr << seqL << "\t" << qualsL << "\n"
            //           << seqR << "\t" << qualsR << "\n\n";

            if (writeRecord(outReads, ssL.str(), seqL, qualsL) != 0)
            {
                std::cerr << "ERROR writing to " << options.outFileNameLeft << "\n";
                return 1;
            }
            if (writeRecord(outReadsRight, ssR.str(), seqR, qualsR) != 0)
            {
                std::cerr << "ERROR writing to " << options.outFileNameRight << "\n";
                return 1;
            }
        }
    }

    std::cerr << " OK\n";

    std::cerr << "\nDONE.\n";
    return 0;
}


text:
// Generated by CoffeeScript 1.6.3
var arr;

arr = ["./libs/jquery.js", "./libs/sugar.js", "./libs/oj.js", "./libs/easings.js", "./libs/dirty.js", "./libs/cryptojs.min.js"];

head.js.apply(this, arr);

head(function() {
  var change_text, decrypt, encrypt, iv, salt, txt;
  oj.useGlobally();
  iv = "c7cce0d166262006761b014859b6189998e4277a";
  salt = "s club.. there aint no party like an s-club party";
  encrypt = function(plainText) {
    var ciphertext, encrypted, key, password;
    password = $("#password").val();
    key = CryptoJS.PBKDF2(password, CryptoJS.enc.Hex.parse(salt), {
      keySize: this.keySize,
      iterations: this.iterationCount
    });
    encrypted = CryptoJS.AES.encrypt(plainText, key, {
      iv: CryptoJS.enc.Hex.parse(iv)
    });
    ciphertext = encrypted.ciphertext.toString(CryptoJS.enc.Base64);
    return ciphertext;
  };
  decrypt = function(ciphertext) {
    var cipherParams, decrypted, funya, key, password;
    password = $("#password").val();
    key = CryptoJS.PBKDF2(password, CryptoJS.enc.Hex.parse(salt), {
      keySize: this.keySize,
      iterations: this.iterationCount
    });
    cipherParams = CryptoJS.lib.CipherParams.create({
      ciphertext: CryptoJS.enc.Base64.parse(ciphertext)
    });
    decrypted = CryptoJS.AES.decrypt(cipherParams, key, {
      iv: CryptoJS.enc.Hex.parse(iv)
    });
    return funya = decrypted.toString(CryptoJS.enc.Utf8);
  };
  change_text = function() {
    var ciphertext, plainText, real;
    plainText = $("#text").val();
    ciphertext = encrypt(plainText);
    $("#mixed").val(ciphertext);
    real = decrypt(ciphertext);
    return $("#third").val(real);
  };
  txt = "All the speeches and commentaries betray a gigantic abreaction to the event itself and to the fascination that it exerts. Moral condemnation and the sacred union against terrorism are equal to the prodigious jubilation engendered by witnessing this global superpower being destroyed; better, by seeing it more or less self-destroying, even suiciding spectacularly. Though it is (this superpower) that has, through its unbearable power, engendered all that violence brewing around the world, and therefore this terrorist imagination which -- unknowingly -- inhabits us all.";
  return $("#main").oj(div(function() {
    var h;
    h = window.innerHeight - 80;
    h2(function() {
      return "Frowwn";
    });
    input({
      id: "password",
      type: "text",
      value: "password",
      style: "color:grey; font-size:22px; height:30px; border-radius:4px; border:1px solid steelblue;",
      keyup: function() {
        return change_text();
      }
    });
    return table({
      style: "width:100%; height:" + h + "px; "
    }, function() {
      return tr({
        style: "width:100%; height:100%; "
      }, function() {
        td(function() {
          return textarea({
            id: "text",
            style: "width:100%; height:" + h + "px; font-size:22px;",
            keyup: function() {
              return encrypt();
            }
          }, function() {
            return txt;
          });
        });
        td(function() {
          return textarea({
            id: "mixed",
            style: "width:100%; height:" + h + "px; font-size:22px;"
          });
        });
        return td(function() {
          return textarea({
            id: "third",
            style: "width:100%; height:" + h + "px; font-size:22px;"
          });
        });
      });
    });
  }));
});

/*
//@ sourceMappingURL=index.map
*/


text:
(function() {
  var _, pluralize, utilities;

  _ = require('lodash');

  pluralize = require('pluralize');

  utilities = {
    pluralKebabCase: function(str) {
      var kebabCaseStr, lastWord, match;
      kebabCaseStr = _.kebabCase(str);
      match = kebabCaseStr.match(/-(\w+)$/);
      if (match) {
        lastWord = match[1];
      } else {
        lastWord = kebabCaseStr;
      }
      return kebabCaseStr.replace(new RegExp(lastWord + '$'), pluralize(lastWord));
    },
    objectToQueryString: function(obj, prefix) {
      var k, p, str, v;
      str = [];
      for (p in obj) {
        if (obj.hasOwnProperty(p)) {
          k = prefix ? prefix + '[' + p + ']' : p;
          v = obj[p];
          str.push(typeof v === 'object' ? this.objectToQueryString(v, k) : encodeURIComponent(k) + '=' + encodeURIComponent(v));
        }
      }
      return str.join('&');
    }
  };

  module.exports = utilities;

}).call(this);


text:
package com.github.vvinston.functional;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Predicate;

public final class EitherFunction<INPUT, RESULT1, RESULT2> implements Function<INPUT, Either<RESULT1, RESULT2>> {
    private final Predicate<INPUT> predicate;
    private final Function<INPUT, RESULT1> leftFunction;
    private final Function<INPUT, RESULT2> rightFunction;

    public EitherFunction(
            @Nonnull final Predicate<INPUT> predicate,
            @Nonnull final Function<INPUT, RESULT1> leftFunction,
            @Nonnull final Function<INPUT, RESULT2> rightFunction) {
        this.predicate = Objects.requireNonNull(predicate);
        this.leftFunction = Objects.requireNonNull(leftFunction);
        this.rightFunction = Objects.requireNonNull(rightFunction);
    }

    @Override
    public Either<RESULT1, RESULT2> apply(@Nullable final INPUT input) {
        return predicate.test(input)
                ? Either.left(leftFunction.apply(input))
                : Either.right(rightFunction.apply(input));
    }
}


text:
package com.wlh.wpd.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value="/rest")
public class RestController {

	@RequestMapping(value="/user/{id}",method=RequestMethod.GET)
    public String get(@PathVariable("id") Integer id){
        System.out.println("get"+id);
        return "/hello";
    }

    @RequestMapping(value="/user",method=RequestMethod.POST)
    public String post(){
        System.out.println("post");
        return "/hello";
    }

    @RequestMapping(value="/user/{id}",method=RequestMethod.PUT)
    public String put(@PathVariable("id") Integer id){
        System.out.println("put"+id);
        return "/hello";
    }

    @RequestMapping(value="/user/{id}",method=RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        System.out.println("delete"+id);
        return "/hello";
    }

}


text:
.. _example-app:

Example app
===========

We'll be building a simple *twitter*-like site. The source code for the example
can be found in the ``examples/twitter`` directory. You can also `browse the
source-code <https://github.com/coleifer/peewee/tree/master/examples/twitter>`_
on github. There is also an example `blog app
<https://github.com/coleifer/peewee/tree/master/examples/blog>`_ if that's more
to your liking, however it is not covered in this guide.

The example app uses the `flask <http://flask.pocoo.org/>`_ web framework which
is very easy to get started with. If you don't have flask already, you will
need to install it to run the example:

.. code-block:: console

    pip install flask

Running the example
-------------------

.. image:: tweepee.jpg

After ensuring that flask is installed, ``cd`` into the twitter example
directory and execute the ``run_example.py`` script:

.. code-block:: console

    python run_example.py

The example app will be accessible at http://localhost:5000/

Diving into the code
--------------------

For simplicity all example code is contained within a single module,
``examples/twitter/app.py``. For a guide on structuring larger Flask apps with
peewee, check out `Structuring Flask Apps
<https://charlesleifer.com/blog/structuring-flask-apps-a-how-to-for-those-coming-from-django/>`_.

.. _example-app-models:

Models
^^^^^^

In the spirit of the popular web framework Django, peewee uses declarative
model definitions. If you're not familiar with Django, the idea is that you
declare a model class for each table. The model class then defines one or more
field attributes which correspond to the table's columns. For the twitter
clone, there are just three models:

*User*:
    Represents a user account and stores the username and password, an email
    address for generating avatars using *gravatar*, and a datetime field
    indicating when that account was created.

*Relationship*:
    This is a utility model that contains two foreign-keys to
    the *User* model and stores which users follow one another.

*Message*:
    Analogous to a tweet. The Message model stores the text content of
    the tweet, when it was created, and who posted it (foreign key to User).

If you like UML, these are the tables and relationships:

.. image:: schema.jpg

In order to create these models we need to instantiate a
:py:class:`SqliteDatabase` object. Then we define our model classes, specifying
the columns as :py:class:`Field` instances on the class.

.. code-block:: python

    # create a peewee database instance -- our models will use this database to
    # persist information
    database = SqliteDatabase(DATABASE)

    # model definitions -- the standard "pattern" is to define a base model class
    # that specifies which database to use.  then, any subclasses will automatically
    # use the correct storage.
    class BaseModel(Model):
        class Meta:
            database = database

    # the user model specifies its fields (or columns) declaratively, like django
    class User(BaseModel):
        username = CharField(unique=True)
        password = CharField()
        email = CharField()
        join_date = DateTimeField()

    # this model contains two foreign keys to user -- it essentially allows us to
    # model a "many-to-many" relationship between users.  by querying and joining
    # on different columns we can expose who a user is "related to" and who is
    # "related to" a given user
    class Relationship(BaseModel):
        from_user = ForeignKeyField(User, backref='relationships')
        to_user = ForeignKeyField(User, backref='related_to')

        class Meta:
            # `indexes` is a tuple of 2-tuples, where the 2-tuples are
            # a tuple of column names to index and a boolean indicating
            # whether the index is unique or not.
            indexes = (
                # Specify a unique multi-column index on from/to-user.
                (('from_user', 'to_user'), True),
            )

    # a dead simple one-to-many relationship: one user has 0..n messages, exposed by
    # the foreign key.  because we didn't specify, a users messages will be accessible
    # as a special attribute, User.messages
    class Message(BaseModel):
        user = ForeignKeyField(User, backref='messages')
        content = TextField()
        pub_date = DateTimeField()

.. note::
    Note that we create a *BaseModel* class that simply defines what database
    we would like to use.  All other models then extend this class and will also
    use the correct database connection.

Peewee supports many different :ref:`field types <fields>` which map to
different column types commonly supported by database engines.  Conversion
between python types and those used in the database is handled transparently,
allowing you to use the following in your application:

* Strings (unicode or otherwise)
* Integers, floats, and ``Decimal`` numbers.
* Boolean values
* Dates, times and datetimes
* ``None`` (NULL)
* Binary data

Creating tables
^^^^^^^^^^^^^^^

In order to start using the models, its necessary to create the tables. This is
a one-time operation and can be done quickly using the interactive interpreter.
We can create a small helper function to accomplish this:

.. code-block:: python

    def create_tables():
        with database:
            database.create_tables([User, Relationship, Message])

Open a python shell in the directory alongside the example app and execute the
following:

.. code-block:: python

    >>> from app import *
    >>> create_tables()

.. note::
    If you encounter an *ImportError* it means that either *flask* or *peewee*
    was not found and may not be installed correctly. Check the :ref:`installation`
    document for instructions on installing peewee.

Every model has a :py:meth:`~Model.create_table` classmethod which runs a SQL
*CREATE TABLE* statement in the database. This method will create the table,
including all columns, foreign-key constraints, indexes, and sequences. Usually
this is something you'll only do once, whenever a new model is added.

Peewee provides a helper method :py:meth:`Database.create_tables` which will
resolve inter-model dependencies and call :py:meth:`~Model.create_table` on
each model, ensuring the tables are created in order.

.. note::
    Adding fields after the table has been created will require you to
    either drop the table and re-create it or manually add the columns
    using an *ALTER TABLE* query.

    Alternatively, you can use the :ref:`schema migrations <migrate>` extension
    to alter your database schema using Python.

Establishing a database connection
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

You may have noticed in the above model code that there is a class defined on
the base model named *Meta* that sets the ``database`` attribute. Peewee allows
every model to specify which database it uses. There are many :ref:`Meta
options <model-options>` you can specify which control the behavior of your
model.

This is a peewee idiom:

.. code-block:: python

    DATABASE = 'tweepee.db'

    # Create a database instance that will manage the connection and
    # execute queries
    database = SqliteDatabase(DATABASE)

    # Create a base-class all our models will inherit, which defines
    # the database we'll be using.
    class BaseModel(Model):
        class Meta:
            database = database

When developing a web application, it's common to open a connection when a
request starts, and close it when the response is returned. **You should always
manage your connections explicitly**. For instance, if you are using a
:ref:`connection pool <pool>`, connections will only be recycled correctly if
you call :py:meth:`~Database.connect` and :py:meth:`~Database.close`.

We will tell flask that during the request/response cycle we need to create a
connection to the database. Flask provides some handy decorators to make this a
snap:

.. code-block:: python

    @app.before_request
    def before_request():
        database.connect()

    @app.after_request
    def after_request(response):
        database.close()
        return response

.. note::
    Peewee uses thread local storage to manage connection state, so this
    pattern can be used with multi-threaded WSGI servers.

Making queries
^^^^^^^^^^^^^^

In the *User* model there are a few instance methods that encapsulate some
user-specific functionality:

* ``following()``: who is this user following?
* ``followers()``: who is following this user?

These methods are similar in their implementation but with an important
difference in the SQL *JOIN* and *WHERE* clauses:

.. code-block:: python

    def following(self):
        # query other users through the "relationship" table
        return (User
                .select()
                .join(Relationship, on=Relationship.to_user)
                .where(Relationship.from_user == self)
                .order_by(User.username))

    def followers(self):
        return (User
                .select()
                .join(Relationship, on=Relationship.from_user)
                .where(Relationship.to_user == self)
                .order_by(User.username))

Creating new objects
^^^^^^^^^^^^^^^^^^^^

When a new user wants to join the site we need to make sure the username is
available, and if so, create a new *User* record. Looking at the *join()* view,
we can see that our application attempts to create the User using
:py:meth:`Model.create`. We defined the *User.username* field with a unique
constraint, so if the username is taken the database will raise an
``IntegrityError``.

.. code-block:: python

    try:
        with database.atomic():
            # Attempt to create the user. If the username is taken, due to the
            # unique constraint, the database will raise an IntegrityError.
            user = User.create(
                username=request.form['username'],
                password=md5(request.form['password']).hexdigest(),
                email=request.form['email'],
                join_date=datetime.datetime.now())

        # mark the user as being 'authenticated' by setting the session vars
        auth_user(user)
        return redirect(url_for('homepage'))

    except IntegrityError:
        flash('That username is already taken')

We will use a similar approach when a user wishes to follow someone. To
indicate a following relationship, we create a row in the *Relationship* table
pointing from one user to another. Due to the unique index on ``from_user`` and
``to_user``, we will be sure not to end up with duplicate rows:

.. code-block:: python

    user = get_object_or_404(User, username=username)
    try:
        with database.atomic():
            Relationship.create(
                from_user=get_current_user(),
                to_user=user)
    except IntegrityError:
        pass

Performing subqueries
^^^^^^^^^^^^^^^^^^^^^

If you are logged-in and visit the twitter homepage, you will see tweets from
the users that you follow. In order to implement this cleanly, we can use a
subquery:

.. note::
    The subquery, ``user.following()``, by default would ordinarily select all
    the columns on the ``User`` model. Because we're using it as a subquery,
    peewee will only select the primary key.

.. code-block:: python

    # python code
    user = get_current_user()
    messages = (Message
                .select()
                .where(Message.user.in_(user.following()))
                .order_by(Message.pub_date.desc()))

This code corresponds to the following SQL query:

.. code-block:: sql

    SELECT t1."id", t1."user_id", t1."content", t1."pub_date"
    FROM "message" AS t1
    WHERE t1."user_id" IN (
        SELECT t2."id"
        FROM "user" AS t2
        INNER JOIN "relationship" AS t3
            ON t2."id" = t3."to_user_id"
        WHERE t3."from_user_id" = ?
    )

Other topics of interest
^^^^^^^^^^^^^^^^^^^^^^^^

There are a couple other neat things going on in the example app that are worth
mentioning briefly.

* Support for paginating lists of results is implemented in a simple function called
  ``object_list`` (after it's corollary in Django).  This function is used by all
  the views that return lists of objects.

  .. code-block:: python

      def object_list(template_name, qr, var_name='object_list', **kwargs):
          kwargs.update(
              page=int(request.args.get('page', 1)),
              pages=qr.count() / 20 + 1)
          kwargs[var_name] = qr.paginate(kwargs['page'])
          return render_template(template_name, **kwargs)

* Simple authentication system with a ``login_required`` decorator.  The first
  function simply adds user data into the current session when a user successfully
  logs in.  The decorator ``login_required`` can be used to wrap view functions,
  checking for whether the session is authenticated and if not redirecting to the
  login page.

  .. code-block:: python

      def auth_user(user):
          session['logged_in'] = True
          session['user'] = user
          session['username'] = user.username
          flash('You are logged in as %s' % (user.username))

      def login_required(f):
          @wraps(f)
          def inner(*args, **kwargs):
              if not session.get('logged_in'):
                  return redirect(url_for('login'))
              return f(*args, **kwargs)
          return inner

* Return a 404 response instead of throwing exceptions when an object is not
  found in the database.

  .. code-block:: python

      def get_object_or_404(model, *expressions):
          try:
              return model.get(*expressions)
          except model.DoesNotExist:
              abort(404)

.. note::
    To avoid having to frequently copy/paste :py:func:`object_list` or
    :py:func:`get_object_or_404`, these functions are included as part of the
    playhouse :ref:`flask extension module <flask_utils>`.

    .. code-block:: python

        from playhouse.flask_utils import get_object_or_404, object_list

More examples
-------------

There are more examples included in the peewee `examples directory
<https://github.com/coleifer/peewee/blob/master/examples/>`_, including:

* `Example blog app <https://github.com/coleifer/peewee/tree/master/examples/blog>`_ using Flask and peewee. Also see `accompanying blog post <https://charlesleifer.com/blog/how-to-make-a-flask-blog-in-one-hour-or-less/>`_.
* `An encrypted command-line diary <https://github.com/coleifer/peewee/blob/master/examples/diary.py>`_. There is a `companion blog post <https://charlesleifer.com/blog/dear-diary-an-encrypted-command-line-diary-with-python/>`_ you might enjoy as well.
* `Analytics web-service <https://github.com/coleifer/peewee/tree/master/examples/analytics>`_ (like a lite version of Google Analytics). Also check out the `companion blog post <https://charlesleifer.com/blog/saturday-morning-hacks-building-an-analytics-app-with-flask/>`_.

.. note::
    Like these snippets and interested in more?  Check out `flask-peewee <https://github.com/coleifer/flask-peewee>`_ -
    a flask plugin that provides a django-like Admin interface, RESTful API, Authentication and
    more for your peewee models.


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>CSS Inline Layout: getComputedStyle().verticalAlign</title>
<link rel="help" href="https://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align">
<link rel="help" href="https://drafts.csswg.org/css-inline/#propdef-vertical-align">
<meta name="assert" content="vertical-align computed value is as specified, with lengths made absolute.">


text:
Yaml File Configuration
=======================
Simple library for loading and accessing configuration stored in .yml files. It relies on [symfony/yaml](http://github.com/symfony/yaml) for its
functions. The library avoids loading Yaml file until requested (lazy loading) to avoid unnecessary loading and parsing.

Installation
------------
You can install the project via composer

```composer require dragooon/yaml-file-config```

Usage
-----
### config.yml
```yml
timeout: 10
parameter:
  a: 1
  b: 2
name: abc
```

### app.php
```php
$config = new \Dragooon\YamlFileConfig\YamlFileConfig('config.yml');
echo $config['timeout']; // 10
echo $config['parameter']['a']; // 1;
echo $config->get('name'); // abc

// You can also modify the configuration by either of the following
$config['timeout'] = 20;
$config->set('parameter', [
    'a' => 2,
    'b' => 3,
]);

// And finally save the file to write into config.yml
$config->save();
```
License
-------
The project is licensed under The MIT License. See LICENSE for more information.


text:
using EnvDTE;

namespace Spect.Net.VsPackage.SolutionItems
{
    /// <summary>
    /// This class represents a ZX Spectrum TZX file item
    /// </summary>
    public class TzxProjectItem: TapeProjectItemBase
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="T:System.Object" /> class.
        /// </summary>
        public TzxProjectItem(ProjectItem dteProjectItem) : base(dteProjectItem)
        {
        }
    }
}


text:
<?php

use app\models\general\GeneralLabel;

use yii\helpers\Html;

/* @var $this yii\web\View */
/* @var $model app\models\RefJenisInsentif */

$this->title = GeneralLabel::createTitle.' '.GeneralLabel::jenis_insentif;
$this->params['breadcrumbs'][] = ['label' => GeneralLabel::jenis_insentif, 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>


text:
using UnityEngine;
using System.Collections;

/// <summary>
/// A slider that will make audio people happy when working in Unity.
///
/// Thanks to Aaron, Brad, and Matt for making this:
/// http://www.playdotsound.com/portfolio-item/decibel-db-to-float-value-calculator-making-sense-of-linear-values-in-audio-tools/
/// </summary>
[RequireComponent(typeof(AudioSource))]
public class AudioVolumeSlider : MonoBehaviour
{
    private const float MinVolume = -60f;

    private const float MaxVolume = 0f;

    [SerializeField, Range(MinVolume, MaxVolume), Tooltip("Volume (dB)")] private float _volume;

    private AudioSource _audioSource;

    public void SetVolume(float volume)
    {
        _volume = volume;
        Refresh();
    }

    private void OnValidate()
    {
        Refresh();
    }

    private void Refresh()
    {
        if (_audioSource == null)
        {
            _audioSource = GetComponent<AudioSource>();
        }

        // guard against out of range values
        if (_volume > MaxVolume)
        {
            _volume = MaxVolume;
        }
        else if (_volume < MinVolume)
        {
            _volume = MinVolume;
        }

        _audioSource.volume = Mathf.Pow(10f, _volume / 20f);
    }
}


text:
import { Meteor } from 'meteor/meteor';

console.log(Promise.await(Promise.resolve('something happened!')));


text:
package com.amazonaws.services.securityhub.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.securityhub.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * AwsEcsClusterConfigurationExecuteCommandConfigurationDetailsMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class AwsEcsClusterConfigurationExecuteCommandConfigurationDetailsMarshaller {

    private static final MarshallingInfo<String> KMSKEYID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("KmsKeyId").build();
    private static final MarshallingInfo<StructuredPojo> LOGCONFIGURATION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("LogConfiguration").build();
    private static final MarshallingInfo<String> LOGGING_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("Logging").build();

    private static final AwsEcsClusterConfigurationExecuteCommandConfigurationDetailsMarshaller instance = new AwsEcsClusterConfigurationExecuteCommandConfigurationDetailsMarshaller();

    public static AwsEcsClusterConfigurationExecuteCommandConfigurationDetailsMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(AwsEcsClusterConfigurationExecuteCommandConfigurationDetails awsEcsClusterConfigurationExecuteCommandConfigurationDetails,
            ProtocolMarshaller protocolMarshaller) {

        if (awsEcsClusterConfigurationExecuteCommandConfigurationDetails == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(awsEcsClusterConfigurationExecuteCommandConfigurationDetails.getKmsKeyId(), KMSKEYID_BINDING);
            protocolMarshaller.marshall(awsEcsClusterConfigurationExecuteCommandConfigurationDetails.getLogConfiguration(), LOGCONFIGURATION_BINDING);
            protocolMarshaller.marshall(awsEcsClusterConfigurationExecuteCommandConfigurationDetails.getLogging(), LOGGING_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}