text:
.class public final Lcom/android/server/AttributeCache;
.super Ljava/lang/Object;
.source "AttributeCache.java"

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/android/server/AttributeCache$Entry;,
        Lcom/android/server/AttributeCache$Package;
    }
.end annotation

# static fields
.field private static sInstance:Lcom/android/server/AttributeCache;

# instance fields
.field private final mConfiguration:Landroid/content/res/Configuration;

.field private final mContext:Landroid/content/Context;

.field private final mPackages:Ljava/util/HashMap;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/HashMap",
            "<",
            "Ljava/lang/String;",
            "Ljava/lang/ref/WeakReference",
            "<",
            "Lcom/android/server/AttributeCache$Package;",
            ">;>;"
        }
    .end annotation
.end field

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 37
    const/4 v0, 0x0

    sput-object v0, Lcom/android/server/AttributeCache;->sInstance:Lcom/android/server/AttributeCache;

    return-void
.end method

.method public constructor <init>(Landroid/content/Context;)V
    .locals 1
    .parameter "context"

    .prologue
    .line 83
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    .line 48
    new-instance v0, Ljava/util/HashMap;

    invoke-direct {v0}, Ljava/util/HashMap;-><init>()V

    iput-object v0, p0, Lcom/android/server/AttributeCache;->mPackages:Ljava/util/HashMap;

    .line 51
    new-instance v0, Landroid/content/res/Configuration;

    invoke-direct {v0}, Landroid/content/res/Configuration;-><init>()V

    iput-object v0, p0, Lcom/android/server/AttributeCache;->mConfiguration:Landroid/content/res/Configuration;

    .line 84
    iput-object p1, p0, Lcom/android/server/AttributeCache;->mContext:Landroid/content/Context;

    .line 85
    return-void
.end method

.method public static init(Landroid/content/Context;)V
    .locals 1
    .parameter "context"

    .prologue
    .line 74
    sget-object v0, Lcom/android/server/AttributeCache;->sInstance:Lcom/android/server/AttributeCache;

    if-nez v0, :cond_0

    .line 75
    new-instance v0, Lcom/android/server/AttributeCache;

    invoke-direct {v0, p0}, Lcom/android/server/AttributeCache;-><init>(Landroid/content/Context;)V

    sput-object v0, Lcom/android/server/AttributeCache;->sInstance:Lcom/android/server/AttributeCache;

    .line 77
    :cond_0
    return-void
.end method

.method public static instance()Lcom/android/server/AttributeCache;
    .locals 1

    .prologue
    .line 80
    sget-object v0, Lcom/android/server/AttributeCache;->sInstance:Lcom/android/server/AttributeCache;

    return-object v0
.end method

# virtual methods
.method public get(Ljava/lang/String;I[I)Lcom/android/server/AttributeCache$Entry;
    .locals 10
    .parameter "packageName"
    .parameter "resId"
    .parameter "styleable"

    .prologue
    const/4 v7, 0x0

    .line 108
    monitor-enter p0

    .line 111
    :try_start_0
    iget-object v8, p0, Lcom/android/server/AttributeCache;->mPackages:Ljava/util/HashMap;

    invoke-virtual {v8, p1}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v6

    check-cast v6, Ljava/lang/ref/WeakReference;

    .line 112
    .local v6, pkgRef:Ljava/lang/ref/WeakReference;,"Ljava/lang/ref/WeakReference<Lcom/android/server/AttributeCache$Package;>;"
    const/4 v5, 0x0

    .line 113
    .local v5, pkg:Lcom/android/server/AttributeCache$Package;
    if-eqz v6, :cond_0

    .line 114
    invoke-virtual {v6}, Ljava/lang/ref/WeakReference;->get()Ljava/lang/Object;

    move-result-object v5

    .end local v5           #pkg:Lcom/android/server/AttributeCache$Package;
    check-cast v5, Lcom/android/server/AttributeCache$Package;

    .line 117
    .restart local v5       #pkg:Lcom/android/server/AttributeCache$Package;
    :cond_0
    const/4 v4, 0x0

    .line 118
    .local v4, map:Ljava/util/HashMap;,"Ljava/util/HashMap<[ILcom/android/server/AttributeCache$Entry;>;"
    const/4 v2, 0x0

    .line 119
    .local v2, ent:Lcom/android/server/AttributeCache$Entry;
    if-eqz v5, :cond_1

    .line 120
    #getter for: Lcom/android/server/AttributeCache$Package;->mMap:Landroid/util/SparseArray;
    invoke-static {v5}, Lcom/android/server/AttributeCache$Package;->access$000(Lcom/android/server/AttributeCache$Package;)Landroid/util/SparseArray;

    move-result-object v8

    invoke-virtual {v8, p2}, Landroid/util/SparseArray;->get(I)Ljava/lang/Object;

    move-result-object v4

    .end local v4           #map:Ljava/util/HashMap;,"Ljava/util/HashMap<[ILcom/android/server/AttributeCache$Entry;>;"
    check-cast v4, Ljava/util/HashMap;

    .line 121
    .restart local v4       #map:Ljava/util/HashMap;,"Ljava/util/HashMap<[ILcom/android/server/AttributeCache$Entry;>;"
    if-eqz v4, :cond_3

    .line 122
    invoke-virtual {v4, p3}, Ljava/util/HashMap;->get(Ljava/lang/Object;)Ljava/lang/Object;

    move-result-object v2

    .end local v2           #ent:Lcom/android/server/AttributeCache$Entry;
    check-cast v2, Lcom/android/server/AttributeCache$Entry;

    .line 123
    .restart local v2       #ent:Lcom/android/server/AttributeCache$Entry;
    if-eqz v2, :cond_3

    .line 124
    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-object v7, v2

    .line 158
    :goto_0
    return-object v7

    .line 130
    :cond_1
    :try_start_1
    iget-object v8, p0, Lcom/android/server/AttributeCache;->mContext:Landroid/content/Context;

    const/4 v9, 0x0

    invoke-virtual {v8, p1, v9}, Landroid/content/Context;->createPackageContext(Ljava/lang/String;I)Landroid/content/Context;
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0
    .catch Landroid/content/pm/PackageManager$NameNotFoundException; {:try_start_1 .. :try_end_1} :catch_0

    move-result-object v0

    .line 131
    .local v0, context:Landroid/content/Context;
    if-nez v0, :cond_2

    .line 132
    :try_start_2
    monitor-exit p0

    goto :goto_0

    .line 159
    .end local v0           #context:Landroid/content/Context;
    .end local v2           #ent:Lcom/android/server/AttributeCache$Entry;
    .end local v4           #map:Ljava/util/HashMap;,"Ljava/util/HashMap<[ILcom/android/server/AttributeCache$Entry;>;"
    .end local v5           #pkg:Lcom/android/server/AttributeCache$Package;
    .end local v6           #pkgRef:Ljava/lang/ref/WeakReference;,"Ljava/lang/ref/WeakReference<Lcom/android/server/AttributeCache$Package;>;"
    :catchall_0
    move-exception v7

    monitor-exit p0
    :try_end_2
    .catchall {:try_start_2 .. :try_end_2} :catchall_0

    throw v7

    .line 134
    .restart local v2       #ent:Lcom/android/server/AttributeCache$Entry;
    .restart local v4       #map:Ljava/util/HashMap;,"Ljava/util/HashMap<[ILcom/android/server/AttributeCache$Entry;>;"
    .restart local v5       #pkg:Lcom/android/server/AttributeCache$Package;
    .restart local v6       #pkgRef:Ljava/lang/ref/WeakReference;,"Ljava/lang/ref/WeakReference<Lcom/android/server/AttributeCache$Package;>;"
    :catch_0
    move-exception v1

    .line 135
    .local v1, e:Landroid/content/pm/PackageManager$NameNotFoundException;
    :try_start_3
    monitor-exit p0

    goto :goto_0

    .line 137
    .end local v1           #e:Landroid/content/pm/PackageManager$NameNotFoundException;
    .restart local v0       #context:Landroid/content/Context;
    :cond_2
    new-instance v5, Lcom/android/server/AttributeCache$Package;

    .end local v5           #pkg:Lcom/android/server/AttributeCache$Package;
    invoke-direct {v5, v0}, Lcom/android/server/AttributeCache$Package;-><init>(Landroid/content/Context;)V

    .line 141
    .restart local v5       #pkg:Lcom/android/server/AttributeCache$Package;
    iget-object v8, p0, Lcom/android/server/AttributeCache;->mPackages:Ljava/util/HashMap;

    new-instance v9, Ljava/lang/ref/WeakReference;

    invoke-direct {v9, v5}, Ljava/lang/ref/WeakReference;-><init>(Ljava/lang/Object;)V

    invoke-virtual {v8, p1, v9}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;

    .end local v0           #context:Landroid/content/Context;
    :cond_3
    move-object v3, v2

    .line 145
    .end local v2           #ent:Lcom/android/server/AttributeCache$Entry;
    .local v3, ent:Lcom/android/server/AttributeCache$Entry;
    if-nez v4, :cond_4

    .line 146
    new-instance v4, Ljava/util/HashMap;

    .end local v4           #map:Ljava/util/HashMap;,"Ljava/util/HashMap<[ILcom/android/server/AttributeCache$Entry;>;"
    invoke-direct {v4}, Ljava/util/HashMap;-><init>()V

    .line 147
    .restart local v4       #map:Ljava/util/HashMap;,"Ljava/util/HashMap<[ILcom/android/server/AttributeCache$Entry;>;"
    #getter for: Lcom/android/server/AttributeCache$Package;->mMap:Landroid/util/SparseArray;
    invoke-static {v5}, Lcom/android/server/AttributeCache$Package;->access$000(Lcom/android/server/AttributeCache$Package;)Landroid/util/SparseArray;

    move-result-object v8

    invoke-virtual {v8, p2, v4}, Landroid/util/SparseArray;->put(ILjava/lang/Object;)V
    :try_end_3
    .catchall {:try_start_3 .. :try_end_3} :catchall_0

    .line 151
    :cond_4
    :try_start_4
    new-instance v2, Lcom/android/server/AttributeCache$Entry;

    iget-object v8, v5, Lcom/android/server/AttributeCache$Package;->context:Landroid/content/Context;

    iget-object v9, v5, Lcom/android/server/AttributeCache$Package;->context:Landroid/content/Context;

    invoke-virtual {v9, p2, p3}, Landroid/content/Context;->obtainStyledAttributes(I[I)Landroid/content/res/TypedArray;

    move-result-object v9

    invoke-direct {v2, v8, v9}, Lcom/android/server/AttributeCache$Entry;-><init>(Landroid/content/Context;Landroid/content/res/TypedArray;)V
    :try_end_4
    .catchall {:try_start_4 .. :try_end_4} :catchall_0
    .catch Landroid/content/res/Resources$NotFoundException; {:try_start_4 .. :try_end_4} :catch_1

    .line 153
    .end local v3           #ent:Lcom/android/server/AttributeCache$Entry;
    .restart local v2       #ent:Lcom/android/server/AttributeCache$Entry;
    :try_start_5
    invoke-virtual {v4, p3, v2}, Ljava/util/HashMap;->put(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;
    :try_end_5
    .catchall {:try_start_5 .. :try_end_5} :catchall_0
    .catch Landroid/content/res/Resources$NotFoundException; {:try_start_5 .. :try_end_5} :catch_2

    .line 158
    :try_start_6
    monitor-exit p0

    move-object v7, v2

    goto :goto_0

    .line 154
    .end local v2           #ent:Lcom/android/server/AttributeCache$Entry;
    .restart local v3       #ent:Lcom/android/server/AttributeCache$Entry;
    :catch_1
    move-exception v1

    move-object v2, v3

    .line 155
    .end local v3           #ent:Lcom/android/server/AttributeCache$Entry;
    .local v1, e:Landroid/content/res/Resources$NotFoundException;
    .restart local v2       #ent:Lcom/android/server/AttributeCache$Entry;
    :goto_1
    monitor-exit p0
    :try_end_6
    .catchall {:try_start_6 .. :try_end_6} :catchall_0

    goto :goto_0

    .line 154
    .end local v1           #e:Landroid/content/res/Resources$NotFoundException;
    :catch_2
    move-exception v1

    goto :goto_1
.end method

.method public removePackage(Ljava/lang/String;)V
    .locals 1
    .parameter "packageName"

    .prologue
    .line 88
    monitor-enter p0

    .line 89
    :try_start_0
    iget-object v0, p0, Lcom/android/server/AttributeCache;->mPackages:Ljava/util/HashMap;

    invoke-virtual {v0, p1}, Ljava/util/HashMap;->remove(Ljava/lang/Object;)Ljava/lang/Object;

    .line 90
    monitor-exit p0

    .line 91
    return-void

    .line 90
    :catchall_0
    move-exception v0

    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v0
.end method

.method public updateConfiguration(Landroid/content/res/Configuration;)V
    .locals 2
    .parameter "config"

    .prologue
    .line 94
    monitor-enter p0

    .line 95
    :try_start_0
    iget-object v1, p0, Lcom/android/server/AttributeCache;->mConfiguration:Landroid/content/res/Configuration;

    invoke-virtual {v1, p1}, Landroid/content/res/Configuration;->updateFrom(Landroid/content/res/Configuration;)I

    move-result v0

    .line 96
    .local v0, changes:I
    const v1, -0x400000a1

    and-int/2addr v1, v0

    if-eqz v1, :cond_0

    .line 102
    iget-object v1, p0, Lcom/android/server/AttributeCache;->mPackages:Ljava/util/HashMap;

    invoke-virtual {v1}, Ljava/util/HashMap;->clear()V

    .line 104
    :cond_0
    monitor-exit p0

    .line 105
    return-void

    .line 104
    .end local v0           #changes:I
    :catchall_0
    move-exception v1

    monitor-exit p0
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    throw v1
.end method


text:
package com.hp.feTest.service;

import com.hp.feTest.dao.UserMapper;
import com.hp.feTest.domain.UserGridObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: rajagova
 * Date: 8/16/12
 * Time: 12:08 PM
 * To change this template use File | Settings | File Templates.
 */
@Service("UserService")
@Transactional(readOnly = false )
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public List<UserGridObject> getUserList() {
        return (List<UserGridObject>)userMapper.getUserList();
    }

    public int updateUsers(UserGridObject userGridObject) {
        return (int)userMapper.updateUsers(userGridObject);
    }

    public int updateRolebyUserId(UserGridObject userGridObject) {
        return (int)userMapper.updateRolebyUserId(userGridObject);
    }

    public long getUserId() {
        return (long)userMapper.getUserId();
    }

    public int insertNewUser(UserGridObject userGridObject) {
        return (int)userMapper.insertNewUser(userGridObject);
    }

    public int insertRoleForUser(UserGridObject userGridObject) {
        return (int)userMapper.insertRoleForUser(userGridObject);
    }

    public int updatePassword(UserGridObject userGridObject){
        return (int)userMapper.updatePassword(userGridObject);
    }

    public boolean checkUserValid(UserGridObject userGridObject){
        return 1 == userMapper.checkUserValid(userGridObject);
    }

    public int removeAllRoles(UserGridObject userGridObject){
        return (int)userMapper.removeAllRoles(userGridObject);
    }

    public boolean checkNewUser(String username) {
        return 1 == userMapper.checkNewUser(username);

    }

    public int updateNewPassword(UserGridObject userGridObject) {
        return (int)userMapper.updateNewPassword(userGridObject);
    }

    public UserGridObject getUser(String username){
        return (UserGridObject)userMapper.getUser(username);
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>js/geom/Point.js - StructureJS</title>
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

StructureJS
 0.9.0

Code and documentation for the StructureJS library.

index

top

Classes

Modules

            <input type="search" id="api-filter" placeholder="Type to filter APIs">

ApplicationCacheController

ApplicationCacheEvent

BaseEvent

BaseModel

BaseObject

BrowserUtil

BulkLoader

BulkLoaderEvent

Collection

ComponentFactory

DateUtil

DisplayObject

DisplayObjectContainer

DOMElement

EventBroker

EventDispatcher

Extend

ImageLoader

LoaderEvent

LocalStorageController

LocalStorageEvent

MathUtil

MerchantUtil

NetworkMonitor

NetworkMonitorEvent

NumberUtil

ObjectManager

Point

Route

Router

RouterEvent

Stage

StringUtil

TemplateFactory

Timer

TimerEvent

Util

ValidationUtil

controller

core

event

geom

model

StructureJS

util

view

File: js/geom/Point.js

(function (deps, factory) {
    if (typeof module === 'object' && typeof module.exports === 'object') {
        var v = factory(require, exports); if (v !== undefined) module.exports = v;
    }
    else if (typeof define === 'function' && define.amd) {
        define(deps, factory);
    }
})(["require", "exports"], function (require, exports) {
    /**
     * The Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
     *
     * @class Point
     * @module StructureJS
     * @submodule geom
     * @constructor
     * @author Robert S. (www.codeBelt.com)
     */
    var Point = (function () {
        function Point(x, y) {
            if (x === void 0) { x = 0; }
            if (y === void 0) { y = 0; }
            /**
             * The horizontal coordinate of the point.
             *
             * @property x
             * @type {number}
             * @public
             */
            this.x = 0;
            /**
             * The vertical coordinate of the point.
             *
             * @property y
             * @type {number}
             * @public
             */
            this.y = 0;
            this.x = x;
            this.y = y;
        }
        return Point;
    })();
    return Point;
});


text:
package repo

import (
	"errors"
	"fmt"
	"net/http"
	"net/url"
	"path"
	"strings"

	"code.gitea.io/gitea/models/perm"
	user_model "code.gitea.io/gitea/models/user"
	"code.gitea.io/gitea/models/webhook"
	"code.gitea.io/gitea/modules/base"
	"code.gitea.io/gitea/modules/context"
	"code.gitea.io/gitea/modules/convert"
	"code.gitea.io/gitea/modules/git"
	"code.gitea.io/gitea/modules/json"
	"code.gitea.io/gitea/modules/setting"
	api "code.gitea.io/gitea/modules/structs"
	"code.gitea.io/gitea/modules/util"
	"code.gitea.io/gitea/modules/web"
	"code.gitea.io/gitea/services/forms"
	webhook_service "code.gitea.io/gitea/services/webhook"
)

const (
	tplHooks        base.TplName = "repo/settings/webhook/base"
	tplHookNew      base.TplName = "repo/settings/webhook/new"
	tplOrgHookNew   base.TplName = "org/settings/hook_new"
	tplAdminHookNew base.TplName = "admin/hook_new"
)

// Webhooks render web hooks list page
func Webhooks(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.settings.hooks")
	ctx.Data["PageIsSettingsHooks"] = true
	ctx.Data["BaseLink"] = ctx.Repo.RepoLink + "/settings/hooks"
	ctx.Data["BaseLinkNew"] = ctx.Repo.RepoLink + "/settings/hooks"
	ctx.Data["Description"] = ctx.Tr("repo.settings.hooks_desc", "https://docs.gitea.io/en-us/webhooks/")

	ws, err := webhook.ListWebhooksByOpts(ctx, &webhook.ListWebhookOptions{RepoID: ctx.Repo.Repository.ID})
	if err != nil {
		ctx.ServerError("GetWebhooksByRepoID", err)
		return
	}
	ctx.Data["Webhooks"] = ws

	ctx.HTML(http.StatusOK, tplHooks)
}

type orgRepoCtx struct {
	OrgID           int64
	RepoID          int64
	IsAdmin         bool
	IsSystemWebhook bool
	Link            string
	LinkNew         string
	NewTemplate     base.TplName
}

// getOrgRepoCtx determines whether this is a repo, organization, or admin (both default and system) context.
func getOrgRepoCtx(ctx *context.Context) (*orgRepoCtx, error) {
	if len(ctx.Repo.RepoLink) > 0 {
		return &orgRepoCtx{
			RepoID:      ctx.Repo.Repository.ID,
			Link:        path.Join(ctx.Repo.RepoLink, "settings/hooks"),
			LinkNew:     path.Join(ctx.Repo.RepoLink, "settings/hooks"),
			NewTemplate: tplHookNew,
		}, nil
	}

	if len(ctx.Org.OrgLink) > 0 {
		return &orgRepoCtx{
			OrgID:       ctx.Org.Organization.ID,
			Link:        path.Join(ctx.Org.OrgLink, "settings/hooks"),
			LinkNew:     path.Join(ctx.Org.OrgLink, "settings/hooks"),
			NewTemplate: tplOrgHookNew,
		}, nil
	}

	if ctx.Doer.IsAdmin {
		// Are we looking at default webhooks?
		if ctx.Params(":configType") == "default-hooks" {
			return &orgRepoCtx{
				IsAdmin:     true,
				Link:        path.Join(setting.AppSubURL, "/admin/hooks"),
				LinkNew:     path.Join(setting.AppSubURL, "/admin/default-hooks"),
				NewTemplate: tplAdminHookNew,
			}, nil
		}

		// Must be system webhooks instead
		return &orgRepoCtx{
			IsAdmin:         true,
			IsSystemWebhook: true,
			Link:            path.Join(setting.AppSubURL, "/admin/hooks"),
			LinkNew:         path.Join(setting.AppSubURL, "/admin/system-hooks"),
			NewTemplate:     tplAdminHookNew,
		}, nil
	}

	return nil, errors.New("unable to set OrgRepo context")
}

func checkHookType(ctx *context.Context) string {
	hookType := strings.ToLower(ctx.Params(":type"))
	if !util.IsStringInSlice(hookType, setting.Webhook.Types, true) {
		ctx.NotFound("checkHookType", nil)
		return ""
	}
	return hookType
}

// WebhooksNew render creating webhook page
func WebhooksNew(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
	ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook.HookEvent{}}

	orCtx, err := getOrgRepoCtx(ctx)
	if err != nil {
		ctx.ServerError("getOrgRepoCtx", err)
		return
	}

	if orCtx.IsAdmin && orCtx.IsSystemWebhook {
		ctx.Data["PageIsAdminSystemHooks"] = true
		ctx.Data["PageIsAdminSystemHooksNew"] = true
	} else if orCtx.IsAdmin {
		ctx.Data["PageIsAdminDefaultHooks"] = true
		ctx.Data["PageIsAdminDefaultHooksNew"] = true
	} else {
		ctx.Data["PageIsSettingsHooks"] = true
		ctx.Data["PageIsSettingsHooksNew"] = true
	}

	hookType := checkHookType(ctx)
	ctx.Data["HookType"] = hookType
	if ctx.Written() {
		return
	}
	if hookType == "discord" {
		ctx.Data["DiscordHook"] = map[string]interface{}{
			"Username": "Gitea",
		}
	}
	ctx.Data["BaseLink"] = orCtx.LinkNew

	ctx.HTML(http.StatusOK, orCtx.NewTemplate)
}

// ParseHookEvent convert web form content to webhook.HookEvent
func ParseHookEvent(form forms.WebhookForm) *webhook.HookEvent {
	return &webhook.HookEvent{
		PushOnly:       form.PushOnly(),
		SendEverything: form.SendEverything(),
		ChooseEvents:   form.ChooseEvents(),
		HookEvents: webhook.HookEvents{
			Create:               form.Create,
			Delete:               form.Delete,
			Fork:                 form.Fork,
			Issues:               form.Issues,
			IssueAssign:          form.IssueAssign,
			IssueLabel:           form.IssueLabel,
			IssueMilestone:       form.IssueMilestone,
			IssueComment:         form.IssueComment,
			Release:              form.Release,
			Push:                 form.Push,
			PullRequest:          form.PullRequest,
			PullRequestAssign:    form.PullRequestAssign,
			PullRequestLabel:     form.PullRequestLabel,
			PullRequestMilestone: form.PullRequestMilestone,
			PullRequestComment:   form.PullRequestComment,
			PullRequestReview:    form.PullRequestReview,
			PullRequestSync:      form.PullRequestSync,
			Wiki:                 form.Wiki,
			Repository:           form.Repository,
			Package:              form.Package,
		},
		BranchFilter: form.BranchFilter,
	}
}

type webhookParams struct {
	// Type should be imported from webhook package (webhook.XXX)
	Type string

	URL         string
	ContentType webhook.HookContentType
	Secret      string
	HTTPMethod  string
	WebhookForm forms.WebhookForm
	Meta        interface{}
}

func createWebhook(ctx *context.Context, params webhookParams) {
	ctx.Data["Title"] = ctx.Tr("repo.settings.add_webhook")
	ctx.Data["PageIsSettingsHooks"] = true
	ctx.Data["PageIsSettingsHooksNew"] = true
	ctx.Data["Webhook"] = webhook.Webhook{HookEvent: &webhook.HookEvent{}}
	ctx.Data["HookType"] = params.Type

	orCtx, err := getOrgRepoCtx(ctx)
	if err != nil {
		ctx.ServerError("getOrgRepoCtx", err)
		return
	}
	ctx.Data["BaseLink"] = orCtx.LinkNew

	if ctx.HasError() {
		ctx.HTML(http.StatusOK, orCtx.NewTemplate)
		return
	}

	var meta []byte
	if params.Meta != nil {
		meta, err = json.Marshal(params.Meta)
		if err != nil {
			ctx.ServerError("Marshal", err)
			return
		}
	}

	w := &webhook.Webhook{
		RepoID:          orCtx.RepoID,
		URL:             params.URL,
		HTTPMethod:      params.HTTPMethod,
		ContentType:     params.ContentType,
		Secret:          params.Secret,
		HookEvent:       ParseHookEvent(params.WebhookForm),
		IsActive:        params.WebhookForm.Active,
		Type:            params.Type,
		Meta:            string(meta),
		OrgID:           orCtx.OrgID,
		IsSystemWebhook: orCtx.IsSystemWebhook,
	}
	err = w.SetHeaderAuthorization(params.WebhookForm.AuthorizationHeader)
	if err != nil {
		ctx.ServerError("SetHeaderAuthorization", err)
		return
	}
	if err := w.UpdateEvent(); err != nil {
		ctx.ServerError("UpdateEvent", err)
		return
	} else if err := webhook.CreateWebhook(ctx, w); err != nil {
		ctx.ServerError("CreateWebhook", err)
		return
	}

	ctx.Flash.Success(ctx.Tr("repo.settings.add_hook_success"))
	ctx.Redirect(orCtx.Link)
}

func editWebhook(ctx *context.Context, params webhookParams) {
	ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
	ctx.Data["PageIsSettingsHooks"] = true
	ctx.Data["PageIsSettingsHooksEdit"] = true

	orCtx, w := checkWebhook(ctx)
	if ctx.Written() {
		return
	}
	ctx.Data["Webhook"] = w

	if ctx.HasError() {
		ctx.HTML(http.StatusOK, orCtx.NewTemplate)
		return
	}

	var meta []byte
	var err error
	if params.Meta != nil {
		meta, err = json.Marshal(params.Meta)
		if err != nil {
			ctx.ServerError("Marshal", err)
			return
		}
	}

	w.URL = params.URL
	w.ContentType = params.ContentType
	w.Secret = params.Secret
	w.HookEvent = ParseHookEvent(params.WebhookForm)
	w.IsActive = params.WebhookForm.Active
	w.HTTPMethod = params.HTTPMethod
	w.Meta = string(meta)

	err = w.SetHeaderAuthorization(params.WebhookForm.AuthorizationHeader)
	if err != nil {
		ctx.ServerError("SetHeaderAuthorization", err)
		return
	}

	if err := w.UpdateEvent(); err != nil {
		ctx.ServerError("UpdateEvent", err)
		return
	} else if err := webhook.UpdateWebhook(w); err != nil {
		ctx.ServerError("UpdateWebhook", err)
		return
	}

	ctx.Flash.Success(ctx.Tr("repo.settings.update_hook_success"))
	ctx.Redirect(fmt.Sprintf("%s/%d", orCtx.Link, w.ID))
}

// GiteaHooksNewPost response for creating Gitea webhook
func GiteaHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, giteaHookParams(ctx))
}

// GiteaHooksEditPost response for editing Gitea webhook
func GiteaHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, giteaHookParams(ctx))
}

func giteaHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewWebhookForm)

	contentType := webhook.ContentTypeJSON
	if webhook.HookContentType(form.ContentType) == webhook.ContentTypeForm {
		contentType = webhook.ContentTypeForm
	}

	return webhookParams{
		Type:        webhook.GITEA,
		URL:         form.PayloadURL,
		ContentType: contentType,
		Secret:      form.Secret,
		HTTPMethod:  form.HTTPMethod,
		WebhookForm: form.WebhookForm,
	}
}

// GogsHooksNewPost response for creating Gogs webhook
func GogsHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, gogsHookParams(ctx))
}

// GogsHooksEditPost response for editing Gogs webhook
func GogsHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, gogsHookParams(ctx))
}

func gogsHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewGogshookForm)

	contentType := webhook.ContentTypeJSON
	if webhook.HookContentType(form.ContentType) == webhook.ContentTypeForm {
		contentType = webhook.ContentTypeForm
	}

	return webhookParams{
		Type:        webhook.GOGS,
		URL:         form.PayloadURL,
		ContentType: contentType,
		Secret:      form.Secret,
		WebhookForm: form.WebhookForm,
	}
}

// DiscordHooksNewPost response for creating Discord webhook
func DiscordHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, discordHookParams(ctx))
}

// DiscordHooksEditPost response for editing Discord webhook
func DiscordHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, discordHookParams(ctx))
}

func discordHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewDiscordHookForm)

	return webhookParams{
		Type:        webhook.DISCORD,
		URL:         form.PayloadURL,
		ContentType: webhook.ContentTypeJSON,
		WebhookForm: form.WebhookForm,
		Meta: &webhook_service.DiscordMeta{
			Username: form.Username,
			IconURL:  form.IconURL,
		},
	}
}

// DingtalkHooksNewPost response for creating Dingtalk webhook
func DingtalkHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, dingtalkHookParams(ctx))
}

// DingtalkHooksEditPost response for editing Dingtalk webhook
func DingtalkHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, dingtalkHookParams(ctx))
}

func dingtalkHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewDingtalkHookForm)

	return webhookParams{
		Type:        webhook.DINGTALK,
		URL:         form.PayloadURL,
		ContentType: webhook.ContentTypeJSON,
		WebhookForm: form.WebhookForm,
	}
}

// TelegramHooksNewPost response for creating Telegram webhook
func TelegramHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, telegramHookParams(ctx))
}

// TelegramHooksEditPost response for editing Telegram webhook
func TelegramHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, telegramHookParams(ctx))
}

func telegramHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewTelegramHookForm)

	return webhookParams{
		Type:        webhook.TELEGRAM,
		URL:         fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage?chat_id=%s", url.PathEscape(form.BotToken), url.QueryEscape(form.ChatID)),
		ContentType: webhook.ContentTypeJSON,
		WebhookForm: form.WebhookForm,
		Meta: &webhook_service.TelegramMeta{
			BotToken: form.BotToken,
			ChatID:   form.ChatID,
		},
	}
}

// MatrixHooksNewPost response for creating Matrix webhook
func MatrixHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, matrixHookParams(ctx))
}

// MatrixHooksEditPost response for editing Matrix webhook
func MatrixHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, matrixHookParams(ctx))
}

func matrixHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewMatrixHookForm)

	return webhookParams{
		Type:        webhook.MATRIX,
		URL:         fmt.Sprintf("%s/_matrix/client/r0/rooms/%s/send/m.room.message", form.HomeserverURL, url.PathEscape(form.RoomID)),
		ContentType: webhook.ContentTypeJSON,
		HTTPMethod:  http.MethodPut,
		WebhookForm: form.WebhookForm,
		Meta: &webhook_service.MatrixMeta{
			HomeserverURL: form.HomeserverURL,
			Room:          form.RoomID,
			MessageType:   form.MessageType,
		},
	}
}

// MSTeamsHooksNewPost response for creating MSTeams webhook
func MSTeamsHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, mSTeamsHookParams(ctx))
}

// MSTeamsHooksEditPost response for editing MSTeams webhook
func MSTeamsHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, mSTeamsHookParams(ctx))
}

func mSTeamsHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewMSTeamsHookForm)

	return webhookParams{
		Type:        webhook.MSTEAMS,
		URL:         form.PayloadURL,
		ContentType: webhook.ContentTypeJSON,
		WebhookForm: form.WebhookForm,
	}
}

// SlackHooksNewPost response for creating Slack webhook
func SlackHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, slackHookParams(ctx))
}

// SlackHooksEditPost response for editing Slack webhook
func SlackHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, slackHookParams(ctx))
}

func slackHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewSlackHookForm)

	return webhookParams{
		Type:        webhook.SLACK,
		URL:         form.PayloadURL,
		ContentType: webhook.ContentTypeJSON,
		WebhookForm: form.WebhookForm,
		Meta: &webhook_service.SlackMeta{
			Channel:  strings.TrimSpace(form.Channel),
			Username: form.Username,
			IconURL:  form.IconURL,
			Color:    form.Color,
		},
	}
}

// FeishuHooksNewPost response for creating Feishu webhook
func FeishuHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, feishuHookParams(ctx))
}

// FeishuHooksEditPost response for editing Feishu webhook
func FeishuHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, feishuHookParams(ctx))
}

func feishuHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewFeishuHookForm)

	return webhookParams{
		Type:        webhook.FEISHU,
		URL:         form.PayloadURL,
		ContentType: webhook.ContentTypeJSON,
		WebhookForm: form.WebhookForm,
	}
}

// WechatworkHooksNewPost response for creating Wechatwork webhook
func WechatworkHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, wechatworkHookParams(ctx))
}

// WechatworkHooksEditPost response for editing Wechatwork webhook
func WechatworkHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, wechatworkHookParams(ctx))
}

func wechatworkHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewWechatWorkHookForm)

	return webhookParams{
		Type:        webhook.WECHATWORK,
		URL:         form.PayloadURL,
		ContentType: webhook.ContentTypeJSON,
		WebhookForm: form.WebhookForm,
	}
}

// PackagistHooksNewPost response for creating Packagist webhook
func PackagistHooksNewPost(ctx *context.Context) {
	createWebhook(ctx, packagistHookParams(ctx))
}

// PackagistHooksEditPost response for editing Packagist webhook
func PackagistHooksEditPost(ctx *context.Context) {
	editWebhook(ctx, packagistHookParams(ctx))
}

func packagistHookParams(ctx *context.Context) webhookParams {
	form := web.GetForm(ctx).(*forms.NewPackagistHookForm)

	return webhookParams{
		Type:        webhook.PACKAGIST,
		URL:         fmt.Sprintf("https://packagist.org/api/update-package?username=%s&apiToken=%s", url.QueryEscape(form.Username), url.QueryEscape(form.APIToken)),
		ContentType: webhook.ContentTypeJSON,
		WebhookForm: form.WebhookForm,
		Meta: &webhook_service.PackagistMeta{
			Username:   form.Username,
			APIToken:   form.APIToken,
			PackageURL: form.PackageURL,
		},
	}
}

func checkWebhook(ctx *context.Context) (*orgRepoCtx, *webhook.Webhook) {
	orCtx, err := getOrgRepoCtx(ctx)
	if err != nil {
		ctx.ServerError("getOrgRepoCtx", err)
		return nil, nil
	}
	ctx.Data["BaseLink"] = orCtx.Link

	var w *webhook.Webhook
	if orCtx.RepoID > 0 {
		w, err = webhook.GetWebhookByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
	} else if orCtx.OrgID > 0 {
		w, err = webhook.GetWebhookByOrgID(ctx.Org.Organization.ID, ctx.ParamsInt64(":id"))
	} else if orCtx.IsAdmin {
		w, err = webhook.GetSystemOrDefaultWebhook(ctx.ParamsInt64(":id"))
	}
	if err != nil || w == nil {
		if webhook.IsErrWebhookNotExist(err) {
			ctx.NotFound("GetWebhookByID", nil)
		} else {
			ctx.ServerError("GetWebhookByID", err)
		}
		return nil, nil
	}

	ctx.Data["HookType"] = w.Type
	switch w.Type {
	case webhook.SLACK:
		ctx.Data["SlackHook"] = webhook_service.GetSlackHook(w)
	case webhook.DISCORD:
		ctx.Data["DiscordHook"] = webhook_service.GetDiscordHook(w)
	case webhook.TELEGRAM:
		ctx.Data["TelegramHook"] = webhook_service.GetTelegramHook(w)
	case webhook.MATRIX:
		ctx.Data["MatrixHook"] = webhook_service.GetMatrixHook(w)
	case webhook.PACKAGIST:
		ctx.Data["PackagistHook"] = webhook_service.GetPackagistHook(w)
	}

	ctx.Data["History"], err = w.History(1)
	if err != nil {
		ctx.ServerError("History", err)
	}
	return orCtx, w
}

// WebHooksEdit render editing web hook page
func WebHooksEdit(ctx *context.Context) {
	ctx.Data["Title"] = ctx.Tr("repo.settings.update_webhook")
	ctx.Data["PageIsSettingsHooks"] = true
	ctx.Data["PageIsSettingsHooksEdit"] = true

	orCtx, w := checkWebhook(ctx)
	if ctx.Written() {
		return
	}
	ctx.Data["Webhook"] = w

	ctx.HTML(http.StatusOK, orCtx.NewTemplate)
}

// TestWebhook test if web hook is work fine
func TestWebhook(ctx *context.Context) {
	hookID := ctx.ParamsInt64(":id")
	w, err := webhook.GetWebhookByRepoID(ctx.Repo.Repository.ID, hookID)
	if err != nil {
		ctx.Flash.Error("GetWebhookByRepoID: " + err.Error())
		ctx.Status(http.StatusInternalServerError)
		return
	}

	// Grab latest commit or fake one if it's empty repository.
	commit := ctx.Repo.Commit
	if commit == nil {
		ghost := user_model.NewGhostUser()
		commit = &git.Commit{
			ID:            git.MustIDFromString(git.EmptySHA),
			Author:        ghost.NewGitSig(),
			Committer:     ghost.NewGitSig(),
			CommitMessage: "This is a fake commit",
		}
	}

	apiUser := convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone)

	apiCommit := &api.PayloadCommit{
		ID:      commit.ID.String(),
		Message: commit.Message(),
		URL:     ctx.Repo.Repository.HTMLURL() + "/commit/" + url.PathEscape(commit.ID.String()),
		Author: &api.PayloadUser{
			Name:  commit.Author.Name,
			Email: commit.Author.Email,
		},
		Committer: &api.PayloadUser{
			Name:  commit.Committer.Name,
			Email: commit.Committer.Email,
		},
	}

	commitID := commit.ID.String()
	p := &api.PushPayload{
		Ref:          git.BranchPrefix + ctx.Repo.Repository.DefaultBranch,
		Before:       commitID,
		After:        commitID,
		CompareURL:   setting.AppURL + ctx.Repo.Repository.ComposeCompareURL(commitID, commitID),
		Commits:      []*api.PayloadCommit{apiCommit},
		TotalCommits: 1,
		HeadCommit:   apiCommit,
		Repo:         convert.ToRepo(ctx.Repo.Repository, perm.AccessModeNone),
		Pusher:       apiUser,
		Sender:       apiUser,
	}
	if err := webhook_service.PrepareWebhook(ctx, w, webhook.HookEventPush, p); err != nil {
		ctx.Flash.Error("PrepareWebhook: " + err.Error())
		ctx.Status(http.StatusInternalServerError)
	} else {
		ctx.Flash.Info(ctx.Tr("repo.settings.webhook.delivery.success"))
		ctx.Status(http.StatusOK)
	}
}

// ReplayWebhook replays a webhook
func ReplayWebhook(ctx *context.Context) {
	hookTaskUUID := ctx.Params(":uuid")

	orCtx, w := checkWebhook(ctx)
	if ctx.Written() {
		return
	}

	if err := webhook_service.ReplayHookTask(ctx, w, hookTaskUUID); err != nil {
		if webhook.IsErrHookTaskNotExist(err) {
			ctx.NotFound("ReplayHookTask", nil)
		} else {
			ctx.ServerError("ReplayHookTask", err)
		}
		return
	}

	ctx.Flash.Success(ctx.Tr("repo.settings.webhook.delivery.success"))
	ctx.Redirect(fmt.Sprintf("%s/%d", orCtx.Link, w.ID))
}

// DeleteWebhook delete a webhook
func DeleteWebhook(ctx *context.Context) {
	if err := webhook.DeleteWebhookByRepoID(ctx.Repo.Repository.ID, ctx.FormInt64("id")); err != nil {
		ctx.Flash.Error("DeleteWebhookByRepoID: " + err.Error())
	} else {
		ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
	}

	ctx.JSON(http.StatusOK, map[string]interface{}{
		"redirect": ctx.Repo.RepoLink + "/settings/hooks",
	})
}


text:
package com.twitter.scalding.typed

import java.io.Serializable

import com.twitter.algebird.Semigroup
import com.twitter.scalding.TupleConverter.tuple2Converter
import com.twitter.scalding.TupleSetter.tup2Setter

import com.twitter.scalding._

import cascading.flow.FlowDef
import cascading.pipe.Pipe
import cascading.tuple.Fields

import Dsl._

/**
 * This encodes the rules that
 * 1) sorting is only possible before doing any reduce,
 * 2) reversing is only possible after sorting.
 * 3) unsorted Groups can be CoGrouped or HashJoined
 *
 * This may appear a complex type, but it makes
 * sure that code won't compile if it breaks the rule
 */
trait Grouped[K, +V]
  extends KeyedListLike[K, V, UnsortedGrouped]
  with HashJoinable[K, V]
  with Sortable[V, ({ type t[+x] = SortedGrouped[K, x] with Reversable[SortedGrouped[K, x]] })#t]
  with WithReducers[Grouped[K, V]]

/**
 * After sorting, we are no longer CoGroupable, and we can only call reverse
 * in the initial SortedGrouped created from the Sortable:
 * .sortBy(_._2).reverse
 * for instance
 *
 * Once we have sorted, we cannot do a HashJoin or a CoGrouping
 */
trait SortedGrouped[K, +V]
  extends KeyedListLike[K, V, SortedGrouped]
  with WithReducers[SortedGrouped[K, V]]

/**
 * This is the state after we have done some reducing. It is
 * not possible to sort at this phase, but it is possible to
 * do a CoGrouping or a HashJoin.
 */
trait UnsortedGrouped[K, +V]
  extends KeyedListLike[K, V, UnsortedGrouped]
  with HashJoinable[K, V]
  with WithReducers[UnsortedGrouped[K, V]]

object Grouped {
  val ValuePosition: Int = 1 // The values are kept in this position in a Tuple
  val valueField: Fields = new Fields("value")
  val kvFields: Fields = new Fields("key", "value")

  def apply[K, V](pipe: TypedPipe[(K, V)])(implicit ordering: Ordering[K]): Grouped[K, V] =
    IdentityReduce(ordering, pipe, None)

  def keySorting[T](ord: Ordering[T]): Fields = sorting("key", ord)
  def valueSorting[T](implicit ord: Ordering[T]): Fields = sorting("value", ord)

  def sorting[T](key: String, ord: Ordering[T]): Fields = {
    val f = new Fields(key)
    f.setComparator(key, ord)
    f
  }
}

/**
 * All sorting methods defined here trigger Hadoop secondary sort on key + value.
 * Hadoop secondary sort is external sorting. i.e. it won't materialize all values
 * of each key in memory on the reducer.
 */
trait Sortable[+T, +Sorted[+_]] {
  def withSortOrdering[U >: T](so: Ordering[U]): Sorted[T]

  def sortBy[B: Ordering](fn: (T) => B): Sorted[T] =
    withSortOrdering(Ordering.by(fn))

  // Sorts the values for each key
  def sorted[B >: T](implicit ord: Ordering[B]): Sorted[T] =
    withSortOrdering(ord)

  def sortWith(lt: (T, T) => Boolean): Sorted[T] =
    withSortOrdering(Ordering.fromLessThan(lt))
}

// Represents something that when we call reverse changes type to R
trait Reversable[+R] {
  def reverse: R
}

/**
 * This is a class that models the logical portion of the reduce step.
 * details like where this occurs, the number of reducers, etc... are
 * left in the Grouped class
 */
sealed trait ReduceStep[K, V1] extends KeyedPipe[K] {
  /**
   * Note, this satisfies KeyedPipe.mapped: TypedPipe[(K, Any)]
   */
  def mapped: TypedPipe[(K, V1)]
  // make the pipe and group it, only here because it is common
  protected def groupOp[V2](gb: GroupBuilder => GroupBuilder): TypedPipe[(K, V2)] = {
    TypedPipeFactory({ (fd, mode) =>
      val reducedPipe = mapped
        .toPipe(Grouped.kvFields)(fd, mode, tup2Setter)
        .groupBy(Grouped.keySorting(keyOrdering))(gb)
      TypedPipe.from(reducedPipe, Grouped.kvFields)(fd, mode, tuple2Converter[K, V2])
    })
  }
}

case class IdentityReduce[K, V1](
  override val keyOrdering: Ordering[K],
  override val mapped: TypedPipe[(K, V1)],
  override val reducers: Option[Int])
  extends ReduceStep[K, V1]
  with Grouped[K, V1] {

  override def withSortOrdering[U >: V1](so: Ordering[U]): IdentityValueSortedReduce[K, V1] =
    IdentityValueSortedReduce[K, V1](keyOrdering, mapped, so, reducers)

  override def withReducers(red: Int): IdentityReduce[K, V1] =
    copy(reducers = Some(red))

  override def filterKeys(fn: K => Boolean) =
    UnsortedIdentityReduce(keyOrdering, mapped.filterKeys(fn), reducers)

  override def mapGroup[V3](fn: (K, Iterator[V1]) => Iterator[V3]) =
    IteratorMappedReduce(keyOrdering, mapped, fn, reducers)

  // It would be nice to return IdentityReduce here, but
  // the type constraints prevent it currently
  override def mapValues[V2](fn: V1 => V2) =
    UnsortedIdentityReduce(keyOrdering, mapped.mapValues(fn), reducers)

  // This is not correct in the type-system, but would be nice to encode
  //override def mapValues[V3](fn: V1 => V3) = IdentityReduce(keyOrdering, mapped.mapValues(fn), reducers)

  override def sum[U >: V1](implicit sg: Semigroup[U]) = {
    // there is no sort, mapValueStream or force to reducers:
    val upipe: TypedPipe[(K, U)] = mapped // use covariance to set the type
    UnsortedIdentityReduce(keyOrdering, upipe.sumByLocalKeys, reducers).sumLeft
  }

  override lazy val toTypedPipe = reducers match {
    case None => mapped // free case
    case Some(reds) =>
      // This is wierd, but it is sometimes used to force a partition
      groupOp { _.reducers(reds) }
  }

  /** This is just an identity that casts the result to V1 */
  override def joinFunction = CoGroupable.castingJoinFunction[V1]
}

case class UnsortedIdentityReduce[K, V1](
  override val keyOrdering: Ordering[K],
  override val mapped: TypedPipe[(K, V1)],
  override val reducers: Option[Int])
  extends ReduceStep[K, V1]
  with UnsortedGrouped[K, V1] {

  override def withReducers(red: Int): UnsortedIdentityReduce[K, V1] =
    copy(reducers = Some(red))

  override def filterKeys(fn: K => Boolean) =
    UnsortedIdentityReduce(keyOrdering, mapped.filterKeys(fn), reducers)

  override def mapGroup[V3](fn: (K, Iterator[V1]) => Iterator[V3]) =
    IteratorMappedReduce(keyOrdering, mapped, fn, reducers)

  // It would be nice to return IdentityReduce here, but
  // the type constraints prevent it currently
  override def mapValues[V2](fn: V1 => V2) =
    UnsortedIdentityReduce(keyOrdering, mapped.mapValues(fn), reducers)

  override def sum[U >: V1](implicit sg: Semigroup[U]) = {
    // there is no sort, mapValueStream or force to reducers:
    val upipe: TypedPipe[(K, U)] = mapped // use covariance to set the type
    UnsortedIdentityReduce(keyOrdering, upipe.sumByLocalKeys, reducers).sumLeft
  }

  override lazy val toTypedPipe = reducers match {
    case None => mapped // free case
    case Some(reds) =>
      // This is wierd, but it is sometimes used to force a partition
      groupOp { _.reducers(reds) }
  }

  /** This is just an identity that casts the result to V1 */
  override def joinFunction = CoGroupable.castingJoinFunction[V1]
}

case class IdentityValueSortedReduce[K, V1](
  override val keyOrdering: Ordering[K],
  override val mapped: TypedPipe[(K, V1)],
  valueSort: Ordering[_ >: V1],
  override val reducers: Option[Int]) extends ReduceStep[K, V1]
  with SortedGrouped[K, V1]
  with Reversable[IdentityValueSortedReduce[K, V1]] {

  override def reverse: IdentityValueSortedReduce[K, V1] =
    IdentityValueSortedReduce[K, V1](keyOrdering, mapped, valueSort.reverse, reducers)

  override def withReducers(red: Int): IdentityValueSortedReduce[K, V1] =
    // copy fails to get the types right, :/
    IdentityValueSortedReduce[K, V1](keyOrdering, mapped, valueSort, reducers = Some(red))

  override def filterKeys(fn: K => Boolean) =
    // copy fails to get the types right, :/
    IdentityValueSortedReduce[K, V1](keyOrdering, mapped.filterKeys(fn), valueSort, reducers)

  override def mapGroup[V3](fn: (K, Iterator[V1]) => Iterator[V3]) =
    ValueSortedReduce[K, V1, V3](keyOrdering, mapped, valueSort, fn, reducers)

  override lazy val toTypedPipe =
    groupOp {
      _.sortBy(Grouped.valueSorting(valueSort))
        .reducers(reducers.getOrElse(-1))
    }
}

case class ValueSortedReduce[K, V1, V2](
  override val keyOrdering: Ordering[K],
  override val mapped: TypedPipe[(K, V1)],
  valueSort: Ordering[_ >: V1],
  reduceFn: (K, Iterator[V1]) => Iterator[V2],
  override val reducers: Option[Int])
  extends ReduceStep[K, V1] with SortedGrouped[K, V2] {

  override def withReducers(red: Int) =
    // copy infers loose types. :(
    ValueSortedReduce[K, V1, V2](
      keyOrdering, mapped, valueSort, reduceFn, Some(red))

  override def filterKeys(fn: K => Boolean) =
    // copy fails to get the types right, :/
    ValueSortedReduce[K, V1, V2](keyOrdering, mapped.filterKeys(fn), valueSort, reduceFn, reducers)

  override def mapGroup[V3](fn: (K, Iterator[V2]) => Iterator[V3]) = {
    // don't make a closure
    val localRed = reduceFn
    val newReduce = { (k: K, iter: Iterator[V1]) => fn(k, localRed(k, iter)) }
    ValueSortedReduce[K, V1, V3](
      keyOrdering, mapped, valueSort, newReduce, reducers)
  }

  override lazy val toTypedPipe = {
    val vSort = Grouped.valueSorting(valueSort)

    groupOp {
      _.sortBy(vSort)
        .every(new cascading.pipe.Every(_, Grouped.valueField,
          new TypedBufferOp(reduceFn, Grouped.valueField), Fields.REPLACE))
        .reducers(reducers.getOrElse(-1))
    }
  }
}

case class IteratorMappedReduce[K, V1, V2](
  override val keyOrdering: Ordering[K],
  override val mapped: TypedPipe[(K, V1)],
  reduceFn: (K, Iterator[V1]) => Iterator[V2],
  override val reducers: Option[Int])
  extends ReduceStep[K, V1] with UnsortedGrouped[K, V2] {

  override def withReducers(red: Int): IteratorMappedReduce[K, V1, V2] =
    copy(reducers = Some(red))

  override def filterKeys(fn: K => Boolean) =
    copy(mapped = mapped.filterKeys(fn))

  override def mapGroup[V3](fn: (K, Iterator[V2]) => Iterator[V3]) = {
    // don't make a closure
    val localRed = reduceFn
    val newReduce = { (k: K, iter: Iterator[V1]) => fn(k, localRed(k, iter)) }
    copy(reduceFn = newReduce)
  }

  override lazy val toTypedPipe =
    groupOp {
      _.every(new cascading.pipe.Every(_, Grouped.valueField,
        new TypedBufferOp(reduceFn, Grouped.valueField), Fields.REPLACE))
        .reducers(reducers.getOrElse(-1))
    }

  override def joinFunction = {
    // don't make a closure
    val localRed = reduceFn;
    { (k, iter, empties) =>
      assert(empties.isEmpty, "this join function should never be called with non-empty right-most")
      localRed(k, iter.map(_.getObject(Grouped.ValuePosition).asInstanceOf[V1]))
    }
  }
}


text:
<?php

namespace Drupal\contextual;

use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * Returns responses for Contextual module routes.
 */
class ContextualController implements ContainerAwareInterface {

  use ContainerAwareTrait;

  /**
   * Returns the requested rendered contextual links.
   *
   * Given a list of contextual links IDs, render them. Hence this must be
   * robust to handle arbitrary input.
   *
   * @see contextual_preprocess()
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The JSON response.
   */
  public function render(Request $request) {
    $ids = $request->request->get('ids');
    if (!isset($ids)) {
      throw new BadRequestHttpException(t('No contextual ids specified.'));
    }

    $rendered = [];
    foreach ($ids as $id) {
      $element = [
        '#type' => 'contextual_links',
        '#contextual_links' => _contextual_id_to_links($id),
      ];
      $rendered[$id] = $this->container->get('renderer')->renderRoot($element);
    }

    return new JsonResponse($rendered);
  }

}


text:
package com.microsoft.applicationinsights.agent.internal.agent;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.instrument.Instrumentation;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.jar.JarFile;

import com.microsoft.applicationinsights.agent.internal.logger.InternalAgentLogger;

/**
 * Created by gupele on 5/6/2015.
 */
public final class AgentImplementation {

    private final static String AGENT_JAR_PREFIX = "applicationinsights-agent";

    private static String agentJarLocation;

    public static void premain(String args, Instrumentation inst) {

        try {
            agentJarLocation = getAgentJarLocation();
            appendJarsToBootstrapClassLoader(inst);
            loadJarsToBootstrapClassLoader(inst);
        } catch (Throwable throwable) {
            InternalAgentLogger.INSTANCE.error("Agent is NOT activated: failed to load to bootstrap class loader: " + throwable.getMessage());
            System.exit(-1);
        }
    }

    @SuppressWarnings("unchecked")
    private static void loadJarsToBootstrapClassLoader(Instrumentation inst) throws Throwable {
        ClassLoader bcl = AgentImplementation.class.getClassLoader().getParent();
        Class<CodeInjector> cic = (Class<CodeInjector>) bcl.loadClass("com.microsoft.applicationinsights.agent.internal.agent.CodeInjector");
        if (cic == null) {
            throw new IllegalStateException("Failed to load CodeInjector");
        }

        cic.getDeclaredConstructor(Instrumentation.class, String.class).newInstance(inst, agentJarLocation);
    }

    private static void appendJarsToBootstrapClassLoader(Instrumentation inst) throws Throwable {
        String agentJarPath = agentJarLocation.startsWith("file:/") ? agentJarLocation : "file:/" + agentJarLocation;

        String agentJarName = null;
        File agentFolder = new File(agentJarLocation);
        for (File file : agentFolder.listFiles()) {
            if (file.getName().indexOf(AGENT_JAR_PREFIX) != -1) {
                agentJarName = file.getName();
                break;
            }
        }

        if (agentJarName == null) {
            throw new RuntimeException("Could not find agent jar");
        }

        InternalAgentLogger.INSTANCE.info("Found jar: " + agentJarPath + " " + agentJarName);

        URL configurationURL = new URL(agentJarPath + agentJarName);

        JarFile agentJar = new JarFile(URLDecoder.decode(configurationURL.getFile(), "UTF-8"));

        inst.appendToBootstrapClassLoaderSearch(agentJar);

        InternalAgentLogger.INSTANCE.trace("Successfully loaded Agent jar");
    }

    public static String getAgentJarLocation() throws UnsupportedEncodingException {
        try {
            ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
            if ((systemClassLoader instanceof URLClassLoader)) {
                for (URL url : ((URLClassLoader)systemClassLoader).getURLs()) {
                    String urlPath = url.getPath();
                    if (urlPath.indexOf(AGENT_JAR_PREFIX) != -1) {
                        int index = urlPath.lastIndexOf('/');
                        urlPath = urlPath.substring(0, index + 1);
                        return urlPath;
                    }
                }
            }
        } catch (Throwable throwable) {
            InternalAgentLogger.INSTANCE.error("Error while trying to fetch Jar Location, Exception: " + throwable.getMessage());
        }

        String path = AgentImplementation.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        return URLDecoder.decode(path, "UTF-8");
    }
}


text:
package org.apereo.portal;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apereo.portal.i18n.LocaleManager;
import org.apereo.portal.security.IPerson;
import org.apereo.portal.user.IUserInstance;

/**
 * A class handling holding all user state information. The class is also responsible for
 * request processing and orchestrating the entire rendering procedure.
 * (this is a replacement for the good old LayoutBean class)
 * @author Peter Kharchenko  {@link pkharchenko@interactivebusiness.com"}
 * @version $Revision$
 */
public class UserInstance implements IUserInstance {
    protected final Log log = LogFactory.getLog(this.getClass());

    // manages layout and preferences
    private final IUserPreferencesManager preferencesManager;
    // manages locale
    private final LocaleManager localeManager;

    private final IPerson person;

    public UserInstance(IPerson person, IUserPreferencesManager preferencesManager, LocaleManager localeManager) {
        this.person = person;
        this.preferencesManager = preferencesManager;
        this.localeManager = localeManager;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.IUserInstance#getPerson()
     */
    @Override
    public IPerson getPerson() {
        return this.person;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.IUserInstance#getPreferencesManager()
     */
    @Override
    public IUserPreferencesManager getPreferencesManager() {
        return this.preferencesManager;
    }

    /* (non-Javadoc)
     * @see org.apereo.portal.IUserInstance#getLocaleManager()
     */
    @Override
    public LocaleManager getLocaleManager() {
        return this.localeManager;
    }
}


text:
//=================================================================================================

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

#ifndef _BLAZEMARK_MTL_INIT_DENSEVECTOR_H_
#define _BLAZEMARK_MTL_INIT_DENSEVECTOR_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <boost/numeric/mtl/vector/dense_vector.hpp>
#include <blaze/util/Random.h>
#include <blazemark/system/Types.h>

namespace blazemark {

namespace mtl {

//=================================================================================================
//
//  KERNEL FUNCTIONS
//
//=================================================================================================

//*************************************************************************************************
/*!\name MTL initialization functions */
//@{
template< typename Type >
void init( ::mtl::dense_vector<Type>& v );
//@}
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Random initialization of the given dense vector.
//
// \param v The dense vector to be initialized.
// \return void
//
// This function initializes the given dense vector with random values.
*/
template< typename Type >  // Data type of the vector
void init( ::mtl::dense_vector<Type>& v )
{
   const size_t N( size( v ) );

   for( size_t i=0UL; i<N; ++i ) {
      v[i] = ::blaze::rand<Type>( 0, 10 );
   }
}
//*************************************************************************************************

} // namespace mtl

} // namespace blazemark

#endif