text:
Today we're going to look at a very important action step to take to help you reach English fluency. Let me tell you what you have to STOP doing first:

You must stop studying lists of words.

Let me say that again:

**You have to stop trying to memorize words all by themselves.**

This habit of memorizing lists of words all by themselves is even worse if you are always trying to learn HUGE, LONG lists of words (like to take the TOEFL or another English test like that).

This ineffective study habit comes from academic, grammar-book-based learning. I did this (very ineffectively, I might say) in my first Spanish class in junior high school and all the way through college as I was studying Spanish. I kept doing this "list of solo words learning" when I started studying Japanese at age 24. I didn't know there was a better way! But then I started doing something different:

**I started studying whole phrases.**

When you study whole phrases (also called "chunks"), you will learn how words are used in context and which words usually go together. It's also best to study phrases or chunks that will be useful for you. So also remember:

**Choose phrases that will help you reach your English fluency goals.**

If you always keep your true, full English fluency goal in mind, you will remember to study and learn useful phrases for YOUR situation and YOUR goals. The steps below will walk you through a technique that will help you really remember important (to you) vocabulary words and phrases.

## Steps to take today:

### Step 1: Find and record

To make this easy, find an interesting or difficult phrase you would like to remember to use later from this very email and write the WHOLE SENTENCE down in your English journal, notebook, or one of your Anki decks.

(If you still don't have a place for your English study materials, get some paper and staple a few sheets together right now, then label the front "English.")

Try to choose a phrase that will be helpful for your main English study goal. Write down the phrase.

### Step 2: Write a new sentence with your chosen phrase

Make up and write down another sentence using the same phrase. This will help you see the phrase in another context.

###  Step 3: Imagine

Close your eyes for 10 seconds and imagine the phrase. How do you feel right now when thinking about this phrase? What situations does this phrase make you think about? Where will you be when you use this phrase? Where are you sitting/standing? Who will you be talking to or writing to when you use this phrase? BONUS POINTS: Think in English as you do this exercise.

[image]

After you sit and imagine the situation for a minute or two, write about your experience. Write about how you felt, what you imagined, and how, where, and with whom you'll be talking when you use this phrase. Read what you wrote out loud to practice speaking.

You can repeat this process as you come across new phrases you would like to remember.

---

Tomorrow's lesson will help you find some good systems for organizing, reviewing, and really remembering all these new words and phrases.

 Bye for now!


text:
Shindo.tests('Fog::Google[:sql] | operation requests', ['google']) do
  @sql = Fog::Google[:sql]
  @instance_id = Fog::Mock.random_letters(16)
  @instance = @sql.instances.create(:instance => @instance_id, :tier => 'D1')
  @instance.wait_for { ready? }

  @get_operation_format = {
    'operation' => String,
    'endTime' => Fog::Nullable::String,
    'enqueuedTime' => String,
    'error' => Fog::Nullable::Array,
    'exportContext' => Fog::Nullable::Array,
    'importContext' => Fog::Nullable::Array,
    'instance' => String,
    'kind' => String,
    'operationType' => String,
    'startTime' => Fog::Nullable::String,
    'state' => String,
    'userEmailAddress' => String,
  }

  @list_operations_format = {
    'kind' => String,
    'items' => [@get_operation_format],
  }

  tests('success') do

    tests('#list_operations').formats(@list_operations_format) do
      @sql.list_operations(@instance_id).body
    end

    tests('#get_operation').formats(@get_operation_format) do
      operation_id = @sql.operations.all(@instance_id).first.operation
      @sql.get_operation(@instance_id, operation_id).body
    end

  end

  @instance.destroy

end

redpajama_set_name: RedPajamaGithub


text:
import json
import requests
from .exchange import Exchange

class Bitmex(Exchange):

	def __init__(self):
		 Exchange.__init__(self, "Bitmex")

	def PullData(self):
		url = "https://www.bitmex.com/api/v1/instrument?symbol=XBTUSD&count=1&reverse=false"
		response = requests.get(url)
		ticker = response.json()[0]

		data = {}
		data['price'] = ticker['lastPrice']
		data['percentChange'] = 0
		data['volume'] = ticker['volume24h']

		return data


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/Android-SpringView.iml" filepath="$PROJECT_DIR$/Android-SpringView.iml" />
      <module fileurl="file://$PROJECT_DIR$/example/example.iml" filepath="$PROJECT_DIR$/example/example.iml" />
      <module fileurl="file://$PROJECT_DIR$/springview/springview.iml" filepath="$PROJECT_DIR$/springview/springview.iml" />
    </modules>
  </component>
</project>


text:
require "content.rb"
require 'yaml'

class HamlContent < Content
  MATCHER = /^(.+)(\.haml)$/

  def content
    haml = @plain_content
    hamlengine = Haml::Engine.new haml
    hamlengine.render @scope
  end

  def to_html scope
    @scope = scope
    if layout?
      hamlContent = HamlContent.new File.join("_layouts", "#{layout}.haml"), @contents
      return hamlContent.to_html self
    end
    content
  end

  protected
  def read
    raise "File #{@name} doesn't exists" if !File.exists? @name

    raise "File #{@name} is not a valid file name" unless valid?

    @plain_content = File.open(@name, "r:utf-8").read
    begin
      if @plain_content =~ /^(---\s*\n.*?\n?)^(---\s*$\n?)/m
        @plain_content = $'
        @datas = YAML.load $1
      end
    rescue => e
      puts "YAML Exception reading #{@name}: #{e.message}"
    end

    slug, ext = *name.match(MATCHER)
    @slug = slug
    @ext = ext
  end

  def valid?
    @name =~ MATCHER
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- Persistence deployment descriptor for dev profile -->
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">

     <persistence-unit name="inumDatabase" transaction-type="RESOURCE_LOCAL">
      <provider>org.hibernate.ejb.HibernatePersistence</provider>
      <jta-data-source>java:/comp/env/jdbc/inumDB</jta-data-source>
      <properties>
         <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
         <property name="hibernate.show_sql" value="true"/>
         <property name="hibernate.format_sql" value="true"/>
         <property name="hibernate.cache.provider_class" value="org.hibernate.cache.HashtableCacheProvider"/>
         <property name="jboss.entity.manager.factory.jndi.name" value="java:/comp/env/InumEntryManagerFactory"/>
      </properties>
   </persistence-unit>
</persistence>


text:
body.page-preview
{
padding-top:10px; padding-left:10px;
}
.page-preview .rnr-c-import,
  .rnr-pagewrapper .page-preview .rnr-c-import,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-c-import
{
margin-bottom:5px;
}
.page-preview .rnr-c-import,
  .rnr-pagewrapper .page-preview .rnr-c-import,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-c-import
{
min-width:500px; display:inline-block
}
.page-preview .rnr-cw-import,
  .rnr-pagewrapper .page-preview .rnr-cw-import,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-cw-import
{
text-align: center;
}
.page-preview .rnr-b-importheader,
  .rnr-pagewrapper .page-preview .rnr-b-importheader,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importheader
{
white-space: nowrap;
}
.page-preview .rnr-b-importheader,
  .rnr-pagewrapper .page-preview .rnr-b-importheader,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importheader
{
text-align: right;
}
.page-preview .rnr-b-importheader > *,
  .rnr-pagewrapper .page-preview .rnr-b-importheader > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importheader > *
{
font-size: 120%;
}
.page-preview .rnr-b-errormessage,
  .rnr-pagewrapper .page-preview .rnr-b-errormessage,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-errormessage
{
white-space: nowrap;
}
.page-preview .rnr-b-errormessage,
  .rnr-pagewrapper .page-preview .rnr-b-errormessage,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-errormessage
{
text-align: right;
}
.page-preview .rnr-b-errormessage > *,
  .rnr-pagewrapper .page-preview .rnr-b-errormessage > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-errormessage > *
{

}
.page-preview .rnr-c-importfields,
  .rnr-pagewrapper .page-preview .rnr-c-importfields,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-c-importfields
{
margin-bottom:5px;
}
.page-preview .rnr-c-importfields,
  .rnr-pagewrapper .page-preview .rnr-c-importfields,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-c-importfields
{
min-width:100px;
}
.page-preview .rnr-b-importheader_text,
  .rnr-pagewrapper .page-preview .rnr-b-importheader_text,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importheader_text
{
white-space: normal;
}
.page-preview .rnr-b-importheader_text,
  .rnr-pagewrapper .page-preview .rnr-b-importheader_text,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importheader_text
{
text-align: right;
}
.page-preview .rnr-b-importheader_text > *,
  .rnr-pagewrapper .page-preview .rnr-b-importheader_text > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importheader_text > *
{

}
.page-preview .rnr-b-importfields,
  .rnr-pagewrapper .page-preview .rnr-b-importfields,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importfields
{
white-space: nowrap;
}
.page-preview .rnr-b-importfields,
  .rnr-pagewrapper .page-preview .rnr-b-importfields,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importfields
{
text-align: right;
}
.page-preview .rnr-b-importfields > *,
  .rnr-pagewrapper .page-preview .rnr-b-importfields > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importfields > *
{

}
.page-preview .rnr-b-import_rawtext_control,
  .rnr-pagewrapper .page-preview .rnr-b-import_rawtext_control,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_rawtext_control
{
white-space: nowrap;
}
.page-preview .rnr-b-import_rawtext_control,
  .rnr-pagewrapper .page-preview .rnr-b-import_rawtext_control,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_rawtext_control
{
text-align: right;
}
.page-preview .rnr-b-import_rawtext_control > *,
  .rnr-pagewrapper .page-preview .rnr-b-import_rawtext_control > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_rawtext_control > *
{

}
.page-preview .rnr-b-import_preview,
  .rnr-pagewrapper .page-preview .rnr-b-import_preview,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_preview
{
white-space: nowrap;
}
.page-preview .rnr-b-import_preview,
  .rnr-pagewrapper .page-preview .rnr-b-import_preview,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_preview
{
text-align: right;
}
.page-preview .rnr-b-import_preview > *,
  .rnr-pagewrapper .page-preview .rnr-b-import_preview > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_preview > *
{

}
.page-preview .rnr-b-import_process,
  .rnr-pagewrapper .page-preview .rnr-b-import_process,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_process
{
white-space: nowrap;
}
.page-preview .rnr-b-import_process,
  .rnr-pagewrapper .page-preview .rnr-b-import_process,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_process
{
text-align: right;
}
.page-preview .rnr-b-import_process > *,
  .rnr-pagewrapper .page-preview .rnr-b-import_process > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_process > *
{

}
.page-preview .rnr-b-import_results,
  .rnr-pagewrapper .page-preview .rnr-b-import_results,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_results
{
white-space: nowrap;
}
.page-preview .rnr-b-import_results,
  .rnr-pagewrapper .page-preview .rnr-b-import_results,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_results
{
text-align: right;
}
.page-preview .rnr-b-import_results > *,
  .rnr-pagewrapper .page-preview .rnr-b-import_results > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-import_results > *
{

}
.page-preview .rnr-b-importbuttons,
  .rnr-pagewrapper .page-preview .rnr-b-importbuttons,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importbuttons
{
white-space: nowrap;
}
.page-preview .rnr-b-importbuttons,
  .rnr-pagewrapper .page-preview .rnr-b-importbuttons,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importbuttons
{
text-align: right;
}
.page-preview .rnr-b-importbuttons > *,
  .rnr-pagewrapper .page-preview .rnr-b-importbuttons > *,
  .rnr-pagewrapper .rnr-pagewrapper .page-preview .rnr-b-importbuttons > *
{

}
body.page-preview .rnr-toptable
{
width:100%;
}
body.page-preview .rnr-top
{
padding-right: 5px;
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Numbers</title>
	<link rel="stylesheet" href="../flat-ui.min.css">

Problem 5. Appearance count

Write a function that counts how many times given number appears in given array.
Write a test function to check if the function is working correctly.

	<input class="form-control" type="text" id="value" placeholder="Enter an array of digits each seperated with a space">
	<input class="form-control" type="text" id="number" placeholder="Enter number">
	<button  class="btn btn-block btn-lg btn-success" id="print-nums-button">Print</button>


text:
using Media_Orgainizer.Classes.Data;
using Media_Orgainizer.Classes.Misc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Media_Orgainizer.Classes.GUI
{
    public partial class Media_Categories : Control
    {
        public Media_Categories()
        {
            InitializeComponent();
            if (!DataManagment.Loaded) DataManagment.Load();
            if (Media.isEmpty) Media.AddMedia("Default");
            Controls.Add(pbShowToggle);
            Controls.Add(stackingPanel1);
            Controls.Add(pbAdd);
            PopulatePanel();

            stackingPanel1.Left = 0 - stackingPanel1.Width;
            pbAdd.Left = 0 - stackingPanel1.Width;
            pbAdd.Top = Height - 25;
            if (SelectedMedia != null) SelectedMedia.SelectControl();
        }

        private bool toogle = true;
        private int position = 0;
        private Media_Control SelectedMedia = null;

        public int ExpandedHeight { get; set; }

        void mc_Click(object sender, EventArgs e)
        {
            SelectedMedia.DeselectControl();
            SelectedMedia = sender as Media_Control;
            SelectedMedia.SelectControl();
            if (SelectedItemChange != null) SelectedItemChange(SelectedMedia.Media);
            pbShowToggle_Click(null, null);
        }

        void mc_MediaUpdated()
        {
            MediaItem mi = SelectedMedia.Media;
            stackingPanel1.Controls.Clear();
            PopulatePanel(mi);
            SelectedMedia.SelectControl();
            if (stackingPanel1.Width != Width - 30) Width = stackingPanel1.Width + 30;
        }

        void PopulatePanel()
        {
            PopulatePanel(null);
        }

        void PopulatePanel(MediaItem Selected)
        {
            foreach (MediaItem mi in Media.MediaList)
            {
                Media_Control mc = new Media_Control(mi);
                if (Selected == null || Selected == mi) SelectedMedia = mc;
                if (SelectedMedia != null) Selected = SelectedMedia.Media;
                mc.Click += mc_Click;
                mc.MediaUpdated += mc_MediaUpdated;
                stackingPanel1.Controls.Add(mc);
            }
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
        }

        private void pbShowToggle_Click(object sender, EventArgs e)
        {
            if (position == 0) position = Top;
            if (toogle)
            {
                pbShowToggle.Image = Properties.Resources.ArrowL;
                Height = ExpandedHeight;
                pbShowToggle.Top = position;
                Top = 10;
                for (int i = 1; i < stackingPanel1.Width; i++)
                {
                    Width += 1;
                    Refresh();
                }
                toogle = false;
                if (ToggleVisible != null) ToggleVisible();
            }
            else
            {
                pbShowToggle.Image = Properties.Resources.ArrowR;
                for (int i = 1; i < stackingPanel1.Width; i++)
                {
                    Width -= 1;
                    Refresh();
                }
                Height = 30;
                pbShowToggle.Top = 0;
                Top = position;
                toogle = true;
                if (ToggleInvisible != null) ToggleInvisible();
            }
        }

        private void pbAdd_Click(object sender, EventArgs e)
        {
            Media_Control mc = new Media_Control();
            mc.Click += mc_Click;
            mc.MediaUpdated += mc_MediaUpdated;
            stackingPanel1.Controls.Add(mc);
        }

        public MediaItem SelectedItem
        {
            get
            {
                return SelectedMedia.Media;
            }
        }

        public delegate void ToggleDelegate();

        public event ToggleDelegate ToggleVisible;

        public event ToggleDelegate ToggleInvisible;

        public delegate void SelectChangeDelegate(MediaItem mi);

        public event SelectChangeDelegate SelectedItemChange;

        public bool Toggle
        {
            get
            {
                return toogle;
            }
            set
            {
                if (!value) pbShowToggle_Click(null, null);
            }
        }
    }
}


text:
# Laravel Passport

- [Introduction](#introduction)
- [Upgrading Passport](#upgrading)
- [Installation](#installation)
    - [Frontend Quickstart](#frontend-quickstart)
    - [Deploying Passport](#deploying-passport)
- [Configuration](#configuration)
    - [Token Lifetimes](#token-lifetimes)
    - [Overriding Default Models](#overriding-default-models)
- [Issuing Access Tokens](#issuing-access-tokens)
    - [Managing Clients](#managing-clients)
    - [Requesting Tokens](#requesting-tokens)
    - [Refreshing Tokens](#refreshing-tokens)
- [Password Grant Tokens](#password-grant-tokens)
    - [Creating A Password Grant Client](#creating-a-password-grant-client)
    - [Requesting Tokens](#requesting-password-grant-tokens)
    - [Requesting All Scopes](#requesting-all-scopes)
    - [Customizing The Username Field](#customizing-the-username-field)
    - [Customizing The Password Validation](#customizing-the-password-validation)
- [Implicit Grant Tokens](#implicit-grant-tokens)
- [Client Credentials Grant Tokens](#client-credentials-grant-tokens)
- [Personal Access Tokens](#personal-access-tokens)
    - [Creating A Personal Access Client](#creating-a-personal-access-client)
    - [Managing Personal Access Tokens](#managing-personal-access-tokens)
- [Protecting Routes](#protecting-routes)
    - [Via Middleware](#via-middleware)
    - [Passing The Access Token](#passing-the-access-token)
- [Token Scopes](#token-scopes)
    - [Defining Scopes](#defining-scopes)
    - [Default Scope](#default-scope)
    - [Assigning Scopes To Tokens](#assigning-scopes-to-tokens)
    - [Checking Scopes](#checking-scopes)
- [Consuming Your API With JavaScript](#consuming-your-api-with-javascript)
- [Events](#events)
- [Testing](#testing)

## Introduction

Laravel already makes it easy to perform authentication via traditional login forms, but what about APIs? APIs typically use tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Passport is built on top of the [League OAuth2 server](https://github.com/thephpleague/oauth2-server) that is maintained by Andy Millington and Simon Hamp.

> {note} This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general [terminology](https://oauth2.thephpleague.com/terminology/) and features of OAuth2 before continuing.

## Upgrading Passport

When upgrading to a new major version of Passport, it's important that you carefully review [the upgrade guide](https://github.com/laravel/passport/blob/master/UPGRADE.md).

## Installation

To get started, install Passport via the Composer package manager:

    composer require laravel/passport

The Passport service provider registers its own database migration directory with the framework, so you should migrate your database after installing the package. The Passport migrations will create the tables your application needs to store clients and access tokens:

    php artisan migrate

Next, you should run the `passport:install` command. This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create "personal access" and "password grant" clients which will be used to generate access tokens:

    php artisan passport:install

After running this command, add the `Laravel\Passport\HasApiTokens` trait to your `App\User` model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes:

    <?php

    namespace App;

    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Passport\HasApiTokens;

    class User extends Authenticatable
    {
        use HasApiTokens, Notifiable;
    }

Next, you should call the `Passport::routes` method within the `boot` method of your `AuthServiceProvider`. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens:

    <?php

    namespace App\Providers;

    use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
    use Illuminate\Support\Facades\Gate;
    use Laravel\Passport\Passport;

    class AuthServiceProvider extends ServiceProvider
    {
        /**
         * The policy mappings for the application.
         *
         * @var array
         */
        protected $policies = [
            'App\Model' => 'App\Policies\ModelPolicy',
        ];

        /**
         * Register any authentication / authorization services.
         *
         * @return void
         */
        public function boot()
        {
            $this->registerPolicies();

            Passport::routes();
        }
    }

Finally, in your `config/auth.php` configuration file, you should set the `driver` option of the `api` authentication guard to `passport`. This will instruct your application to use Passport's `TokenGuard` when authenticating incoming API requests:

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],

        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

### Migration Customization

If you are not going to use Passport's default migrations, you should call the `Passport::ignoreMigrations` method in the `register` method of your `AppServiceProvider`. You may export the default migrations using `php artisan vendor:publish --tag=passport-migrations`.

By default, Passport uses an integer column to store the `user_id`. If your application uses a different column type to identify users (for example: UUIDs), you should modify the default Passport migrations after publishing them.

### Frontend Quickstart

> {note} In order to use the Passport Vue components, you must be using the [Vue](https://vuejs.org) JavaScript framework. These components also use the Bootstrap CSS framework. However, even if you are not using these tools, the components serve as a valuable reference for your own frontend implementation.

Passport ships with a JSON API that you may use to allow your users to create clients and personal access tokens. However, it can be time consuming to code a frontend to interact with these APIs. So, Passport also includes pre-built [Vue](https://vuejs.org) components you may use as an example implementation or starting point for your own implementation.

To publish the Passport Vue components, use the `vendor:publish` Artisan command:

    php artisan vendor:publish --tag=passport-components

The published components will be placed in your `resources/js/components` directory. Once the components have been published, you should register them in your `resources/js/app.js` file:

    Vue.component(
        'passport-clients',
        require('./components/passport/Clients.vue').default
    );

    Vue.component(
        'passport-authorized-clients',
        require('./components/passport/AuthorizedClients.vue').default
    );

    Vue.component(
        'passport-personal-access-tokens',
        require('./components/passport/PersonalAccessTokens.vue').default
    );

> {note} Prior to Laravel v5.7.19, appending `.default` when registering components results in a console error. An explanation for this change can be found in the [Laravel Mix v4.0.0 release notes](https://github.com/JeffreyWay/laravel-mix/releases/tag/v4.0.0).

After registering the components, make sure to run `npm run dev` to recompile your assets. Once you have recompiled your assets, you may drop the components into one of your application's templates to get started creating clients and personal access tokens:

    <passport-clients></passport-clients>
    <passport-authorized-clients></passport-authorized-clients>
    <passport-personal-access-tokens></passport-personal-access-tokens>

### Deploying Passport

When deploying Passport to your production servers for the first time, you will likely need to run the `passport:keys` command. This command generates the encryption keys Passport needs in order to generate access token. The generated keys are not typically kept in source control:

    php artisan passport:keys

If necessary, you may define the path where Passport's keys should be loaded from. You may use the `Passport::loadKeysFrom` method to accomplish this:

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::loadKeysFrom('/secret-keys/oauth');
    }

Additionally, you may publish Passport's configuration file using `php artisan vendor:publish --tag=passport-config`, which will then provide the option to load the encryption keys from your environment variables:

    PASSPORT_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
    <private key here>
    -----END RSA PRIVATE KEY-----"

    PASSPORT_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----
    <public key here>
    -----END PUBLIC KEY-----"

## Configuration

### Token Lifetimes

By default, Passport issues long-lived access tokens that expire after one year. If you would like to configure a longer / shorter token lifetime, you may use the `tokensExpireIn`, `refreshTokensExpireIn`, and `personalAccessTokensExpireIn` methods. These methods should be called from the `boot` method of your `AuthServiceProvider`:

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::tokensExpireIn(now()->addDays(15));

        Passport::refreshTokensExpireIn(now()->addDays(30));

        Passport::personalAccessTokensExpireIn(now()->addMonths(6));
    }

### Overriding Default Models

You are free to extend the models used internally by Passport:

    use App\Models\Passport\Client as PassportClient;

    class Client extends PassportClient
    {
        // ...
    }

Then, you may instruct Passport to use your custom models via the `Passport` class:

    use App\Models\Passport\AuthCode;
    use App\Models\Passport\Client;
    use App\Models\Passport\PersonalAccessClient;
    use App\Models\Passport\Token;

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::useTokenModel(Token::class);
        Passport::useClientModel(Client::class);
        Passport::useAuthCodeModel(AuthCode::class);
        Passport::usePersonalAccessClientModel(PersonalAccessClient::class);
    }

## Issuing Access Tokens

Using OAuth2 with authorization codes is how most developers are familiar with OAuth2. When using authorization codes, a client application will redirect a user to your server where they will either approve or deny the request to issue an access token to the client.

### Managing Clients

First, developers building applications that need to interact with your application's API will need to register their application with yours by creating a "client". Typically, this consists of providing the name of their application and a URL that your application can redirect to after users approve their request for authorization.

#### The `passport:client` Command

The simplest way to create a client is using the `passport:client` Artisan command. This command may be used to create your own clients for testing your OAuth2 functionality. When you run the `client` command, Passport will prompt you for more information about your client and will provide you with a client ID and secret:

    php artisan passport:client

**Redirect URLs**

If you would like to whitelist multiple redirect URLs for your client, you may specify them using a comma-delimited list when prompted for the URL by the `passport:client` command:

    http://example.com/callback,http://examplefoo.com/callback

> {note} Any URLs which contains commas must be encoded.

#### JSON API

Since your users will not be able to utilize the `client` command, Passport provides a JSON API that you may use to create clients. This saves you the trouble of having to manually code controllers for creating, updating, and deleting clients.

However, you will need to pair Passport's JSON API with your own frontend to provide a dashboard for your users to manage their clients. Below, we'll review all of the API endpoints for managing clients. For convenience, we'll use [Axios](https://github.com/axios/axios) to demonstrate making HTTP requests to the endpoints.

The JSON API is guarded by the `web` and `auth` middleware; therefore, it may only be called from your own application. It is not able to be called from an external source.

> {tip} If you don't want to implement the entire client management frontend yourself, you can use the [frontend quickstart](#frontend-quickstart) to have a fully functional frontend in a matter of minutes.

#### `GET /oauth/clients`

This route returns all of the clients for the authenticated user. This is primarily useful for listing all of the user's clients so that they may edit or delete them:

    axios.get('/oauth/clients')
        .then(response => {
            console.log(response.data);
        });

#### `POST /oauth/clients`

This route is used to create new clients. It requires two pieces of data: the client's `name` and a `redirect` URL. The `redirect` URL is where the user will be redirected after approving or denying a request for authorization.

When a client is created, it will be issued a client ID and client secret. These values will be used when requesting access tokens from your application. The client creation route will return the new client instance:

    const data = {
        name: 'Client Name',
        redirect: 'http://example.com/callback'
    };

    axios.post('/oauth/clients', data)
        .then(response => {
            console.log(response.data);
        })
        .catch (response => {
            // List errors on response...
        });

#### `PUT /oauth/clients/{client-id}`

This route is used to update clients. It requires two pieces of data: the client's `name` and a `redirect` URL. The `redirect` URL is where the user will be redirected after approving or denying a request for authorization. The route will return the updated client instance:

    const data = {
        name: 'New Client Name',
        redirect: 'http://example.com/callback'
    };

    axios.put('/oauth/clients/' + clientId, data)
        .then(response => {
            console.log(response.data);
        })
        .catch (response => {
            // List errors on response...
        });

#### `DELETE /oauth/clients/{client-id}`

This route is used to delete clients:

    axios.delete('/oauth/clients/' + clientId)
        .then(response => {
            //
        });

### Requesting Tokens

#### Redirecting For Authorization

Once a client has been created, developers may use their client ID and secret to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's `/oauth/authorize` route like so:

    Route::get('/redirect', function (Request $request) {
        $request->session()->put('state', $state = Str::random(40));

        $query = http_build_query([
            'client_id' => 'client-id',
            'redirect_uri' => 'http://example.com/callback',
            'response_type' => 'code',
            'scope' => '',
            'state' => $state,
        ]);

        return redirect('http://your-app.com/oauth/authorize?'.$query);
    });

> {tip} Remember, the `/oauth/authorize` route is already defined by the `Passport::routes` method. You do not need to manually define this route.

#### Approving The Request

When receiving authorization requests, Passport will automatically display a template to the user allowing them to approve or deny the authorization request. If they approve the request, they will be redirected back to the `redirect_uri` that was specified by the consuming application. The `redirect_uri` must match the `redirect` URL that was specified when the client was created.

If you would like to customize the authorization approval screen, you may publish Passport's views using the `vendor:publish` Artisan command. The published views will be placed in `resources/views/vendor/passport`:

    php artisan vendor:publish --tag=passport-views

Sometimes you may wish to skip the authorization prompt, such as when authorizing a first-party client. You may accomplish this by defining a `skipsAuthorization` method on the client model. If `skipsAuthorization` returns `true` the client will be approved and the user will be redirected back to the `redirect_uri` immediately:

    <?php

    namespace App\Models\Passport;

    use Laravel\Passport\Client as BaseClient;

    class Client extends BaseClient
    {
        /**
         * Determine if the client should skip the authorization prompt.
         *
         * @return bool
         */
        public function skipsAuthorization()
        {
            return $this->firstParty();
        }
    }

#### Converting Authorization Codes To Access Tokens

If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should first verify the `state` parameter against the value that was stored prior to the redirect. If the state parameter matches the consumer should issue a `POST` request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request. In this example, we'll use the Guzzle HTTP library to make the `POST` request:

    Route::get('/callback', function (Request $request) {
        $state = $request->session()->pull('state');

        throw_unless(
            strlen($state) > 0 && $state === $request->state,
            InvalidArgumentException::class
        );

        $http = new GuzzleHttp\Client;

        $response = $http->post('http://your-app.com/oauth/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => 'client-id',
                'client_secret' => 'client-secret',
                'redirect_uri' => 'http://example.com/callback',
                'code' => $request->code,
            ],
        ]);

        return json_decode((string) $response->getBody(), true);
    });

This `/oauth/token` route will return a JSON response containing `access_token`, `refresh_token`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the access token expires.

> {tip} Like the `/oauth/authorize` route, the `/oauth/token` route is defined for you by the `Passport::routes` method. There is no need to manually define this route. By default, this route is throttled using the settings of the `ThrottleRequests` middleware.

### Refreshing Tokens

If your application issues short-lived access tokens, users will need to refresh their access tokens via the refresh token that was provided to them when the access token was issued. In this example, we'll use the Guzzle HTTP library to refresh the token:

    $http = new GuzzleHttp\Client;

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'refresh_token',
            'refresh_token' => 'the-refresh-token',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'scope' => '',
        ],
    ]);

    return json_decode((string) $response->getBody(), true);

This `/oauth/token` route will return a JSON response containing `access_token`, `refresh_token`, and `expires_in` attributes. The `expires_in` attribute contains the number of seconds until the access token expires.

## Password Grant Tokens

The OAuth2 password grant allows your other first-party clients, such as a mobile application, to obtain an access token using an e-mail address / username and password. This allows you to issue access tokens securely to your first-party clients without requiring your users to go through the entire OAuth2 authorization code redirect flow.

### Creating A Password Grant Client

Before your application can issue tokens via the password grant, you will need to create a password grant client. You may do this using the `passport:client` command with the `--password` option. If you have already run the `passport:install` command, you do not need to run this command:

    php artisan passport:client --password

### Requesting Tokens

Once you have created a password grant client, you may request an access token by issuing a `POST` request to the `/oauth/token` route with the user's email address and password. Remember, this route is already registered by the `Passport::routes` method so there is no need to define it manually. If the request is successful, you will receive an `access_token` and `refresh_token` in the JSON response from the server:

    $http = new GuzzleHttp\Client;

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'username' => 'taylor@laravel.com',
            'password' => 'my-password',
            'scope' => '',
        ],
    ]);

    return json_decode((string) $response->getBody(), true);

> {tip} Remember, access tokens are long-lived by default. However, you are free to [configure your maximum access token lifetime](#configuration) if needed.

### Requesting All Scopes

When using the password grant or client credentials grant, you may wish to authorize the token for all of the scopes supported by your application. You can do this by requesting the `*` scope. If you request the `*` scope, the `can` method on the token instance will always return `true`. This scope may only be assigned to a token that is issued using the `password` or `client_credentials` grant:

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'username' => 'taylor@laravel.com',
            'password' => 'my-password',
            'scope' => '*',
        ],
    ]);

### Customizing The Username Field

When authenticating using the password grant, Passport will use the `email` attribute of your model as the "username". However, you may customize this behavior by defining a `findForPassport` method on your model:

    <?php

    namespace App;

    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Passport\HasApiTokens;

    class User extends Authenticatable
    {
        use HasApiTokens, Notifiable;

        /**
         * Find the user instance for the given username.
         *
         * @param  string  $username
         * @return \App\User
         */
        public function findForPassport($username)
        {
            return $this->where('username', $username)->first();
        }
    }

### Customizing The Password Validation

When authenticating using the password grant, Passport will use the `password` attribute of your model to validate the given password. If your model does not have a `password` attribute or you wish to customize the password validation logic, you can define a `validateForPassportPasswordGrant` method on your model:

    <?php

    namespace App;

    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Support\Facades\Hash;
    use Laravel\Passport\HasApiTokens;

    class User extends Authenticatable
    {
        use HasApiTokens, Notifiable;

        /**
         * Validate the password of the user for the Passport password grant.
         *
         * @param  string  $password
         * @return bool
         */
        public function validateForPassportPasswordGrant($password)
        {
            return Hash::check($password, $this->password);
        }
    }

## Implicit Grant Tokens

The implicit grant is similar to the authorization code grant; however, the token is returned to the client without exchanging an authorization code. This grant is most commonly used for JavaScript or mobile applications where the client credentials can't be securely stored. To enable the grant, call the `enableImplicitGrant` method in your `AuthServiceProvider`:

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::enableImplicitGrant();
    }

Once a grant has been enabled, developers may use their client ID to request an access token from your application. The consuming application should make a redirect request to your application's `/oauth/authorize` route like so:

    Route::get('/redirect', function (Request $request) {
        $request->session()->put('state', $state = Str::random(40));

        $query = http_build_query([
            'client_id' => 'client-id',
            'redirect_uri' => 'http://example.com/callback',
            'response_type' => 'token',
            'scope' => '',
            'state' => $state,
        ]);

        return redirect('http://your-app.com/oauth/authorize?'.$query);
    });

> {tip} Remember, the `/oauth/authorize` route is already defined by the `Passport::routes` method. You do not need to manually define this route.

## Client Credentials Grant Tokens

The client credentials grant is suitable for machine-to-machine authentication. For example, you might use this grant in a scheduled job which is performing maintenance tasks over an API.

Before your application can issue tokens via the client credentials grant, you will need to create a client credentials grant client. You may do this using the `--client` option of the `passport:client` command:

    php artisan passport:client --client

Next, to use this grant type, you need to add the `CheckClientCredentials` middleware to the `$routeMiddleware` property of your `app/Http/Kernel.php` file:

    use Laravel\Passport\Http\Middleware\CheckClientCredentials;

    protected $routeMiddleware = [
        'client' => CheckClientCredentials::class,
    ];

Then, attach the middleware to a route:

    Route::get('/orders', function (Request $request) {
        ...
    })->middleware('client');

To restrict access to the route to specific scopes you may provide a comma-delimited list of the required scopes when attaching the `client` middleware to the route:

    Route::get('/orders', function (Request $request) {
        ...
    })->middleware('client:check-status,your-scope');

### Retrieving Tokens

To retrieve a token using this grant type, make a request to the `oauth/token` endpoint:

    $guzzle = new GuzzleHttp\Client;

    $response = $guzzle->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'client_credentials',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'scope' => 'your-scope',
        ],
    ]);

    return json_decode((string) $response->getBody(), true)['access_token'];

## Personal Access Tokens

Sometimes, your users may want to issue access tokens to themselves without going through the typical authorization code redirect flow. Allowing users to issue tokens to themselves via your application's UI can be useful for allowing users to experiment with your API or may serve as a simpler approach to issuing access tokens in general.

### Creating A Personal Access Client

Before your application can issue personal access tokens, you will need to create a personal access client. You may do this using the `passport:client` command with the `--personal` option. If you have already run the `passport:install` command, you do not need to run this command:

    php artisan passport:client --personal

If you have already defined a personal access client, you may instruct Passport to use it using the `personalAccessClientId` method. Typically, this method should be called from the `boot` method of your `AuthServiceProvider`:

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::personalAccessClientId('client-id');
    }

### Managing Personal Access Tokens

Once you have created a personal access client, you may issue tokens for a given user using the `createToken` method on the `User` model instance. The `createToken` method accepts the name of the token as its first argument and an optional array of [scopes](#token-scopes) as its second argument:

    $user = App\User::find(1);

    // Creating a token without scopes...
    $token = $user->createToken('Token Name')->accessToken;

    // Creating a token with scopes...
    $token = $user->createToken('My Token', ['place-orders'])->accessToken;

#### JSON API

Passport also includes a JSON API for managing personal access tokens. You may pair this with your own frontend to offer your users a dashboard for managing personal access tokens. Below, we'll review all of the API endpoints for managing personal access tokens. For convenience, we'll use [Axios](https://github.com/mzabriskie/axios) to demonstrate making HTTP requests to the endpoints.

The JSON API is guarded by the `web` and `auth` middleware; therefore, it may only be called from your own application. It is not able to be called from an external source.

> {tip} If you don't want to implement the personal access token frontend yourself, you can use the [frontend quickstart](#frontend-quickstart) to have a fully functional frontend in a matter of minutes.

#### `GET /oauth/scopes`

This route returns all of the [scopes](#token-scopes) defined for your application. You may use this route to list the scopes a user may assign to a personal access token:

    axios.get('/oauth/scopes')
        .then(response => {
            console.log(response.data);
        });

#### `GET /oauth/personal-access-tokens`

This route returns all of the personal access tokens that the authenticated user has created. This is primarily useful for listing all of the user's tokens so that they may edit or delete them:

    axios.get('/oauth/personal-access-tokens')
        .then(response => {
            console.log(response.data);
        });

#### `POST /oauth/personal-access-tokens`

This route creates new personal access tokens. It requires two pieces of data: the token's `name` and the `scopes` that should be assigned to the token:

    const data = {
        name: 'Token Name',
        scopes: []
    };

    axios.post('/oauth/personal-access-tokens', data)
        .then(response => {
            console.log(response.data.accessToken);
        })
        .catch (response => {
            // List errors on response...
        });

#### `DELETE /oauth/personal-access-tokens/{token-id}`

This route may be used to delete personal access tokens:

    axios.delete('/oauth/personal-access-tokens/' + tokenId);

## Protecting Routes

### Via Middleware

Passport includes an [authentication guard](/docs/{{version}}/authentication#adding-custom-guards) that will validate access tokens on incoming requests. Once you have configured the `api` guard to use the `passport` driver, you only need to specify the `auth:api` middleware on any routes that require a valid access token:

    Route::get('/user', function () {
        //
    })->middleware('auth:api');

### Passing The Access Token

When calling routes that are protected by Passport, your application's API consumers should specify their access token as a `Bearer` token in the `Authorization` header of their request. For example, when using the Guzzle HTTP library:

    $response = $client->request('GET', '/api/user', [
        'headers' => [
            'Accept' => 'application/json',
            'Authorization' => 'Bearer '.$accessToken,
        ],
    ]);

## Token Scopes

Scopes allow your API clients to request a specific set of permissions when requesting authorization to access an account. For example, if you are building an e-commerce application, not all API consumers will need the ability to place orders. Instead, you may allow the consumers to only request authorization to access order shipment statuses. In other words, scopes allow your application's users to limit the actions a third-party application can perform on their behalf.

### Defining Scopes

You may define your API's scopes using the `Passport::tokensCan` method in the `boot` method of your `AuthServiceProvider`. The `tokensCan` method accepts an array of scope names and scope descriptions. The scope description may be anything you wish and will be displayed to users on the authorization approval screen:

    use Laravel\Passport\Passport;

    Passport::tokensCan([
        'place-orders' => 'Place orders',
        'check-status' => 'Check order status',
    ]);

### Default Scope

If a client does not request any specific scopes, you may configure your Passport server to attach a default scope to the token using the `setDefaultScope` method. Typically, you should call this method from the `boot` method of your `AuthServiceProvider`:

    use Laravel\Passport\Passport;

    Passport::setDefaultScope([
        'check-status',
        'place-orders',
    ]);

### Assigning Scopes To Tokens

#### When Requesting Authorization Codes

When requesting an access token using the authorization code grant, consumers should specify their desired scopes as the `scope` query string parameter. The `scope` parameter should be a space-delimited list of scopes:

    Route::get('/redirect', function () {
        $query = http_build_query([
            'client_id' => 'client-id',
            'redirect_uri' => 'http://example.com/callback',
            'response_type' => 'code',
            'scope' => 'place-orders check-status',
        ]);

        return redirect('http://your-app.com/oauth/authorize?'.$query);
    });

#### When Issuing Personal Access Tokens

If you are issuing personal access tokens using the `User` model's `createToken` method, you may pass the array of desired scopes as the second argument to the method:

    $token = $user->createToken('My Token', ['place-orders'])->accessToken;

### Checking Scopes

Passport includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given scope. To get started, add the following middleware to the `$routeMiddleware` property of your `app/Http/Kernel.php` file:

    'scopes' => \Laravel\Passport\Http\Middleware\CheckScopes::class,
    'scope' => \Laravel\Passport\Http\Middleware\CheckForAnyScope::class,

#### Check For All Scopes

The `scopes` middleware may be assigned to a route to verify that the incoming request's access token has *all* of the listed scopes:

    Route::get('/orders', function () {
        // Access token has both "check-status" and "place-orders" scopes...
    })->middleware('scopes:check-status,place-orders');

#### Check For Any Scopes

The `scope` middleware may be assigned to a route to verify that the incoming request's access token has *at least one* of the listed scopes:

    Route::get('/orders', function () {
        // Access token has either "check-status" or "place-orders" scope...
    })->middleware('scope:check-status,place-orders');

#### Checking Scopes On A Token Instance

Once an access token authenticated request has entered your application, you may still check if the token has a given scope using the `tokenCan` method on the authenticated `User` instance:

    use Illuminate\Http\Request;

    Route::get('/orders', function (Request $request) {
        if ($request->user()->tokenCan('place-orders')) {
            //
        }
    });

#### Additional Scope Methods

The `scopeIds` method will return an array of all defined IDs / names:

    Laravel\Passport\Passport::scopeIds();

The `scopes` method will return an array of all defined scopes as instances of `Laravel\Passport\Scope`:

    Laravel\Passport\Passport::scopes();

The `scopesFor` method will return an array of `Laravel\Passport\Scope` instances matching the given IDs / names:

    Laravel\Passport\Passport::scopesFor(['place-orders', 'check-status']);

You may determine if a given scope has been defined using the `hasScope` method:

    Laravel\Passport\Passport::hasScope('place-orders');

## Consuming Your API With JavaScript

When building an API, it can be extremely useful to be able to consume your own API from your JavaScript application. This approach to API development allows your own application to consume the same API that you are sharing with the world. The same API may be consumed by your web application, mobile applications, third-party applications, and any SDKs that you may publish on various package managers.

Typically, if you want to consume your API from your JavaScript application, you would need to manually send an access token to the application and pass it with each request to your application. However, Passport includes a middleware that can handle this for you. All you need to do is add the `CreateFreshApiToken` middleware to your `web` middleware group in your `app/Http/Kernel.php` file:

    'web' => [
        // Other middleware...
        \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
    ],

> {note} You should ensure that the `CreateFreshApiToken` middleware is the last middleware listed in your middleware stack.

This Passport middleware will attach a `laravel_token` cookie to your outgoing responses. This cookie contains an encrypted JWT that Passport will use to authenticate API requests from your JavaScript application. Now, you may make requests to your application's API without explicitly passing an access token:

    axios.get('/api/user')
        .then(response => {
            console.log(response.data);
        });

#### Customizing The Cookie Name

If needed, you can customize the `laravel_token` cookie's name using the `Passport::cookie` method. Typically, this method should be called from the `boot` method of your `AuthServiceProvider`:

    /**
     * Register any authentication / authorization services.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Passport::routes();

        Passport::cookie('custom_name');
    }

#### CSRF Protection

When using this method of authentication, you will need to ensure a valid CSRF token header is included in your requests. The default Laravel JavaScript scaffolding includes an Axios instance, which will automatically use the encrypted `XSRF-TOKEN` cookie value to send a `X-XSRF-TOKEN` header on same-origin requests.

> {tip} If you choose to send the `X-CSRF-TOKEN` header instead of `X-XSRF-TOKEN`, you will need to use the unencrypted token provided by `csrf_token()`.

## Events

Passport raises events when issuing access tokens and refresh tokens. You may use these events to prune or revoke other access tokens in your database. You may attach listeners to these events in your application's `EventServiceProvider`:

    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'Laravel\Passport\Events\AccessTokenCreated' => [
            'App\Listeners\RevokeOldTokens',
        ],

        'Laravel\Passport\Events\RefreshTokenCreated' => [
            'App\Listeners\PruneOldTokens',
        ],
    ];

## Testing

Passport's `actingAs` method may be used to specify the currently authenticated user as well as its scopes. The first argument given to the `actingAs` method is the user instance and the second is an array of scopes that should be granted to the user's token:

    use App\User;
    use Laravel\Passport\Passport;

    public function testServerCreation()
    {
        Passport::actingAs(
            factory(User::class)->create(),
            ['create-servers']
        );

        $response = $this->post('/api/create-server');

        $response->assertStatus(201);
    }

Passport's `actingAsClient` method may be used to specify the currently authenticated client as well as its scopes. The first argument given to the `actingAsClient` method is the client instance and the second is an array of scopes that should be granted to the client's token:

    use Laravel\Passport\Client;
    use Laravel\Passport\Passport;

    public function testGetOrders()
    {
        Passport::actingAsClient(
            factory(Client::class)->create(),
            ['check-status']
        );

        $response = $this->get('/api/orders');

        $response->assertStatus(200);
    }


text:
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Security::Cryptography;
using namespace Windows::Security::Cryptography::Core;
using namespace Windows::Storage::Streams;
using namespace Windows::Foundation::Collections;

namespace Sodium
{
	public ref class Utilities sealed
	{
	public:
		static Array<unsigned char>^ Increment(const Array<unsigned char>^ value);

		[Windows::Foundation::Metadata::DefaultOverloadAttribute]
		static bool Compare(const Array<unsigned char>^ a, const Array<unsigned char>^ b);
		static bool Compare(String^ a, String^ b);
	};
}


text:
package com.ibm.icu.impl;

// 1.3 compatibility layer
public class Assert {
    public static void fail(Exception e) {
        fail(e.toString()); // can't wrap exceptions in jdk 1.3
    }
    public static void fail(String msg) {
        throw new IllegalStateException("failure '" + msg + "'");
    }
    public static void assrt(boolean val) {
        if (!val) throw new IllegalStateException("assert failed");
    }
    public static void assrt(String msg, boolean val) {
        if (!val) throw new IllegalStateException("assert '" + msg + "' failed");
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.apache.poi.hssf.record.aggregates Class Hierarchy (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Hierarchy For Package org.apache.poi.hssf.record.aggregates

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.apache.poi.hssf.record.aggregates.RecordAggregate.PositionTrackingVisitor (implements org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor)

org.apache.poi.hssf.record.RecordBase

org.apache.poi.hssf.record.aggregates.RecordAggregate

org.apache.poi.hssf.record.aggregates.CFRecordsAggregate

org.apache.poi.hssf.record.aggregates.ChartSubstreamRecordAggregate

org.apache.poi.hssf.record.aggregates.ColumnInfoRecordsAggregate (implements java.lang.Cloneable)

org.apache.poi.hssf.record.aggregates.ConditionalFormattingTable

org.apache.poi.hssf.record.aggregates.CustomViewSettingsRecordAggregate

org.apache.poi.hssf.record.aggregates.DataValidityTable

org.apache.poi.hssf.record.aggregates.FormulaRecordAggregate (implements org.apache.poi.hssf.record.CellValueRecordInterface)

org.apache.poi.hssf.record.aggregates.MergedCellsTable

org.apache.poi.hssf.record.aggregates.PageSettingsBlock

org.apache.poi.hssf.record.aggregates.RowRecordsAggregate

org.apache.poi.hssf.record.aggregates.WorksheetProtectionBlock

org.apache.poi.hssf.record.aggregates.SharedValueManager

org.apache.poi.hssf.record.aggregates.ValueRecordsAggregate (implements java.lang.Iterable<T>)

Interface Hierarchy

org.apache.poi.hssf.record.aggregates.RecordAggregate.RecordVisitor

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

                Copyright 2016 The Apache Software Foundation or
        its licensors, as applicable.


text:
<!DOCTYPE html>

		<meta charset="utf-8" />

		<link rel="stylesheet" type="text/css" href="../../richtext/richtext.css" />
		<link rel="stylesheet" type="text/css" href="http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" />
		<title>A simple, reusable rich text editor using jQuery and Font Awesome</title>

Hyperlink extension

			Support for hyperlink comes as an extension. Just load
			it after the main script file and use the button names
			createLink and removeLink.

			Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod
			tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At
			vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren,
			no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit
			amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut
			labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam
			et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
			sanctus est Lorem ipsum dolor sit amet.


text:
title:  Penciptaan Kejadian Sebagai Dasar Bahagian 2
date:  23/05/2020
---

### Bacaan Untuk Pelajaran Minggu Ini
Ayub  26:7–10; Kejadian 1–2; Kejadian 5; Kejadian 11; 1 Chron. 1:18–27; Mat. 19:4, 5; Yoh. 1:1–3.

>
Ayat Hafalan

> "Langit menceritakan kemuliaan Tuhan, dan cakrawala memberitakan pekerjaan tangan-Nya; " (Mazmur 19:1).

Ramai pemikir yang hebat telah diilhami oleh Kitab Suci untuk meneroka dunia yang diciptakan Tuhan; Hasilnya, sains moden dilahirkan. Johannes Kepler, Isaac Newton, John Ray, Robert Boyle, dan ahli-ahli sains awal yang lain percaya bahawa kerja mereka telah mendedahkan lebih banyak lagi tentang hasil karya ciptaan Tuhan.

Bagaimanapun, selepas Revolusi Perancis, sains abad kesembilan belas mula beralih daripada pandangan teistik (evolusi) kepada suatu yang berdasarkan kejadian semula jadi dan materialisme, selalunya tiada tempat bagi supernatural sama sekali. Idea-idea filosofis ini dipopularkan oleh Charles Darwin On the Origin of Species (1859). Sejak pada masa itu, sains telah semakin menjauhkan diri daripada asas alkitabiahnya, menyebabkan penafsiran radikal kepada cerita dalam buku Kejadian.

Adakah Alkitab mengajar pandangan kosmologi yang kuno dan tidak ilmiah? Adakah cerita Alkitab hanya dipinjam dari bangsa kafir di sekeliling? Adakah cerita Alkitab disesuaikan oleh tempat dan waktunya, atau apakah sifatnya yang diilhami meninggikan kita untuk melihat asal-usul yang lengkap dalam kerangka kerja ilahi?

Ini adalah beberapa isu yang akan kita sentuh dalam pelajaran minggu ini.

_*Sila kaji pelajaran minggu ini untuk persediaan Sabat, 30 Mei._


text:
module DateParams
  VERSION = "2.1.0"
end


text:
#include <iterator>
#include <memory>
#include <tuple>
#include <utility>

#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "mlir/IR/Attributes.h"  // from @llvm-project
#include "mlir/IR/Builders.h"  // from @llvm-project
#include "mlir/IR/BuiltinOps.h"  // from @llvm-project
#include "mlir/IR/Identifier.h"  // from @llvm-project
#include "mlir/IR/MLIRContext.h"  // from @llvm-project
#include "mlir/IR/Operation.h"  // from @llvm-project
#include "mlir/IR/Types.h"  // from @llvm-project
#include "mlir/IR/Value.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Pass/PassRegistry.h"  // from @llvm-project
#include "mlir/Support/LogicalResult.h"  // from @llvm-project
#include "mlir/Transforms/RegionUtils.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_device.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_types.h"
#include "tensorflow/compiler/mlir/tensorflow/utils/serialize_mlir_module_utils.h"
#define DEBUG_TYPE "tf-tpu-merge-variables-with-execute"

namespace mlir {
namespace TFTPU {

namespace {
constexpr char kAliasingAttr[] = "tf.aliasing_output";
constexpr char kDeviceAttr[] = "device";
constexpr char kFuncDeviceAttr[] = "tf.device";

// A pass that finds on-device resource variable reads/assigns surrounding a
// tf.TPUExecute op, and merges them into a tf.TPUExecuteAndUpdateVariables.
// This allows the TPU execution to perform in-place variable updates.
//
// For example,
//
//   %0 = "tf.ReadVariableOp"(%arg0)
//   %1 = "tf.ReadVariableOp"(%arg1)
//   %2 = "tf.TPUExecute"(%0, %1, %compile)
//   %3 = "tf.AssignVariableOp"(%arg0, %2)
//
// will be transformed into
//
//   %2 = "tf.TPUExecuteAndUpdateVariables"(%arg0, %arg1, %compile)
//     { device_var_reads_indices = [0, 1],
//       device_var_updates_indices = [0, -1] }
//
// The transformation happens only for on-device variables. The above
// transformation requires %arg0, %arg1 to have the same device assignment as
// the TPUExecute op.

struct TPUMergeVariablesWithExecutePass
    : public PassWrapper<TPUMergeVariablesWithExecutePass, FunctionPass> {
  void runOnFunction() override;
};

// Information for a pair of input/output of the TPUExecute op and the
// surrounding read/assign ops.
struct VariableAccessInfo {
  int execute_input_index = -1;
  int execute_output_index = -1;
  Operation* read = nullptr;
  Operation* assign = nullptr;
};

// Information about all resource accesses to be fused into a TPUExecute op.
struct VariableAccessesForTPUExecute {
  // Maps each resource detected to VariableAccessInfo.
  llvm::SmallDenseMap<Value, VariableAccessInfo, 8> per_resource_info;
  // The corresponding new output index in TPUExecuteAndUpdateVariables for
  // each old output index in TPUExecute.
  llvm::SmallVector<int, 8> old_to_new_output_mapping;
  // The resources read by ReadVariableOps that are inputs to TPUExecute.
  // Ordered by the input indices to TPUExecute
  llvm::SmallVector<Value, 8> resources_read;
  // Operands for the new TPUExecuteAndUpdateVariables.
  llvm::SmallVector<Value, 8> new_operand_values;
};

// Returns if an op accesses a resource.
//
// TODO(yuanzx): Decide how to make this fine-grained. Right now we do not know
// if the resources alias.
bool OpAccessesResource(Operation* op) {
  return llvm::any_of(op->getOperandTypes(), [](const Type& type) {
    return type.isa<TF::ResourceType>() ||
           (type.isa<TensorType>() &&
            type.cast<TensorType>().getElementType().isa<TF::ResourceType>());
  });
}

// Finds the variable access info for a TPUExecute op.
//  - `check_device` specifies  whether it checks the device assignment of the
//  variables to match the TPUExecute op. This is optional in some context,
//  e.g., guaranteed by replication.
//  - `check_same_region` specifies whether the reads/assigns need to be in the
//  same region as `execute`. This is needed if `execute` is inside ReplicateOp.
VariableAccessesForTPUExecute BuildVariableAccessInfo(
    tf_device::LaunchOp execute_launch, bool check_device,
    bool check_same_region) {
  VariableAccessesForTPUExecute infos;
  Attribute device_attr = execute_launch.deviceAttr();
  if (check_device && !device_attr) return infos;
  auto func = execute_launch.getParentOfType<mlir::FuncOp>();

  // Track the first read op found, which is used later to check if there are
  // assign ops between it and the TPUExecute op. We will exclude reads before
  // interferencing accesses in a conservative way (see below). We do not
  // consider resource accesses in other islands since they ordering is enforced
  // by inter-island dependencies.
  Operation* first_read = nullptr;
  Operation& execute = execute_launch.GetBody().front();
  auto parallel_execute = llvm::dyn_cast<tf_device::ParallelExecuteOp>(
      execute_launch.getParentOp());
  Operation* execute_parent =
      parallel_execute ? parallel_execute.getOperation() : execute_launch;
  // Find inputs that are variable reads.
  for (auto operand : llvm::enumerate(execute.getOpOperands())) {
    infos.new_operand_values.push_back(operand.value().get());
    if (!operand.value().get().getDefiningOp()) continue;
    auto read_op = llvm::dyn_cast<TF::ReadVariableOp>(
        operand.value().get().getDefiningOp());
    if (!read_op) continue;
    if (check_same_region &&
        read_op.getParentRegion() != execute_parent->getParentRegion())
      continue;

    auto resource = read_op.resource();

    if (check_device) {
      // TODO(lyandy): Wrap resource ops in tf_device.launch.
      if (auto* resource_op = resource.getDefiningOp()) {
        auto resource_attr = resource_op->getAttr(kDeviceAttr);
        // Check device matching for the node defining the resource.
        if (!resource_attr || resource_attr != device_attr) continue;
      } else {
        auto resource_arg = resource.dyn_cast<BlockArgument>();
        assert(resource_arg);
        if (resource_arg.getOwner() != &func.front()) continue;
        // Check device matching for the argument defining the resource.
        auto resource_attr = func.getArgAttrOfType<mlir::StringAttr>(
            resource_arg.getArgNumber(), kFuncDeviceAttr);
        if (!resource_attr || resource_attr != device_attr) continue;
      }
    }

    auto emplace_res =
        infos.per_resource_info.try_emplace(resource, VariableAccessInfo());
    if (!emplace_res.second) {
      LLVM_DEBUG(llvm::dbgs()
                 << "Skipping execute that has multiple reads of a variable: "
                 << execute << "\n");
      infos.per_resource_info.shrink_and_clear();
      return infos;
    }

    auto& info = emplace_res.first->getSecond();
    info.execute_input_index = operand.index();
    info.read = read_op;
    infos.new_operand_values[operand.index()] = resource;
    infos.resources_read.push_back(resource);
    if (!first_read || info.read->isBeforeInBlock(first_read)) {
      first_read = info.read;
    }
  }

  if (!first_read) return infos;

  // Conservatively find the last resource-accessing op between first_read and
  // execute, excluding ReadVariableOps since they are read-only. This should
  // work fine for the reads/assigns created by resource lifting, since they are
  // placed close to the TPUExecute.
  Operation* last_may_modify_resource_access_before_execute = nullptr;
  for (Operation& op :
       llvm::reverse(llvm::make_range(std::next(first_read->getIterator()),
                                      execute_parent->getIterator()))) {
    if (llvm::dyn_cast<TF::ReadVariableOp>(&op)) continue;
    if (!OpAccessesResource(&op)) continue;
    last_may_modify_resource_access_before_execute = &op;
    break;
  }

  if (last_may_modify_resource_access_before_execute) {
    // Remove the reads before last_unknown_resource_access_before_execute.
    for (auto& op : llvm::make_range(
             first_read->getIterator(),
             last_may_modify_resource_access_before_execute->getIterator())) {
      auto read = llvm::dyn_cast<TF::ReadVariableOp>(&op);
      if (!read) continue;
      auto info_it = infos.per_resource_info.find(read.resource());
      if (info_it == infos.per_resource_info.end()) continue;
      int input_index = info_it->getSecond().execute_input_index;
      infos.new_operand_values[input_index] = execute.getOperand(input_index);
      infos.per_resource_info.erase(info_it);
    }
    infos.resources_read.erase(
        llvm::remove_if(infos.resources_read,
                        [&](const Value resource) {
                          return infos.per_resource_info.count(resource) == 0;
                        }),
        infos.resources_read.end());
  }

  if (infos.per_resource_info.empty()) {
    return infos;
  }

  // Find outputs that are variable assigns.
  Operation* last_assign = nullptr;
  llvm::SmallPtrSet<Operation*, 8> all_assigns;
  llvm::SmallVector<bool, 8> output_fused(execute_launch.getNumResults(),
                                          false);

  auto execute_outputs =
      parallel_execute
          ? parallel_execute.GetRegionOutputs(
                execute_launch.getParentRegion()->getRegionNumber())
          : execute_launch.getResults();
  for (auto execute_output : llvm::enumerate(execute_outputs)) {
    // TODO(lyandy): Handle updates to resource writes by remapping to parent
    // launch result and checking if launch result is an AssignVariableOp.
    auto result = execute_output.value();
    if (!result.hasOneUse()) continue;
    auto assign_op = llvm::dyn_cast<TF::AssignVariableOp>(*result.user_begin());
    if (!assign_op) continue;
    auto resource = assign_op.resource();
    auto it = infos.per_resource_info.find(resource);
    if (it == infos.per_resource_info.end()) continue;
    auto& info = it->getSecond();
    if (info.assign) {
      LLVM_DEBUG(llvm::dbgs()
                 << "Skipping execute that has multiple assigns of a variable: "
                 << execute << "\n");
      infos.per_resource_info.shrink_and_clear();
      return infos;
    }
    info.execute_output_index = execute_output.index();
    info.assign = assign_op;
    if (!last_assign || last_assign->isBeforeInBlock(assign_op)) {
      last_assign = assign_op;
    }
    all_assigns.insert(assign_op);
    output_fused[execute_output.index()] = true;
  }

  // Check if there are other resource accesses after execute.
  Operation* first_unknown_resource_access_after_execute = nullptr;
  if (last_assign) {
    for (auto& op : llvm::make_range(std::next(execute_parent->getIterator()),
                                     last_assign->getIterator())) {
      if (all_assigns.count(&op) > 0) continue;
      if (!OpAccessesResource(&op)) continue;
      first_unknown_resource_access_after_execute = &op;
      break;
    }
  }
  if (first_unknown_resource_access_after_execute) {
    // Remove the assigns after first_unknown_resource_access_after_execute.
    for (auto& op : llvm::make_range(
             first_unknown_resource_access_after_execute->getIterator(),
             std::next(last_assign->getIterator()))) {
      if (auto assign = llvm::dyn_cast<TF::AssignVariableOp>(&op)) {
        if (all_assigns.count(assign) == 0) continue;
        auto info_it = infos.per_resource_info.find(assign.resource());
        if (info_it == infos.per_resource_info.end()) continue;
        output_fused[info_it->second.execute_output_index] = false;
        info_it->second.execute_output_index = -1;
        info_it->second.assign = nullptr;
      }
    }
  }

  // Populate infos.old_to_new_output_mapping.
  int new_output_index = 0;
  infos.old_to_new_output_mapping.resize(execute_launch.getNumResults());
  for (int i = 0, end = execute_launch.getNumResults(); i < end; ++i) {
    if (output_fused[i]) {
      infos.old_to_new_output_mapping[i] = -1;
    } else {
      infos.old_to_new_output_mapping[i] = new_output_index;
      ++new_output_index;
    }
  }
  return infos;
}

// Appends result types of tf_device.parallel_execute from `start` index region
// (inclusive) to `end` index region (exclusive) to `output_types` and returns
// the number of types added.
int AppendTypes(llvm::SmallVectorImpl<Type>* output_types,
                tf_device::ParallelExecuteOp parallel_execute, int start,
                int end) {
  const int size_before = output_types->size();
  for (int index = start; index < end; ++index) {
    Block& block = parallel_execute.GetRegionBlockWithIndex(index);
    auto terminator_operand_types = block.getTerminator()->getOperandTypes();
    output_types->append(terminator_operand_types.begin(),
                         terminator_operand_types.end());
  }
  return output_types->size() - size_before;
}

// Replaces TPUExecute with TPUExecuteAndUpdateVariables in a
// tf_device.parallel_execute op.
void ReplaceParallelExecute(tf_device::ParallelExecuteOp parallel_execute,
                            tf_device::LaunchOp execute_launch,
                            tf_device::LaunchOp merged_execute_launch,
                            const VariableAccessesForTPUExecute& infos,
                            OpBuilder* builder) {
  Operation* parallel_execute_op = parallel_execute.getOperation();

  // Collect result types of tf_device.parallel_execute and update region
  // result types with the new merged execute result types.
  llvm::SmallVector<Type, 8> output_types;
  const int parallel_execute_num_results = parallel_execute_op->getNumResults();
  output_types.reserve(parallel_execute_num_results);
  Region* execute_region = merged_execute_launch.getParentRegion();
  const int region_index = execute_region->getRegionNumber();
  const int num_results_before_region =
      AppendTypes(&output_types, parallel_execute, 0, region_index);
  // Append updated results from merged execute.
  output_types.append(merged_execute_launch.getResultTypes().begin(),
                      merged_execute_launch.getResultTypes().end());
  const int num_regions = parallel_execute_op->getNumRegions();
  const int num_results_after_region = AppendTypes(
      &output_types, parallel_execute, region_index + 1, num_regions);

  builder->setInsertionPoint(parallel_execute);
  auto new_parallel_execute = builder->create<tf_device::ParallelExecuteOp>(
      parallel_execute.getLoc(), num_regions, output_types);

  // Replace the uses of the original parallel_execute before region containing
  // merged execute.
  Operation* new_parallel_execute_op = new_parallel_execute.getOperation();
  for (int i = 0; i < num_results_before_region; ++i)
    parallel_execute_op->getResult(i).replaceAllUsesWith(
        new_parallel_execute_op->getResult(i));

  // Replace the uses of the original parallel_execute after region containing
  // merged execute. The number of results changed in the region containing the
  // merged execute, but they should match, so results are replaced starting
  // from the ends of both parallel_execute.
  const int new_parallel_execute_num_results =
      new_parallel_execute_op->getNumResults();
  for (int i = 0; i < num_results_after_region; ++i)
    parallel_execute_op->getResult(parallel_execute_num_results - i - 1)
        .replaceAllUsesWith(new_parallel_execute_op->getResult(
            new_parallel_execute_num_results - i - 1));

  // Replace the uses of the original parallel_execute for the region containing
  // the merged execute.
  auto old_region_results = parallel_execute.GetRegionOutputs(region_index);
  for (int i = 0, end = infos.old_to_new_output_mapping.size(); i < end; ++i) {
    if (infos.old_to_new_output_mapping[i] < 0) continue;
    old_region_results[i].replaceAllUsesWith(new_parallel_execute_op->getResult(
        infos.old_to_new_output_mapping[i] + num_results_before_region));
  }

  // Replace original terminator with new terminator for returning merged
  // execute results.
  Operation* old_terminator = execute_region->front().getTerminator();
  builder->setInsertionPointToEnd(&execute_region->front());
  builder->create<tf_device::ReturnOp>(old_terminator->getLoc(),
                                       merged_execute_launch.getResults());
  old_terminator->erase();

  // Remove the original TPUExecute op.
  execute_launch.erase();

  // Move all regions from old parallel_execute to new parallel_execute.
  for (auto region : llvm::zip(new_parallel_execute_op->getRegions(),
                               parallel_execute_op->getRegions()))
    std::get<0>(region).takeBody(std::get<1>(region));

  // Remove the original parallel_execute.
  parallel_execute_op->dropAllUses();
  parallel_execute.erase();
}

// Replaces TPUExecute with TPUExecuteAndUpdateVariables.
void ReplaceExecute(tf_device::LaunchOp execute_launch,
                    tf_device::LaunchOp merged_execute_launch,
                    const VariableAccessesForTPUExecute& infos) {
  // Replace the uses.
  for (int i = 0, end = infos.old_to_new_output_mapping.size(); i < end; ++i) {
    if (infos.old_to_new_output_mapping[i] < 0) continue;
    execute_launch.getResult(i).replaceAllUsesWith(
        merged_execute_launch.getResult(infos.old_to_new_output_mapping[i]));
  }

  // Remove the original TPUExecute op.
  execute_launch.getOperation()->dropAllUses();
  execute_launch.erase();
}

// Returns TPUCompileMlir op that generates the program executed by the
// TPUExecute op.
TF::_TPUCompileMlirOp GetTPUCompileOp(tf_device::LaunchOp execute_launch) {
  auto execute =
      llvm::dyn_cast<TF::TPUExecuteOp>(execute_launch.GetBody().front());
  if (!execute) return {};
  auto compile_launch = llvm::dyn_cast_or_null<tf_device::LaunchOp>(
      execute.getOperand(execute.getNumOperands() - 1).getDefiningOp());
  if (!compile_launch) return {};
  return llvm::dyn_cast<TF::_TPUCompileMlirOp>(
      compile_launch.GetBody().front());
}

// Updates the serialized module associated with the TPUExecute op to reflect
// the aliasing information for better management of device memory.
LogicalResult UpdateSerializedModule(tf_device::LaunchOp execute_launch,
                                     VariableAccessesForTPUExecute& infos) {
  TF::_TPUCompileMlirOp compile = GetTPUCompileOp(execute_launch);

  // Skip adding alias information in case of model parallelism i.e.,
  // TPUCompileMlir op generates multiple programs.
  if (!compile || compile.program().size() > 1) return failure();

  // Parse the serialized module
  mlir::OwningModuleRef module_ref;
  tensorflow::Status status = tensorflow::DeserializeMlirModule(
      compile.mlir_module().str(), compile.getContext(), &module_ref);
  if (!status.ok()) {
    LLVM_DEBUG(llvm::dbgs() << "Error in parsing serialized module: "
                            << status.error_message() << "\n");

    return failure();
  }

  // Add aliasing information to main function arguments.
  FuncOp main_func = module_ref->lookupSymbol<FuncOp>("main");
  if (!main_func) return failure();

  OpBuilder builder(main_func.getContext());
  for (auto resource : infos.resources_read) {
    auto& info = infos.per_resource_info[resource];
    if (info.execute_input_index < 0 || info.execute_output_index < 0) continue;
    auto aliasing_attr = main_func.getArgAttrOfType<mlir::IntegerAttr>(
        info.execute_input_index, kAliasingAttr);

    // Set only if aliasing attribute does not exist.
    if (!aliasing_attr) {
      main_func.setArgAttr(
          info.execute_input_index, kAliasingAttr,
          builder.getI64IntegerAttr(info.execute_output_index));
      continue;
    }
    // If aliasing attribute already exists, it must match the new value.
    assert(aliasing_attr.getInt() == info.execute_output_index);
  }

  // Serialize the updated module back into the TPUCompileMlir op.
  auto module_string = tensorflow::SerializeMlirModule(module_ref.get());
  compile.mlir_moduleAttr(
      mlir::StringAttr::get(module_string, module_ref->getContext()));
  return success();
}

// Merges the variable accesses into one TPUExecute op.
void MergeForOneTPUExecute(tf_device::LaunchOp execute_launch,
                           bool check_device, bool check_same_region,
                           OpBuilder* builder) {
  auto infos =
      BuildVariableAccessInfo(execute_launch, check_device, check_same_region);
  if (infos.per_resource_info.empty()) {
    return;
  }

  // Update the serialized module with aliasing information for better memory
  // management on device.
  // TODO(b/172608422): Benchmark the cost of deserialization/serialization of
  // the attached module. We can avoid it by serializing it at the end of the
  // bridge pipeline.
  if (failed(UpdateSerializedModule(execute_launch, infos))) {
    LLVM_DEBUG(
        llvm::dbgs()
        << "Unable to update the serialized module with aliasing information "
           "which can lead to poor memory management on device.\n");
  }

  // Start creating the new TPUExecuteAndUpdateVariables op.
  builder->setInsertionPoint(execute_launch);
  // Output types. Skip the original outputs for fused assigns.
  llvm::SmallVector<Type, 8> new_output_types;
  int old_output_index = 0;
  for (const auto& type : execute_launch.getResultTypes()) {
    if (infos.old_to_new_output_mapping[old_output_index] >= 0) {
      new_output_types.push_back(type);
    }
    ++old_output_index;
  }
  // The attributes for fused variable reads and updates.
  llvm::SmallVector<int64_t, 8> device_var_reads_indices;
  llvm::SmallVector<int64_t, 8> device_var_updates_indices;
  for (auto resource : infos.resources_read) {
    const auto& info = infos.per_resource_info[resource];
    device_var_reads_indices.push_back(info.execute_input_index);
    device_var_updates_indices.push_back(info.execute_output_index);
  }
  auto merged_execute = builder->create<TF::TPUExecuteAndUpdateVariablesOp>(
      execute_launch.getLoc(), new_output_types, infos.new_operand_values,
      llvm::ArrayRef<NamedAttribute>{
          builder->getNamedAttr(
              "device_var_reads_indices",
              builder->getI64ArrayAttr(device_var_reads_indices)),
          builder->getNamedAttr(
              "device_var_updates_indices",
              builder->getI64ArrayAttr(device_var_updates_indices))});

  // Wrap in launch for device assignment.
  auto merged_execute_launch = builder->create<tf_device::LaunchOp>(
      merged_execute.getLoc(), execute_launch.deviceAttr(),
      merged_execute.getResultTypes());
  merged_execute_launch.body().push_back(new Block);

  builder->setInsertionPointToEnd(&merged_execute_launch.GetBody());
  builder->create<tf_device::ReturnOp>(merged_execute.getLoc(),
                                       merged_execute.getResults());

  merged_execute.getOperation()->moveBefore(
      merged_execute_launch.GetBody().getTerminator());

  if (auto parallel_execute = llvm::dyn_cast<tf_device::ParallelExecuteOp>(
          execute_launch.getParentOp()))
    ReplaceParallelExecute(parallel_execute, execute_launch,
                           merged_execute_launch, infos, builder);
  else
    ReplaceExecute(execute_launch, merged_execute_launch, infos);

  // Remove the assign ops.
  for (const auto& entry : infos.per_resource_info) {
    const auto& info = entry.getSecond();
    if (info.assign) info.assign->erase();
  }

  // Remove the read ops if they have no more uses.
  for (const auto& entry : infos.per_resource_info) {
    const auto& info = entry.getSecond();
    if (info.read->use_empty()) info.read->erase();
  }
}

// Checks if an ops parent is a tf_device.parallel_execute and the region the
// op is in is perfectly wrapped.
bool ParentParallelExecuteWrapsSingleOp(Operation* op) {
  auto parallel_execute =
      llvm::dyn_cast<tf_device::ParallelExecuteOp>(op->getParentOp());
  if (!parallel_execute) return true;

  return parallel_execute.RegionWrapsSingleOp(
      op->getParentRegion()->getRegionNumber());
}

void TPUMergeVariablesWithExecutePass::runOnFunction() {
  // Find all the executes first, since we will mutate the nodes around each
  // execute.
  llvm::SmallVector<tf_device::LaunchOp, 8> execute_launches;
  getFunction().walk([&](tf_device::LaunchOp op) {
    if (op.WrapsSingleOp() &&
        llvm::isa<TF::TPUExecuteOp>(op.GetBody().front()) &&
        ParentParallelExecuteWrapsSingleOp(op))
      execute_launches.push_back(op);
  });

  for (auto execute_launch : execute_launches) {
    OpBuilder builder(&getContext());
    const bool parent_is_replicate =
        llvm::isa<tf_device::ReplicateOp>(execute_launch.getParentOp()) ||
        (llvm::isa<tf_device::ParallelExecuteOp>(
             execute_launch.getParentOp()) &&
         llvm::isa<tf_device::ReplicateOp>(
             execute_launch.getParentOp()->getParentOp()));

    // If this is inside a tf_device::ReplicateOp, the variables are guaranteed
    // to be on the same device as the TPUExecute op. Skip device checking in
    // that case, but we need to check that we are only merging reads/assigns
    // that are also in this replicated region.
    MergeForOneTPUExecute(execute_launch, /*check_device=*/!parent_is_replicate,
                          /*check_same_region=*/parent_is_replicate, &builder);
  }
}

}  // namespace

std::unique_ptr<OperationPass<FuncOp>>
CreateTPUMergeVariablesWithExecutePass() {
  return std::make_unique<TPUMergeVariablesWithExecutePass>();
}

static PassRegistration<TPUMergeVariablesWithExecutePass> pass(
    "tf-tpu-merge-variables-with-execute",
    "Merges device variable reads/updates into tpu execute nodes");

}  // namespace TFTPU
}  // namespace mlir