text:
Imports System.ComponentModel.Composition
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Imports Microsoft.VisualStudio.Utilities
Imports Roslyn.Compilers.Internal
Imports Roslyn.Compilers.VisualBasic
Imports Roslyn.Services.Commands
Imports Roslyn.Services.Internal.Extensions
Imports Roslyn.Services.Internal.Utilities
Imports Roslyn.Services.VisualBasic.Commands
Imports Roslyn.Services.VisualBasic.Utilities
Imports System.Text
Imports Roslyn.Services.Workspaces
Imports Roslyn.Services.VisualBasic.Extensions

Namespace Roslyn.Services.VisualBasic.DocumentationComments
    <Export(GetType(ICommandHandler))>
    <Name(VisualBasicCommandHandlerNames.DocumentationComments)>
    <Order(After:=VisualBasicCommandHandlerNames.IntelliSense)>
    <ContentType(ContentTypeNames.VisualBasicContentType)>
    Friend NotInheritable Class DocumentationCommentCommandHandler
        Implements ICommandHandler(Of TypeCharCommandArgs)
        Implements ICommandHandler(Of ReturnKeyCommandArgs)
        Implements ICommandHandler(Of InsertCommentCommandArgs)

        Private ReadOnly _workspace As Workspace

        <ImportingConstructor()>
        Public Sub New(ByVal workspace As Workspace)
            Contract.ThrowIfNull(workspace)

            _workspace = workspace
        End Sub

        Public Function GetCommandState_InsertCommandCommandHandler(ByVal args As TypeCharCommandArgs, ByVal nextHandler As Func(Of CommandState)) As CommandState Implements ICommandHandler(Of TypeCharCommandArgs).GetCommandState
            Return nextHandler()
        End Function

        Public Sub ExecuteCommand_InsertCommandCommandHandler(ByVal args As InsertCommentCommandArgs, ByVal nextHandler As Action) Implements ICommandHandler(Of InsertCommentCommandArgs).ExecuteCommand
            If Not InsertCommentOnContainingMember(args.TextView, args.SubjectBuffer) Then
                nextHandler()
            End If
        End Sub

        Public Function GetCommandState_TypeCharCommandHandler(ByVal args As ReturnKeyCommandArgs, ByVal nextHandler As Func(Of CommandState)) As CommandState Implements ICommandHandler(Of ReturnKeyCommandArgs).GetCommandState
            Return nextHandler()
        End Function

        Public Sub ExecuteCommand_TypeCharCommandHandler(ByVal args As TypeCharCommandArgs, ByVal nextHandler As Action) Implements ICommandHandler(Of TypeCharCommandArgs).ExecuteCommand
            ' Ensure the character is actually typed in the editor
            nextHandler()

            If args.TypedChar = "'"c Then
                InsertCommentAfterTripleApostrophes(args.TextView, args.SubjectBuffer)
            End If
        End Sub

        Public Function GetCommandState_ReturnKeyCommandHandler(ByVal args As InsertCommentCommandArgs, ByVal nextHandler As Func(Of CommandState)) As CommandState Implements ICommandHandler(Of InsertCommentCommandArgs).GetCommandState
            Return nextHandler()
        End Function

        Public Sub ExecuteCommand_ReturnKeyCommandHandler(ByVal args As ReturnKeyCommandArgs, ByVal nextHandler As Action) Implements ICommandHandler(Of ReturnKeyCommandArgs).ExecuteCommand
            ' There are three interesting cases when pressing ENTER in an XML doc comment.
            '
            '     1. If pressing enter at the end of an XML doc comment that contains only ''' we should generate
            '        the doc comment as if the user had typed '''. This situation can happen after an undo.
            '
            '     2. If pressing enter after the ''' of a single-line doc comment that has an incorrect target produces
            '        a doc comment that has a correct target, we should generate. This happens when
            '        typing '''' at the start of a method and pressing ENTER. E.g. |Sub M()
            '
            '    3. If pressing enter inside of an XML doc comment in any other situation, we should automatically insert
            '        a ''' at the appropriate indent on the next line.

            Dim subjectBufferCaretPosition = New SubjectBufferCaretPosition(args.TextView, args.SubjectBuffer)
            Dim caretPosition = If(subjectBufferCaretPosition.Position, -1)
            If caretPosition < 0 Then
                nextHandler()
                Return
            End If

            Dim snapshot = args.SubjectBuffer.CurrentSnapshot
            Dim tree As SyntaxTree = Nothing
            If Not _workspace.TryGetSyntaxTree(snapshot, tree) Then
                nextHandler()
                Return
            End If

            ' Note that the doc comment span starts *after* the first exterior trivia
            Dim documentationComment = GetDocumentationComment(tree, caretPosition)
            If documentationComment Is Nothing OrElse
                Not ExteriorTriviaStartsLine(tree, documentationComment, caretPosition) OrElse
                caretPosition < documentationComment.Span.Start Then

                nextHandler()
                Return
            End If

            If Not SpansSingleLine(documentationComment, snapshot) Then
                ' The documentation comment is valid, but does not meet the criteria for cases #1 or #2.
                ' So, it must be case #3
                InsertLineBreakAndTripleApostrophesAtCaret(subjectBufferCaretPosition)
                Return
            End If

            Dim targetMember = GetDocumentationCommentTargetMember(documentationComment)
            If targetMember.SupportsDocumentationComments() AndAlso
                targetMember.Span.Start > documentationComment.Span.Start Then
                If Not IsRestOfLineWhitespace(snapshot, caretPosition) Then
                    ' Since there is text to the right, this must be cast #3 (e.g. /// <summary>|</summary>)
                    InsertLineBreakAndTripleApostrophesAtCaret(subjectBufferCaretPosition)
                Else
                    ' At this point, we know it's case #1
                    InsertCommentAfterTripleApostrophesCore(targetMember, tree, caretPosition, subjectBufferCaretPosition)
                End If

                Return
            End If

            ' Now, determine whether pressing ENTER produced a valid doc comment with an appropriate
            ' target member. If so, it is case #2. Otherwise, it's case #3.

            ' Let the ENTER key pass through to the editor
            nextHandler()

            Dim postSnapshot = args.SubjectBuffer.CurrentSnapshot
            Dim postTree As SyntaxTree = Nothing
            If Not _workspace.TryGetSyntaxTree(postSnapshot, postTree) Then
                Return
            End If

            ' Note that we use the same caret position as we did before ENTER was passed to the editor.
            ' This should give us back the same doc comment.

            Dim postDocumentationComment = GetDocumentationComment(postTree, caretPosition)
            If postDocumentationComment Is Nothing Then
                Return
            End If

            If Not SpansSingleLine(postDocumentationComment, postSnapshot) OrElse
                Not IsExteriorTriviaLeftOfPosition(postDocumentationComment, caretPosition) Then
                Return
            End If

            Dim postTargetMember = GetDocumentationCommentTargetMember(postDocumentationComment)
            If Not postTargetMember.SupportsDocumentationComments() OrElse
                caretPosition > postTargetMember.Span.Start Then
                Return
            End If

            ' If we got here, it's case #2

            Dim indent = postSnapshot.GetLeadingWhitespaceOfLineAtPosition(caretPosition)
            Dim replaceSpan = Span.FromBounds(caretPosition, postTargetMember.GetFirstToken().Span.Start)

            Dim pair = GenerateDocumentationCommentText(
                postTargetMember, postTree, indent,
                prependExteriorTrivia:=False,
                appendLineBreakAndIndent:=True)

            ' Note that we replace the inserted line break and any indent that was added to ensure that
            ' everything lines up properly.

            ReplaceWithCommentText(
                replaceSpan,
                commentText:=pair.Item1,
                caretOffset:=pair.Item2,
                subjectBufferCaretPosition:=subjectBufferCaretPosition)
        End Sub

        Private Function InsertCommentAfterTripleApostrophes(ByVal textView As ITextView, ByVal subjectBuffer As ITextBuffer) As Boolean
            ' We generate a documentation comment when typing ''' under very specific circumstances:
            '     * The caret is immediately after the ''' of a documentation comment
            '     * After the caret, the line only contains only whitespace
            '     * The documentation comment only spans a single line
            '     * The documentation comment is attached to an appropriate member

            Dim subjectBufferCaretPosition As New subjectBufferCaretPosition(textView, subjectBuffer)

            Dim caretPosition = If(subjectBufferCaretPosition.Position, -1)
            If caretPosition < 0 Then
                Return False
            End If

            Dim snapshot = subjectBuffer.CurrentSnapshot

            If Not IsRestOfLineWhitespace(snapshot, caretPosition) Then
                Return False
            End If

            Dim tree As SyntaxTree = Nothing
            If Not _workspace.TryGetSyntaxTree(snapshot, tree) Then
                Return False
            End If

            Dim documentationComment = GetDocumentationComment(tree, caretPosition)
            If documentationComment Is Nothing OrElse
                Not IsExteriorTriviaLeftOfPosition(documentationComment, caretPosition) OrElse
                Not SpansSingleLine(documentationComment, snapshot) Then

                Return False
            End If

            Dim targetMember = GetDocumentationCommentTargetMember(documentationComment)
            If Not targetMember.SupportsDocumentationComments() Then
                Return False
            End If

            If caretPosition > targetMember.Span.Start Then
                Return False
            End If

            InsertCommentAfterTripleApostrophesCore(targetMember, tree, caretPosition, subjectBufferCaretPosition)

            Return True
        End Function

        Private Sub InsertCommentAfterTripleApostrophesCore(
            ByVal targetMember As StatementSyntax,
            ByVal tree As SyntaxTree,
            ByVal position As Integer,
            ByVal subjectBufferCaretPosition As SubjectBufferCaretPosition)

            Dim indent = tree.Text.GetLeadingWhitespaceOfLineAtPosition(position)

            Dim pair = GenerateDocumentationCommentText(
                targetMember, tree, indent,
                prependExteriorTrivia:=False,
                appendLineBreakAndIndent:=False)

            InsertCommentText(
                position:=position,
                commentText:=pair.Item1,
                caretOffset:=pair.Item2,
                subjectBufferCaretPosition:=subjectBufferCaretPosition)
        End Sub

        Private Function InsertCommentOnContainingMember(ByVal textView As ITextView, ByVal subjectBuffer As ITextBuffer) As Boolean
            ' The strategy here is simple. Retrieve the member declaration that contains the caret.
            ' If it supports documentation comments and doesn't already have one, generate and
            ' insert a documentation comment.

            Dim subjectBufferCaretPosition As New subjectBufferCaretPosition(textView, subjectBuffer)

            Dim caretPosition = If(subjectBufferCaretPosition.Position, -1)
            If caretPosition < 0 Then
                Return False
            End If

            Dim snapshot = subjectBuffer.CurrentSnapshot
            Dim tree As SyntaxTree = Nothing
            If Not _workspace.TryGetSyntaxTree(snapshot, tree) Then
                Return False
            End If

            Dim token = tree.Root.FindToken(caretPosition)

            Dim targetMember = token.GetContainingMember()
            If Not targetMember.SupportsDocumentationComments() OrElse
                targetMember.Span.Start > caretPosition OrElse
                targetMember.Span.End < caretPosition Then

                Return False
            End If

            If targetMember.HasDocumentationComment() Then
                Return False
            End If

            Dim indent = tree.Text.GetLeadingWhitespaceOfLineAtPosition(targetMember.GetFirstToken().Span.Start)

            Dim pair = GenerateDocumentationCommentText(
                targetMember, tree, indent,
                prependExteriorTrivia:=True,
                appendLineBreakAndIndent:=True)

            InsertCommentText(
                position:=targetMember.Span.Start,
                commentText:=pair.Item1,
                caretOffset:=pair.Item2,
                subjectBufferCaretPosition:=subjectBufferCaretPosition)

            Return True
        End Function

        Private Sub InsertLineBreakAndTripleApostrophesAtCaret(ByVal subjectBufferCaretPosition As SubjectBufferCaretPosition)
            Dim caretPosition = If(subjectBufferCaretPosition.Position, -1)
            If caretPosition < 0 Then
                Return
            End If

            Dim subjectBuffer = subjectBufferCaretPosition.SubjectBufferSnapshot.TextBuffer

            Dim snapshot = subjectBuffer.CurrentSnapshot
            Dim lineNumber = snapshot.GetLineNumberFromPosition(caretPosition)

            Dim indent = String.Empty
            If lineNumber >= 0 Then
                Dim line = snapshot.GetLineFromLineNumber(lineNumber)
                Dim lineText = line.GetText()
                Dim slashesIndex = lineText.IndexOf("'''")
                If slashesIndex >= 0 Then
                    indent = New String(" "c, slashesIndex)
                End If
            End If

            Dim text = vbCrLf & indent & "''' "

            Dim newSnapshot = subjectBuffer.Insert(caretPosition, text)
            Dim caretPoint = New SnapshotPoint(newSnapshot, caretPosition + text.Length)

            subjectBufferCaretPosition.TryMoveTo(caretPoint)
        End Sub

        Private Sub InsertCommentText(
            ByVal position As Integer,
            ByVal commentText As String,
            ByVal caretOffset As Integer,
            ByVal subjectBufferCaretPosition As SubjectBufferCaretPosition)

            If String.IsNullOrWhiteSpace(commentText) Then
                Return
            End If

            Dim subjectBuffer = subjectBufferCaretPosition.SubjectBufferSnapshot.TextBuffer
            Dim newSnapshot = subjectBuffer.Insert(position, commentText)
            Dim caretPoint = New SnapshotPoint(newSnapshot, position + caretOffset)
            subjectBufferCaretPosition.TryMoveTo(caretPoint)
        End Sub

        Private Sub ReplaceWithCommentText(
            ByVal replaceSpan As Span,
            ByVal commentText As String,
            ByVal caretOffset As Integer,
            ByVal subjectBufferCaretPosition As SubjectBufferCaretPosition)

            If String.IsNullOrWhiteSpace(commentText) Then
                Return
            End If

            Dim subjectBuffer = subjectBufferCaretPosition.SubjectBufferSnapshot.TextBuffer
            Dim newSnapshot = subjectBuffer.Replace(replaceSpan, commentText)
            Dim caretPoint = New SnapshotPoint(newSnapshot, replaceSpan.Start + caretOffset)
            subjectBufferCaretPosition.TryMoveTo(caretPoint)
        End Sub

        Private Function IsRestOfLineWhitespace(ByVal snapshot As ITextSnapshot, ByVal position As Integer) As Boolean
            Dim line = snapshot.GetLineFromPosition(position)
            Dim lineTextToEnd = line.GetText().Substring(position - line.Start.Position)
            Return String.IsNullOrWhiteSpace(lineTextToEnd)
        End Function

        Private Function GetDocumentationComment(ByVal tree As SyntaxTree, ByVal position As Integer) As DocumentationCommentSyntax
            Dim trivia = tree.Root.FindTrivia(position)
            If (trivia.Kind = SyntaxKind.DocumentationComment) Then
                Return DirectCast(trivia.GetStructure(), DocumentationCommentSyntax)
            Else
                Return Nothing
            End If
        End Function

        Private Function ExteriorTriviaStartsLine(ByVal tree As SyntaxTree, ByVal documentationComment As DocumentationCommentSyntax, ByVal position As Integer) As Boolean
            Dim line = tree.Text.GetLineFromPosition(position)
            Dim firstNonWhitespacePosition = line.GetFirstNonWhitespacePosition()
            If Not firstNonWhitespacePosition.HasValue Then
                Return False
            End If

            Dim token = documentationComment.FindToken(firstNonWhitespacePosition.Value)
            Dim trivia = token.LeadingTrivia.FirstOrDefault()
            Return trivia.Kind = SyntaxKind.DocumentationCommentExteriorTrivia
        End Function

        Private Function IsExteriorTriviaLeftOfPosition(ByVal documentationComment As DocumentationCommentSyntax, ByVal position As Integer) As Boolean
            Dim token = documentationComment.FindToken(position)
            Dim trivia = token.LeadingTrivia.FirstOrDefault()
            Return trivia.Kind = SyntaxKind.DocumentationCommentExteriorTrivia AndAlso
                trivia.Span.End = position
        End Function

        Private Function GetDocumentationCommentTargetMember(ByVal documentationComment As DocumentationCommentSyntax) As StatementSyntax
            Dim parentTrivia = documentationComment.ParentTrivia
            Return parentTrivia.Token.GetAncestor(Of StatementSyntax)()
        End Function

        Private Function SpansSingleLine(ByVal documentationComment As DocumentationCommentSyntax, ByVal snapshot As ITextSnapshot) As Boolean
            ' Use full span to include leading exterior trivia
            Dim startLine = snapshot.GetLineNumberFromPosition(documentationComment.FullSpan.Start)

            ' The last token *should* be an XmlTextLiteralNewLineToken and we'll use the start of its span
            ' to ensure that we aren't getting the line number after the line break.
            Dim lastToken = documentationComment.GetLastToken()
            Dim endLine = snapshot.GetLineNumberFromPosition(lastToken.Span.Start)

            Return startLine = endLine
        End Function

        ''' <summary>
        ''' Calculates the documentation comment for a target member and returns a tuple containing the text of the comment and
        ''' the offset of the expected caret position.
        ''' </summary>
        Private Function GenerateDocumentationCommentText(
            ByVal targetMember As StatementSyntax,
            ByVal tree As SyntaxTree,
            ByVal indent As String,
            Optional ByVal prependExteriorTrivia As Boolean = True,
            Optional ByVal appendLineBreakAndIndent As Boolean = False) As Tuple(Of String, Integer)

            Dim builder As New StringBuilder

            If prependExteriorTrivia Then
                builder.Append("'''")
            End If

            ' Append summary
            builder.AppendLine(" <summary>")
            builder.Append(indent + "''' ")
            Dim offset = builder.Length
            builder.AppendLine()
            builder.Append(indent + "''' </summary>")

            ' Append any type parameters
            Dim typeParameterList = targetMember.GetTypeParameterList()
            If typeParameterList IsNot Nothing Then
                For Each typeParameter In typeParameterList.Parameters
                    builder.AppendLine()

                    builder.Append(indent + "''' <typeparam name=""")

                    Dim typeParameterName = typeParameter.Name.GetText()
                    If Not String.IsNullOrWhiteSpace(typeParameterName) Then
                        builder.Append(typeParameterName)
                    Else
                        builder.Append("?")
                    End If

                    builder.Append("""></typeparam>")
                Next
            End If

            ' Append any parameters
            Dim parameterList = targetMember.GetParameterList()
            If parameterList IsNot Nothing Then
                For Each parameter In parameterList.Parameters
                    builder.AppendLine()

                    builder.Append(indent + "''' <param name=""")
                    builder.Append(parameter.Name.GetText())
                    builder.Append("""></param>")
                Next
            End If

            ' Append return type
            Dim returnType = targetMember.GetReturnType()
            If returnType IsNot Nothing Then
                builder.AppendLine()
                builder.Append(indent + "''' <returns></returns>")
            End If

            If appendLineBreakAndIndent Then
                builder.AppendLine()
                builder.Append(indent)
            End If

            Return Tuple.Create(builder.ToString(), offset)
        End Function
    End Class
End Namespace


text:
<?php

/**
 * @namespace
 */
namespace Application\Tests\Test;

use Application\Tests\TestCase;
use Application\Tests\Fixtures\Users\UserHasPermission;
use Bluz\Proxy\Auth;

/**
 * @package Application\Tests\Test
 * @author   Anton Shevchuk
 * @created  19.05.2014 12:08
 */
class WidgetDeniedTest extends TestCase
{
    /**
     * Try with permissions
     */
    public function testAllow()
    {
        Auth::setIdentity(new UserHasPermission());
        $this->getApp()->widget('test', 'acl-denied');
    }

    /**
     * @expectedException \Bluz\Application\Exception\ForbiddenException
     */
    public function testDenied()
    {
        $this->getApp()->widget('test', 'acl-denied');
    }
}

redpajama_set_name: RedPajamaGithub


text:
exports.dir = "";

exports.status  = function( retorno ){

	exec( ' git status -s' , {cwd: this.dir },function(error, stdout, stderr){
		retorno(stdout)
	});
}

exports.add = function( arquivo, retorno ){
		sys.puts(arquivo)
	exec( 'git add '+ arquivo,{ cwd: this.dir} ,function(error, stdout, stderr){
		retorno(stdout);
	});
}

exports.commit = function( titulo, msg, retorno ){
	exec(' git commit -m "'+ titulo + '\s\n' + msg + '"' ,{ cwd: this.dir},function(error, stdout, stderr){
		retorno(stdout);
		// sys.puts(error)
	});
}

exports.gitListContribuidores = function(retorno ){

	exec( 'git shortlog -s' ,{ cwd: this.dir},function(error, stdout, stderr){
		retorno(stdout);
		// puts( error, stdout, stderr );
		// console.log( error, stdout, stderr)
	});
}

exports.branchAtual = function(retorno){
	exec( 'git branch' ,{ cwd: this.dir},function(error, stdout, stderr){
		retorno(stdout);
		// puts( error, stdout, stderr );
	});
}

exports.listaBranch = function(retorno){
	exec( 'git branch -a' ,{ cwd: this.dir},function(error, stdout, stderr){

		var b = stdout;
			b = b.toString("utf8");
			b = b.split(/\n/)
			b.pop()
		retorno(b);
	});
}


text:
===========================
Wagtail 2.7.1 release notes
===========================

.. contents::
    :local:
    :depth: 1

What's new
==========

Bug fixes
~~~~~~~~~

 * Management command startup checks under ``ManifestStaticFilesStorage`` no longer fail if ``collectstatic`` has not been run first (Alex Tomkins)


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title>My app documentation</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="icon" type="image/x-icon" href="../images/favicon.ico">
	    <link rel="stylesheet" href="../styles/style.css">

            My app documentation
            <button type="button" class="btn btn-default btn-menu fa fa-bars" id="btn-menu"></button>

                <input type="text" placeholder="Type to search">

                        My app documentation

                        Getting started

                                        Overview

                            Modules

                                    AppModule

                            Components

                                    AdminDashboardComponent

                                    AdminRegisterComponent

                                    AdminUsersComponent

                                    AppComponent

                                    BoxComponent

                                    BoxesComponent

                                    DashboardComponent

                                    HomeComponent

                                    IconComponent

                                    ListGroupComponent

                                    LoginComponent

                                    ModalComponent

                                    NavbarComponent

                                    ProfileComponent

                                    ProgressbarComponent

                                    RegisterComponent

                                    SidebarComponent

                                    TableColumnsComponent

                                    TableComponent

                                    UploadFileComponent

                                    UploadPortfolioComponent

                            Classes

                                    AngularSrcPage

                        Routes

                            Injectables

                                    AdministratorGuard

                                    AdministratorsService

                                    AuthGuard

                                    AuthService

                                    OrganizationsService

                                    UsersService

                                    UtilitiesService

                                    ValidateService

                        Miscellaneous

                        Documentation coverage

                            Documentation generated using

                               My app documentation

                                   <input type="text" placeholder="Type to search">

                               Getting started

                                               Overview

                                   Modules

                                           AppModule

                                   Components

                                           AdminDashboardComponent

                                           AdminRegisterComponent

                                           AdminUsersComponent

                                           AppComponent

                                           BoxComponent

                                           BoxesComponent

                                           DashboardComponent

                                           HomeComponent

                                           IconComponent

                                           ListGroupComponent

                                           LoginComponent

                                           ModalComponent

                                           NavbarComponent

                                           ProfileComponent

                                           ProgressbarComponent

                                           RegisterComponent

                                           SidebarComponent

                                           TableColumnsComponent

                                           TableComponent

                                           UploadFileComponent

                                           UploadPortfolioComponent

                                   Classes

                                           AngularSrcPage

                               Routes

                                   Injectables

                                           AdministratorGuard

                                           AdministratorsService

                                           AuthGuard

                                           AuthService

                                           OrganizationsService

                                           UsersService

                                           UtilitiesService

                                           ValidateService

                               Miscellaneous

                               Documentation coverage

                                   Documentation generated using

Injectables

AuthService

        Infos

        Source

File

            app/services/auth.service.ts

Constructor

                                    constructor(http: Http)

Methods

                                     registerUser

            registerUser(user: any)

                                            Returns:     void

                                     authenticateUser

            authenticateUser(user: any)

                                            Returns:     void

                                     storeUserData

            storeUserData(token: any, user: any, role: any)

                                            Returns:     void

                                     logout

            logout()

                                            Returns:     void

                                     getProfile

            getProfile()

                                            Returns:     void

                                     loadToken

            loadToken()

                                            Returns:     void

                                     getUserIdLoggedIn

            getUserIdLoggedIn()

                                            Returns:     void

                                     loadVariables

            loadVariables()

                                            Returns:     void

                                     checkLoggedIn

            checkLoggedIn()

                                            Returns:     void

Properties

                                     authToken

                                    authToken:     any
            </bcode>

                                     user

                                    user:     any
            </bcode>

                                     userRole

                                    userRole:     Number
            </bcode>

'use strict'
//Modules
import { Injectable } from '@angular/core';
import {Http,Headers} from '@angular/http';
import 'rxjs/add/operator/map';
//Third party Module
import {tokenNotExpired} from 'angular2-jwt';

@Injectable()
export class AuthService {
  authToken:any;
  user:any;
  userRole:Number;
  // inject the http module into the constructor. like the service
  constructor(private http:Http) { }
//
  // this always is going to be a user object because i do the validation in the register view
  // this is the post to register a new user
  registerUser(user){
    let headers = new Headers();
    //set the Content-Type to application/json
    headers.append('Content-Type','application/json');
    if(!user.role){
      return;
    }

    console.log("rol de que registra: " + user.role);
    if(user.role == 2){
      // return an observable with the response
      // here I make the Post http call. The second parameter is the data the I want to send to the post call,third parameter are the options. .map map or convert every value to a json
      return this.http.post('/users/register',{headers:headers,user}).map(res => res.json()); // change this to localhost when testing
    }else if (user.role ==1 ){
      console.log("registrandolo como administrator");
      return this.http.post('/administrator/register',{headers:headers,user}).map(res => res.json());
    }
  }

  // Make Http Call to Login user
  authenticateUser(user){
    let headers = new Headers();
    //set the Content-Type to application/json
    headers.append('Content-Type','application/json');
    // observable make the http call to authenticate user
    // This is going to send the succes message and the authenticate Token
    return this.http.post('/users/authenticate',user,{headers:headers}).map(res => res.json());
  }

  // authenticater user login with the token
  storeUserData(token,user,role){
    // when using jwt-token it look for this key exactly id_token. saving token to local storage
    localStorage.setItem('id_token',token)
    // save to local storage user. we need to store as a string because it cant store object. when we need it back we parse it back to json
    // localStorage.setItem('user',JSON.stringify(user))
    localStorage.setItem('user',user)
    // set localStorage role
    localStorage.setItem('role',role)

    // set values to the variable
    this.authToken = token;
    this.user = user;
    // cargar underscore verificar si role no es empty y setiar el role. pq
    // si voy a estar confiando tanto en el role de auth.servoce tengo que asegurarme que nunca
    // sea nullo pq si no esto puede traer mucho comportamiento inesperado
    this.userRole = role;
  }

  logout(){
    // set variables to null
    this.authToken = null;
    this.user = null;
    // clear local storage
    localStorage.clear()
  }

  // Get Profile
  getProfile(){
    let headers = new Headers();
    //set the Content-Type to application/json
    // with this now we have acces to the token.
    this.loadToken()
    // append the token to the header
    headers.append('Authorization',this.authToken);
    headers.append('Content-Type','application/json');
    // this get request send the token and user info in a json response
    return this.http.get('/users/profile',{headers:headers}).map(res => res.json());
  }

  loadToken(){
    // Load token from local storage
    const token = localStorage.getItem('id_token');
    this.authToken = token;
  }

  getUserIdLoggedIn(){
    if(this.checkLoggedIn()){
      const userId = localStorage.getItem('user');
      return userId;
    }
  }
  loadVariables(){

  }

  // check if there's a user sing in
  checkLoggedIn(){
    return tokenNotExpired('id_token');
  }

}

 results matching ""

No results matching ""


text:
namespace flutter {

// A view displaying Flutter content.
class FlutterView {
 public:
  explicit FlutterView(FlutterDesktopViewRef view) : view_(view) {}

  virtual ~FlutterView() = default;

  // Prevent copying.
  FlutterView(FlutterView const&) = delete;
  FlutterView& operator=(FlutterView const&) = delete;

#ifndef WINUWP
  // Returns the backing HWND for the view.
  HWND GetNativeWindow() { return FlutterDesktopViewGetHWND(view_); }
#endif

 private:
  // Handle for interacting with the C API's view.
  FlutterDesktopViewRef view_ = nullptr;
};

}  // namespace flutter

#endif  // FLUTTER_SHELL_PLATFORM_WINDOWS_CLIENT_WRAPPER_INCLUDE_FLUTTER_FLUTTER_VIEW_H_


text:
"""
.. module: security_monkey.watchers.github.org
    :platform: Unix
    :synopsis: Watcher for GitHub Organizations.

.. version:: $$VERSION$$
.. moduleauthor:: Mike Grima <mgrima@netflix.com>

"""
from security_monkey import app
from security_monkey.common.github.util import get_github_creds, iter_org, strip_url_fields
from security_monkey.datastore import Account
from security_monkey.decorators import record_exception
from security_monkey.exceptions import InvalidResponseCodeFromGitHubError
from security_monkey.watcher import Watcher, ChangeItem
import requests

GITHUB_URL = "https://api.github.com/"

class GitHubOrg(Watcher):
    index = 'organization'
    i_am_singular = 'organization'
    i_am_plural = 'organizations'
    account_type = 'GitHub'

    def __init__(self, accounts=None, debug=False):
        super(GitHubOrg, self).__init__(accounts=accounts, debug=debug)
        self.honor_ephemerals = True
        self.ephemeral_paths = [
            "disk_usage",
            "owned_private_repos",
            "public_repos",
            "disk_usage"
        ]
        self.github_creds = get_github_creds(self.accounts)

    def slurp(self):
        @record_exception(source="{index}-watcher".format(index=self.index))
        def fetch_org_details(**kwargs):
            item_list = []
            account = Account.query.filter(Account.name == kwargs["account_name"]).first()

            # Fetch the initial GitHub organization details:
            app.logger.debug("Fetching initial org details for: {}".format(account.identifier))
            org_details = strip_url_fields(self.get_org_details(account.identifier))

            # Now, fetch details about the users within the organization:
            app.logger.debug("Fetching members for: {}".format(account.identifier))
            members = self.list_org_members(account.identifier)
            org_details["members"] = sorted(members)

            app.logger.debug("Fetching owners for: {}".format(account.identifier))
            owners = self.list_org_members(account.identifier, role="admin")
            org_details["owners"] = sorted(owners)

            app.logger.debug("Fetching members without 2FA for: {}".format(account.identifier))
            no_twofa = self.list_org_members(account.identifier, twofa="2fa_disabled")
            org_details["no_2fa_members"] = sorted(no_twofa)

            # Fetch outside collabs:
            app.logger.debug("Fetching all outside collaborators for: {}".format(account.identifier))
            outside_collabs = self.list_org_outside_collabs(account.identifier)
            org_details["outside_collaborators"] = sorted(outside_collabs)

            # Fetch teams:
            app.logger.debug("Fetching all teams for: {}".format(account.identifier))
            teams = self.list_org_teams(account.identifier)
            org_details["teams"] = sorted(teams)

            item_list.append(GitHubOrgItem(
                account=account.name,
                name=account.identifier,
                arn=account.identifier,
                config=org_details
            ))

            return item_list, kwargs["exception_map"]

        @iter_org(orgs=self.accounts)
        def slurp_items(**kwargs):
            # Are we skipping this org?
            if self.check_ignore_list(kwargs["account_name"]):
                app.logger.debug("Skipping ignored account: {}".format(kwargs["account_name"]))
                return [], kwargs["exception_map"]

            # Exception handling complexities...
            results = fetch_org_details(**kwargs)
            if not results:
                return [], kwargs["exception_map"]

            return results

        items, exc = slurp_items(index=self.index)

        return items, exc

    def get_org_details(self, org):
        headers = {
            'Authorization': 'token {}'.format(self.github_creds[org])
        }

        url = "{}orgs/{}".format(GITHUB_URL, org)

        result = requests.get(url, headers=headers)

        if result.status_code != 200:
            raise InvalidResponseCodeFromGitHubError(org, result.status_code)

        return result.json()

    def list_org_members(self, org, role="all", twofa="all"):
        headers = {
            'Authorization': 'token {}'.format(self.github_creds[org])
        }

        params = {
            "page": 1,
            "role": role,
            "filter": twofa
        }
        done = False

        members = set()

        while not done:
            url = "{}orgs/{}/members".format(GITHUB_URL, org)
            result = requests.get(url, headers=headers, params=params)

            if result.status_code != 200:
                raise InvalidResponseCodeFromGitHubError(org, result.status_code)

            if not result.links.get("last"):
                done = True
            else:
                params["page"] += 1

            result_json = result.json()
            for member in result_json:
                members.add(member["login"])

        return list(members)

    def list_org_outside_collabs(self, org):
        headers = {
            'Authorization': 'token {}'.format(self.github_creds[org])
        }

        params = {
            "page": 1,
        }

        done = False
        collabs = set()
        url = "{}orgs/{}/outside_collaborators".format(GITHUB_URL, org)

        while not done:
            result = requests.get(url, headers=headers, params=params)

            if result.status_code != 200:
                raise InvalidResponseCodeFromGitHubError(org, result.status_code)

            if not result.links.get("last"):
                done = True
            else:
                params["page"] += 1

            result_json = result.json()
            for collab in result_json:
                collabs.add(collab["login"])

        return list(collabs)

    def list_org_teams(self, org):
        headers = {
            'Authorization': 'token {}'.format(self.github_creds[org])
        }

        params = {
            "page": 1,
        }

        done = False
        teams = set()
        url = "{}orgs/{}/teams".format(GITHUB_URL, org)

        while not done:
            result = requests.get(url, headers=headers, params=params)

            if result.status_code != 200:
                raise InvalidResponseCodeFromGitHubError(org, result.status_code)

            if not result.links.get("last"):
                done = True
            else:
                params["page"] += 1

            result_json = result.json()
            for team in result_json:
                teams.add(team["name"])

        return list(teams)

class GitHubOrgItem(ChangeItem):
    def __init__(self, account=None, name=None, arn=None, config=None):
        if config is None:
            config = {}
        super(GitHubOrgItem, self).__init__(index=GitHubOrg.index,
                                            region="universal",
                                            account=account,
                                            name=name,
                                            arn=arn,
                                            new_config=config)


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <note/>
    <predicate lemma="calligraphy">
        <note/>
        <roleset framnet="" id="calligraphy.01" name="Write decoratively" vncls="">
            <roles>
                <role descr="Writer, artist" f="" n="0"/>
                <note/>
                <role descr="Words written in calligraphy" f="" n="1"/>
                <role descr="Entity decorated with calligraphy" f="" n="2"/>
            </roles>
            <note>Roleset based on instances in nouns-lv.  Probably only works as eventive noun in LVC. Comparison to 'write'.</note>
            <example name="Arg 0 only, within LVC" src="nouns-lv" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>" When I was little , my grandfather taught me *PRO* to read Chinese poems and do calligraphy .</text>
                <note/>
                <arg f="" n="0">*PRO*</arg>
                <arg f="lvb" n="m">do</arg>
                <rel f="">calligraphy</rel>
            </example>
        </roleset>
    </predicate>
</frameset>


text:
"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

exports.__esModule = true;
exports.getGatsbyVersion = void 0;

var _path = _interopRequireDefault(require("path"));

const getGatsbyVersion = () => {
  try {
    return require(_path.default.join(process.cwd(), `node_modules`, `gatsby`, `package.json`)).version;
  } catch (e) {
    return ``;
  }
};

exports.getGatsbyVersion = getGatsbyVersion;


text:
#include "DT3Core/Types/Utility/Error.hpp"
#include "DT3Core/Types/Utility/Callback.hpp"
#include "DT3Core/Types/Utility/ConsoleStream.hpp"

//==============================================================================
//==============================================================================

namespace DT3 {

//==============================================================================
//==============================================================================

std::shared_ptr<Callback<const DTcharacter*, const DTcharacter*, DTint, const DTcharacter*>>   ErrorImpl::_callback_error_msg;
std::shared_ptr<Callback<const DTcharacter*, const DTcharacter*, DTint, const DTcharacter*>>   ErrorImpl::_callback_warning_msg;

//==============================================================================
//==============================================================================

void ErrorImpl::set_callback_error_msg (std::shared_ptr<Callback<const DTcharacter*, const DTcharacter*, DTint, const DTcharacter*>> cb)
{
    _callback_error_msg = cb;
}

void ErrorImpl::call_error_msg (const DTcharacter* file, const DTcharacter* func, DTint line, const DTcharacter *msg)
{
    if (_callback_error_msg)
        (*_callback_error_msg)(file, func, line, msg);
    else {
        LOG_ERROR << "In file " << file << " in function " << func << " on line " << line << ": " << msg;
    }
}

//==============================================================================
//==============================================================================

void ErrorImpl::set_callback_warning_msg (std::shared_ptr<Callback<const DTcharacter*, const DTcharacter*, DTint, const DTcharacter*>> cb)
{
    _callback_error_msg = cb;
}

void ErrorImpl::call_warning_msg (const DTcharacter* file, const DTcharacter* func, DTint line, const DTcharacter *msg)
{
    if (_callback_warning_msg)
        (*_callback_warning_msg)(file, func, line, msg);
    else {
        LOG_MESSAGE << "In file " << file << " in function " << func << " on line " << line << ": " << msg;
    }
}

//==============================================================================
//==============================================================================

} // DT3


text:
package javax.imageio.spi;

/*
 * Dummy class used by ServiceRegistryTest
 */
public class CorrectProviderConfiguration {

}


text:
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CodeFixes;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;

namespace RefactoringEssentials.CSharp.Diagnostics
{

	[ExportCodeFixProvider(LanguageNames.CSharp), System.Composition.Shared]
    public class RedundantDelegateCreationCodeFixProvider : CodeFixProvider
    {
        public override ImmutableArray<string> FixableDiagnosticIds
        {
            get
            {
                return ImmutableArray.Create(CSharpDiagnosticIDs.RedundantDelegateCreationAnalyzerID);
            }
        }

        public override FixAllProvider GetFixAllProvider()
        {
            return WellKnownFixAllProviders.BatchFixer;
        }

        public async override Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var document = context.Document;
            var cancellationToken = context.CancellationToken;
            var span = context.Span;
            var diagnostics = context.Diagnostics;
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
            var diagnostic = diagnostics.First();
            var objectCreation = root.FindNode(context.Span) as ObjectCreationExpressionSyntax;
            var argument = objectCreation?.ArgumentList.Arguments[0];

            if (argument == null)
                return;

            var newRoot = root.ReplaceNode(objectCreation,
                argument.Expression
                .WithoutLeadingTrivia()
                .WithAdditionalAnnotations(Formatter.Annotation));
            context.RegisterCodeFix(CodeActionFactory.Create(objectCreation.Span, diagnostic.Severity, "Remove redundant 'new'", document.WithSyntaxRoot(newRoot)), diagnostic);
        }

    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: dwendlandt
 * Date: 13/08/14
 * Time: 22:39
 */

namespace Elastification\Client\Tests\Unit\Response\V090x;

use Elastification\Client\Exception\ResponseException;
use Elastification\Client\Response\V090x\SearchResponse;
use Elastification\Client\Serializer\Gateway\NativeArrayGateway;
use Elastification\Client\Serializer\Gateway\NativeObjectGateway;

class SearchResponseTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    private $serializer;

    protected function setUp()
    {
        parent::setUp();

        $this->serializer = $this->getMockBuilder('Elastification\Client\Serializer\SerializerInterface')
            ->disableOriginalConstructor()
            ->getMock();
    }

    protected function tearDown()
    {
        $this->serializer = null;
        parent::tearDown();
    }

    public function testInstance()
    {
        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse('data', $this->serializer);
        $this->assertInstanceOf('Elastification\Client\Response\ResponseInterface', $response);
        $this->assertInstanceOf('Elastification\Client\Response\Response', $response);
        $this->assertInstanceOf('Elastification\Client\Response\V090x\SearchResponse', $response);
    }

    public function testGetIndexArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_INDEX], $response->getIndex());
    }

    public function testGetIndexObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_INDEX], $response->getIndex());
    }

    public function testGetTypeArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_TYPE], $response->getType());
    }

    public function testGetTypeObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_TYPE], $response->getType());
    }

    public function testTimedOutArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_TIMED_OUT], $response->timedOut());
    }

    public function testTimedOutObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_TIMED_OUT], $response->timedOut());
    }

    public function testTookArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_TOOK], $response->took());
    }

    public function testTookObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_TOOK], $response->took());
    }

    public function testGetShardsArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertEquals($data[SearchResponse::PROP_SHARDS]->getGatewayValue(), $response->getShards());
    }

    public function testGetShardsObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertEquals($data[SearchResponse::PROP_SHARDS]->getGatewayValue(), $response->getShards());
    }

    public function testGetHitsArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertEquals($data[SearchResponse::PROP_HITS]->getGatewayValue(), $response->getHits());
    }

    public function testGetHitsObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertEquals($data[SearchResponse::PROP_HITS]->getGatewayValue(), $response->getHits());
    }

    public function testTotalHitsArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_HITS][SearchResponse::PROP_HITS_TOTAL], $response->totalHits());
    }

    public function testTotalHitsObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $hits = $data[SearchResponse::PROP_HITS];
        $this->assertSame($hits[SearchResponse::PROP_HITS_TOTAL], $response->totalHits());
    }

    public function testTotalHitsNestedObject()
    {
        $data = $this->getData(true);
        $data->{SearchResponse::PROP_HITS} = $this->getHitsData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $hits = $data[SearchResponse::PROP_HITS];
        $this->assertSame($hits[SearchResponse::PROP_HITS_TOTAL], $response->totalHits());
    }

    public function testMaxScoreHitsArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame(
            $data[SearchResponse::PROP_HITS][SearchResponse::PROP_HITS_MAX_SCORE],
            $response->maxScoreHits()
        );
    }

    public function testMaxScoreHitsObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $hits = $data[SearchResponse::PROP_HITS];
        $this->assertSame($hits[SearchResponse::PROP_HITS_MAX_SCORE], $response->maxScoreHits());
    }

    public function testMaxScoreHitsNestedObject()
    {
        $data = $this->getData(true);
        $data->{SearchResponse::PROP_HITS} = $this->getHitsData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $hits = $data[SearchResponse::PROP_HITS];
        $this->assertSame($hits[SearchResponse::PROP_HITS_MAX_SCORE], $response->maxScoreHits());
    }

    public function testHitsHitsArray()
    {
        $data = $this->getData();

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $this->assertSame($data[SearchResponse::PROP_HITS][SearchResponse::PROP_HITS_HITS]->getGatewayValue(),
            $response->getHitsHits());
    }

    public function testHitsHitsObject()
    {
        $data = $this->getData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $hits = $data[SearchResponse::PROP_HITS];
        $this->assertSame($hits[SearchResponse::PROP_HITS_HITS]->getGatewayValue(), $response->getHitsHits());
    }

    public function testHitsHitsNestedObject()
    {
        $data = $this->getData(true);
        $data->{SearchResponse::PROP_HITS} = $this->getHitsData(true);

        $this->serializer->expects($this->once())
            ->method('deserialize')
            ->with(
                $this->equalTo($data),
                $this->equalTo(array())
            )
            ->will($this->returnValue($data));

        /** @noinspection PhpParamsInspection */
        $response = new SearchResponse($data, $this->serializer);
        $hits = $data[SearchResponse::PROP_HITS];
        $this->assertSame($hits[SearchResponse::PROP_HITS_HITS]->getGatewayValue(), $response->getHitsHits());
    }

    private function getData($asObject = false)
    {
        $data = [
            SearchResponse::PROP_INDEX => 'test-index',
            SearchResponse::PROP_TYPE => 'test-type',
            SearchResponse::PROP_TIMED_OUT => false,
            SearchResponse::PROP_TOOK => 1,
            SearchResponse::PROP_SHARDS => array('shard1' => array('ok')),
            SearchResponse::PROP_HITS => $this->getHitsData()
        ];

        if ($asObject) {
            return new NativeObjectGateway((object)$data);
        }

        return new NativeArrayGateway($data);
    }

    private function getHitsData($asObject = false)
    {
        $hits = array(
            SearchResponse::PROP_HITS_TOTAL => 8,
            SearchResponse::PROP_HITS_MAX_SCORE => 2,
            SearchResponse::PROP_HITS_HITS => array(
                'data' => 'test'
            )
        );

        if ($asObject) {
            return (object)$hits;
        }

        return $hits;
    }
}


text:
package org.camunda.bpm.engine.rest.dto.history;

import java.util.Date;

import org.camunda.bpm.engine.history.HistoricActivityInstance;

public class HistoricActivityInstanceDto {

  private String id;
  private String parentActivityInstanceId;
  private String activityId;
  private String activityName;
  private String activityType;
  private String processDefinitionKey;
  private String processDefinitionId;
  private String processInstanceId;
  private String executionId;
  private String taskId;
  private String calledProcessInstanceId;
  private String calledCaseInstanceId;
  private String assignee;
  private Date startTime;
  private Date endTime;
  private Long durationInMillis;
  private Boolean canceled;
  private Boolean completeScope;
  private String tenantId;
  private Date removalTime;
  private String rootProcessInstanceId;

  public String getId() {
    return id;
  }

  public String getParentActivityInstanceId() {
    return parentActivityInstanceId;
  }

  public String getActivityId() {
    return activityId;
  }

  public String getActivityName() {
    return activityName;
  }

  public String getActivityType() {
    return activityType;
  }

  public String getProcessDefinitionKey() {
    return processDefinitionKey;
  }

  public String getProcessDefinitionId() {
    return processDefinitionId;
  }

  public String getProcessInstanceId() {
    return processInstanceId;
  }

  public String getExecutionId() {
    return executionId;
  }

  public String getTaskId() {
    return taskId;
  }

  public String getCalledProcessInstanceId() {
    return calledProcessInstanceId;
  }

  public String getCalledCaseInstanceId() {
    return calledCaseInstanceId;
  }

  public String getAssignee() {
    return assignee;
  }

  public Date getStartTime() {
    return startTime;
  }

  public Date getEndTime() {
    return endTime;
  }

  public Long getDurationInMillis() {
    return durationInMillis;
  }

  public Boolean getCanceled() {
    return canceled;
  }

  public Boolean getCompleteScope() {
    return completeScope;
  }

  public String getTenantId() {
    return tenantId;
  }

  public Date getRemovalTime() {
    return removalTime;
  }

  public String getRootProcessInstanceId() {
    return rootProcessInstanceId;
  }

  public static void fromHistoricActivityInstance(HistoricActivityInstanceDto dto,
                                                  HistoricActivityInstance historicActivityInstance) {

    dto.id = historicActivityInstance.getId();
    dto.parentActivityInstanceId = historicActivityInstance.getParentActivityInstanceId();
    dto.activityId = historicActivityInstance.getActivityId();
    dto.activityName = historicActivityInstance.getActivityName();
    dto.activityType = historicActivityInstance.getActivityType();
    dto.processDefinitionKey = historicActivityInstance.getProcessDefinitionKey();
    dto.processDefinitionId = historicActivityInstance.getProcessDefinitionId();
    dto.processInstanceId = historicActivityInstance.getProcessInstanceId();
    dto.executionId = historicActivityInstance.getExecutionId();
    dto.taskId = historicActivityInstance.getTaskId();
    dto.calledProcessInstanceId = historicActivityInstance.getCalledProcessInstanceId();
    dto.calledCaseInstanceId = historicActivityInstance.getCalledCaseInstanceId();
    dto.assignee = historicActivityInstance.getAssignee();
    dto.startTime = historicActivityInstance.getStartTime();
    dto.endTime = historicActivityInstance.getEndTime();
    dto.durationInMillis = historicActivityInstance.getDurationInMillis();
    dto.canceled = historicActivityInstance.isCanceled();
    dto.completeScope = historicActivityInstance.isCompleteScope();
    dto.tenantId = historicActivityInstance.getTenantId();
    dto.removalTime = historicActivityInstance.getRemovalTime();
    dto.rootProcessInstanceId = historicActivityInstance.getRootProcessInstanceId();
  }
}


text:
package com.algaworks.pedidovenda.repository.filter;

import java.io.Serializable;

import com.algaworks.pedidovenda.validation.SKU;

public class ProdutoFilter implements Serializable {

	private static final long serialVersionUID = 1L;

	private String sku;
	private String nome;

	@SKU
	public String getSku() {
		return sku;
	}

	public void setSku(String sku) {
		this.sku = sku == null ? null : sku.toUpperCase();
	}

	public String getNome() {
		return nome;
	}
	public void setNome(String nome) {
		this.nome = nome;
	}

}


text:
Starting from Tower 3.3, OAuth2 will be used as the new means of token-based authentication. Users
will be able to manage OAuth2 tokens as well as applications, a server-side representation of API
clients used to generate tokens. With OAuth2, a user can authenticate by passing a token as part of
the HTTP authentication header. The token can be scoped to have more restrictive permissions on top of
the base RBAC permissions of the user.  Refer to [RFC 6749](https://tools.ietf.org/html/rfc6749) for
more details of OAuth2 specification.

## Basic Usage

To get started using OAuth2 tokens for accessing the browsable API using OAuth2, this document will walk through the steps of acquiring a token and using it.

1. Make an application with `authorization_grant_type` set to 'password'. HTTP POST the following to the `/api/v2/applications/`  endpoint (supplying your own `organization-id`):
```
{
    "name": "Admin Internal Application",
    "description": "For use by secure services & clients. ",
    "client_type": "confidential",
    "redirect_uris": "",
    "authorization_grant_type": "password",
    "skip_authorization": false,
    "organization": <organization-id>
}
```
2. Make a token with a POST to the `/api/v2/tokens/` endpoint:
```
{
    "description": "My Access Token",
    "application": <application-id>,
    "scope": "write"
}
```
This will return a `<token-value>` that you can use to authenticate with for future requests (this will not be shown again)

3. Use token to access a resource.  We will use `curl` to demonstrate this:
```
curl -H "Authorization: Bearer <token-value>" -X GET https://<awx>/api/v2/users/
```
> The `-k` flag may be needed if you have not set up a CA yet and are using SSL.

This token can be revoked by making a DELETE on the detail page for that token.  All you need is that token's id.  For example:
```
curl -ku <user>:<password> -X DELETE https://<awx>/api/v2/tokens/<pk>/
```

Similarly, using a token:
```
curl -H "Authorization: Bearer <token-value>" -X DELETE https://<awx>/api/v2/tokens/<pk>/ -k
```

## More Information

#### Managing OAuth2 Applications and Tokens

Applications and tokens can be managed as a top-level resource at `/api/v2/applications` and
`/api/v2/tokens`. These resources can also be accessed respective to the user at
`/api/v2/users/N/<resource>`.  Applications can be created by making a POST to either `api/v2/applications`
or `/api/v2/users/N/applications`.

Each OAuth2 application represents a specific API client on the server side. For an API client to use the API via an application token,
it must first have an application and issue an access token.

Individual applications will be accessible via their primary keys:
`/api/v2/applications/<pk>/`. Here is a typical application:
```
{
    "id": 1,
    "type": "o_auth2_application",
    "url": "/api/v2/applications/1/",
    "related": {
        "user": "/api/v2/users/1/",
        "tokens": "/api/v2/applications/1/tokens/",
        "activity_stream": "/api/v2/applications/1/activity_stream/"
    },
    "summary_fields": {
        "user": {
            "id": 1,
            "username": "root",
            "first_name": "",
            "last_name": ""
        },
        "tokens": {
            "count": 1,
            "results": [
                {
                    "scope": "read",
                    "token": "*************",
                    "id": 2
                }
            ]
        }
    },
    "created": "2018-02-20T23:06:43.215315Z",
    "modified": "2018-02-20T23:06:43.215375Z",
    "name": "Default application for root",
    "user": 1,
    "client_id": "BIyE720WAjr14nNxGXrBbsRsG0FkjgeL8cxNmIWP",
    "client_secret": "OdO6TMNAYxUVv4HLitLOnRdAvtClEV8l99zlb8EJEZjlzVNaVVlWiKXicznLDeANwu5qRgeQRvD3AnuisQGCPXXRCx79W1ARQ5cSmc9mrU1JbqW7nX3IZYhLIFgsDH8u",
    "client_type": "confidential",
    "redirect_uris": "",
    "authorization_grant_type": "password",
    "skip_authorization": false
},
```
In the above example, `user` is the primary key of the user associated to this application and `name` is
 a human-readable identifier for the application. The other fields, like `client_id` and
`redirect_uris`, are mainly used for OAuth2 authorization, which will be covered later in the 'Using
OAuth2 Token System' section.

Fields `client_id` and `client_secret` are immutable identifiers of applications, and will be
generated during creation; Fields `user` and `authorization_grant_type`, on the other hand, are
*immutable on update*, meaning they are required fields on creation, but will become read-only after
that.

**On RBAC side:**
- System admins will be able to see and manipulate all applications in the system;
- Organization admins will be able to see and manipulate all applications belonging to Organization
  members;
- Other normal users will only be able to see, update and delete their own applications, but
  cannot create any new applications.

Tokens, on the other hand, are resources used to actually authenticate incoming requests and mask the
permissions of the underlying user. Tokens can be created by POSTing to `/api/v2/tokens/`
endpoint by providing `application` and `scope` fields to point to related application and specify
token scope; or POSTing to `/api/v2/applications/<pk>/tokens/` by providing only `scope`, while
the parent application will be automatically linked.

Individual tokens will be accessible via their primary keys at
`/api/v2/tokens/<pk>/`. Here is a typical token:
```
{
    "id": 4,
    "type": "o_auth2_access_token",
    "url": "/api/v2/tokens/4/",
    "related": {
        "user": "/api/v2/users/1/",
        "application": "/api/v2/applications/1/",
        "activity_stream": "/api/v2/tokens/4/activity_stream/"
    },
    "summary_fields": {
        "application": {
            "id": 1,
            "name": "Default application for root",
            "client_id": "mcU5J5uGQcEQMgAZyr5JUnM3BqBJpgbgL9fLOVch"
        },
        "user": {
            "id": 1,
            "username": "root",
            "first_name": "",
            "last_name": ""
        }
    },
    "created": "2018-02-23T14:39:32.618932Z",
    "modified": "2018-02-23T14:39:32.643626Z",
    "description": "App Token Test",
    "user": 1,
    "token": "*************",
    "refresh_token": "*************",
    "application": 1,
    "expires": "2018-02-24T00:39:32.618279Z",
    "scope": "read"
},
```
For an OAuth2 token, the only fully mutable fields are `scope` and `description`. The `application`
field is *immutable on update*, and all other fields are totally immutable, and will be auto-populated
during creation.
* `user` - this field corresponds to the user the token is created for
* `expires` will be generated according to Tower configuration setting `OAUTH2_PROVIDER`
* `token` and `refresh_token` will be auto-generated to be non-clashing random strings.

Both application tokens and personal access tokens will be shown at the `/api/v2/tokens/`
endpoint.  Personal access tokens can be identified by the `application` field being `null`.

**On RBAC side:**
- A user will be able to create a token if they are able to see the related application;
- The System Administrator is able to see and manipulate every token in the system;
- Organization admins will be able to see and manipulate all tokens belonging to Organization
  members;
  System Auditors can see all tokens and applications
- Other normal users will only be able to see and manipulate their own tokens.
> Note: Users can only see the token or refresh-token _value_ at the time of creation ONLY.

#### Using OAuth2 Token System for Personal Access Tokens (PAT)
The most common usage of OAuth2 is authenticating users. The `token` field of a token is used
as part of the HTTP authentication header, in the format `Authorization: Bearer <token field value>`.  This _Bearer_
token can be obtained by doing a curl to the `/api/o/token/` endpoint. For example:
```
curl -ku <user>:<password> -H "Content-Type: application/json" -X POST \
-d '{"description":"Tower CLI", "application":null, "scope":"write"}' \
https://<awx>/api/v2/users/1/personal_tokens/ | python -m json.tool
```
Here is an example of using that PAT to access an API endpoint using `curl`:
```
curl -H "Authorization: Bearer kqHqxfpHGRRBXLNCOXxT5Zt3tpJogn" http://<awx>/api/v2/credentials/
```

According to OAuth2 specification, users should be able to acquire, revoke and refresh an access
token. In AWX the equivalent, and easiest, way of doing that is creating a token, deleting
a token, and deleting a token quickly followed by creating a new one.

The specification also provides standard ways of doing this. RFC 6749 elaborates
on those topics, but in summary, an OAuth2 token is officially acquired via authorization using
authorization information provided by applications (special application fields mentioned above).
There are dedicated endpoints for authorization and acquiring tokens. The `token` endpoint
is also responsible for token refresh, and token revoke can be done by the dedicated token revoke endpoint.

In AWX, our OAuth2 system is built on top of
[Django Oauth Toolkit](https://django-oauth-toolkit.readthedocs.io/en/latest/), which provides full
support on standard authorization, token revoke and refresh. AWX implements them and puts related
endpoints under `/api/o/` endpoint. Detailed examples on the most typical usage of those endpoints
are available as description text of `/api/o/`. See below for information on Application Access Token usage.
> Note: The `/api/o/` endpoints can only be used for application tokens, and are not valid for personal access tokens.

#### Token Scope Mask Over RBAC System

The scope of an OAuth2 token is a space-separated string composed of keywords like 'read' and 'write'.
These keywords are configurable and used to specify permission level of the authenticated API client.
For the initial OAuth2 implementation, we use the most simple scope configuration, where the only
valid scope keywords are 'read' and 'write'.

Read and write scopes provide a mask layer over the RBAC permission system of AWX. In specific, a
'write' scope gives the authenticated user the full permissions the RBAC system provides, while 'read'
scope gives the authenticated user only read permissions the RBAC system provides.

For example, if a user has admin permission to a job template, he/she can both see and modify, launch
and delete the job template if authenticated via session or basic auth. On the other hand, if the user
is authenticated using OAuth2 token, and the related token scope is 'read', the user can only see but
not manipulate or launch the job template, despite being an admin. If the token scope is
'write' or 'read write', she can take full advantage of the job template as its admin.  Note that 'write'
implies 'read' as well.

## Application Functions

This page lists OAuth2 utility endpoints used for authorization, token refresh and revoke.
Note endpoints other than `/api/o/authorize/` are not meant to be used in browsers and do not
support HTTP GET. The endpoints here strictly follow
[RFC specs for OAuth2](https://tools.ietf.org/html/rfc6749), so please use that for detailed
reference. Below are some examples to demonstrate the typical usage of these endpoints in
AWX context (note that the AWX net location defaults to `http://localhost:8013` in these examples).

#### Application Using `authorization code` Grant Type

This application grant type is intended to be used when the application is executing on the server.  To create
an application named `AuthCodeApp` with the `authorization-code` grant type,
make a POST to the `/api/v2/applications/` endpoint:
```text
{
    "name": "AuthCodeApp",
    "user": 1,
    "client_type": "confidential",
    "redirect_uris": "http://<awx>/api/v2",
    "authorization_grant_type": "authorization-code",
    "skip_authorization": false
}
```
You can test the authorization flow out with this new application by copying the `client_id` and URI link into the
homepage [here](http://django-oauth-toolkit.herokuapp.com/consumer/) and click submit. This is just a simple test
application `Django-oauth-toolkit` provides.

From the client app, the user makes a GET to the Authorize endpoint with the `response_type`,
`client_id`, `redirect_uris`, and `scope`.  AWX will respond with the authorization `code` and `state`
to the `redirect_uri` specified in the application. The client application will then make a POST to the
`api/o/token/` endpoint on AWX with the `code`, `client_id`, `client_secret`, `grant_type`, and `redirect_uri`.
AWX will respond with the `access_token`, `token_type`, `refresh_token`, and `expires_in`. For more
information on testing this flow, refer to [django-oauth-toolkit](http://django-oauth-toolkit.readthedocs.io/en/latest/tutorial/tutorial_01.html#test-your-authorization-server).

#### Application Using `password` Grant Type

This is also called the `resource owner credentials grant`. This is for use by users who have
native access to the web app. This should be used when the client is the Resource owner.  Suppose
we have an application `Default Application` with grant type `password`:
```text
{
    "id": 6,
    "type": "application",
    ...
    "name": "Default Application",
    "user": 1,
    "client_id": "gwSPoasWSdNkMDtBN3Hu2WYQpPWCO9SwUEsKK22l",
    "client_secret": "fI6ZpfocHYBGfm1tP92r0yIgCyfRdDQt0Tos9L8a4fNsJjQQMwp9569eIaUBsaVDgt2eiwOGe0bg5m5vCSstClZmtdy359RVx2rQK5YlIWyPlrolpt2LEpVeKXWaiybo",
    "client_type": "confidential",
    "redirect_uris": "",
    "authorization_grant_type": "password",
    "skip_authorization": false
}
```

Login is not required for `password` grant type, so we can simply use `curl` to acquire a personal access token
via `/api/o/token/`:
```bash
curl -X POST \
  -d "grant_type=password&username=<username>&password=<password>&scope=read" \
  -u "gwSPoasWSdNkMDtBN3Hu2WYQpPWCO9SwUEsKK22l:fI6ZpfocHYBGfm1tP92r0yIgCyfRdDQt0Tos9L8a4fNsJjQQMwp9569e
IaUBsaVDgt2eiwOGe0bg5m5vCSstClZmtdy359RVx2rQK5YlIWyPlrolpt2LEpVeKXWaiybo" \
  http://<awx>/api/o/token/ -i
```
In the above POST request, parameters `username` and `password` are the username and password of the related
AWX user of the underlying application, and the authentication information is of format
`<client_id>:<client_secret>`, where `client_id` and `client_secret` are the corresponding fields of
underlying application.

Upon success, the access token, refresh token and other information are given in the response body in JSON
format:
```text
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Tue, 05 Dec 2017 16:48:09 GMT
Content-Type: application/json
Content-Length: 163
Connection: keep-alive
Content-Language: en
Vary: Accept-Language, Cookie
Pragma: no-cache
Cache-Control: no-store
Strict-Transport-Security: max-age=15768000

{"access_token": "9epHOqHhnXUcgYK8QanOmUQPSgX92g", "token_type": "Bearer", "expires_in": 315360000000, "refresh_token": "jMRX6QvzOTf046KHee3TU5mT3nyXsz", "scope": "read"}
```

## Token Functions

#### Refresh an Existing Access Token

Suppose we have an existing access token with refresh token provided:
```text
{
    "id": 35,
    "type": "access_token",
    ...
    "user": 1,
    "token": "omMFLk7UKpB36WN2Qma9H3gbwEBSOc",
    "refresh_token": "AL0NK9TTpv0qp54dGbC4VUZtsZ9r8z",
    "application": 6,
    "expires": "2017-12-06T03:46:17.087022Z",
    "scope": "read write"
}
```
The `/api/o/token/` endpoint is used for refreshing the access token:
```bash
curl -X POST \
  -d "grant_type=refresh_token&refresh_token=AL0NK9TTpv0qp54dGbC4VUZtsZ9r8z" \
  -u "gwSPoasWSdNkMDtBN3Hu2WYQpPWCO9SwUEsKK22l:fI6ZpfocHYBGfm1tP92r0yIgCyfRdDQt0Tos9L8a4fNsJjQQMwp9569eIaUBsaVDgt2eiwOGe0bg5m5vCSstClZmtdy359RVx2rQK5YlIWyPlrolpt2LEpVeKXWaiybo" \
  http://<awx>/api/o/token/ -i
```
In the above POST request, `refresh_token` is provided by `refresh_token` field of the access token
above. The authentication information is of format `<client_id>:<client_secret>`, where `client_id`
and `client_secret` are the corresponding fields of underlying related application of the access token.

Upon success, the new (refreshed) access token with the same scope information as the previous one is
given in the response body in JSON format:
```text
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Tue, 05 Dec 2017 17:54:06 GMT
Content-Type: application/json
Content-Length: 169
Connection: keep-alive
Content-Language: en
Vary: Accept-Language, Cookie
Pragma: no-cache
Cache-Control: no-store
Strict-Transport-Security: max-age=15768000

{"access_token": "NDInWxGJI4iZgqpsreujjbvzCfJqgR", "token_type": "Bearer", "expires_in": 315360000000, "refresh_token": "DqOrmz8bx3srlHkZNKmDpqA86bnQkT", "scope": "read write"}
```
Internally, the refresh operation deletes the existing token and a new token is created immediately
after, with information like scope and related application identical to the original one. We can
verify by checking the new token is present and the old token is deleted at the `/api/v2/tokens/` endpoint.

#### Revoke an Access Token

##### Alternatively Revoke Using the /api/o/revoke-token/ Endpoint

Revoking an access token by this method is the same as deleting the token resource object, but it allows you to delete a token by providing its token value, and the associated `client_id` (and `client_secret` if the application is `confidential`).  For example:
```bash
curl -X POST -d "token=rQONsve372fQwuc2pn76k3IHDCYpi7" \
  -u "gwSPoasWSdNkMDtBN3Hu2WYQpPWCO9SwUEsKK22l:fI6ZpfocHYBGfm1tP92r0yIgCyfRdDQt0Tos9L8a4fNsJjQQMwp9569eIaUBsaVDgt2eiwOGe0bg5m5vCSstClZmtdy359RVx2rQK5YlIWyPlrolpt2LEpVeKXWaiybo" \
  http://<awx>/api/o/revoke_token/ -i
```
`200 OK` means a successful delete.

We can verify the effect by checking if the token is no longer present
at `/api/v2/tokens/`.

## Acceptance Criteria

* All CRUD operations for OAuth2 applications and tokens should function as described.
* RBAC rules applied to OAuth2 applications and tokens should behave as described.
* A default application should be auto-created for each new user.
* Incoming requests using unexpired OAuth2 token correctly in authentication header should be able
  to successfully authenticate themselves.
* Token scope mask over RBAC should work as described.
* Tower configuration setting `OAUTH2_PROVIDER` should be configurable and function as described.
* `/api/o/` endpoint should work as expected. In specific, all examples given in the description
  help text should be working (a user following the steps should get expected result).


text:
declare function touch(filename: string, cb: (err: any) => any): void;
declare function touch(filename: string, opts: touch.Options, cb: (err: any) => any): void;

declare namespace touch {
    export interface Options {
        force?: boolean;
        time?: Date | string | number;
        atime?: boolean | Date;
        mtime?: boolean | Date;
        ref?: string;
        nocreate?: boolean;
    }

    export function sync(filename: string, opts?: touch.Options): void;

    export function ftouch(fd: number, cb: (err: any) => any): void;
    export function ftouch(fd: number, opts: touch.Options, cb: (err: any) => any): void;

    export namespace ftouch {
        export function sync(fd: number, opts?: touch.Options): void;
    }

    export const ftouchSync: typeof ftouch.sync;
}

export = touch;


text: print 'this is my test branch file'


text:
namespace hpl
{
void GridLayout::calculate(std::vector<Geometry>& geometries)
{
	unsigned rows = round(sqrt(geometries.size()));
	if (rows > maxrows) {
		rows = maxrows;
	}
	unsigned cols = ceil(static_cast<double>(geometries.size()) / rows);
	if (cols > maxcols) {
		cols = maxcols;
		rows = ceil(static_cast<double>(geometries.size()) / cols);
	}
	double w = 1.0 / cols;
	double h = 1.0 / rows;
	unsigned j = 0;
    for(auto it = geometries.begin(); it != geometries.end(); ++it) {
		double x;
		double y;
		if (orientation == TopLeftToBottomRight || orientation == TopRightToBottomLeft) {
			y = 1.0 - h - floor(j / cols) * h;
		} else {
			y = floor(j / cols) * h;
		}
		if (orientation == TopLeftToBottomRight || orientation == BottomLeftToTopRight) {
			x = (j % cols) * w;
		} else {
			x = 1.0 - w - (j % cols) * w;
		}
		it->set(x, y, w, h);
		++j;
    }
}

void GridLayout::setMaxRows(unsigned mr)
{
	maxcols = std::numeric_limits<unsigned>::max();
	maxrows = mr;
	changed.invoke(id());
}

void GridLayout::setMaxCols(unsigned mc)
{
	maxrows = std::numeric_limits<unsigned>::max();
	maxcols = mc;
	changed.invoke(id());
}

void GridLayout::changeOrientation(Orientation orientation)
{
    this->orientation = orientation;
    changed.invoke(id());
}
}


text:
TOP=`pwd`
CND_PLATFORM=GNU-Linux-x86
CND_CONF=Debug
CND_DISTDIR=dist
CND_BUILDDIR=build
CND_DLIB_EXT=so
NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging
TMPDIRNAME=tmp-packaging
OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/oop-homework-6
OUTPUT_BASENAME=oop-homework-6
PACKAGE_TOP_DIR=oop-homework-6/

# Functions
function checkReturnCode
{
    rc=$?
    if [ $rc != 0 ]
    then
        exit $rc
    fi
}
function makeDirectory
# $1 directory path
# $2 permission (optional)
{
    mkdir -p "$1"
    checkReturnCode
    if [ "$2" != "" ]
    then
      chmod $2 "$1"
      checkReturnCode
    fi
}
function copyFileToTmpDir
# $1 from-file path
# $2 to-file path
# $3 permission
{
    cp "$1" "$2"
    checkReturnCode
    if [ "$3" != "" ]
    then
        chmod $3 "$2"
        checkReturnCode
    fi
}

# Setup
cd "${TOP}"
mkdir -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package
rm -rf ${NBTMPDIR}
mkdir -p ${NBTMPDIR}

# Copy files and create directories and links
cd "${TOP}"
makeDirectory "${NBTMPDIR}/oop-homework-6/bin"
copyFileToTmpDir "${OUTPUT_PATH}" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}" 0755

# Generate tar file
cd "${TOP}"
rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/oop-homework-6.tar
cd ${NBTMPDIR}
tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/oop-homework-6.tar *
checkReturnCode

# Cleanup
cd "${TOP}"
rm -rf ${NBTMPDIR}


text:
redis = node['redisio']

redis['servers'].each do |current_server|
  server_name = current_server['name'] || current_server['port']
  resource_name = if node['redisio']['job_control'] == 'systemd'
                    "service[redis@#{server_name}]"
                  else
                    "service[redis#{server_name}]"
                  end
  resource = resources(resource_name)
  resource.action Array(resource.action)
  resource.action.concat [:start, :enable]
end


text:
..
  SPDX-License-Identifier: CC-BY-4.0
  Copyright Contributors to the OpenColorIO Project.

ASWF
====

.. toctree::
   :caption: ASWF

   license
   charter
   cla_dco
   aswf_docker


text:
import React from 'react';
import Document, { Main, NextScript } from 'next/document';
import { renderStatic } from 'glamor/server';

import Metadata from '../components/Metadata';

export default class MyDocument extends Document {
  static async getInitialProps({ renderPage }) {
    const page = renderPage();
    const styles = renderStatic(() => page.html);
    return { ...page, ...styles };
  }
  constructor(props) {
    super(props);
    const { __NEXT_DATA__, ids } = props;
    if (ids) {
      __NEXT_DATA__.ids = this.props.ids;
    }
  }
  render() {
    return (
      <html lang="en-US">
        <Metadata />
        <body>
          <style dangerouslySetInnerHTML={{ __html: this.props.css }} />
          <Main />
          <NextScript />
        </body>
      </html>
    );
  }
}


text:
module.exports = function (grunt) { 'use strict';
  require('load-grunt-tasks')(grunt, { scope: 'devDependencies' });

  grunt.initConfig({
    jshint: {
      all: [
        'Gruntfile.js',
        'tasks/*.js'
      ],
      options: {
        jshintrc: '.jshintrc'
      }
    },

    'minor-major-milestone': {
      minor: {
        options: {
            elem: 'minor'
        }
      },
      major: {
        options: {
            elem: 'major'
        }
      },
      milestone: {
        options: {
            elem: 'milestone'
        }
      },
      reset: {
        options: {
            elem: 'reset'
        }
      }
    }
  });

  grunt.loadTasks('tasks');

  grunt.registerTask('minor', ['minor-major-milestone:minor']);
  grunt.registerTask('major', ['minor-major-milestone:major']);
  grunt.registerTask('milestone', ['minor-major-milestone:milestone']);
  grunt.registerTask('reset', ['minor-major-milestone:reset']);
  grunt.registerTask('default', ['jshint']);
};