text:
var expect = require('chai').expect,
    assert = require('chai').assert,
    should = require('chai').should();

var request = require('supertest');
var superagent = require('superagent');
var agent = superagent.agent();
var agent2 = superagent.agent();
var agentAdmin = superagent.agent();

var apiUrl = 'http://localhost:9010';

var surveyTest = null;
var surveyName = null;
var adminTest = null;
var userTest = null;
var user2Test = null;

describe('Survey', function () {
    describe('Preparation', function () {
        it('must create a new admin', function (done) {
            request(apiUrl)
                .post('/admin')
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    adminTest = res.body.data._id;
                    done();
                });
        });

        it('must logged the admin', function (done) {
            request(apiUrl)
                .post('/auth')
                .send({
                    username: "admintest.admintest",
                    password: '098f6bcd4621d373cade4e832627b4f6'
                })
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    expect(res.body.message).to.equal("Authentification successfull");
                    agentAdmin.saveCookies(res);
                    done();
                });
        });

        it('must create a new test user', function (done) {
            var req = request(apiUrl).post('/users');
            agentAdmin.attachCookies(req);
            req.send({
                    firstName: 'surveyTest',
                    lastName: 'surveyTest',
                    email: 'something@email.com'
                })
                .end(function (err, res) {
                    if (err) return done(err);
                    expect(res.body.success).to.equal(1);
                    userTest = res.body.data._id;
                    done();
                });
        });

        it('must logged the test user', function (done) {
            request(apiUrl)
                .post('/auth')
                .send({
                    username: "surveytest.surveytest",
                    password: '098f6bcd4621d373cade4e832627b4f6'
                })
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    expect(res.body.message).to.equal("Authentification successfull");
                    agent.saveCookies(res);
                    done();
                });
        });

        it('must create a second new test user', function (done) {
            var req = request(apiUrl).post('/users');
            agentAdmin.attachCookies(req);
            req.send({
                    firstName: 'surveyTest2',
                    lastName: 'surveyTest2',
                    email: 'something@email.com'
                })
                .end(function (err, res) {
                    if (err) return done(err);
                    expect(res.body.success).to.equal(1);
                    user2Test = res.body.data._id;
                    done();
                });
        });

        it('must logged the second test user', function (done) {
            request(apiUrl)
                .post('/auth')
                .send({
                    username: "surveytest2.surveytest2",
                    password: '098f6bcd4621d373cade4e832627b4f6'
                })
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    expect(res.body.message).to.equal("Authentification successfull");
                    agent2.saveCookies(res);
                    done();
                });
        });
    });

    describe('.createSurvey()', function () {
        it('must to be logged', function (done) {
            request(apiUrl)
                .post('/surveys')
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(0);
                    expect(res.body.message).to.equal("Error : Not logged");
                    done();
                });
        });

        it('must need a name', function (done) {
            var req = request(apiUrl).post('/surveys');
            agent.attachCookies(req);
            req.end(function (err, res) {
                if (err) return err;
                expect(res.body.success).to.equal(0);
                expect(res.body.message).to.equal("Error : No name given");
                done();
            });
        });

        it('must create a new Survey', function (done) {
            var req = request(apiUrl).post('/surveys');
            agent.attachCookies(req);
            req.send({
                    name: "Mon Sondage Test"
                })
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    expect(res.body.data.name).to.equal("Mon Sondage Test");
                    expect(res.body.data.author).to.equal(userTest);
                    surveyTest = res.body.data._id;
                    surveyName = res.body.data.name;
                    done();
                });
        });

        it('must check if name\'s survey already exists', function (done) {
            var req = request(apiUrl).post('/surveys');
            agent.attachCookies(req);
            req.send({
                    name: "Mon Sondage Test"
                })
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(0);
                    expect(res.body.message).to.equal("Error : Survey's name already exists");
                    done();
                });
        });
    });

    describe(".getSurveys()", function () {
        it('must return at least one survey', function (done) {
            request(apiUrl)
                .get("/surveys")
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    expect(res.body.data).not.to.be.empty;
                    done();
                });
        });
    });

    describe(".getSurvey()", function () {
        it('must return the survey', function (done) {
            request(apiUrl)
                .get("/surveys/" + surveyTest)
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    expect(res.body.data.name).to.equal(surveyName);
                    done();
                });
        });
    });

    describe(".editSurvey()", function () {
        editSurvey("name", "SuperSondage");
        editSurvey("description", "Pour ou contre le Super Sondage ?");

        it("admin can edit a survey", function (done) {
            var req = request(apiUrl).put('/surveys/' + surveyTest);
            agentAdmin.attachCookies(req);
            req.send({
                    name: "AdminSondage"
                })
                .end(function (err, res) {
                    if (err) return done(err);
                    expect(res.body.success).to.equal(1);
                    expect(res.body.data.name).to.equal("AdminSondage");
                    done();
                });
        });

        it("other user cannot edit a survey", function (done) {
            var req = request(apiUrl).put('/surveys/' + surveyTest);
            agent2.attachCookies(req);
            req.send({
                    name: "AdminSondage"
                })
                .end(function (err, res) {
                    if (err) return done(err);
                    expect(res.body.success).to.equal(0);
                    expect(res.body.message).to.equal("Error : You're not an admin");
                    done();
                });
        });
    });

    describe(".deleteSurvey()", function () {
        it("other user cannot delete a survey", function (done) {
            var req = request(apiUrl).delete("/surveys/" + surveyTest);
            agent2.attachCookies(req);
            req.end(function (err, res) {
                    if (err) return done(err);
                    expect(res.body.success).to.equal(0);
                    expect(res.body.message).to.equal("Error : You're not an admin");
                    done();
                });
        });

        it('user can delete the survey', function (done) {
            var req = request(apiUrl).delete("/surveys/" + surveyTest);
            agent.attachCookies(req);
            req.end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    done();
                });
        });

        it('must have delete the survey', function (done) {
            request(apiUrl)
                .get("/surveys/" + surveyTest)
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(0);
                    done();
                });
        });

        it('must have delete the survey items', function (done) {
            request(apiUrl)
                .get("/surveyItems/" + surveyTest)
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(1);
                    expect(res.body.data).to.be.empty;
                    done();
                });
        });

        it('must have delete the survey votes', function (done) {
            request(apiUrl)
                .get("/surveyVotes/" + surveyTest)
                .end(function (err, res) {
                    if (err) return err;
                    expect(res.body.success).to.equal(0);
                    done();
                });
        });
    });

    describe("End of test", function () {
        it('must logout the userTest', function (done) {
            var req = request(apiUrl).delete('/auth')
            agent.attachCookies(req);
            req.end(function (err, res) {
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });

        it('must delete the userTest', function (done) {
            var req = request(apiUrl)
                .delete('/users/' + userTest);
            agentAdmin.attachCookies(req);
            req.end(function (err, res) {
                if (err) return done(err);
                expect(res.body.success).to.equal(1);
                done();
            });
        });

        it('must logout the user2Test', function (done) {
            var req = request(apiUrl).delete('/auth')
            agent2.attachCookies(req);
            req.end(function (err, res) {
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });

        it('must delete the user2Test', function (done) {
            var req = request(apiUrl)
                .delete('/users/' + user2Test);
            agentAdmin.attachCookies(req);
            req.end(function (err, res) {
                if (err) return done(err);
                expect(res.body.success).to.equal(1);
                done();
            });
        });

        it('must delete the adminTest', function (done) {
            var req = request(apiUrl)
                .delete('/users/' + adminTest);
            agentAdmin.attachCookies(req);
            req.end(function (err, res) {
                if (err) return done(err);
                expect(res.body.success).to.equal(1);
                done();
            });
        });

        it('must logout the adminTest', function (done) {
            var req = request(apiUrl).delete('/auth')
            agentAdmin.attachCookies(req);
            req.end(function (err, res) {
                if (err) return err;
                expect(res.body.success).to.equal(1);
                done();
            });
        });
    });
});

function editSurvey(type, value) {
    it('must edit the ' + type, function (done) {
        var params = {}
        params[type] = value;

        var req = request(apiUrl).put('/surveys/' + surveyTest);
        agent.attachCookies(req);
        req.send(params)
            .end(function (err, res) {
                if (err) return done(err);
                expect(res.body.data[type]).to.equal(value);
                done();
            });
    });
}


text:
using System.Collections.ObjectModel;

namespace Xamarin.Forms
{
	public interface IPageController
	{
		Rectangle ContainerArea { get; set; }

		bool IgnoresContainerArea { get; set; }

		ObservableCollection<Element> InternalChildren { get; }

		void SendAppearing();

		void SendDisappearing();
	}
}

redpajama_set_name: RedPajamaGithub


text:
package org.neo4j.index.impl.lucene;

import org.neo4j.test.OtherThreadExecutor.WorkerCommand;

public class CreateNodeAndIndexByCommand implements WorkerCommand<CommandState, Void>
{
    private String key;
    private String value;

    public CreateNodeAndIndexByCommand( String key, String value )
    {
        this.key = key;
        this.value = value;
    }

    @Override
    public Void doWork( CommandState state )
    {
        state.node = state.graphDb.createNode();
        state.index.add( state.node, key, value );
        return null;
    }
}


text:
@implementation ZYPAuraController

- (NSArray *)specifiers {
	if (!_specifiers) {
		_specifiers = [self loadSpecifiersFromPlistName:@"Aura" target:self];
	}

	return _specifiers;
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	self.navigationController.navigationController.navigationBar.tintColor = RedColor;
	self.navigationController.navigationController.navigationBar.barTintColor = DarkRedColor;
	self.navigationController.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor whiteColor]};

	[UISlider appearanceWhenContainedInInstancesOfClasses:@[[self class]]].tintColor = RedColor;
	[UISwitch appearanceWhenContainedInInstancesOfClasses:@[[self class]]].onTintColor = RedColor;
	[UISegmentedControl appearanceWhenContainedInInstancesOfClasses:@[[self class]]].tintColor = RedColor;

	prevStatusStyle = [[UIApplication sharedApplication] statusBarStyle];
	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	self.navigationController.navigationController.navigationBar.tintColor = nil;
	self.navigationController.navigationController.navigationBar.barTintColor = nil;
	self.navigationController.navigationController.navigationBar.titleTextAttributes = nil;

	[[UIApplication sharedApplication] setStatusBarStyle:prevStatusStyle];
	prevStatusStyle = [[UIApplication sharedApplication] statusBarStyle];
}

@end

@implementation ZYBackgrounderIconIndicatorOptionsListController

- (NSArray *)specifiers {
	if (!_specifiers) {
		_specifiers = [self loadSpecifiersFromPlistName:@"AuraIconOptions" target:self];
	}

	return _specifiers;
}

@end

@implementation ZYBackgrounderStatusbarOptionsListController

- (NSArray *)specifiers {
	if (!_specifiers) {
		_specifiers = [self loadSpecifiersFromPlistName:@"AuraStatusBarOptions" target:self];
	}

	return _specifiers;
}

@end


text:
external help file: Microsoft.Azure.Commands.Sql.dll-Help.xml
online version:
schema: 2.0.0
---

# New-AzureRmSqlDatabaseFailoverGroup

## SYNOPSIS
This command creates a new Azure SQL Database Failover Group.

## SYNTAX

```
New-AzureRmSqlDatabaseFailoverGroup -ServerName <String> -FailoverGroupName <String>
 [-PartnerResourceGroupName <String>] -PartnerServerName <String> [-FailoverPolicy <FailoverPolicy>]
 [-GracePeriodWithDataLossHours <Int32>] -ResourceGroupName <String> [<CommonParameters>]
```

## DESCRIPTION
Creates a new Azure SQL Database Failover Group for the specified servers.

Two Azure SQL Database TDS endpoints are created at '<FailoverGroupName>.<SqlDatabaseDnsSuffix>' (for example, '<FailoverGroupName>.database.windows.net') and '<FailoverGroupName>.secondary.<SqlDatabaseDnsSuffix>.' These endpoints may be used to connect to the primary and secondary servers in the Failover Group, respectively. If the primary server is affected by an outage, automatic failover of the endpoints and databases will be triggered as dictated by the Failover Group's failover policy and grace period.

Newly created Failover Groups do not contain any databases. To control the set of databases in a Failover Group, use the 'Add-AzureRmSqlDatabaseToFailoverGroup' and 'Remove-AzureRmSqlDatabaseFromFailoverGroup' cmdlets.

During preview of the Failover Groups feature, only values greater than or equal to 1 hour are supported for the '-GracePeriodWithDataLossHours' parameter.

## EXAMPLES

### Example 1
```
C:\> $failoverGroup = New-AzureRMSqlDatabaseFailoverGroup -ResourceGroupName rg -ServerName primaryserver -PartnerServerName secondaryserver -FailoverGroupName fg -FailoverPolicy Automatic -GracePeriodWithDataLossHours 1
```

This command creates a new Failover Group with failover policy 'Automatic' for two servers in the same resource group.

### Example 2
```
C:\> $failoverGroup = New-AzureRMSqlDatabaseFailoverGroup -ResourceGroupName rg1 -ServerName primaryserver -PartnerResourceGroupName rg2 -PartnerServerName secondaryserver1 -FailoverGroupName fg -FailoverPolicy Manual
```

This command creates a new Failover Group with failover policy 'Manual' for two servers in different resource groups.

## PARAMETERS

### -AllowReadOnlyFailoverToPrimary
Whether an outage on the secondary server should trigger automatic failover of the read-only endpoint. This feature is not yet supported.

```yaml
Type: AllowReadOnlyFailoverToPrimary
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -FailoverGroupName
The name of the Azure SQL Database Failover Group to create.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -FailoverPolicy
The failover policy of the Azure SQL Database Failover Group.

```yaml
Type: FailoverPolicy
Parameter Sets: (All)
Aliases:
Accepted values: Automatic, Manual

Required: False
Position: Named
Default value: Automatic
Accept pipeline input: False
Accept wildcard characters: False
```

### -GracePeriodWithDataLossHours
Interval before automatic failover is initiated if an outage occurs on the primary server and failover cannot be completed without data loss.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: 1
Accept pipeline input: False
Accept wildcard characters: False
```

### -PartnerResourceGroupName
The name of the secondary resource group of the Azure SQL Database Failover Group.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -PartnerServerName
The name of the secondary server of the Azure SQL Database Failover Group.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ResourceGroupName
The name of the resource group.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ServerName
The name of the primary Azure SQL Database Server of the Failover Group.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.String

## OUTPUTS

### System.Object

## NOTES

## RELATED LINKS

[Set-AzureRmSqlDatabaseFailoverGroup](./Set-AzureRmSqlDatabaseFailoverGroup.md)

[Get-AzureRmSqlDatabaseFailoverGroup](./Get-AzureRmSqlDatabaseFailoverGroup.md)

[Add-AzureRmSqlDatabaseToFailoverGroup](./Add-AzureRmSqlDatabaseToFailoverGroup.md)

[Remove-AzureRmSqlDatabaseFromFailoverGroup](./Remove-AzureRmSqlDatabaseFromFailoverGroup.md)

[Switch-AzureRmSqlDatabaseFailoverGroup](./Switch-AzureRmSqlDatabaseFailoverGroup.md)

[Remove-AzureRmSqlDatabaseFailoverGroup](./Remove-AzureRmSqlDatabaseFailoverGroup.md)


text:
`Установить composer, если нет`

`git clone git@github.com:GotFly/books.git .`

`composer update`

`yii migrate`

`php yii serve`

`Перейти по ссылке http://localhost:8080/books (логин/пароль стандартный: admin/admin)`


text:
using System.Windows;
using System.Windows.Input;
using Microsoft.Msagl.Drawing;

namespace Microsoft.Msagl.WpfGraphControl {
    internal class GvMouseEventArgs : MsaglMouseEventArgs {
        MouseEventArgs args;
        Point position;

        internal GvMouseEventArgs(MouseEventArgs argsPar, GraphViewer graphScrollerP) {
            args = argsPar;
            position = args.GetPosition((IInputElement) graphScrollerP.GraphCanvas.Parent);
        }

        public override bool LeftButtonIsPressed {
            get { return args.LeftButton == MouseButtonState.Pressed; }
        }

        public override bool MiddleButtonIsPressed {
            get { return args.MiddleButton == MouseButtonState.Pressed; }
        }

        public override bool RightButtonIsPressed {
            get { return args.RightButton == MouseButtonState.Pressed; }
        }

        public override bool Handled {
            get { return args.Handled; }
            set { args.Handled = value; }
        }

        public override int X {
            get { return (int) position.X; }
        }

        public override int Y {
            get { return (int) position.Y; }
        }

        /// <summary>
        ///     number of clicks
        /// </summary>
        public override int Clicks {
            get {
                var e = args as MouseButtonEventArgs;
                return e != null ? e.ClickCount : 0;
            }
        }
    }
}


text:
Forked from the Lanyon theme.

## Author

**Mark Otto**
- <https://github.com/mdo>
- <https://twitter.com/mdo>

## License

Open sourced under the [MIT license](LICENSE.md).

<3


text:
package searcher

import (
	"fmt"

	"github.com/blugelabs/bluge/search"
)

func NewMultiTermSearcher(indexReader search.Reader, terms []string,
	field string, boost float64, scorer search.Scorer, compScorer search.CompositeScorer,
	options search.SearcherOptions, limit bool) (
	search.Searcher, error) {
	if tooManyClauses(len(terms)) {
		if optionsDisjunctionOptimizable(options) {
			return optimizeMultiTermSearcher(indexReader, terms, nil, field, boost, scorer, options)
		}
		if limit {
			return nil, tooManyClausesErr(field, len(terms))
		}
	}

	qsearchers, err := makeBatchSearchers(indexReader, terms, nil, field, boost, scorer, options)
	if err != nil {
		return nil, err
	}

	// build disjunction searcher of these ranges
	return newMultiTermSearcherInternal(indexReader, qsearchers, compScorer, options, limit)
}

func NewMultiTermSearcherIndividualBoost(indexReader search.Reader, terms []string, termBoosts []float64,
	field string, boost float64, scorer search.Scorer, compScorer search.CompositeScorer,
	options search.SearcherOptions, limit bool) (search.Searcher, error) {
	if tooManyClauses(len(terms)) {
		if optionsDisjunctionOptimizable(options) {
			return optimizeMultiTermSearcher(indexReader, terms, termBoosts, field, boost, scorer, options)
		}
		if limit {
			return nil, tooManyClausesErr(field, len(terms))
		}
	}

	qsearchers, err := makeBatchSearchers(indexReader, terms, termBoosts, field, boost, scorer, options)
	if err != nil {
		return nil, err
	}

	// build disjunction searcher of these ranges
	return newMultiTermSearcherInternal(indexReader, qsearchers, compScorer, options, limit)
}

func NewMultiTermSearcherBytes(indexReader search.Reader, terms [][]byte,
	field string, boost float64, scorer search.Scorer, compScorer search.CompositeScorer,
	options search.SearcherOptions, limit bool) (search.Searcher, error) {
	if tooManyClauses(len(terms)) {
		if optionsDisjunctionOptimizable(options) {
			return optimizeMultiTermSearcherBytes(indexReader, terms, field, boost, scorer, options)
		}

		if limit {
			return nil, tooManyClausesErr(field, len(terms))
		}
	}

	qsearchers, err := makeBatchSearchersBytes(indexReader, terms, field, boost, scorer, options)
	if err != nil {
		return nil, err
	}

	// build disjunction searcher of these ranges
	return newMultiTermSearcherInternal(indexReader, qsearchers, compScorer, options, limit)
}

func newMultiTermSearcherInternal(indexReader search.Reader,
	searchers []search.Searcher, compScorer search.CompositeScorer,
	options search.SearcherOptions, limit bool) (
	search.Searcher, error) {
	// build disjunction searcher of these ranges
	searcher, err := newDisjunctionSearcher(indexReader, searchers, 0, compScorer, options,
		limit)
	if err != nil {
		for _, s := range searchers {
			_ = s.Close()
		}
		return nil, err
	}

	return searcher, nil
}

func optimizeMultiTermSearcher(indexReader search.Reader, terms []string, termBoosts []float64,
	field string, boost float64, scorer search.Scorer, options search.SearcherOptions) (
	search.Searcher, error) {
	var finalSearcher search.Searcher
	for len(terms) > 0 {
		var batchTerms []string
		var batchBoosts []float64
		if len(terms) > DisjunctionMaxClauseCount {
			batchTerms = terms[:DisjunctionMaxClauseCount]
			terms = terms[DisjunctionMaxClauseCount:]
			if termBoosts != nil {
				batchBoosts = termBoosts[:DisjunctionMaxClauseCount]
				termBoosts = termBoosts[DisjunctionMaxClauseCount:]
			}
		} else {
			batchTerms = terms
			terms = nil
			batchBoosts = termBoosts
			termBoosts = nil
		}
		batch, err := makeBatchSearchers(indexReader, batchTerms, batchBoosts, field, boost, scorer, options)
		if err != nil {
			return nil, err
		}
		if finalSearcher != nil {
			batch = append(batch, finalSearcher)
		}
		cleanup := func() {
			for _, searcher := range batch {
				if searcher != nil {
					_ = searcher.Close()
				}
			}
		}
		finalSearcher, err = optimizeCompositeSearcher("disjunction:unadorned",
			indexReader, batch, options)
		// all searchers in batch should be closed, regardless of error or optimization failure
		// either we're returning, or continuing and only finalSearcher is needed for next loop
		cleanup()
		if err != nil {
			return nil, err
		}
		if finalSearcher == nil {
			return nil, fmt.Errorf("unable to optimize")
		}
	}
	return finalSearcher, nil
}

func makeBatchSearchers(indexReader search.Reader, terms []string, termBoosts []float64, field string,
	boost float64, scorer search.Scorer, options search.SearcherOptions) ([]search.Searcher, error) {
	qsearchers := make([]search.Searcher, len(terms))
	qsearchersClose := func() {
		for _, searcher := range qsearchers {
			if searcher != nil {
				_ = searcher.Close()
			}
		}
	}
	for i, term := range terms {
		var err error
		if termBoosts != nil {
			qsearchers[i], err = NewTermSearcher(indexReader, term, field, boost*termBoosts[i], scorer, options)
		} else {
			qsearchers[i], err = NewTermSearcher(indexReader, term, field, boost, scorer, options)
		}
		if err != nil {
			qsearchersClose()
			return nil, err
		}
	}
	return qsearchers, nil
}

func optimizeMultiTermSearcherBytes(indexReader search.Reader, terms [][]byte,
	field string, boost float64, scorer search.Scorer, options search.SearcherOptions) (
	search.Searcher, error) {
	var finalSearcher search.Searcher
	for len(terms) > 0 {
		var batchTerms [][]byte
		if len(terms) > DisjunctionMaxClauseCount {
			batchTerms = terms[:DisjunctionMaxClauseCount]
			terms = terms[DisjunctionMaxClauseCount:]
		} else {
			batchTerms = terms
			terms = nil
		}
		batch, err := makeBatchSearchersBytes(indexReader, batchTerms, field, boost, scorer, options)
		if err != nil {
			return nil, err
		}
		if finalSearcher != nil {
			batch = append(batch, finalSearcher)
		}
		cleanup := func() {
			for _, searcher := range batch {
				if searcher != nil {
					_ = searcher.Close()
				}
			}
		}
		finalSearcher, err = optimizeCompositeSearcher("disjunction:unadorned",
			indexReader, batch, options)
		// all searchers in batch should be closed, regardless of error or optimization failure
		// either we're returning, or continuing and only finalSearcher is needed for next loop
		cleanup()
		if err != nil {
			return nil, err
		}
		if finalSearcher == nil {
			return nil, fmt.Errorf("unable to optimize")
		}
	}
	return finalSearcher, nil
}

func makeBatchSearchersBytes(indexReader search.Reader, terms [][]byte, field string,
	boost float64, scorer search.Scorer, options search.SearcherOptions) ([]search.Searcher, error) {
	qsearchers := make([]search.Searcher, len(terms))
	qsearchersClose := func() {
		for _, searcher := range qsearchers {
			if searcher != nil {
				_ = searcher.Close()
			}
		}
	}
	for i, term := range terms {
		var err error
		qsearchers[i], err = NewTermSearcherBytes(indexReader, term, field, boost, scorer, options)
		if err != nil {
			qsearchersClose()
			return nil, err
		}
	}
	return qsearchers, nil
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
H. G. A. Engler, Pflanzenr. IV. 5(Heft 18):117. 1903

#### Original name
null

### Remarks
null


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Am. phil. Soc. , New Series 4(2): 157 (1832)

#### Original name
Polyporus lobatus Schwein., 1832

### Remarks
null


text:
package org.apache.kafka.connect.mirror;

import org.apache.kafka.common.Configurable;
import org.apache.kafka.common.annotation.InterfaceStability;
import java.util.Map;

/** Defines which topics should be replicated. */
@InterfaceStability.Evolving
public interface TopicFilter extends Configurable, AutoCloseable {

    boolean shouldReplicateTopic(String topic);

    default void close() {
        //nop
    }

    default void configure(Map<String, ?> props) {
        //nop
    }
}


text:
"""Linear bijector."""

import abc
from typing import Sequence, Tuple

from distrax._src.bijectors import bijector as base
import jax.numpy as jnp

Array = base.Array

class Linear(base.Bijector, metaclass=abc.ABCMeta):
  """Base class for linear bijectors.

  This class provides a base class for bijectors defined as `f(x) = Ax`,
  where `A` is a `DxD` matrix and `x` is a `D`-dimensional vector.
  """

  def __init__(self,
               event_dims: int,
               batch_shape: Sequence[int],
               dtype: jnp.dtype):
    """Initializes a `Linear` bijector.

    Args:
      event_dims: the dimensionality `D` of the event `x`. It is assumed that
        `x` is a vector of length `event_dims`.
      batch_shape: the batch shape of the bijector.
      dtype: the data type of matrix `A`.
    """
    super().__init__(event_ndims_in=1, is_constant_jacobian=True)
    self._event_dims = event_dims
    self._batch_shape = tuple(batch_shape)
    self._dtype = dtype

  @property
  def matrix(self) -> Array:
    """The matrix `A` of the transformation.

    To be optionally implemented in a subclass.

    Returns:
      An array of shape `batch_shape + (event_dims, event_dims)` and data type
      `dtype`.
    """
    raise NotImplementedError(
        f"Linear bijector {self.name} does not implement `matrix`.")

  @property
  def event_dims(self) -> int:
    """The dimensionality `D` of the event `x`."""
    return self._event_dims

  @property
  def batch_shape(self) -> Tuple[int, ...]:
    """The batch shape of the bijector."""
    return self._batch_shape

  @property
  def dtype(self) -> jnp.dtype:
    """The data type of matrix `A`."""
    return self._dtype


text:
Dex Lazy Loader (DYL) [![Build Status](https://travis-ci.org/guicamest/dexlazyloader.svg?branch=master)](https://travis-ci.org/guicamest/dexlazyloader/branches) [ ![JCenter](https://api.bintray.com/packages/guicamest/maven/dexlazyloader/images/download.svg) ](https://bintray.com/guicamest/maven/dexlazyloader/\_latestVersion)
======

*Call me when you need me! - Somebody*

Dex Lazy Loader (DYL) library and plugin were born as a result of reading Macarse's Lazy Loading Dex files article. If you haven't read it yet, I strongly recommend you do before considering using DYL.

The library provides a LazyLoader to load dexed jars on runtime.

The plugin takes care of dexing provided dependencies and jars located at dyl folder into your assets folder.
For more information, visit the website.

Sample
------

You can find a sample application under the *sample* folder.


text:
package io.grpc.netty;

import static com.google.common.base.Preconditions.checkNotNull;

import io.grpc.Attributes;
import io.grpc.Metadata;
import io.grpc.Status;
import io.grpc.internal.AbstractServerStream;
import io.grpc.internal.StatsTraceContext;
import io.grpc.internal.WritableBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.handler.codec.http2.Http2Headers;
import io.netty.handler.codec.http2.Http2Stream;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Server stream for a Netty HTTP2 transport. Must only be called from the sending application
 * thread.
 */
class NettyServerStream extends AbstractServerStream {
  private static final Logger log = Logger.getLogger(NettyServerStream.class.getName());

  private final Sink sink = new Sink();
  private final TransportState state;
  private final Channel channel;
  private final WriteQueue writeQueue;
  private final Attributes attributes;

  public NettyServerStream(Channel channel, TransportState state, Attributes transportAttrs,
      StatsTraceContext statsTraceCtx) {
    super(new NettyWritableBufferAllocator(channel.alloc()), statsTraceCtx);
    this.state = checkNotNull(state, "transportState");
    this.channel = checkNotNull(channel, "channel");
    this.writeQueue = state.handler.getWriteQueue();
    this.attributes = checkNotNull(transportAttrs);
  }

  @Override
  protected TransportState transportState() {
    return state;
  }

  @Override
  protected Sink abstractServerStreamSink() {
    return sink;
  }

  @Override
  public Attributes attributes() {
    return attributes;
  }

  private class Sink implements AbstractServerStream.Sink {
    @Override
    public void request(final int numMessages) {
      if (channel.eventLoop().inEventLoop()) {
        // Processing data read in the event loop so can call into the deframer immediately
        transportState().requestMessagesFromDeframer(numMessages);
      } else {
        channel.eventLoop().execute(new Runnable() {
          @Override
          public void run() {
            transportState().requestMessagesFromDeframer(numMessages);
          }
        });
      }
    }

    @Override
    public void writeHeaders(Metadata headers) {
      writeQueue.enqueue(new SendResponseHeadersCommand(transportState(),
          Utils.convertServerHeaders(headers), false),
          true);
    }

    @Override
    public void writeFrame(WritableBuffer frame, boolean flush) {
      if (frame == null) {
        writeQueue.scheduleFlush();
        return;
      }
      ByteBuf bytebuf = ((NettyWritableBuffer) frame).bytebuf();
      final int numBytes = bytebuf.readableBytes();
      // Add the bytes to outbound flow control.
      onSendingBytes(numBytes);
      writeQueue.enqueue(
          new SendGrpcFrameCommand(transportState(), bytebuf, false),
          channel.newPromise().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
              // Remove the bytes from outbound flow control, optionally notifying
              // the client that they can send more bytes.
              transportState().onSentBytes(numBytes);
            }
          }), flush);
    }

    @Override
    public void writeTrailers(Metadata trailers, boolean headersSent) {
      Http2Headers http2Trailers = Utils.convertTrailers(trailers, headersSent);
      writeQueue.enqueue(
          new SendResponseHeadersCommand(transportState(), http2Trailers, true), true);
    }

    @Override
    public void cancel(Status status) {
      writeQueue.enqueue(new CancelServerStreamCommand(transportState(), status), true);
    }
  }

  /** This should only called from the transport thread. */
  public static class TransportState extends AbstractServerStream.TransportState
      implements StreamIdHolder {
    private final Http2Stream http2Stream;
    private final NettyServerHandler handler;

    public TransportState(NettyServerHandler handler, Http2Stream http2Stream, int maxMessageSize,
        StatsTraceContext statsTraceCtx) {
      super(maxMessageSize, statsTraceCtx);
      this.http2Stream = checkNotNull(http2Stream, "http2Stream");
      this.handler = checkNotNull(handler, "handler");
    }

    @Override
    public void bytesRead(int processedBytes) {
      handler.returnProcessedBytes(http2Stream, processedBytes);
      handler.getWriteQueue().scheduleFlush();
    }

    @Override
    protected void deframeFailed(Throwable cause) {
      log.log(Level.WARNING, "Exception processing message", cause);
      Status status = Status.fromThrowable(cause);
      transportReportStatus(status);
      handler.getWriteQueue().enqueue(new CancelServerStreamCommand(this, status), true);
    }

    void inboundDataReceived(ByteBuf frame, boolean endOfStream) {
      super.inboundDataReceived(new NettyReadableBuffer(frame.retain()), endOfStream);
    }

    @Override
    public int id() {
      return http2Stream.id();
    }
  }
}


text:
import { SET_LIGHTS, UPDATE_LIGHT } from '../actions';

export default function (state={}, action) {
	switch (action.type) {
		case SET_LIGHTS:
			return action.payload;
		case UPDATE_LIGHT:
			return { ...state, [action.payload.lightNum]: action.payload }
		default:
			return state;
	}
}


text:
const path = require('path')
const config = require('./config')

const _ = module.exports = {}

_.outputPath = config.electron ?
	path.join(__dirname, '../app/dist') :
	path.join(__dirname, '../dist')

_.outputIndexPath = config.electron ?
	path.join(__dirname, '../app/dist/index.html') :
	path.join(__dirname, '../dist/index.html')

_.target = config.electron ? 'electron-renderer' : 'web'


text:
package olympian.party.vertx;

import org.vertx.scala.platform.Verticle
import org.vertx.scala.mods.ScalaBusMod
import scala.concurrent.Promise
import scala.util.{Try, Success, Failure}
import org.vertx.scala.core.eventbus.Message
import org.vertx.java.core.json.JsonObject
import org.vertx.scala.core.eventbus.MessageData
import olympian.repository.mongo.MongoRepository
import olympian.party.engine.EngineRegistry
import org.vertx.scala.core.eventbus.JsonObjectData
import org.vertx.scala.core.json.Json
import olympian.party.engine.PartyServices
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule

/**
 * This will start all the event bus listeners and also instantiate the
 * repository configs.
 */
class App extends Verticle {

  override def start(): Unit = {
    super.start

    val objectMapper = new ObjectMapper
    objectMapper.registerModule(DefaultScalaModule)

    val repositoryConfig = container.config.getObject("repository")

    EngineRegistry.initialize(repositoryConfig.toString())

    vertx.eventBus registerHandler ("party.version", { msg: Message[JsonObject] =>
      msg reply Json.obj("version" -> "1.0.0")
    })

    vertx.eventBus registerHandler ("party.group.create", { msg: Message[JsonObject] =>
      {

        val body = msg.body

        body match {
          case null => msg.fail(-1, "Body of request was null")
          case _ => {
            val name = body.getString("name")
            val externalRef = body.getString("externalRef")
            val ownerId = body.getString("owner")

            if (name == null || externalRef == null) {
              msg.fail(100, s"Invalid input given in the form of [${body.toString}]")
            } else {
              PartyServices.addGroup(externalRef, name, ownerId) match {
                case Some(group) => msg reply Json.fromObjectString(objectMapper.writeValueAsString(group))
                case _ => msg.fail(200, s"Group failed to add for input [${body.toString}]")
              }
            }
          }
        }
      }
    })

    vertx.eventBus registerHandler ("party.group.read", { msg: Message[JsonObject] =>
      {

        val body = msg.body

        body match {
          case null => msg.fail(-1, "Body of request was null")
          case _ => {
            val id = body.getString("id")
            val externalRef = body.getString("externalRef")
            val ownerId = body.getString("owner")

            if (id != null ^ (externalRef != null && ownerId != null)) {

              id match {
                case null => msg.fail(200, s"Not implemented yet")
                case _ => PartyServices.retrieveGroup(id) match {
                  case Some(group) => msg reply Json.fromObjectString(objectMapper.writeValueAsString(group))
                  case _ => msg.fail(200, s"Group failed to add for input [${body.toString}]")
                }
              }

            } else {
              msg.fail(100, s"Invalid input given in the form of [${body.toString}]")
            }
          }
        }
      }
    })

    vertx.eventBus registerHandler ("party.group.update", { msg: Message[JsonObject] => {

        val body = msg.body

        val ACTIVATE_DEACTIVATE_REG = "(activate|deactivate)".r

       	body.getString("action") match {
          case ACTIVATE_DEACTIVATE_REG => {
            val request = body.getObject("request")
            val id = request.getString("id")
            val externalRef = request.getString("externalRef")
            val ownerId = request.getString("owner")

            if (id != null ^ (externalRef != null && ownerId != null)) {

              id match {
                case null => PartyServices.changeActivateStatusGroup(externalRef, ownerId, body.getString("action").equals("activate")) match {
                  case Some(result) => msg reply Json.obj("success" -> result)
                  case _ => msg.fail(200, s"Group failed to change active status of group for input [${body.toString}]")
                }
                case _ => PartyServices.changeActivateStatusGroup(id, body.getString("action").equals("activate")) match {
                  case Some(result) => msg reply Json.obj("success" -> result)
                  case _ => msg.fail(200, s"Group failed to change active status of group for input [${body.toString}]")
                }
              }

            } else {
              msg.fail(100, s"Invalid input given in the form of [${body.toString}]")
            }
          }
          case _ => {
            msg.fail(200, s"Not implemented [${msg.body.toString}]")
          }

        }
      }
    })

  }

  override def stop(): Unit = {
    super.stop
  }

}


text:
[![unix_build](https://img.shields.io/travis/voxy/bluecanary.svg?label=unix%20build)](https://travis-ci.org/voxy/bluecanary)
[![windows_build](https://img.shields.io/appveyor/ci/marcwebbie/bluecanary.svg?label=windows%20build)](https://ci.appveyor.com/project/marcwebbie/bluecanary)
[![Landscape Code Health](https://landscape.io/github/voxy/bluecanary/master/landscape.svg?style=plastic)](https://landscape.io/github/voxy/bluecanary/master)
[![Code Climate](https://codeclimate.com/github/voxy/bluecanary/badges/gpa.svg)](https://codeclimate.com/github/voxy/bluecanary)

Documentation available here: [http://bluecanary.readthedocs.org/en/latest/README/](http://bluecanary.readthedocs.org/en/latest/README/)

## Installation

Blue Canary supports Python 2 and 3 and can be installed via pip:

```
pip install bluecanary
```

## Usage

Blue Canary currently supports two commands: `update_tags` and `update_alarms`

__update_tags__:
update_tags will tag each resource with the given key/value pair.

__update_alarms__:
update_alarms will create and/or update alarms for any resource in your AWS account that matches your specified key/value tags.

**Example usage**:
```
bluecanary update_tags -p /path/to/config/ -v
```

### Parameters

Both `update_tags` and `update_alarms` accept the following parameters and options:

`--path (-p)`: Path to yaml file or directory.  If a directory, Blue Canary will recursively load any yaml files in the directory.  May be provided multiple times to specify multiple files or directories.

`--verbose (-v)`: Enable verbose output.  Add the flag multiple times for additional output (.eg -vv, -vvv)

## Configuration

To use Blue Canary you must set up authentication credentials.  AWS credentials are configured in the [IAM Console](https://console.aws.amazon.com/iam/home).  Once you have a set of valid AWS credentials, you can set them up in several ways:

1.) Credentials Files

You can set up credentials in ~/.aws/credentials and regions in ~/.aws/config

~/.aws/credentials

```
[default]
aws_access_key_id = <<YOUR_ACCESS_KEY>>
aws_secret_access_key = <<YOUR_SECRET_KEY>>
```

~/.aws/config

```
[default]
region=us-east-1
```

2.) Environment Variables

```
export AWS_ACCESS_KEY_ID=<<YOUR_ACCESS_KEY>>
export AWS_SECRET_ACCESS_KEY=<<YOUR_SECRET_KEY>>
export AWS_DEFAULT_REGION=us-east-1
```

3.) Within Blue Canary configuration files. See the Setup section below.

## Setup

Blue Canary is configured via yaml files. There are 4 sections:

1. `Configuration`:
Currently used to configured the locations of additional alarm plugins.
2. `AWSProfiles`:
If you do not wish to store AWS credentials in ~/.aws/credentials or environment variables, you can define them here.
3. `AlarmGroups`:
Definitions of suites of alarms to be created/applied to any resources that match the specified tag/value combination.
4. `TagGroups`:
Lists of resources to be tagged with the given tag/value combination.

/example/blue-canary-configuration.yaml
```
---
Configuration:
  Plugins:
    - /path/to/additional/alarm/plugins
AWSProfiles:
  -
    AWS_PROFILE: <<profile name>>
    AWS_ACCESS_KEY_ID: <<aws access key>>
    AWS_SECRET_ACCESS_KEY: <<aws secret key>>
    AWS_DEFAULT_REGION: <<aws region>>
AlarmGroups:
  -
    AWSProfile: example_profile
    TagKey: <<aws ec2 tag key>>
    TagValue: <<aws tag value>>
    Alarms:
      -
        MetricName: CPUUtilization
        Statistic: Average
        Period: 60
        EvaluationPeriods: 5
        Threshold: 90.0
        ComparisonOperator: GreaterThanOrEqualToThreshold
        AlarmActions:
          - <<aws arn identifier>>
        Namespace: AWS/EC2
  -
    AWSProfile: another_example_profile
    TagKey: <<aws elb tag key>>
    TagValue: <<aws elb tag value)
    Alarms:
      -
        MetricName: Latency
        Statistic: Average
        Period: 60
        EvaluationPeriods: 5
        Threshold: 5.0
        ComparisonOperator: GreaterThanThreshold
        AlarmActions:
          - <<aws arn identifier>>
        Namespace: AWS/ELB
TagGroups:
  -
    Profile: example_profile
    TagKey: <<aws ec2 tag key>>
    TagValue: <<aws ec2 tag value>>
    Type: EC2
    Resources:
      - i-12345678
  -
    AWSProfile: another_example_profile
    TagKey: <<aws elb tag key>>
    TagValue: <<aws elb tag value>>
    Type: ELB
    Resources:
      - example-load-balancer
```

## Development

### Getting Set Up

Assuming you already have Python 3 installed you can set up Blue Canary by cloning from GitHub:

```
$ git clone https://github.com/voxy/blue-canary.git
$ cd blue-canary
$ virtualenv venv
$ source venv/bin/activate
$ make develop
```

### Running Tests

```
$ make test
```

or

```
$ make test-with-coverage
```

## Licence [![license](http://img.shields.io/badge/license-MIT-blue.svg?style=flat-square)](./LICENSE)

Copyright (c) 2016 Voxy, <http://github.com/voxy>

> Read full license here: [LICENSE](./LICENSE)


text:
class ApplicationController < ActionController::Base
  protect_from_forgery
  rescue_from ActionView::MissingTemplate, :with => :render_html

  helper_method :current_user

  def render_html
    if Rails.env.production?
      render :format => "html"
    else
      raise ActionView::MissingTemplate
    end
  end

  private

  def current_user
    begin
      @current_user ||= User.find(session[:user_id]) if session[:user_id]
    rescue
      session[:user_id] = nil
      current_user
    end
  end
end


text:
package com.linecorp.armeria.common.logging;

import static com.google.common.base.Preconditions.checkState;

import java.util.Arrays;
import java.util.Set;

import com.google.common.collect.Sets;

/**
 * A property of {@link RequestLog}, used for identifying properties that have been populated during request
 * processing.
 */
public enum RequestLogProperty {

    // Request properties

    /**
     * {@link RequestLog#requestStartTimeMicros()}, {@link RequestLog#requestStartTimeMillis()},
     * {@link RequestLog#requestStartTimeNanos()}.
     */
    REQUEST_START_TIME(true),

    /**
     * {@link RequestLog#requestEndTimeNanos()}, {@link RequestLog#requestDurationNanos()}.
     */
    REQUEST_END_TIME(true),

    /**
     * {@link RequestLog#requestFirstBytesTransferredTimeNanos()}.
     */
    REQUEST_FIRST_BYTES_TRANSFERRED_TIME(true),

    /**
     * {@link RequestLog#channel()}, {@link RequestLog#sessionProtocol()}, {@link RequestLog#sslSession()},
     * {@link RequestLog#connectionTimings()}.
     */
    SESSION(true),

    /**
     * {@link RequestLog#scheme()}.
     */
    SCHEME(true),

    /**
     * {@link RequestLog#name()}.
     */
    NAME(true),

    /**
     * {@link RequestLog#requestHeaders()}.
     */
    REQUEST_HEADERS(true),

    /**
     * {@link RequestLog#requestContent()}, {@link RequestLog#rawRequestContent()}.
     */
    REQUEST_CONTENT(true),

    /**
     * {@link RequestLog#requestContentPreview()}.
     */
    REQUEST_CONTENT_PREVIEW(true),

    /**
     * {@link RequestLog#requestTrailers()}.
     */
    REQUEST_TRAILERS(true),

    /**
     * {@link RequestLog#requestLength()}.
     */
    REQUEST_LENGTH(true),

    /**
     * {@link RequestLog#requestCause()}.
     */
    REQUEST_CAUSE(true),

    // Response properties

    /**
     * {@link RequestLog#responseStartTimeMicros()}, {@link RequestLog#responseStartTimeMillis()},
     * {@link RequestLog#responseStartTimeNanos()}.
     */
    RESPONSE_START_TIME(false),

    /**
     * {@link RequestLog#responseEndTimeNanos()}, {@link RequestLog#responseDurationNanos()},
     * {@link RequestLog#totalDurationNanos()}.
     */
    RESPONSE_END_TIME(false),

    /**
     * {@link RequestLog#responseFirstBytesTransferredTimeNanos()}.
     */
    RESPONSE_FIRST_BYTES_TRANSFERRED_TIME(false),

    /**
     * {@link RequestLog#responseHeaders()}.
     */
    RESPONSE_HEADERS(false),

    /**
     * {@link RequestLog#responseContent()}.
     */
    RESPONSE_CONTENT(false),

    /**
     * {@link RequestLog#responseContentPreview()}.
     */
    RESPONSE_CONTENT_PREVIEW(false),

    /**
     * {@link RequestLog#responseTrailers()}.
     */
    RESPONSE_TRAILERS(false),

    /**
     * {@link RequestLog#responseLength()}.
     */
    RESPONSE_LENGTH(false),

    /**
     * {@link RequestLog#responseCause()}.
     */
    RESPONSE_CAUSE(false);

    private static final Set<RequestLogProperty> REQUEST_PROPERTIES =
            Arrays.stream(values())
                  .filter(p -> p.isRequestProperty)
                  .collect(Sets.toImmutableEnumSet());

    private static final Set<RequestLogProperty> RESPONSE_PROPERTIES =
            Arrays.stream(values())
                  .filter(p -> !p.isRequestProperty)
                  .collect(Sets.toImmutableEnumSet());

    static final int FLAGS_REQUEST_COMPLETE;
    static final int FLAGS_RESPONSE_COMPLETE;
    static final int FLAGS_ALL_COMPLETE;

    static {
        FLAGS_REQUEST_COMPLETE = flags(REQUEST_PROPERTIES);
        FLAGS_RESPONSE_COMPLETE = flags(RESPONSE_PROPERTIES);
        FLAGS_ALL_COMPLETE = FLAGS_REQUEST_COMPLETE | FLAGS_RESPONSE_COMPLETE;
    }

    /**
     * Returns the {@link RequestLogProperty}s for requests.
     */
    public static Set<RequestLogProperty> requestProperties() {
        return REQUEST_PROPERTIES;
    }

    /**
     * Returns the {@link RequestLogProperty}s for responses.
     */
    public static Set<RequestLogProperty> responseProperties() {
        return RESPONSE_PROPERTIES;
    }

    static int flags(RequestLogProperty... properties) {
        int flags = 0;
        for (RequestLogProperty property : properties) {
            flags |= property.flag();
        }
        return flags;
    }

    static int flags(Iterable<RequestLogProperty> properties) {
        int flags = 0;
        for (RequestLogProperty property : properties) {
            flags |= property.flag();
        }
        return flags;
    }

    private final int flag;
    private final boolean isRequestProperty;

    RequestLogProperty(boolean isRequestProperty) {
        // We only allow 31 properties so negative flags can be used as a default value.
        checkState(ordinal() <= 30,
                   "More than 31 properties defined. " +
                   "Please switch all 'flags' to long and update this check to 62.");
        flag = 1 << ordinal();
        this.isRequestProperty = isRequestProperty;
    }

    int flag() {
        return flag;
    }
}


text:
/*global ace:true*/
define(['react', 'lodash']/*, 'ace'*/, function (React, _/*, ace*/) {
    'use strict';
    return React.createClass({
        displayName: 'BraceEditor',
        propTypes: {
            id: React.PropTypes.string,
            mode: React.PropTypes.string,
            readOnly: React.PropTypes.bool,
            value: React.PropTypes.string,
            valueLink: React.PropTypes.string,
            onChange: React.PropTypes.function
        },
        getInitialState: function () {
            return {
                editorId: _.uniqueId()
            };
        },
        componentWillMount: function () {
        },
        render: function () {
            var props = _.omit(this.props, ['ref', 'key', 'value', 'valueLink', 'onChange']);
            props.id = this.props.id || this.state.editorId;
            return React.DOM.div(props);
        },
        componentWillUpdate: function (nextProps/*, nextState*/) {
            var value = nextProps.valueLink ? nextProps.valueLink() : nextProps.value;
            if (this.editor && this.editor.getValue() !== value) {
                this.editor.setValue(value, 0);
            }
        },
        componentDidMount: function () {
            this.editor = ace.edit(this.props.id || this.state.editorId);
//        this.editor.setTheme('ace/theme/monokai');
            this.editor.setTheme('ace/theme/solarized_light');
            if (this.props.mode !== 'html') {
                this.editor.getSession().setMode('ace/mode/javascript');
            } else {
                this.editor.getSession().setMode('ace/mode/html');
            }
            this.editor.getSession().setUseWorker(false);

            var value = this.props.valueLink ? this.props.valueLink() : this.props.value;
            this.editor.setValue(value, 0);
            if (this.props.readOnly) {
                this.editor.setReadOnly(true);
            } else {
                this.editor.setReadOnly(false);
                this.editor.on('change', function (/*e*/) {
                    if (this.props.valueLink) {
                        this.props.valueLink(this.editor.getValue());
                    } else if (this.props.onChange) {
                        this.props.onChange({target: {value: this.editor.getValue()}});
                    }
                }.bind(this));
            }
            this.editor.clearSelection();
        },
        componentWillUnmount: function () {
            this.editor.destroy();
        }
    });
});


text:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "logindialog.h"
#include <qdebug.h>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow), isTakingPhoto(false)
{
    QString name, password;
    LoginDialog *login = new LoginDialog(&name, &password);
    connect(login, SIGNAL(rejected()), this, SLOT(quit()));
    login->exec();

    qDebug() << name << password;
    /* validate */

    QStringList departments;
    QStringList jobs;
    QStringList permissions;

    departments.push_back("Lol1");
    departments.push_back("Lol2");
    departments.push_back("Lol3");

    jobs.push_back("top1");
    jobs.push_back("top2");
    jobs.push_back("top3");

    permissions.push_back("No Priviledge");
    permissions.push_back("Priviledged");
    permissions.push_back("Admin");

    ui->setupUi(this);
    connect(ui->tabs, SIGNAL(currentChanged(int)), this, SLOT(slot_tabChanged(int)));

    /* regist tab--> */
    camera = new QCamera;
    imageCapture = new QCameraImageCapture(0);

    ui->regist_cameraPushButton->setEnabled(false);
    connect(ui->regist_addUserPushButton, SIGNAL(pressed()), this, SLOT(regist_commit()));
    connect(ui->regist_cameraPushButton, SIGNAL(pressed()), this, SLOT(camera_takePicture()));
    ui->regist_departmentsComboBox->insertItems(0, departments);
    ui->regist_jobComboBox->insertItems(0, jobs);
    ui->regist_permissionComboBox->insertItems(0, permissions);

    /* camera--> */
    setCamera(QCameraInfo::defaultCamera());
    //    foreach (const QCameraInfo &cameraInfo, QCameraInfo::availableCameras()) {
    //        ui->regist_cameraComboBox->insertItem(ui->regist_cameraComboBox->count(), cameraInfo.description(), QVariant::fromValue(cameraInfo));
    //    }
    /* <--camera */
    /* <--regist tab */

    /* search tab--> */
    connect(ui->search_searchPushButton, SIGNAL(pressed()), this, SLOT(search_commit()));
    ui->search_departmentsComboBox->insertItems(0, departments);
    ui->search_jobsComboBox->insertItems(0, jobs);
    ui->search_permissionsComboBox->insertItems(0, permissions);
    /* <--search tab */

    /* send message tab--> */
    connect(ui->msgs_sendPushButton, SIGNAL(pressed()), this, SLOT(sendMsg_commit()));
    /* <--send message tab */

    /* flow tab--> */
    connect(ui->flow_autoUpdateCheckBox, SIGNAL(clicked(bool)), &flow, SLOT(setAutoUpdate(bool)));
    connect(ui->flow_reloadPushButton, SIGNAL(pressed()), &flow, SLOT(checkForData()));
    ui->flow_autoUpdateCheckBox->setChecked(true);
    flow.setTable(ui->flow_tableWidget);
    flow.setAutoUpdate(true);
    /* <--flow tab*/

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::setCamera(QCameraInfo cameraInfo)
{
    delete imageCapture;
    delete camera;

    camera = new QCamera(cameraInfo);

    imageCapture = new QCameraImageCapture(camera);

    connect(imageCapture, SIGNAL(imageCaptured(int,QImage)), this, SLOT(camera_captureImage(int,QImage)));
    connect(imageCapture, SIGNAL(readyForCaptureChanged(bool)), this, SLOT(camera_readyForCapture(bool)));
    connect(imageCapture, SIGNAL(error(int,QCameraImageCapture::Error,QString)), this,
            SLOT(displayCaptureError(int,QCameraImageCapture::Error,QString)));

    //    connect(ui->regist_cameraPushButton, SIGNAL(pressed()), , SLOT());

    camera->setViewfinder(ui->cameraOutput);
    camera->start();
}

void MainWindow::slot_tabChanged(int idx)
{
    switch(idx){
    case 0:
        break;
    case 1:
        break;
    case 2:
        break;
    case 3:
        break;
    default:
        qDebug() << "Literally wtf!?!?";
        break;
    }
}

void MainWindow::regist_name()
{
    regist.setName(ui->regist_nameLineEdit->text());
}

void MainWindow::regist_contact()
{
    regist.setContactNumber(ui->regist_contactLineEdit->text());
}

void MainWindow::regist_email()
{
    regist.setEmail(ui->regist_emailLineEdit->text());
}

void MainWindow::regist_commit()
{
    regist.setName(ui->regist_nameLineEdit->text());
    regist.setContactNumber(ui->regist_contactLineEdit->text());
    regist.setEmail(ui->regist_emailLineEdit->text());
    regist.setDepartIdx(ui->regist_departmentsComboBox->currentIndex());
    regist.setJobsIdx(ui->regist_jobComboBox->currentIndex());
    regist.setPermissionsIdx(ui->regist_permissionComboBox->currentIndex());
    regist.setBirth(ui->regist_birthDateEdit->date());
    regist.commitUser();
}

void MainWindow::camera_select()
{
    //    setCamera(static_cast<QCameraInfo>(ui->regist_cameraComboBox->currentData(ui->regist_cameraComboBox->currentIndex())));
    setCamera(QCameraInfo::defaultCamera());
}

void MainWindow::camera_readyForCapture(bool ready)
{
    ui->regist_cameraPushButton->setEnabled(ready);
}

void MainWindow::camera_captureImage(int requestId, QImage img)
{
    Q_UNUSED(requestId);

    regist.addFace(img);

    isTakingPhoto = false;
}

void MainWindow::camera_takePicture()
{
    if(!isTakingPhoto){
        isTakingPhoto = true;
        imageCapture->capture();
    }
}

void MainWindow::search_name()
{
    search.setName(ui->search_idLineEdit->text());
}

void MainWindow::search_commit()
{
    search.setName(ui->search_idLineEdit->text());
    search.setDepartIdx(ui->search_departmentsComboBox->currentIndex());
    search.setJobsIdx(ui->search_jobsComboBox->currentIndex());
    search.setPermissions(ui->search_permissionsComboBox->currentIndex());
    search.commit();
}

void MainWindow::sendMsg_commit()
{
    sendMsg.setId(ui->msgs_idLineEdit->text());
    sendMsg.setBroadcast((ui->msgs_broadCastCheckBox->checkState() == Qt::Unchecked) ? false : true);
    sendMsg.setMsg(ui->msgs_messageTextEdit->toPlainText());
    sendMsg.commit();
}

void MainWindow::quit()
{
    exit(0);
}


text:
* [Articles](#articles)
* [Algorithms](#algorithms)
* [Coding](#coding)
* [Interview Question](#interview-questions)
* [Guides](#guides)
* [Maths](#maths)
* [Misc](#misc)
* [Questions](#questions)
* [Systems Design](#systems-design)
* [Unix](#unix)
* [Videos](#videos)
* [other repos](#similar-github-repos)

## Articles

* Carlos Bueno – **Get That Job at Facebook** [[web][a_cb]]
* Daniel Blumenthal – **How to Prepare for Technical Interviews** [[web][a_db3]]
* David Byttow – **ABC: Always Be Coding** [[web][a_db]]
* David Byttow – **Four Steps to Google, Without a Degree** [[web][a_db2]]
* HayGen       - **Interview Advice** [[web][a_db5]]
* MyJobHelper - **Best Questions to Ask a Potential Employer During a Job Interview** [[web][a_db4]]
* Thomas L. Friedman – **How to Get a Job at Google** [[part 1][a_tf]] [[part 2][a_tf2]]
* Andrew Rothbart – **Preparing for a technical interview with programming contests** [[web][a_ar]]
* Steve Yegge – **Ten Tips for a (Slightly) Less Awful Resume** [[web][a_sy2]]

[a_cb]:  https://www.facebook.com/notes/10150964382448920
[a_ar]:  https://www.facebook.com/notes/10151298476823920
[a_db]:  https://medium.com/tech-talk/d5f8051afce2
[a_db2]: https://medium.com/this-happened-to-me/8f381aa6bd5e
[a_db3]: http://dandreamsofcoding.com/2012/11/25/how-to-prepare-for-technical-interviews/
[a_db4]: http://blog.myjobhelper.com/2014/10/20/best-questions-ask-potential-employer-job-interview/
[a_db5]: http://hagenhc.com/interview-advice/
[a_sy]:  http://steve-yegge.blogspot.co.uk/2008/03/get-that-job-at-google.html
[a_sy2]: http://steve-yegge.blogspot.co.uk/2007_09_01_archive.html
[a_tf]:  http://mobile.nytimes.com/2014/02/23/opinion/sunday/friedman-how-to-get-a-job-at-google.html
[a_tf2]: http://mobile.nytimes.com/2014/04/20/opinion/sunday/friedman-how-to-get-a-job-at-google-part-2.html

## Algorithms

Recommended: Steven Skiena – **The Algorithm Design Manual** [[Amazon][b_tadm_amzn]] [[pdf][b_tadm_pdf]] [[web][b_tadm_web]]

* Jon Bentley – **Programming Pearls** [[Amazon][b_pp_amzn]] [[web (full text)][b_pp_web]]
* Cormen, Leiserson, Rivest, Stein – **Introduction to Algorithms** [[Amazon][b_clrs_amzn]] [[pdf][b_clrs_pdf]]
* more – **Free Algorithms Books** [[Github][b_fbp]]

[b_clrs_amzn]: http://www.amazon.com/dp/0262033844
[b_clrs_pdf]: https://www.google.com/search?q=cormen+pdf
[b_tadm_web]: http://www.algorist.com/
[b_pp_web]: http://www.cs.bell-labs.com/cm/cs/pearls/
[b_fbp]: https://github.com/vicky002/AlgoWiki/blob/gh-pages/Free-Books/Algorithms-Data_Structures.md

## Coding

Recommended: **Talentbuddy** [[web][c_tb]] [[free app][c_tb_app]]

* **Coderust** (great selection of problems) [[$10 app][c_cr]]
* **Hacker Rank** [[web][c_hr]]
* **Interview Cake** [[web][c_ic]]
* **HackerEarth** [[web][c_he]]
* **HiredInTech** [[web][c_hit]]
* **Project Euler** [[web][c_pe]]
* **Google Code Jam practice problems** [[web][c_gcj]]
* **Top Coder tutorials** [[web][c_tct]]
* **Infoarena training path** (RO) [[web][c_itp]]
* **LeetCode Online Judge** [[web][c-lc]]
* more – **Free Programming Resources** [[web][c_fpr]]
* more - **Web Resources and Tutorials That Don't Suck** [[web][c_p]]

[c_cr]: http://coderust.com/
[c_fpr]: http://resrc.io/
[c_gcj]: https://code.google.com/codejam/contests.html
[c_he]: http://www.hackerearth.com/
[c_hit]: http://www.hiredintech.com/
[c_hr]: https://www.hackerrank.com/
[c_ic]: https://www.interviewcake.com/
[c_itp]: http://www.infoarena.ro/training-path
[c_p]: http://pineapple.io/
[c_pe]: https://projecteuler.net/
[c_tb]: http://www.talentbuddy.co/
[c_tb_app]: https://itunes.apple.com/us/app/talentbuddy/id845593905
[c_tct]: http://www.topcoder.com/tc?d1=tutorials&d2=alg_index&module=Static
[c-lc]: http://oj.leetcode.com/

## Interview Questions
Highly Recommended: **zouzhile's Repository** [[web][c_tb]] [[Github][c_tb_app1]]
* [CareerCup](http://www.careercup.com/page)
* [CoolInterview](http://www.coolinterview.com)
* [GeekInterview](http://www.geekinterview.com/)
* [IndiaBix](http://www.indiabix.com)
* [CrazyForCode](http://www.crazyforcode.com/)
* [Glassdoor](http://glassdoor.com/)
* [CodeChef](www.codechef.com)
* [TopCoder](www.topcoder.com)
* [LeetCode](http://www.leetcode.com)
* [Hackerrank](http://www.hackerrank.com/)
* [CodeKata](http://codekata.pragprog.com/2007/01/code_kata_backg.html)
* [GeeksforGeeks](http://geeksforgeeks.org/forum/forum/interview-questions)
* [Impact Interview](http://www.impactinterview.com/2009/10/140-google-interview-questions/#software_engineer)
* [Dynamic Programming](http://hawstein.com/posts/dp-novice-to-advanced.html)
* [Interviewbit](https://www.interviewbit.com/)

[c_tb_app1]: https://github.com/zouzhile/interview

## Guides

Recommended (resume): Gayle McDowell –  **The Google Resume** [[Amazon][g_tgr_amzn]] [[pdf][g_tgr_pdf]]

Recommended (interview): Gayle McDowell – **Cracking the Coding Interview** [[Amazon][g_cci_amzn]] [[pdf][g_cci_pdf]]

* **CareerCup** [[web][g_cc]]
* **Interview Cake** [[web][g_i_cake]]
* **Coding for Interviews** [[web][g_cfi]]
* **Here's How to Prepare for Tech Interviews** [[reddit][g_rd]]
* **Programming Interviews Exposed** [[Amazon][g_pie_amzn]] [[pdf][g_pie_pdf]]
* **Elements of Programming Interviews** [[Amazon][g_epibook]] [[web][g_epiweb]]
* Mina Azib – **Resources for Preparing for the Google Interview** [[web][g_ma]]

[g_cc]: http://www.careercup.com/
[g_cci_amzn]: http://www.amazon.com/dp/098478280X
[g_cci_pdf]: https://www.google.com/search?q=cracking+the+coding+interview+pdf
[g_i_cake]: https://www.interviewcake.com/
[g_cfi]: http://codingforinterviews.com/
[g_ma]:  http://itsallonesandzeroes.blogspot.de/2013/07/prepping-for-google-interview.html
[g_pie_amzn]: http://www.amazon.com/dp/047012167X
[g_pie_pdf]: https://www.google.com/search?q=programming+interviews+exposed+it-ebooks
[g_rd]: http://redd.it/1jov24
[g_tgr_amzn]: http://www.amazon.com/dp/0470927623
[g_tgr_pdf]: https://www.google.com/search?q=the+google+resume+pdf
[g_epiweb]: https://code.google.com/p/elements-of-programming-interviews/
[g_epibook]: http://www.amazon.com/Elements-Programming-Interviews-Insiders-Guide/dp/1479274836

Follow Interview and Programming related Topics on Quora!

**Quora**:
* [How to prepare for my Google/Facebook interview if I have 6 months left?](http://www.quora.com/Career-Advice/What-are-the-ways-to-utilize-6-months-to-build-skill-set-to-get-into-Facebook-or-Google)
* [How should I prepare for my Google interview if I have 1 month left?](https://www.quora.com/Google-Interview-Questions/How-should-I-prepare-for-my-Google-interview-if-I-have-1-month-left)
* [What is the best advice for an engineering internship interview at Google or Facebook?](https://www.quora.com/What-is-the-best-advice-for-an-engineering-internship-interview-at-Google-or-Facebook)
* [What graph topics should I study in order to be adequately prepared for a Google Software Engineer interview?](https://www.quora.com/Google-Interview-Questions/What-graph-topics-should-I-study-in-order-to-be-adequately-prepared-for-a-Google-Software-Engineer-interview)
* [What are the best programming interview questions you've ever asked or been asked?](https://www.quora.com/What-are-the-best-programming-interview-questions-youve-ever-asked-or-been-asked)
* [How much time did you spend preparing for Google's interviews?](https://www.quora.com/How-much-time-did-you-spend-preparing-for-Googles-interviews)
* [During an interview what's an appropriate answer when asked "where do you see yourself in 5 years?](https://www.quora.com/During-an-interview-whats-an-appropriate-answer-when-asked-where-do-you-see-yourself-in-5-years)

## Maths

Recommended: MIT - **Mathematics for Computer Science** [[Youtube][m_mit_yt]] [[web][m_mit_web]]

* Graham, Knuth, Patashnik – **Concrete Mathematics: A Foundation for Computer Science** [[Amazon][m_cm_amzn]] [[pdf][m_cm_pdf]]

[m_cm_amzn]: http://www.amazon.com/dp/0201558025/
[m_cm_pdf]: https://www.google.co.uk/search?q=knuth+concrete+mathematics+pdf
[m_mit_web]: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-042j-mathematics-for-computer-science-fall-2010/
[m_mit_yt]: https://www.youtube.com/watch?v=L3LMbpZIKhQ&list=PLB7540DEDD482705B

## Misc

* Aaron Swartz – **How I Hire Programmers** [[web](http://www.aaronsw.com/weblog/hiring)]
* Joel Spolsky – **The Guerrilla Guide to Interviewing (v.3)** [[web](http://www.joelonsoftware.com/articles/GuerrillaInterviewing3.html)]
* Steve Yegge – **Done, and Gets Things Smart** [[web](http://steve-yegge.blogspot.co.uk/2008/06/done-and-gets-things-smart.html)]

**Quora**

* [How does an interviewer define the difficulty level of a question?](http://www.quora.com/Programming-Interviews/How-does-an-interviewer-define-the-difficulty-level-of-a-question)

## Questions

Recommended: MIT – **Hacking a Google Interview** [[web][q_hgi]]

* **Computer Science Primer / Interview Questions** [[web][q_csp]]
* **Programming Interview Questions** [[web][q_piq]]
* **Prismo-Skills** [[web][q_ps]]
* Jeff Atwood – **How Good an Estimator Are You?** [[web][q_ja]]
* Daniel Blumenthal – **Questions I Want to Ask, but Can't** [[web][q_db]]
* Steve Yegge – **The Five Essential Phone-Screen Questions** [[web][q_feps]]

[q_db]: http://dandreamsofcoding.com/2013/03/01/questions-i-want-to-ask-but-cant/
[q_csp]: http://www.grokit.ca/spc/computer_science_review/
[q_feps]: https://sites.google.com/site/steveyegge2/five-essential-phone-screen-questions
[q_hgi]: https://courses.csail.mit.edu/iap/interview/materials.php
[q_ja]: http://blog.codinghorror.com/how-good-an-estimator-are-you/
[q_piq]: http://maxnoy.com/interviews.html
[q_ps]: http://prismoskills.appspot.com/freshers.jsp

## Systems Design

**Quora**

* [How should I prepare system design questions for Google/Facebook interview?](http://www.quora.com/Job-Interviews/How-should-I-prepare-system-design-questions-for-Google-Facebook-Interview)

## Unix

**Quora**

* [What is the difference between a process and a thread?](http://www.quora.com/What-is-the-difference-between-a-process-and-a-thread)

## Videos

Recommended: **Candidate Coaching Session: Tech Interviewing** [[Youtube][v_ccs]]

* Gayle McDowell – **Cracking the Coding Interview** [[Youtube][v_cci]]
* Gayle McDowell - **Cracking the Coding Interview (examples)** [[one][v_cci2]] [[two][v_cci3]]
* Hangouts on Air: **Google Recruiters Share Interview Tips** [[technical][v_gt]] [[non-technical][v_gnt]]
* Ladies Storm Hackathons: **Interview Prep Round 1: Strings, Arrays, Linked Lists** [[technical][v_lsh1]]

[v_cci]: http://youtu.be/rEJzOhC5ZtQ
[v_cci2]: http://youtu.be/aClxtDcdpsQ
[v_cci3]: http://youtu.be/2cf9xo1S134
[v_ccs]: http://youtu.be/oWbUtlUhwa8
[v_gt]: http://youtu.be/qc1owf2-220
[v_gnt]: http://youtu.be/DINxNbBOEoI
[v_lsh1]: http://youtu.be/fIpliB-ton8

## Similar Github repos

* [schmatz/cs-interview-guide](https://github.com/schmatz/cs-interview-guide) **(NEW)**
* [SITZ/JobPuzzles](https://github.com/SITZ/JobPuzzles) **(NEW)**
* [interview-resources](https://github.com/davidhampgonsalves/interview-resources)
* [code-problems](https://github.com/blakeembrey/code-problems)
* [InterviewThis](https://github.com/ChiperSoft/InterviewThis)
* [job_interview](https://github.com/ruby-jokes/job_interview)
* [what-happens-when](https://github.com/alex/what-happens-when)


text:
package fi.aalto.trafficsense.regularroutes.ui;

import android.app.ActionBar;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Point;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.view.Display;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.caverock.androidsvg.PreserveAspectRatio;
import com.caverock.androidsvg.SVG;
import com.caverock.androidsvg.SVGImageView;
import com.caverock.androidsvg.SVGParseException;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import fi.aalto.trafficsense.regularroutes.R;
import fi.aalto.trafficsense.regularroutes.RegularRoutesApplication;
import fi.aalto.trafficsense.regularroutes.RegularRoutesConfig;
import fi.aalto.trafficsense.regularroutes.backend.BackendStorage;
import fi.aalto.trafficsense.regularroutes.backend.rest.RestApi;
import fi.aalto.trafficsense.regularroutes.util.HandlerExecutor;
import retrofit.RestAdapter;

public class EnergyCertificateActivity extends Activity {

    private RelativeLayout container;
    private SVGImageView svgImageView;
    private BackendStorage mStorage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_energy_certificate);
        getActionBar().setDisplayHomeAsUpEnabled(true);

        container = (RelativeLayout) findViewById(R.id.energy_certificate);
        svgImageView = new SVGImageView(this);
        container.addView(svgImageView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);

        mStorage = BackendStorage.create(this);

    }

    @Override
    protected void onStart() {
        super.onStart();
        fetchCertificate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        fetchCertificate();
    }

    private void fetchCertificate() {
        try {
            String sessionToken = mStorage.readSessionToken().get();
            final RegularRoutesConfig config = ((RegularRoutesApplication) this.getApplication()).getConfig();
            URL url = new URL(config.server.toString() + "/svg/" + sessionToken);
            DownloadDataTask downloader = new DownloadDataTask();
            downloader.execute(url);
        } catch (MalformedURLException e) {
            Context context = getApplicationContext();
            Toast toast = Toast.makeText(context, "URL was broken", Toast.LENGTH_SHORT);
            toast.show();
            return;
        }
    }

    private class DownloadDataTask extends AsyncTask<URL, Void, String> {
        protected String doInBackground(URL... urls) {
            String returnVal = null;
            if (urls.length != 1) {
                return "Certificate downloader attempted to get more or less than one URL";
            }

            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) urls[0].openConnection();
                InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
                if (s.hasNext()) {
                    returnVal = s.next();
                }
                else {
                    returnVal = "No data!";
                }
                in.close();

            }
            catch (IOException e) {
                return "error connecting to URL";
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            return returnVal;
        }

        protected void onPostExecute(String info) {
            SVG svgImage;
            try {
                svgImage = SVG.getFromString(info);
            } catch(SVGParseException e) {
                Context context = getApplicationContext();
                Toast toast = Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT);
                toast.show();
                return;
            }
            svgImageView.setSVG(svgImage);
        }
    }
}