text:
package gov.nih.nci.evs.reportwriter.servlet;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.log4j.*;
import org.apache.poi.hssf.usermodel.*;

import gov.nih.nci.evs.reportwriter.utils.*;
import gov.nih.nci.evs.reportwriter.bean.*;
import gov.nih.nci.evs.reportwriter.properties.*;

/**
 *
 */

/**
 * @author EVS Team (Kim Ong, David Yee)
 * @version 1.0
 */

public final class FileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private final Logger _logger = Logger.getLogger(FileServlet.class);

    /**
     * Route the user to the execute method
     *
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet exception occurs
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        execute(request, response);
    }

    /**
     * Route the user to the execute method
     *
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet exception occurs
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        execute(request, response);
    }

    /**
     * Process the specified HTTP request, and create the corresponding HTTP
     * response (or forward to another web component that will create it).
     *
     * @param request The HTTP request we are processing
     * @param response The HTTP response we are creating
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet exception occurs
     */

    public void sendErrorResponse(HttpServletRequest request,
            HttpServletResponse response, String message) throws IOException,
            ServletException {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setAttribute("message", message);

            String nextJSP = "/pages/message.jsf";
            RequestDispatcher dispatcher =
                getServletContext().getRequestDispatcher(nextJSP);
            dispatcher.forward(request, response);
        }
    }

    public void sendResponse(HttpServletRequest request, HttpServletResponse response, String fullPathName, String format)
            throws IOException, ServletException {
        response.setContentType("text/html");
        // String line_br = "\n";
        String line_br = "\r\n";

        response.setHeader("Cache-Control", "no-cache");

        if (format.indexOf("Excel") != -1) {
            String contentType = "application/vnd.ms-excel";
            response.setContentType(contentType);
            line_br = "";
        }

        File file = new File(fullPathName);
        String filename = file.getName();
System.out.println("sendResponse fullPathName: " + fullPathName);
System.out.println("sendResponse format: " + format);
System.out.println("sendResponse filename: " + filename);

        // HKR, GForge# 19467 - wrong placement of '\' in header.
        response.addHeader("Content-Disposition", "attachment;filename=\""
                + filename + "\"");

        _logger.debug("Full path name =" + fullPathName);
        _logger.debug("File name =" + filename);

        if (format.indexOf("Excel") == -1) {
            try {
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                BufferedReader br = new BufferedReader(new InputStreamReader(bis));

                String s = "";
                while (true) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    s = s + line + line_br;
                }
                PrintWriter out = response.getWriter();
                out.write(s);
                out.flush();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (format.indexOf("Excel") != -1) {
            try {
                InputStream myxls = new FileInputStream(fullPathName);
                HSSFWorkbook wb = new HSSFWorkbook(myxls);
                try {
                    wb.write(response.getOutputStream());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            } catch (Exception e) {
                // LogUtils.log(logger, Level.ERROR, e);
                e.printStackTrace();
            }
        }
    }

    public void sendResponse(HttpServletRequest request, HttpServletResponse response,
            StandardReport standardReport) throws IOException, ServletException {
        // processing download
        String fullPathName = standardReport.getPathName();
        ReportFormat rf = standardReport.getFormat();
        String format = rf.getDescription();
        sendResponse(request, response, fullPathName, format);
    }

    public void sendResponse(HttpServletRequest request, HttpServletResponse response,
                             int formatId,
	                         int templateId) throws IOException, ServletException {
		String hibernate_cfg_xml = request.getSession().getServletContext().getRealPath(JDBCUtil.HIBERNATE_CFG_PATH);//"/WEB-INF/classes/hibernate.cfg.xml");

		File f = new File(hibernate_cfg_xml);
		if (f.exists()) {
			JDBCUtil util = new JDBCUtil(hibernate_cfg_xml);
			Vector report_metadata_vec = util.getReportData();

			for (int i=0; i<report_metadata_vec.size(); i++) {
				ReportMetadata rmd = (ReportMetadata) report_metadata_vec.elementAt(i);
				int template_Id = rmd.getTemplateId();
				int format_Id = rmd.getFormatId();
				if (format_Id == formatId && template_Id == templateId) {
					String fullPathName = rmd.getPathName();
					if (fullPathName == null || fullPathName.compareTo("") == 0) {
						String templateLabel = rmd.getTemplateLabel();
						String version = rmd.getVersion();
						String download_dir = AppProperties.getInstance().getProperty(AppProperties.REPORT_DOWNLOAD_DIRECTORY);
						fullPathName = download_dir + File.separator + templateLabel + "__" + version + "."
						   + DataUtils.getFileExtension(rmd.getFormatId()) ;
						fullPathName = fullPathName.replaceAll(" ", "_");
					}
					String format = rmd.getFormat();
					sendResponse(request, response, fullPathName, format);
					return;
				}
			}
		} else {
			String message = "Report not found (format id: " + formatId + " templateId: " + templateId + ")";
			sendErrorResponse(request, response, message);
		}
	}

    public void execute(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        // <a
        // href="<%=request.getContextPath() %>/fileServlet?template=<%=templateId%>&format=<%=formatId%>"
        // ><%=template%> (<%=formatDescription%>)

        // Get ReportFormat from database
        Vector report_metadata_vec = null;
        String action = request.getParameter("action");
        if (action != null && action.compareTo("download") == 0) {
		    String hibernate_cfg_xml = request.getSession().getServletContext().getRealPath(JDBCUtil.HIBERNATE_CFG_PATH);//"/WEB-INF/classes/hibernate.cfg.xml");
			//C:\Tomcat 7.0.54\webapps\ncireportwriter\WEB-INF\classes\hibernate.cfg.xml
			//hibernate_cfg_xml = hibernate_cfg_xml.replaceAll("\"", "/");

            _logger.debug("FileServlet executing download...");

			File f = new File(hibernate_cfg_xml);
			if (f.exists()) {
				_logger.debug("Configuration file exists " + hibernate_cfg_xml);

				JDBCUtil util = new JDBCUtil(hibernate_cfg_xml);
				report_metadata_vec = util.getReportData();
				if (report_metadata_vec != null) {
					request.getSession().setAttribute("report_metadata_vec", report_metadata_vec);
				}
			} else {
				_logger.debug("WARNING: Unable to access the configuration file - " + hibernate_cfg_xml);
			}

			try {
				String nextJSP = "/pages/main/download_nologin.jsf";
				RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
				dispatcher.forward(request,response);

			} catch (Exception ex) {
				String message = "ERROR JDBCUtil - Unable to retrieve report data.";
				sendErrorResponse(request, response, message);
				ex.printStackTrace();
			}

			return;
		}

        String formatId = request.getParameter("format");
        String templateId = request.getParameter("template");

System.out.println("FileServlet formatId: " +  formatId);
System.out.println("FileServlet templateId: " +  templateId);

        sendResponse(request, response, Integer.parseInt(formatId), Integer.parseInt(templateId));

/*

        StandardReportTemplate standardReportTemplate = null;
        String message = "Format ID " + formatId + " not found.";
        try {
            String FQName = "gov.nih.nci.evs.reportwriter.bean.ReportFormat";
            String methodName = "setId";
            int format_id = Integer.parseInt(formatId);
            SDKClientUtil sdkclientutil = new SDKClientUtil();
            Object reportFormat_obj =
                sdkclientutil.search(FQName, methodName, format_id);
            if (reportFormat_obj == null) {

System.out.println("FileServlet unable to find ReportFormat with Id: " +  formatId);

                sendErrorResponse(request, response, message);
                return;
            }
            // Get StandardReportTemplate from database
            message = "Template ID " + templateId + " not found.";
            try {
                // Get all
                // gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate
                // Find ov.nih.nci.evs.reportwriter.bean.StandardReport with
                // matched template and format
                // Find the fullpath of the StandardReport
                // Check ReportStatus (send not available or pending approval
                // message as needed)

                FQName =
                    "gov.nih.nci.evs.reportwriter.bean.StandardReportTemplate";
                methodName = "setId";
                int template_id = Integer.parseInt(templateId);
                Object standardReportTemplate_obj =
                    sdkclientutil.search(FQName, methodName, template_id);
                if (standardReportTemplate_obj == null) {

System.out.println("FileServlet unable to find StandardReportTemplate with Id: " +  templateId);

                    sendErrorResponse(request, response, message);
                }

                standardReportTemplate =
                    (StandardReportTemplate) standardReportTemplate_obj;

                // Search for the matched StandardReport in the database (by
                // template and format)
                FQName = "gov.nih.nci.evs.reportwriter.bean.StandardReport";
                message = "The selected report is not available for download.";

                Object[] objs = sdkclientutil.search(FQName);

                if (objs == null || objs.length == 0) {

System.out.println("FileServlet unable to search for StandardReport");

                    sendErrorResponse(request, response, message);
                } else {
                    for (int i = 0; i < objs.length; i++) {
                        StandardReport standardReport =
                            (StandardReport) objs[i];

 System.out.println("FileServlet StandardReport " + i);

                        StandardReportTemplate srt =
                            standardReport.getTemplate();

  System.out.println("FileServlet StandardReportTemplate " + srt.getLabel());

                        int i1 = srt.getId().intValue();
                        int i2 = standardReportTemplate.getId().intValue();

                        if (i1 == i2) {
                            ReportFormat rf = standardReport.getFormat();
                            if (rf != null && rf.getId() == format_id) {
                                HttpSession session = request.getSession(false);
                                Boolean isAdmin =
                                    (Boolean) session.getAttribute("isAdmin");
                                if (isAdmin != null
                                        && isAdmin.equals(Boolean.TRUE)) {
                                    sendResponse(response, standardReport);
                                } else {
                                    // Check if the report has been approved:
                                    ReportStatus rs =
                                        standardReport.getStatus();
                                    if (rs != null) {
                                        String approved = "APPROVED";
                                        if (approved.equals(rs.getLabel())) {
                                            sendResponse(response,
                                                    standardReport);
                                        } else {
                                            sendErrorResponse(request,
                                                    response,
                                                    "The selected report has not yet been approved.");
                                        }
                                    } else {
                                        sendErrorResponse(request, response,
                                                "The selected report has not yet been approved.");
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                sendErrorResponse(request, response, message);
                ex.printStackTrace();
            }

        } catch (Exception ex) {
            sendErrorResponse(request, response, message);
            ex.printStackTrace();
        }
*/

    }
}


text:
rerun_option_usage() {
    grep '^#/ usage:' <"$0" | cut -c4- >&2
    return 2
}

# print USAGE and exit
rerun_option_error() {
    if [[ "$RERUN_COLOR" == "true" ]]
    then echo -e ${red}"SYNTAX: $*"${_red} >&2
    else echo "SYNTAX: $*" >&2
    fi
    exit 2
}

# check option has its argument
rerun_option_check() {
    [ "$1" -lt 2 ] && rerun_option_error
}

# options: [module name ovewrite template]
while [ "$#" -gt 0 ]; do
    OPT="$1"
    case "$OPT" in
        -m|-module) rerun_option_check $# ; MODULE=$2 ; shift ;;
 -c|-command) rerun_option_check $# ; COMMAND=$2 ; shift ;;
 -overwrite) rerun_option_check $# ; OVERWRITE=$2 ; shift ;;
 -template) rerun_option_check $# ; TEMPLATE=$2 ; shift ;;
        # unknown option
        -?)
            rerun_option_usage
            exit 2
            ;;
        # end of options, just arguments left
        *)
          break
    esac
    shift
done

# If defaultable options variables are unset, set them to their DEFAULT
[ -z "$OVERWRITE" ] && OVERWRITE=false
[ -z "$TEMPLATE" ] && TEMPLATE=$RERUN_MODULE_DIR/templates/script

redpajama_set_name: RedPajamaGithub


text:
package pages

type ClearPage struct {
	BasePage
}

func NewClearPage() Page {
	clearPage := new(ClearPage)
	clearPage.BasePage = NewBasePage()
	clearPage.BasePage.SetBackground(LoadImage("bg.png"))
	return clearPage
}

func (p *ClearPage) Process() bool {
	return true
}


text:
- add support for PHPUnit 6

## 2.0.0 (2017-09-10)
- change `Session` constructor to take `Cookie` instance instead of
  `HeaderInterface` to have a much cleaner implementation and separation of
  `Cookie` and `Session`. See [README.md](README.md) for the updated
  documentation
- Fix issues found by [Psalm](https://getpsalm.org/)

## 1.0.2 (2017-08-08)
- fix possible duplicate `Max-Age` when deleting cookie

## 1.0.1 (2017-08-07)
- `Cookie::delete` will set `Max-Age=0` telling the browser to delete the
  cookie (#1)

## 1.0.0 (2017-06-30)
- initial release


text:
.class final synthetic Lcom/android/server/-$Lambda$3ppOfNoHK7gU64PsFhIJAmO8LxY$10;
.super Ljava/lang/Object;

# interfaces
.implements Ljava/util/function/Consumer;

# instance fields
.field private final synthetic -$f0:I

.field private final synthetic -$f1:Ljava/lang/Object;

# direct methods
.method private final synthetic $m$0(Ljava/lang/Object;)V
    .locals 2

    iget-object v0, p0, Lcom/android/server/-$Lambda$3ppOfNoHK7gU64PsFhIJAmO8LxY$10;->-$f1:Ljava/lang/Object;

    check-cast v0, [B

    iget v1, p0, Lcom/android/server/-$Lambda$3ppOfNoHK7gU64PsFhIJAmO8LxY$10;->-$f0:I

    check-cast p1, Lcom/android/server/SdpManagerService;

    invoke-static {v0, v1, p1}, Lcom/android/server/LockSettingsService;->lambda$-com_android_server_LockSettingsService_107491([BILcom/android/server/SdpManagerService;)V

    return-void
.end method

.method public synthetic constructor <init>(ILjava/lang/Object;)V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput p1, p0, Lcom/android/server/-$Lambda$3ppOfNoHK7gU64PsFhIJAmO8LxY$10;->-$f0:I

    iput-object p2, p0, Lcom/android/server/-$Lambda$3ppOfNoHK7gU64PsFhIJAmO8LxY$10;->-$f1:Ljava/lang/Object;

    return-void
.end method

# virtual methods
.method public final accept(Ljava/lang/Object;)V
    .locals 0

    invoke-direct {p0, p1}, Lcom/android/server/-$Lambda$3ppOfNoHK7gU64PsFhIJAmO8LxY$10;->$m$0(Ljava/lang/Object;)V

    return-void
.end method


text:
// Copyright 2017-present, Institute for Artificial Intelligence - University of Bremen
// Author: Andrei Haidu (http://haidu.eu)

#include "Events/SLPutDownEvent.h"
#include "Individuals/Type/SLBaseIndividual.h"
#include "Owl/SLOwlExperimentStatics.h"

// Constructor with initialization
FSLPutDownEvent::FSLPutDownEvent(const FString& InId, const float InStart, const float InEnd, const uint64 InPairId,
	USLBaseIndividual* InManipulator, USLBaseIndividual* InIndividual) :
	ISLEvent(InId, InStart, InEnd), PairId(InPairId), Manipulator(InManipulator), Individual(InIndividual)
{
}

// Constructor initialization without end time
FSLPutDownEvent::FSLPutDownEvent(const FString& InId, const float InStart, const uint64 InPairId,
	USLBaseIndividual* InIndividual, USLBaseIndividual* InManipulator) :
	ISLEvent(InId, InStart), PairId(InPairId), Manipulator(InManipulator), Individual(InIndividual)
{
}

/* Begin ISLEvent interface */
// Get an owl representation of the event
FSLOwlNode FSLPutDownEvent::ToOwlNode() const
{
	// Create the Lift event node
	FSLOwlNode EventIndividual = FSLOwlExperimentStatics::CreateEventIndividual(
		"log", Id, "PutDownSituation");
	EventIndividual.AddChildNode(FSLOwlExperimentStatics::CreateStartTimeProperty("log", StartTime));
	EventIndividual.AddChildNode(FSLOwlExperimentStatics::CreateEndTimeProperty("log", EndTime));
	EventIndividual.AddChildNode(FSLOwlExperimentStatics::CreatePerformedByProperty("log", Manipulator->GetIdValue()));
	EventIndividual.AddChildNode(FSLOwlExperimentStatics::CreateObjectActedOnProperty("log", Individual->GetIdValue()));
	EventIndividual.AddChildNode(FSLOwlExperimentStatics::CreateInEpisodeProperty("log", EpisodeId));
	return EventIndividual;
}

// Add the owl representation of the event to the owl document
void FSLPutDownEvent::AddToOwlDoc(FSLOwlDoc* OutDoc)
{
	// Add timepoint individuals
	// We know that the document is of type FOwlExperiment,
	// we cannot use the safer dynamic_cast because RTTI is not enabled by default
	// if (FOwlEvents* EventsDoc = dynamic_cast<FOwlEvents*>(OutDoc))
	FSLOwlExperiment* EventsDoc = static_cast<FSLOwlExperiment*>(OutDoc);
	EventsDoc->RegisterTimepoint(StartTime);
	EventsDoc->RegisterTimepoint(EndTime);
	EventsDoc->RegisterObject(Manipulator);
	EventsDoc->RegisterObject(Individual);
	OutDoc->AddIndividual(ToOwlNode());
}

// Get event context data as string (ToString equivalent)
FString FSLPutDownEvent::Context() const
{
	return FString::Printf(TEXT("PutDown - %lld"), PairId);
}

// Get the tooltip data
FString FSLPutDownEvent::Tooltip() const
{
	return FString::Printf(TEXT("\'O1\',\'%s\',\'Id\',\'%s\',\'O2\',\'%s\',\'Id\',\'%s\',\'Id\',\'%s\'"),
		*Individual->GetClassValue(), *Individual->GetIdValue(), *Manipulator->GetClassValue(), *Manipulator->GetIdValue(), *Id);
}

// Get the data as string
FString FSLPutDownEvent::ToString() const
{
	return FString::Printf(TEXT("Individual:[%s] Manipulator:[%s] PairId:%lld"),
		*Individual->GetInfo(), *Manipulator->GetInfo(), PairId);
}
/* End ISLEvent interface */


text:
<?php
Yii::import('RestfullYii.actions.ERestBaseAction');

class EActionRestPUT extends ERestBaseAction
{
	/**
	 * run
	 *
	 * Called by Yii for DELETE verb
	 *
	 * @param (Mixed/Int) (id) unique identifier of the resource
	 * @param (Mixed) (param1) first param sent in the request; Often subresource name
	 * @param (Mixed) (param2) Second param sent in the request: Often subresource ID
	 */
	public function run($id=null, $param1=null, $param2=null)
	{
    switch ($this->getRequestActionType($id, $param1, $param2, 'put')) {
			case 'RESOURCES':
				throw new CHttpException('405', 'Method Not Allowed');
				break;
			case 'CUSTOM':
				$this->controller->emitRest("req.put.$id.render", [$this->controller->emitRest(ERestEvent::REQ_DATA_READ), $param1, $param2]);
				break;
			case 'SUBRESOURCES':
				throw new CHttpException('405', 'Method Not Allowed');
				break;
			case 'SUBRESOURCE':
				$this->controller->emitRest(ERestEvent::REQ_PUT_SUBRESOURCE_RENDER, [
					$this->handlePutSubresource($id, $param1, $param2),
					$param1,
					$param2,
				]);
				break;
			case 'RESOURCE':
				$this->controller->emitRest(ERestEvent::REQ_PUT_RESOURCE_RENDER, [$this->handlePut($id), $this->getRelations()]);
				break;
			default:
				throw new CHttpException(404, "Resource Not Found");
		}
	}

	/**
	 * handlePut
	 *
	 * Helper method for delete actions
	 *
	 * @param (Mixed/Int) (id) unique identifier of the resource to put
	 *
	 * @return (Object) Returns the model of the updated resource
	 */
	public function handlePut($id)
	{
		$model = $this->controller->emitRest(
			ERestEvent::MODEL_ATTACH_BEHAVIORS,
			$this->getModel($id)
		);
		$data = $this->controller->emitRest(ERestEvent::REQ_DATA_READ);
		$restricted_properties = $this->controller->emitRest(ERestEvent::MODEL_RESTRICTED_PROPERTIES);
		$model = $this->controller->emitRest(ERestEvent::MODEL_APPLY_PUT_DATA, [$model, $data, $restricted_properties]);
		return $this->controller->emitRest(ERestEvent::MODEL_SAVE, [$model]);
	}

	/**
	 * handlePutSubresource
	 *
	 * Helper method for put subresource actions
	 *
	 * @param (Mixed/Int) (id) unique identifier of the resource
	 * @param (String) (subresource_name) name of the subresource
	 * @param (Mixed/Int) (subresource_id) unique identifier of the subresource to put
	 *
	 * @return (Object) Returns the model containing the updated subresource
	 */
	public function handlePutSubresource($id, $subresource_name, $subresource_id)
	{
		$model = $this->controller->emitRest(
			ERestEvent::MODEL_ATTACH_BEHAVIORS,
			$this->getModel($id)
		);
		$this->controller->emitRest(ERestEvent::MODEL_SUBRESOURCE_SAVE, [$model, $subresource_name, $subresource_id]);
		return $model;
	}
}


text:
<?php declare(strict_types=1);

namespace GraphQL\Language\AST;

class SelectionSetNode extends Node
{
    public string $kind = NodeKind::SELECTION_SET;

    /** @var NodeList<SelectionNode&Node> */
    public NodeList $selections;
}


text:
<?php

namespace frontend\models\produccion;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use frontend\models\produccion\Producciones;

/**
 * ProduccionesSerach represents the model behind the search form about `frontend\models\produccion\Producciones`.
 */
class ProduccionesSerach extends Producciones
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['IdProduccion', 'IdCentroTrabajo', 'IdMaquina', 'IdUsuario', 'IdProduccionEstatus', 'IdProceso'], 'integer'],
            [['Fecha'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Producciones::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query->andFilterWhere([
            'IdProduccion' => $this->IdProduccion,
            'IdCentroTrabajo' => $this->IdCentroTrabajo,
            'IdMaquina' => $this->IdMaquina,
            'IdUsuario' => $this->IdUsuario,
            'IdProduccionEstatus' => $this->IdProduccionEstatus,
            'Fecha' => $this->Fecha,
            'IdProceso' => $this->IdProceso,
        ]);

        return $dataProvider;
    }
}


text:
VERSION=0.22.0
SHA256=25159de982ec8896fc8213499df0a7003dfb4a03dd861f90fa5679d16faf0f99
curl --location --output /usr/local/bin/buildifier https://github.com/bazelbuild/buildtools/releases/download/"$VERSION"/buildifier \
  && echo "$SHA256" '/usr/local/bin/buildifier' | sha256sum --check \
  && chmod +x /usr/local/bin/buildifier

# GCC for everything.
export CC=gcc
export CXX=g++

echo "Building Bazel-managed deps (//bazel/external:all_external)"
mkdir /bazel-prebuilt-root /bazel-prebuilt-output
BAZEL_OPTIONS="--output_user_root=/bazel-prebuilt-root --output_base=/bazel-prebuilt-output"
cd /bazel-prebuilt
for BAZEL_MODE in opt dbg fastbuild; do
  bazel ${BAZEL_OPTIONS} build -c "${BAZEL_MODE}" //bazel/external:all_external
done
# Allow access by non-root for building.
chmod -R a+rX /bazel-prebuilt-root /bazel-prebuilt-output


text:
package org.kie.uberfire.social.activities.events;

import java.io.Serializable;

import org.jboss.errai.common.client.api.annotations.MapsTo;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.kie.uberfire.social.activities.model.SocialUser;

/**
 * Created by Cristiano Nicolai.
 */
@Portable
public class SocialUserFollowedEvent implements Serializable {

    private static final long serialVersionUID = 1L;

    private final SocialUser user;
    private final SocialUser follow;

    public SocialUserFollowedEvent( @MapsTo( "user" ) SocialUser user, @MapsTo( "follow" ) SocialUser follow ) {
        this.user = user;
        this.follow = follow;
    }

    public SocialUser getFollow() {
        return follow;
    }

    public SocialUser getUser() {
        return user;
    }

    @Override
    public String toString() {
        return "SocialUserFollowedEvent{" +
                "user=" + user +
                ", follow=" + follow +
                '}';
    }

    @Override
    public boolean equals( Object o ) {
        if ( this == o ) return true;
        if ( o == null || getClass() != o.getClass() ) return false;

        SocialUserFollowedEvent that = (SocialUserFollowedEvent) o;

        if ( !user.equals( that.user ) ) return false;
        return follow.equals( that.follow );

    }

    @Override
    public int hashCode() {
        int result = user.hashCode();
        result = 31 * result + follow.hashCode();
        return result;
    }
}


text:
package	org.apache.derby.impl.sql.compile;

import java.util.List;
import org.apache.derby.catalog.AliasInfo;
import org.apache.derby.catalog.TypeDescriptor;
import org.apache.derby.catalog.types.AggregateAliasInfo;
import org.apache.derby.catalog.types.RoutineAliasInfo;
import org.apache.derby.catalog.types.SynonymAliasInfo;
import org.apache.derby.catalog.types.UDTAliasInfo;
import org.apache.derby.iapi.error.StandardException;
import org.apache.derby.iapi.reference.JDBC40Translation;
import org.apache.derby.iapi.reference.SQLState;
import org.apache.derby.iapi.services.sanity.SanityManager;
import org.apache.derby.iapi.sql.dictionary.AliasDescriptor;
import org.apache.derby.iapi.sql.dictionary.DataDictionary;
import org.apache.derby.iapi.sql.dictionary.SchemaDescriptor;
import org.apache.derby.iapi.sql.execute.ConstantAction;
import org.apache.derby.iapi.types.DataTypeDescriptor;
import org.apache.derby.iapi.types.TypeId;

/**
 * A CreateAliasNode represents a CREATE ALIAS statement.
 *
 */

public class CreateAliasNode extends DDLStatementNode
{
    // indexes into routineElements
    public static final int PARAMETER_ARRAY = 0;
    public static final int TABLE_NAME = PARAMETER_ARRAY + 1;
    public static final int DYNAMIC_RESULT_SET_COUNT = TABLE_NAME + 1;
    public static final int LANGUAGE = DYNAMIC_RESULT_SET_COUNT + 1;
    public static final int EXTERNAL_NAME = LANGUAGE + 1;
    public static final int PARAMETER_STYLE = EXTERNAL_NAME + 1;
    public static final int SQL_CONTROL = PARAMETER_STYLE + 1;
    public static final int DETERMINISTIC = SQL_CONTROL + 1;
    public static final int NULL_ON_NULL_INPUT = DETERMINISTIC + 1;
    public static final int RETURN_TYPE = NULL_ON_NULL_INPUT + 1;
    public static final int ROUTINE_SECURITY_DEFINER = RETURN_TYPE + 1;
    public static final int VARARGS = ROUTINE_SECURITY_DEFINER + 1;

    // Keep ROUTINE_ELEMENT_COUNT last (determines set cardinality).
    // Note: Remember to also update the map ROUTINE_CLAUSE_NAMES in
    // sqlgrammar.jj when elements are added.
    public static final int ROUTINE_ELEMENT_COUNT = VARARGS + 1;

    //
    // These are the names of 1-arg builtin functions which are represented in the
    // grammar as non-reserved keywords. These names may not be used as
    // the unqualified names of user-defined aggregates.
    //
    // If additional 1-arg builtin functions are added to the grammar, they should
    // be put in this table.
    //
    private static  final   String[]  NON_RESERVED_FUNCTION_NAMES =
    {
        "ABS",
        "ABSVAL",
        "DATE",
        "DAY",
        "LCASE",
        "LENGTH",
        "MONTH",
        "SQRT",
        "TIME",
        "TIMESTAMP",
        "UCASE",
    };

    //
    // These are aggregate names defined by the SQL Standard which do not
    // behave as reserved keywords in Derby.
    //
    private static  final   String[]    NON_RESERVED_AGGREGATES =
    {
        "COLLECT",
        "COUNT",
        "EVERY",
        "FUSION",
        "INTERSECTION",
        "STDDEV_POP",
        "STDDEV_SAMP",
        "VAR_POP",
        "VAR_SAMP",
    };

    // aggregate arguments
    public  static  final   int AGG_FOR_TYPE = 0;
    public  static  final   int AGG_RETURN_TYPE = AGG_FOR_TYPE + 1;
    public  static  final   int AGG_ELEMENT_COUNT = AGG_RETURN_TYPE + 1;

	private String				javaClassName;
	private String				methodName;
	private char				aliasType;

	private AliasInfo aliasInfo;

	/**
	 * Initializer for a CreateAliasNode
	 *
	 * @param aliasName				The name of the alias
	 * @param targetObject			Target name
	 * @param methodName		    The method name
	 * @param aliasType				The alias type
     *
	 * @exception StandardException		Thrown on error
	 */
	public void init(
						Object aliasName,
						Object targetObject,
						Object methodName,
						Object aliasSpecificInfo,
                        Object aliasType)
		throws StandardException
	{
		TableName qn = (TableName) aliasName;
		this.aliasType = ((Character) aliasType).charValue();

		initAndCheck(qn);

		switch (this.aliasType)
		{
			case AliasInfo.ALIAS_TYPE_AGGREGATE_AS_CHAR:
				this.javaClassName = (String) targetObject;

				Object[] aggElements = (Object[]) aliasSpecificInfo;
                TypeDescriptor  aggForType = bindUserCatalogType( (TypeDescriptor) aggElements[ AGG_FOR_TYPE ] );
                TypeDescriptor  aggReturnType = bindUserCatalogType( (TypeDescriptor) aggElements[ AGG_RETURN_TYPE ] );

                // XML not allowed because SQLXML support has not been implemented
                if (
                    (aggForType.getJDBCTypeId() == JDBC40Translation.SQLXML) ||
                    (aggReturnType.getJDBCTypeId() == JDBC40Translation.SQLXML)
                   )
                {
                    throw StandardException.newException( SQLState.LANG_XML_NOT_ALLOWED_DJRS );
                }

				aliasInfo = new AggregateAliasInfo( aggForType, aggReturnType );
				implicitCreateSchema = true;
                break;

			case AliasInfo.ALIAS_TYPE_UDT_AS_CHAR:
				this.javaClassName = (String) targetObject;
				aliasInfo = new UDTAliasInfo();

				implicitCreateSchema = true;
                break;

			case AliasInfo.ALIAS_TYPE_PROCEDURE_AS_CHAR:
			case AliasInfo.ALIAS_TYPE_FUNCTION_AS_CHAR:
			{
				this.javaClassName = (String) targetObject;
				this.methodName = (String) methodName;

				//routineElements contains the description of the procedure.
				//
				// 0 - Object[] 3 element array for parameters
				// 1 - TableName - specific name
				// 2 - Integer - dynamic result set count
				// 3 - String language (always java) - ignore
				// 4 - String external name (also passed directly to create alias node - ignore
				// 5 - Integer parameter style
				// 6 - Short - SQL control
				// 7 - Boolean - whether the routine is DETERMINISTIC
				// 8 - Boolean - CALLED ON NULL INPUT (always TRUE for procedures)
				// 9 - TypeDescriptor - return type (always NULL for procedures)

				Object[] routineElements = (Object[]) aliasSpecificInfo;
				Object[] parameters = (Object[]) routineElements[PARAMETER_ARRAY];
				int paramCount = ((List) parameters[0]).size();

				// Support for Java signatures in Derby was added in 10.1
				// Check to see the catalogs have been upgraded to 10.1 before
				// accepting such a method name for a routine. Otherwise
				// a routine that works in 10.1 soft upgrade mode would
				// exist when running 10.0 but not resolve to anything.
				if (this.methodName.indexOf('(') != -1)
				{
					getDataDictionary().checkVersion(
							DataDictionary.DD_VERSION_DERBY_10_1,
                            "EXTERNAL NAME 'class.method(<signature>)'");

				}

				String[] names = null;
				TypeDescriptor[] types = null;
				int[] modes = null;

				if (paramCount != 0) {

                    names = (String[]) ((List) parameters[0]).toArray(
                            new String[paramCount]);

                    types = (TypeDescriptor[]) ((List) parameters[1]).toArray(
                            new TypeDescriptor[paramCount]);

					modes = new int[paramCount];
					for (int i = 0; i < paramCount; i++) {
                        int currentMode =  ((Integer) (((List) parameters[2]).get(i))).intValue();
                        modes[i] = currentMode;

                        //
                        // We still don't support XML values as parameters.
                        // Presumably, the XML datatype would map to a JDBC java.sql.SQLXML type.
                        // We have no support for that type today.
                        //
                        if ( !types[ i ].isUserDefinedType() )
                        {
                            if (TypeId.getBuiltInTypeId(types[i].getJDBCTypeId()).isXMLTypeId())
                            { throw StandardException.newException(SQLState.LANG_LONG_DATA_TYPE_NOT_ALLOWED, names[i]); }
                        }
                    }

					if (paramCount > 1) {
						String[] dupNameCheck = new String[paramCount];
						System.arraycopy(names, 0, dupNameCheck, 0, paramCount);
						java.util.Arrays.sort(dupNameCheck);
						for (int dnc = 1; dnc < dupNameCheck.length; dnc++) {
							if (! dupNameCheck[dnc].equals("") && dupNameCheck[dnc].equals(dupNameCheck[dnc - 1]))
								throw StandardException.newException(SQLState.LANG_DB2_DUPLICATE_NAMES, dupNameCheck[dnc], getFullName());
						}
					}
				}

				Integer drso = (Integer) routineElements[DYNAMIC_RESULT_SET_COUNT];
				int drs = drso == null ? 0 : drso.intValue();

				short sqlAllowed;
				Short sqlAllowedObject = (Short) routineElements[SQL_CONTROL];
				if (sqlAllowedObject != null)
					sqlAllowed = sqlAllowedObject.shortValue();
				else
					sqlAllowed = (this.aliasType == AliasInfo.ALIAS_TYPE_PROCEDURE_AS_CHAR ?
					RoutineAliasInfo.MODIFIES_SQL_DATA : RoutineAliasInfo.READS_SQL_DATA);

				Boolean isDeterministicO = (Boolean) routineElements[DETERMINISTIC];
                boolean isDeterministic = (isDeterministicO == null) ? false : isDeterministicO.booleanValue();

				Boolean hasVarargsO = (Boolean) routineElements[ VARARGS ];
                boolean hasVarargs = (hasVarargsO == null) ? false : hasVarargsO.booleanValue();

                Boolean definersRightsO =
                    (Boolean) routineElements[ROUTINE_SECURITY_DEFINER];
                boolean definersRights  =
                    (definersRightsO == null) ? false :
                    definersRightsO.booleanValue();

				Boolean calledOnNullInputO = (Boolean) routineElements[NULL_ON_NULL_INPUT];
				boolean calledOnNullInput;
				if (calledOnNullInputO == null)
					calledOnNullInput = true;
				else
					calledOnNullInput = calledOnNullInputO.booleanValue();

                // bind the return type if it is a user defined type. this fills
                // in the class name.
                TypeDescriptor returnType = (TypeDescriptor) routineElements[RETURN_TYPE];
                if ( returnType != null )
                {
                    DataTypeDescriptor dtd = DataTypeDescriptor.getType( returnType );

                    dtd = bindUserType( dtd );
                    returnType = dtd.getCatalogType();
                }

                aliasInfo = new RoutineAliasInfo(
                    this.methodName,
                    paramCount,
                    names,
                    types,
                    modes,
                    drs,
                    // parameter style:
                    ((Short) routineElements[PARAMETER_STYLE]).shortValue(),
                    sqlAllowed,
                    isDeterministic,
                    hasVarargs,
                    definersRights,
                    calledOnNullInput,
                    returnType );

				implicitCreateSchema = true;
				}
				break;

			case AliasInfo.ALIAS_TYPE_SYNONYM_AS_CHAR:
				String targetSchema;
				implicitCreateSchema = true;
				TableName t = (TableName) targetObject;
				if (t.getSchemaName() != null)
					targetSchema = t.getSchemaName();
				else targetSchema = getSchemaDescriptor().getSchemaName();
				aliasInfo = new SynonymAliasInfo(targetSchema, t.getTableName());
				break;

			default:
				if (SanityManager.DEBUG)
				{
					SanityManager.THROWASSERT(
						"Unexpected value for aliasType (" + aliasType + ")");
				}
		}
	}

	public String statementToString()
	{
		switch (this.aliasType)
		{
		case AliasInfo.ALIAS_TYPE_AGGREGATE_AS_CHAR:
			return "CREATE DERBY AGGREGATE";
		case AliasInfo.ALIAS_TYPE_UDT_AS_CHAR:
			return "CREATE TYPE";
		case AliasInfo.ALIAS_TYPE_PROCEDURE_AS_CHAR:
			return "CREATE PROCEDURE";
		case AliasInfo.ALIAS_TYPE_SYNONYM_AS_CHAR:
			return "CREATE SYNONYM";
		default:
			return "CREATE FUNCTION";
		}
	}

	// We inherit the generate() method from DDLStatementNode.

	/**
	 * Bind this CreateAliasNode.  This means doing any static error
	 * checking that can be done before actually creating the table.
	 * For example, verifying that the column name list does not
	 * contain any duplicate column names.
	 *
	 *
	 * @exception StandardException		Thrown on error
	 */

	public void bindStatement() throws StandardException
	{
		//Are we dealing with user defined function or procedure?
		if (aliasType == AliasInfo.ALIAS_TYPE_FUNCTION_AS_CHAR ||
				aliasType == AliasInfo.ALIAS_TYPE_PROCEDURE_AS_CHAR) {

            RoutineAliasInfo    rai = (RoutineAliasInfo)aliasInfo;

            // Set the collation for all string types in parameters
            // and return types including row multi-sets to be that of
            // the schema the routine is being defined in.
            rai.setCollationTypeForAllStringTypes(
                    getSchemaDescriptor().getCollationType());

            bindParameterTypes( (RoutineAliasInfo)aliasInfo );

            if ( rai.hasVarargs() )
            {
                switch ( rai.getParameterStyle() )
                {
                case RoutineAliasInfo.PS_DERBY_JDBC_RESULT_SET:
                case RoutineAliasInfo.PS_DERBY:
                    break;

                default:
                    throw StandardException.newException( SQLState.LANG_VARARGS_PARAMETER_STYLE );
                }

                if ( rai.getMaxDynamicResultSets() > 0 )
                {
                    throw StandardException.newException( SQLState.LANG_VARARGS_RETURN_RESULT_SETS );
                }
            }

            if (
                (rai.getParameterStyle() == RoutineAliasInfo.PS_DERBY) &&
                !rai.hasVarargs()
                )
            {
                throw StandardException.newException( SQLState.LANG_DERBY_PARAMETER_STYLE );
            }
		}

        // validity checking for UDTs
        if ( aliasType == AliasInfo.ALIAS_TYPE_UDT_AS_CHAR )
        {
            //
            // Make sure that the java class name is not the name of a builtin
            // type. This skirts problems caused by logic across the system
            // which assumes a tight association between the builtin SQL types
            // and the Java classes which implement them.
            //
            // For security reasons we do not allow the user to bind a UDT
            // to a Derby class.
            //
            TypeId[] allSystemTypeIds = TypeId.getAllBuiltinTypeIds();
            int systemTypeCount = allSystemTypeIds.length;

            boolean foundConflict = javaClassName.startsWith( "org.apache.derby." );

            if ( !foundConflict )
            {
                for ( int i = 0; i < systemTypeCount; i++ )
                {
                    TypeId systemType = allSystemTypeIds[ i ];
                    String systemTypeName = systemType.getCorrespondingJavaTypeName();

                    if ( systemTypeName.equals( javaClassName ) )
                    {
                        foundConflict = true;
                        break;
                    }
                }
            }

            if ( foundConflict )
            {
                throw StandardException.newException
                    ( SQLState.LANG_UDT_BUILTIN_CONFLICT, javaClassName );
            }

            return;
        }

        // validity checking for aggregates
        if ( aliasType == AliasInfo.ALIAS_TYPE_AGGREGATE_AS_CHAR ) { bindAggregate(); }

		// Aggregates, procedures and functions do not check class or method validity until
		// runtime execution. Synonyms do need some validity checks.
		if (aliasType != AliasInfo.ALIAS_TYPE_SYNONYM_AS_CHAR)
			return;

		// Don't allow creating synonyms in SESSION schema. Causes confusion if
		// a temporary table is created later with same name.
		if (isSessionSchema(getSchemaDescriptor().getSchemaName()))
			throw StandardException.newException(SQLState.LANG_OPERATION_NOT_ALLOWED_ON_SESSION_SCHEMA_TABLES);

		String targetSchema = ((SynonymAliasInfo)aliasInfo).getSynonymSchema();
		String targetTable = ((SynonymAliasInfo)aliasInfo).getSynonymTable();
		if (this.getObjectName().equals(targetSchema, targetTable))
			throw StandardException.newException(SQLState.LANG_SYNONYM_CIRCULAR,
						this.getFullName(),
						targetSchema+"."+targetTable);

		SchemaDescriptor targetSD = getSchemaDescriptor(targetSchema, false);
		if ((targetSD != null) && isSessionSchema(targetSD))
			throw StandardException.newException(SQLState.LANG_OPERATION_NOT_ALLOWED_ON_SESSION_SCHEMA_TABLES);

	}

    /** Extra logic for binding user-defined aggregate definitions */
    private void    bindAggregate() throws StandardException
    {
        String                      unqualifiedName = getRelativeName();

        //
        // A user-defined aggregate cannot have the name of a builtin function which takes 1 argument.
        //
        SchemaDescriptor    sysfun = getSchemaDescriptor( "SYSFUN", true );
        List                        systemFunctions = getDataDictionary().getRoutineList
            (
             sysfun.getUUID().toString(), unqualifiedName,
             AliasInfo.ALIAS_NAME_SPACE_FUNCTION_AS_CHAR
             );

        for ( int i = 0; i < systemFunctions.size(); i++ )
        {
			AliasDescriptor function = (AliasDescriptor) systemFunctions.get(i);

			RoutineAliasInfo routineInfo = (RoutineAliasInfo) function.getAliasInfo();
			int parameterCount = routineInfo.getParameterCount();
			if ( parameterCount == 1 )  { throw illegalAggregate(); }
        }

        //
        // Additional builtin 1-arg functions which are represented in the grammar
        // as non-reserved keywords.
        //
        for ( int i = 0; i < NON_RESERVED_FUNCTION_NAMES.length; i++ )
        {
            if ( NON_RESERVED_FUNCTION_NAMES[ i ].equals( unqualifiedName ) )  { throw illegalAggregate(); }
        }

        //
        // Additional SQL Standard aggregate names which are not represented in
        // the Derby grammar as reserved keywords.
        //
        for ( int i = 0; i < NON_RESERVED_AGGREGATES.length; i++ )
        {
            if ( NON_RESERVED_AGGREGATES[ i ].equals( unqualifiedName ) )  { throw illegalAggregate(); }
        }

        // now bind the input and return types
        AggregateAliasInfo  aai = (AggregateAliasInfo) aliasInfo;

        aai.setCollationTypeForAllStringTypes( getSchemaDescriptor().getCollationType() );
    }

    /** Construct an exception flagging an illegal aggregate name */
    private StandardException   illegalAggregate()
    {
        return StandardException.newException( SQLState.LANG_ILLEGAL_UDA_NAME, getRelativeName() );
    }

    /** Bind the class names for UDTs */
    private void bindParameterTypes( RoutineAliasInfo aliasInfo ) throws StandardException
    {
        TypeDescriptor[] parameterTypes = aliasInfo.getParameterTypes();

        if ( parameterTypes == null ) { return; }

        int count = parameterTypes.length;
        for ( int i = 0; i < count; i++ )
        {
            parameterTypes[ i ] = bindUserCatalogType( parameterTypes[ i ] );
        }
    }

	/**
	 * Create the Constant information that will drive the guts of Execution.
	 *
	 * @exception StandardException		Thrown on failure
	 */
	public ConstantAction	makeConstantAction() throws StandardException
	{
		String schemaName = getSchemaDescriptor().getSchemaName();

		return	getGenericConstantActionFactory().getCreateAliasConstantAction(
											  getRelativeName(),
											  schemaName,
											  javaClassName,
											  aliasInfo,
											  aliasType);
	}
}


text:
import os
import sys
from argparse import SUPPRESS

import numpy as np
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from tqdm import tqdm

try:
    from apex import amp

except ImportError:
    amp = None

from dataset import LMDBDataset
from pixelsnail import PixelSNAIL
from scheduler import CycleScheduler

file_path = os.path.dirname(os.path.realpath(__file__))

import candle

additional_definitions = [
    {
        "name": "sched_mode",
        "type": str,
        "default": None,
        "help": "Mode of learning rate scheduler",
    },
    {
        "name": "lmdb_filename",
        "type": str,
        "default": SUPPRESS,
        "help": "lmdb dataset path",
    },
    {"name": "amp", "type": str, "default": "O0", "help": ""},
    {"name": "hier", "type": str, "default": "top", "help": ""},
    {"name": "channel", "type": int, "default": 256, "help": ""},
    {"name": "n_res_block", "type": int, "default": 4, "help": ""},
    {"name": "n_res_channel", "type": int, "default": 256, "help": ""},
    {"name": "n_out_res_block", "type": int, "default": 0, "help": ""},
    {"name": "n_cond_res_block", "type": int, "default": 3, "help": ""},
    {
        "name": "ckpt_restart",
        "type": str,
        "default": None,
        "help": "Checkpoint to restart from",
    },
]

required = [
    "batch_size",
    "epochs",
    "hier",
    "learning_rate",
    "channel",
    "n_res_block",
    "n_res_channel",
    "n_out_res_block",
    "n_cond_res_block",
    "dropout",
    "amp",
    "sched_mode",
    "lmdb_filename",
]

class TrPxSnBk(candle.Benchmark):
    def set_locals(self):
        """Functionality to set variables specific for the benchmark
        - required: set of required parameters for the benchmark.
        - additional_definitions: list of dictionaries describing the additional parameters for the
        benchmark.
        """

        if required is not None:
            self.required = set(required)
        if additional_definitions is not None:
            self.additional_definitions = additional_definitions

def initialize_parameters(default_model="train_pixelsnail_default_model.txt"):

    # Build benchmark object
    trpsn = TrPxSnBk(
        file_path,
        default_model,
        "pytorch",
        prog="train_pixelsnail_baseline",
        desc="Histology train pixelsnail - Examples",
    )

    print("Created sample benchmark")

    # Initialize parameters
    gParameters = candle.finalize_parameters(trpsn)
    print("Parameters initialized")

    return gParameters

def train(args, epoch, loader, model, optimizer, scheduler, device):
    loader = tqdm(loader, file=sys.stdout)

    criterion = nn.CrossEntropyLoss()

    for i, (top, bottom, label) in enumerate(loader):
        model.zero_grad()

        top = top.to(device)

        if args.hier == "top":
            target = top
            out, _ = model(top)

        elif args.hier == "bottom":
            bottom = bottom.to(device)
            target = bottom
            out, _ = model(bottom, condition=top)

        loss = criterion(out, target)
        loss.backward()

        if scheduler is not None:
            scheduler.step()
        optimizer.step()

        _, pred = out.max(1)
        correct = (pred == target).float()
        accuracy = correct.sum() / target.numel()

        lr = optimizer.param_groups[0]["lr"]

        loader.set_description(
            (
                f"epoch: {epoch + 1}; loss: {loss.item():.5f}; "
                f"acc: {accuracy:.5f}; lr: {lr:.5f}"
            )
        )

class PixelTransform:
    def __init__(self):
        pass

    def __call__(self, input):
        ar = np.array(input)

        return torch.from_numpy(ar).long()

def run(params):

    args = candle.ArgumentStruct(**params)
    # Configure GPUs
    ndevices = torch.cuda.device_count()
    if ndevices < 1:
        raise Exception("No CUDA gpus available")

    device = "cuda"

    dataset = LMDBDataset(args.lmdb_filename)
    loader = DataLoader(
        dataset, batch_size=args.batch_size, shuffle=True, num_workers=4, drop_last=True
    )

    ckpt = {}

    if args.ckpt_restart is not None:
        ckpt = torch.load(args.ckpt_restart)
        args = ckpt["args"]

    if args.hier == "top":
        model = PixelSNAIL(
            [32, 32],
            512,
            args.channel,
            5,
            4,
            args.n_res_block,
            args.n_res_channel,
            dropout=args.dropout,
            n_out_res_block=args.n_out_res_block,
        )

    elif args.hier == "bottom":
        model = PixelSNAIL(
            [64, 64],
            512,
            args.channel,
            5,
            4,
            args.n_res_block,
            args.n_res_channel,
            attention=False,
            dropout=args.dropout,
            n_cond_res_block=args.n_cond_res_block,
            cond_res_channel=args.n_res_channel,
        )

    if "model" in ckpt:
        model.load_state_dict(ckpt["model"])

    model = model.to(device)
    optimizer = optim.Adam(model.parameters(), lr=args.learning_rate)

    if amp is not None:
        model, optimizer = amp.initialize(model, optimizer, opt_level=args.amp)

    model = nn.DataParallel(model)
    model = model.to(device)

    scheduler = None
    if args.sched_mode == "cycle":
        scheduler = CycleScheduler(
            optimizer,
            args.learning_rate,
            n_iter=len(loader) * args.epochs,
            momentum=None,
        )

    for i in range(args.epochs):
        train(args, i, loader, model, optimizer, scheduler, device)
        torch.save(
            {"model": model.module.state_dict(), "args": args},
            f"{args.ckpt_directory}/checkpoint/pixelsnail_{args.hier}_{str(i + 1).zfill(3)}.pt",
        )

def main():
    params = initialize_parameters()
    run(params)

if __name__ == "__main__":
    main()


text:
//    nVLC
//
//    Author:  Roman Ginzburg
//
//    nVLC is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    nVLC is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//    GNU General Public License for more details.
//
// ========================================================================

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Nequeo.Media.Vlc.Events
{
   /// <summary>
   /// Events raised by IMediaList object
   /// </summary>
   public interface IMediaListEvents
   {
      event EventHandler<MediaListItemAdded> ItemAdded;

      event EventHandler<MediaListWillAddItem> WillAddItem;

      event EventHandler<MediaListItemDeleted> ItemDeleted;

      event EventHandler<MediaListWillDeleteItem> WillDeleteItem;
   }
}


text:
{% extends "ctms_base.html" %}
{% load staticfiles %}

{% block title %}
{% if course_form %}Create new course
{% else %}
  {% if my_courses %}
  My courses
  {% elif shared_courses %}
  Shared courses
  {% else %}
  Courselets
  {% endif %}
{% endif %}
{% endblock %}

{% block content %}
  {% if form %}
    {% include 'ctms/includes/create_course.html' %}
  {% else %}
    {% with 'My courses' as list_name %}
      {% with my_courses as courses %}
        {% include 'ctms/includes/courses_list.html' %}
      {% endwith %}
    {% endwith %}
{% endif %}
{% endblock %}

{% block js %}
<script src="https://player.vimeo.com/api/player.js"></script>
  <script>
    // Add listeners once the DOM is ready
    $(function(){
      // Redirect when the user closes the final video
      $("[data-fancybox]").fancybox({
        afterShow: function() {
          var iframe = $(".fancybox-iframe");
          var player = new Vimeo.Player(iframe);
          player.on('ended', function() {
            if ( document.fullscreen ) {
              document.exitFullscreen();
            }
            parent.$.fancybox.close();
          });
        }
      });
    });
  </script>
{% endblock %}


text:
![logo](./public/img/cooltext166439939110449.png)

[![Join the chat at https://gitter.im/pollseed/github-extension-api](https://badges.gitter.im/pollseed/github-extension-api.svg)](https://gitter.im/pollseed/github-extension-api?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

GitHub extension API.
Docs is http://docs.githubextensionapi.apiary.io

## Route Sample

### Order by columns parameters
github_id
stargazers_count
forks_count
commit_created_at
commit_updated_at
owner_id
owner_followers
owner_following
owner_created_at
owner_updated_at

### Response Parameters

column name|detail
:--:|:--:|
id|Ignore column for AI, Return NULL
github_id|GitHub repository ID
name| Repository name
language| Programing language
stargazers_count| star count
forks_count|fork count
html_url|github repository URL
commit_created_at| repository create date
commit_updated_at|repository update date
owner_id|GitHub user ID
owner_followers|user follower count
owner_following|user following count
owner_created_at|user create date
owner_updated_at|user update date
---
### All repositories
#### Route
`GET /github`
#### Request Sample
`http://localhost:9393/github?order_by=forks_count&desc_flg=1&limit=1`
#### Response Sample
```.json
[

    {
        "id": null,
        "github_id": 943149,
        "name": "d3",
        "language": "javascript",
        "stargazers_count": 46308,
        "forks_count": 12401,
        "html_url": "https://github.com/mbostock/d3",
        "commit_created_at": "2010-09-27T17:22:42.000Z",
        "commit_updated_at": "2016-02-11T03:00:20.000Z",
        "owner_id": 230541,
        "owner_followers": 11348,
        "owner_following": 13,
        "owner_created_at": "2010-03-25T22:02:56.000Z",
        "owner_updated_at": "2016-02-06T04:52:06.000Z"
    }

]
```
---
### By language
#### Route
`/github/language/:language`

#### Language Parameters
java
ruby
javascript
php
python
perl
c
c#
c++
objective-c
swift
go
bash
scala
lisp
ecma script
groovy
lua
haskell
visual basic
assembly
css

#### Request Sample
`http://localhost:9393/github/language/ruby?order_by=forks_count&limit=1`
#### Response Sample
```.json
[

    {
        "id": null,
        "github_id": 8237199,
        "name": "motion-xray",
        "language": "ruby",
        "stargazers_count": 586,
        "forks_count": 12,
        "html_url": "https://github.com/colinta/motion-xray",
        "commit_created_at": "2013-02-16T15:07:15.000Z",
        "commit_updated_at": "2016-01-29T21:57:34.000Z",
        "owner_id": 27570,
        "owner_followers": 177,
        "owner_following": 4,
        "owner_created_at": "2008-10-04T17:51:46.000Z",
        "owner_updated_at": "2016-01-28T14:38:48.000Z"
    }

]
```
---
### GitHub id
#### Route
`/github/:id`
#### Request Sample
`http://localhost:9393/github/id/13584262`
#### Response Sample
```.json
{

    "id": null,
    "github_id": 13584262,
    "name": "webtorrent",
    "language": "javascript",
    "stargazers_count": 9019,
    "forks_count": 644,
    "html_url": "https://github.com/feross/webtorrent",
    "commit_created_at": "2013-10-15T08:16:40.000Z",
    "commit_updated_at": "2016-02-11T02:26:21.000Z",
    "owner_id": 121766,
    "owner_followers": 3578,
    "owner_following": 175,
    "owner_created_at": "2009-09-01T06:06:14.000Z",
    "owner_updated_at": "2016-02-07T04:04:43.000Z"

}
```


text:
deploy_echoplexus
# deploy_ejabberd
# deploy_firefly
deploy_gitannex
deploy_gitlab_builddeps
deploy_gitlab_config
deploy_gitlab_runtimedeps
deploy_gitlab_src
deploy_gogs_src
deploy_h5ai
# deploy_hordewebmail       bad
# deploy_klaus
# deploy_lumina
deploy_mdwiki
# deploy_minidlna
deploy_monit
# deploy_murmur
# deploy_mysql_percona55
# deploy_nginx
# deploy_owncloud
# deploy_pfsense
deploy_phabricator
# deploy_php_apache24
# deploy_php_nginx
# deploy_piwik
deploy_postfix
# deploy_postgresql93
# deploy_postgresql94
deploy_pydio
# deploy_redis_unix
# deploy_squid
deploy_transfersh
deploy_uploadsh
# deploy_vnc
deploy_zabbix


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'chrome://resources/cr_elements/cr_icons_css.m.js';
import 'chrome://resources/cr_elements/cr_toggle/cr_toggle.m.js';
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js';
import 'chrome://resources/cr_elements/cr_radio_group/cr_radio_group.m.js';
import 'chrome://resources/cr_elements/cr_radio_button/cr_radio_button.m.js';
import 'chrome://resources/cr_elements/policy/cr_policy_indicator.m.js';

import {assert} from 'chrome://resources/js/assert.m.js';
import {html, mixinBehaviors, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';

import {I18nBehavior, loadTimeData} from './i18n_setup.js';
import {ChromeCartProxy} from './modules/cart/chrome_cart_proxy.js';
import {ModuleRegistry} from './modules/module_registry.js';
import {NewTabPageProxy} from './new_tab_page_proxy.js';

/**
 * Element that lets the user configure modules settings.
 * @polymer
 * @extends {PolymerElement}
 */
class CustomizeModulesElement extends mixinBehaviors
([I18nBehavior], PolymerElement) {
  static get is() {
    return 'ntp-customize-modules';
  }

  static get template() {
    return html`{__html_template__}`;
  }

  static get properties() {
    return {
      /**
       * If true, modules are customizable. If false, all modules are hidden.
       * @private
       */
      show_: {
        type: Boolean,
        observer: 'onShowChange_',
      },

      /** @private */
      showManagedByPolicy_: {
        type: Boolean,
        value: () => loadTimeData.getBoolean('modulesVisibleManagedByPolicy'),
      },

      /**
       * @private {
       *   !Array<{
       *     name: string,
       *     id: string,
       *     checked: boolean,
       *     initiallyChecked: boolean,
       *     disabled: boolean,
       *   }>
       * }
       */
      modules_: {
        type: Array,
        value: () => ModuleRegistry.getInstance().getDescriptors().map(
            d => ({name: d.name, id: d.id, checked: true, hidden: false})),
      },

      /**
       * @private {
       *   !Object<{
       *     enabled: boolean,
       *     initiallyEnabled: boolean,
       *   }>
       * }
       */
      // Discount toggle is a workaround for crbug.com/1199465 and will be
      // removed after module customization is better defined. Please avoid
      // using similar pattern for other features.
      discountToggle_: {
        type: Object,
        value: {enabled: false, initiallyEnabled: false},
      },

      /** @private */
      discountToggleEligible_: {
        type: Boolean,
        value: false,
      }
    };
  }

  constructor() {
    super();
    /** @private {?number} */
    this.setDisabledModulesListenerId_ = null;
  }

  /** @override */
  connectedCallback() {
    super.connectedCallback();
    this.setDisabledModulesListenerId_ =
        NewTabPageProxy.getInstance()
            .callbackRouter.setDisabledModules.addListener((all, ids) => {
              this.show_ = !all;
              this.modules_.forEach(({id}, i) => {
                const checked = !all && !ids.includes(id);
                this.set(`modules_.${i}.checked`, checked);
                this.set(`modules_.${i}.initiallyChecked`, checked);
                this.set(`modules_.${i}.disabled`, ids.includes(id));
              });
            });
    NewTabPageProxy.getInstance().handler.updateDisabledModules();
    this.set(
        'discountToggleEligible_',
        loadTimeData.getBoolean('ruleBasedDiscountEnabled'));
    if (!this.discountToggleEligible_) {
      return;
    }
    ChromeCartProxy.getHandler().getDiscountEnabled().then(({enabled}) => {
      this.set('discountToggle_.enabled', enabled);
      this.discountToggle_.initiallyEnabled = enabled;
    });
  }

  /** @override */
  disconnectedCallback() {
    super.disconnectedCallback();
    NewTabPageProxy.getInstance().callbackRouter.removeListener(
        assert(this.setDisabledModulesListenerId_));
  }

  /** @override */
  ready() {
    // |window.CrPolicyStrings.controlledSettingPolicy| populates the tooltip
    // text of <cr-policy-indicator indicator-type="devicePolicy" /> elements.
    // Needs to be called before |super.ready()| so that the string is available
    // when <cr-policy-indicator> gets instantiated.
    window.CrPolicyStrings = {
      controlledSettingPolicy:
          loadTimeData.getString('controlledSettingPolicy'),
    };
    super.ready();
  }

  apply() {
    const handler = NewTabPageProxy.getInstance().handler;
    handler.setModulesVisible(this.show_);
    this.modules_
        .filter(({checked, initiallyChecked}) => checked !== initiallyChecked)
        .forEach(({id, checked}) => {
          // Don't set disabled status of a module if we are in hide all mode to
          // preserve the status for the next time we go into customize mode.
          if (this.show_) {
            handler.setModuleDisabled(id, !checked);
          }
          const base = `NewTabPage.Modules.${checked ? 'Enabled' : 'Disabled'}`;
          chrome.metricsPrivate.recordSparseHashable(base, id);
          chrome.metricsPrivate.recordSparseHashable(`${base}.Customize`, id);
        });
    // Discount toggle is a workaround for crbug.com/1199465 and will be
    // removed after module customization is better defined. Please avoid
    // using similar pattern for other features.
    if (this.discountToggleEligible_ &&
        this.discountToggle_.enabled !==
            this.discountToggle_.initiallyEnabled) {
      ChromeCartProxy.getHandler().setDiscountEnabled(
          this.discountToggle_.enabled);
      chrome.metricsPrivate.recordUserAction(`NewTabPage.Carts.${
          this.discountToggle_.enabled ? 'EnableDiscount' :
                                         'DisableDiscount'}`);
    }
  }

  /**
   * @param {!CustomEvent<{value: string}>} e
   * @private
   */
  onShowRadioSelectionChanged_(e) {
    this.show_ = e.detail.value === 'customize';
  }

  /** @private */
  onShowChange_() {
    this.modules_.forEach(
        (m, i) => this.set(`modules_.${i}.checked`, this.show_ && !m.disabled));
  }

  /**
   * @return {string}
   * @private
   */
  radioSelection_() {
    return this.show_ ? 'customize' : 'hide';
  }

  /**
   * @return {boolean}
   * @private
   */
  moduleToggleDisabled_() {
    return this.showManagedByPolicy_ || !this.show_;
  }

  /**
   * @param {string} id
   * @param {boolean} checked
   * @param {boolean} eligible
   * @return {boolean}
   * @private
   */
  showDiscountToggle_(id, checked, eligible) {
    return id === 'chrome_cart' && checked && eligible;
  }
}

customElements.define(CustomizeModulesElement.is, CustomizeModulesElement);


text:
package com.jarvis.cache.aop.nutz;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import org.nutz.aop.MethodInterceptor;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.aop.SimpleAopMaker;
import org.nutz.ioc.loader.annotation.IocBean;

import com.jarvis.cache.AbstractCacheManager;
import com.jarvis.cache.annotation.CacheDelete;

@IocBean(name = "$aop_delcache")
public class DelCacheAopConfigration extends SimpleAopMaker<CacheDelete> {

	public List<? extends MethodInterceptor> makeIt(CacheDelete cache, Method method, Ioc ioc) {
		return Arrays.asList(new DelCacheAopInterceptor(ioc.get(AbstractCacheManager.class, "cachePointCut"), cache, method));
	}
}


text:
require 'json'

module Sprockets
  module Bower
    # Internal: All supported bower.json files.
    #
    # https://github.com/bower/json/blob/0.4.0/lib/json.js#L7
    POSSIBLE_BOWER_JSONS = ['bower.json', 'component.json', '.bower.json']

    # Internal: Override resolve_alternates to install bower.json behavior.
    #
    # load_path    - String environment path
    # logical_path - String path relative to base
    #
    # Returns nothing.
    def resolve_alternates(load_path, logical_path, &block)
      super

      # bower.json can only be nested one level deep
      if !logical_path.index('/')
        dirname = File.join(load_path, logical_path)
        stat    = self.stat(dirname)

        if stat && stat.directory?
          filenames = POSSIBLE_BOWER_JSONS.map { |basename| File.join(dirname, basename) }
          filename  = filenames.detect { |fn| self.file?(fn) }

          if filename
            read_bower_main(dirname, filename, &block)
          end
        end
      end

      nil
    end

    # Internal: Read bower.json's main directive.
    #
    # dirname  - String path to component directory.
    # filename - String path to bower.json.
    #
    # Returns nothing.
    def read_bower_main(dirname, filename)
      bower = JSON.parse(File.read(filename), create_additions: false)

      case bower['main']
      when String
        yield File.expand_path(bower['main'], dirname)
      when Array
        bower['main'].each do |name|
          yield File.expand_path(name, dirname)
        end
      end
    end
  end
end


text:
<?php

// autoload.php @generated by Composer

require_once __DIR__ . '/composer' . '/autoload_real.php';

return ComposerAutoloaderInit32103958e2b1a92ab9412ae8794971a5::getLoader();


text:
package org.kuali.rice.kim.api.identity.visa;

import org.kuali.rice.core.api.mo.common.GloballyUnique;
import org.kuali.rice.core.api.mo.common.Identifiable;
import org.kuali.rice.core.api.mo.common.Versioned;

/**
 * visa information for a KIM identity
 *
 * @author Kuali Rice Team (kuali-rice@googlegroups.com)
 *
 */
public interface EntityVisaContract extends Versioned, GloballyUnique, Identifiable {

	/**
     * Gets this {@link EntityVisaContract}'s identity id.
     * @return the identity id for this {@link EntityVisaContract}, or null if none has been assigned.
     */
	String getEntityId();

    /**
     * Gets this {@link EntityVisaContract}'s visa type key.
     * @return the visa type key for this {@link EntityVisaContract}, or null if none has been assigned.
     */
	String getVisaTypeKey();

	/**
     * Gets this {@link EntityVisaContract}'s visa entry.
     * @return the visa entry for this {@link EntityVisaContract}, or null if none has been assigned.
     */
	String getVisaEntry();

	/**
     * Gets this {@link EntityVisaContract}'s visa id.
     * @return the visa id for this {@link EntityVisaContract}, or null if none has been assigned.
     */
	String getVisaId();
}


text:
<?php

App::uses('AppModel', 'Model');

class PayPalAppModel extends AppModel {

}


text:
package org.kantega.restmakeover.template;

import org.kantega.restmakeover.api.templates.TemplateRenderer;
import org.kantega.reststop.api.Export;
import org.kantega.reststop.api.Plugin;

@Plugin
public class TemplatesPlugin {

    @Export
    private final TemplateRenderer templateRenderer;

    public TemplatesPlugin() {
        templateRenderer = new VelicityTemplateRenderer();
    }

}


text:
package com.wyldkat.expman.dto;

public class UserDto extends BaseDto {
    private String username;
    private String email;
    private String fullName;
    private String createdDate;

    public UserDto() {
    }

    public UserDto(String username, String email, String fullName, String createdDate) {
        super(null);
        this.username = username;
        this.email = email;
        this.fullName = fullName;
        this.createdDate = createdDate;
    }

    public String getUsername() {
        return username;
    }

    public String getEmail() {
        return email;
    }

    public String getFullName() {
        return fullName;
    }

    public String getCreatedDate() {
        return createdDate;
    }

    public static class UserDtoBuilder {
        private String username;
        private String email;
        private String fullName;
        private String createdDate;

        public UserDtoBuilder setUsername(String username) {
            this.username = username;
            return this;
        }

        public UserDtoBuilder setEmail(String email) {
            this.email = email;
            return this;
        }

        public UserDtoBuilder setFullName(String fullName) {
            this.fullName = fullName;
            return this;
        }

        public UserDtoBuilder setCreatedDate(String createdDate) {
            this.createdDate = createdDate;
            return this;
        }

        public UserDto build() {
            return new UserDto(username, email, fullName, createdDate);
        }
    }

}


text:
[<- Back to Index](../index.md)

This section describes how you can subscribe to events related to the grpc server.

## Table of Contents <!-- omit in toc -->

- [Event Overview](#event-overview)
  - [GrpcServerLifecycleEvent](#grpcserverlifecycleevent)
  - [GrpcServerStartedEvent](#grpcserverstartedevent)
  - [GrpcServerShutdownEvent](#grpcservershutdownevent)
  - [GrpcServerTerminatedEvent](#grpcserverterminatedevent)
- [Subscribing to Events](#subscribing-to-events)

## Additional Topics <!-- omit in toc -->

- [Getting Started](getting-started.md)
- [Configuration](configuration.md)
- [Exception Handling](exception-handling.md)
- [Contextual Data / Scoped Beans](contextual-data.md)
- [Testing the Service](testing.md)
- *Server Events*
- [Security](security.md)

## Event Overview

### GrpcServerLifecycleEvent

Abstract base class for all events related to `GrpcServerLifecycle` changes.

### GrpcServerStartedEvent

This event will be fired after the server has been started.

### GrpcServerShutdownEvent

This event will be fired before the server starts to shutdown. The server will no longer process new requests.

### GrpcServerTerminatedEvent

This event will be fired after the server completed to shutdown. The server will no longer process requests.

## Subscribing to Events

In order to subscribe to any of these events you can just use the `@EventListener` annotation on a public method
in any of your `@Component`s.

````java
@Component
public class MyEventListenerComponent {

    @EventListener
    public void onServerStarted(GrpcServerStartedEvent event) {
        System.out.println("gRPC Server started, listening on address: " + event.getAddress() + ", port: " + event.getPort());
    }

}
````

## Additional Topics <!-- omit in toc -->

- [Getting Started](getting-started.md)
- [Configuration](configuration.md)
- [Exception Handling](exception-handling.md)
- [Contextual Data / Scoped Beans](contextual-data.md)
- [Testing the Service](testing.md)
- *Server Events*
- [Security](security.md)

----------

[<- Back to Index](../index.md)


text:
package io.netty.util.concurrent;

import org.junit.Test;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

@SuppressWarnings("unchecked")
public class DefaultPromiseTest {

    @Test(expected = CancellationException.class)
    public void testCancellationExceptionIsThrownWhenBlockingGet() throws InterruptedException, ExecutionException {
        final Promise<Void> promise = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE);
        promise.cancel(false);
        promise.get();
    }

    @Test(expected = CancellationException.class)
    public void testCancellationExceptionIsThrownWhenBlockingGetWithTimeout() throws InterruptedException,
            ExecutionException, TimeoutException {
        final Promise<Void> promise = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE);
        promise.cancel(false);
        promise.get(1, TimeUnit.SECONDS);
    }

    @Test
    public void testNoStackOverflowErrorWithImmediateEventExecutorA() throws Exception {
        final Promise<Void>[] p = new DefaultPromise[128];
        for (int i = 0; i < p.length; i ++) {
            final int finalI = i;
            p[i] = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE);
            p[i].addListener(new FutureListener<Void>() {
                @Override
                public void operationComplete(Future<Void> future) throws Exception {
                    if (finalI + 1 < p.length) {
                        p[finalI + 1].setSuccess(null);
                    }
                }
            });
        }

        p[0].setSuccess(null);

        for (Promise<Void> a: p) {
            assertThat(a.isSuccess(), is(true));
        }
    }

    @Test
    public void testNoStackOverflowErrorWithImmediateEventExecutorB() throws Exception {
        final Promise<Void>[] p = new DefaultPromise[128];
        for (int i = 0; i < p.length; i ++) {
            final int finalI = i;
            p[i] = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE);
            p[i].addListener(new FutureListener<Void>() {
                @Override
                public void operationComplete(Future<Void> future) throws Exception {
                    DefaultPromise.notifyListener(ImmediateEventExecutor.INSTANCE, future, new FutureListener<Void>() {
                        @Override
                        public void operationComplete(Future<Void> future) throws Exception {
                            if (finalI + 1 < p.length) {
                                p[finalI + 1].setSuccess(null);
                            }
                        }
                    });
                }
            });
        }

        p[0].setSuccess(null);

        for (Promise<Void> a: p) {
            assertThat(a.isSuccess(), is(true));
        }
    }

    @Test
    public void testListenerNotifyOrder() throws Exception {
        EventExecutor executor = new TestEventExecutor();
        try {
            final BlockingQueue<FutureListener<Void>> listeners = new LinkedBlockingQueue<FutureListener<Void>>();
            int runs = 100000;

            for (int i = 0; i < runs; i++) {
                final Promise<Void> promise = new DefaultPromise<Void>(executor);
                final FutureListener<Void> listener1 = new FutureListener<Void>() {
                    @Override
                    public void operationComplete(Future<Void> future) throws Exception {
                        listeners.add(this);
                    }
                };
                final FutureListener<Void> listener2 = new FutureListener<Void>() {
                    @Override
                    public void operationComplete(Future<Void> future) throws Exception {
                        listeners.add(this);
                    }
                };
                final FutureListener<Void> listener4 = new FutureListener<Void>() {
                    @Override
                    public void operationComplete(Future<Void> future) throws Exception {
                        listeners.add(this);
                    }
                };
                final FutureListener<Void> listener3 = new FutureListener<Void>() {
                    @Override
                    public void operationComplete(Future<Void> future) throws Exception {
                        listeners.add(this);
                        future.addListener(listener4);
                    }
                };

                GlobalEventExecutor.INSTANCE.execute(new Runnable() {
                    @Override
                    public void run() {
                        promise.setSuccess(null);
                    }
                });

                promise.addListener(listener1).addListener(listener2).addListener(listener3);

                assertSame("Fail 1 during run " + i + " / " + runs, listener1, listeners.take());
                assertSame("Fail 2 during run " + i + " / " + runs, listener2, listeners.take());
                assertSame("Fail 3 during run " + i + " / " + runs, listener3, listeners.take());
                assertSame("Fail 4 during run " + i + " / " + runs, listener4, listeners.take());
                assertTrue("Fail during run " + i + " / " + runs, listeners.isEmpty());
            }
        } finally {
            executor.shutdownGracefully(0, 0, TimeUnit.SECONDS).sync();
        }
    }

    @Test
    public void testListenerNotifyLater() throws Exception {
        // Testing first execution path in DefaultPromise
        testListenerNotifyLater(1);

        // Testing second execution path in DefaultPromise
        testListenerNotifyLater(2);
    }

    @Test(timeout = 2000)
    public void testPromiseListenerAddWhenCompleteFailure() throws Exception {
        testPromiseListenerAddWhenComplete(fakeException());
    }

    @Test(timeout = 2000)
    public void testPromiseListenerAddWhenCompleteSuccess() throws Exception {
        testPromiseListenerAddWhenComplete(null);
    }

    @Test(timeout = 2000)
    public void testLateListenerIsOrderedCorrectlySuccess() throws InterruptedException {
        testLateListenerIsOrderedCorrectly(null);
    }

    @Test(timeout = 2000)
    public void testLateListenerIsOrderedCorrectlyFailure() throws InterruptedException {
        testLateListenerIsOrderedCorrectly(fakeException());
    }

    /**
     * This test is mean to simulate the following sequence of events, which all take place on the I/O thread:
     *

     *
A write is done

     *
The write operation completes, and the promise state is changed to done

     *
A listener is added to the return from the write. The {@link FutureListener#operationComplete()} updates
     * state which must be invoked before the response to the previous write is read.

     *
The write operation

     *

     */
    private static void testLateListenerIsOrderedCorrectly(Throwable cause) throws InterruptedException {
        final EventExecutor executor = new TestEventExecutor();
        try {
            final AtomicInteger state = new AtomicInteger();
            final CountDownLatch latch1 = new CountDownLatch(1);
            final CountDownLatch latch2 = new CountDownLatch(2);
            final Promise<Void> promise = new DefaultPromise<Void>(executor);

            // Add a listener before completion so "lateListener" is used next time we add a listener.
            promise.addListener(new FutureListener<Void>() {
                @Override
                public void operationComplete(Future<Void> future) throws Exception {
                    assertTrue(state.compareAndSet(0, 1));
                }
            });

            // Simulate write operation completing, which will execute listeners in another thread.
            if (cause == null) {
                promise.setSuccess(null);
            } else {
                promise.setFailure(cause);
            }

            // Add a "late listener"
            promise.addListener(new FutureListener<Void>() {
                @Override
                public void operationComplete(Future<Void> future) throws Exception {
                    assertTrue(state.compareAndSet(1, 2));
                    latch1.countDown();
                }
            });

            // Wait for the listeners and late listeners to be completed.
            latch1.await();
            assertEquals(2, state.get());

            // This is the important listener. A late listener that is added after all late listeners
            // have completed, and needs to update state before a read operation (on the same executor).
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    promise.addListener(new FutureListener<Void>() {
                        @Override
                        public void operationComplete(Future<Void> future) throws Exception {
                            assertTrue(state.compareAndSet(2, 3));
                            latch2.countDown();
                        }
                    });
                }
            });

            // Simulate a read operation being queued up in the executor.
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    // This is the key, we depend upon the state being set in the next listener.
                    assertEquals(3, state.get());
                    latch2.countDown();
                }
            });

            latch2.await();
        } finally {
            executor.shutdownGracefully(0, 0, TimeUnit.SECONDS).sync();
        }
    }

    private static void testPromiseListenerAddWhenComplete(Throwable cause) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);
        final Promise<Void> promise = new DefaultPromise<Void>(ImmediateEventExecutor.INSTANCE);
        promise.addListener(new FutureListener<Void>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                promise.addListener(new FutureListener<Void>() {
                    @Override
                    public void operationComplete(Future<Void> future) throws Exception {
                        latch.countDown();
                    }
                });
            }
        });
        if (cause == null) {
            promise.setSuccess(null);
        } else {
            promise.setFailure(cause);
        }
        latch.await();
    }

    private static void testListenerNotifyLater(final int numListenersBefore) throws Exception {
        EventExecutor executor = new TestEventExecutor();
        int expectedCount = numListenersBefore + 2;
        final CountDownLatch latch = new CountDownLatch(expectedCount);
        final FutureListener<Void> listener = new FutureListener<Void>() {
            @Override
            public void operationComplete(Future<Void> future) throws Exception {
                latch.countDown();
            }
        };
        final Promise<Void> promise = new DefaultPromise<Void>(executor);
        executor.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < numListenersBefore; i++) {
                    promise.addListener(listener);
                }
                promise.setSuccess(null);

                GlobalEventExecutor.INSTANCE.execute(new Runnable() {
                    @Override
                    public void run() {
                        promise.addListener(listener);
                    }
                });
                promise.addListener(listener);
            }
        });

        assertTrue("Should have notifed " + expectedCount + " listeners", latch.await(5, TimeUnit.SECONDS));
        executor.shutdownGracefully().sync();
    }

    private static final class TestEventExecutor extends SingleThreadEventExecutor {
        TestEventExecutor() {
            super(null, new DefaultExecutorServiceFactory(TestEventExecutor.class).newExecutorService(1), true);
        }

        @Override
        protected void run() {
            Runnable task = takeTask();
            if (task != null) {
                task.run();
                updateLastExecutionTime();
            }

            if (confirmShutdown()) {
                cleanupAndTerminate(true);
            } else {
                scheduleExecution();
            }
        }
    }

    private static RuntimeException fakeException() {
        return new RuntimeException("fake exception");
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.sample</groupId>
	<artifactId>firstboot</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.2.0.RELEASE</version>
	</parent>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>Camden.RELEASE</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>


text:
#ifndef WEBRTC_MODULES_AUDIO_CODING_CODECS_G722_AUDIO_ENCODER_G722_H_
#define WEBRTC_MODULES_AUDIO_CODING_CODECS_G722_AUDIO_ENCODER_G722_H_

#include <memory>

#include "webrtc/api/audio_codecs/audio_format.h"
#include "webrtc/base/buffer.h"
#include "webrtc/base/constructormagic.h"
#include "webrtc/modules/audio_coding/codecs/audio_encoder.h"
#include "webrtc/modules/audio_coding/codecs/g722/g722_interface.h"

namespace webrtc {

struct CodecInst;

class AudioEncoderG722 final : public AudioEncoder {
 public:
  struct Config {
    bool IsOk() const;

    int payload_type = 9;
    int frame_size_ms = 20;
    size_t num_channels = 1;
  };

  explicit AudioEncoderG722(const Config& config);
  explicit AudioEncoderG722(const CodecInst& codec_inst);
  AudioEncoderG722(int payload_type, const SdpAudioFormat& format);
  ~AudioEncoderG722() override;

  static constexpr const char* GetPayloadName() { return "G722"; }
  static rtc::Optional<AudioCodecInfo> QueryAudioEncoder(
      const SdpAudioFormat& format);

  int SampleRateHz() const override;
  size_t NumChannels() const override;
  int RtpTimestampRateHz() const override;
  size_t Num10MsFramesInNextPacket() const override;
  size_t Max10MsFramesInAPacket() const override;
  int GetTargetBitrate() const override;
  void Reset() override;

 protected:
  EncodedInfo EncodeImpl(uint32_t rtp_timestamp,
                         rtc::ArrayView<const int16_t> audio,
                         rtc::Buffer* encoded) override;

 private:
  // The encoder state for one channel.
  struct EncoderState {
    G722EncInst* encoder;
    std::unique_ptr<int16_t[]> speech_buffer;   // Queued up for encoding.
    rtc::Buffer encoded_buffer;                 // Already encoded.
    EncoderState();
    ~EncoderState();
  };

  size_t SamplesPerChannel() const;

  const size_t num_channels_;
  const int payload_type_;
  const size_t num_10ms_frames_per_packet_;
  size_t num_10ms_frames_buffered_;
  uint32_t first_timestamp_in_buffer_;
  const std::unique_ptr<EncoderState[]> encoders_;
  rtc::Buffer interleave_buffer_;
  RTC_DISALLOW_COPY_AND_ASSIGN(AudioEncoderG722);
};

}  // namespace webrtc
#endif  // WEBRTC_MODULES_AUDIO_CODING_CODECS_G722_AUDIO_ENCODER_G722_H_


text:
import React from 'react';
import Snackbar from 'material-ui/Snackbar';
import RaisedButton from 'material-ui/RaisedButton';

export default class SnackbarExampleTwice extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      message: 'Event 1 added to your calendar',
      open: false,
    };
    this.timer = undefined;
  }

  componentWillUnMount() {
    clearTimeout(this.timer);
  }

  handleClick = () => {
    this.setState({
      open: true,
    });

    this.timer = setTimeout(() => {
      this.setState({
        message: `Event ${Math.round(Math.random() * 100)} added to your calendar`,
      });
    }, 1500);
  };

  handleRequestClose = () => {
    this.setState({
      open: false,
    });
  };

  render() {
    return (
      <div>
        <RaisedButton
          onClick={this.handleClick}
          label="Add to my calendar two times"
        />
        <Snackbar
          open={this.state.open}
          message={this.state.message}
          action="undo"
          autoHideDuration={3000}
          onRequestClose={this.handleRequestClose}
        />
      </div>
    );
  }
}


text:
import { module } from 'angular';
import { react2angular } from 'react2angular';

import SlackChannelSelector from './SlackChannelSelector';
import { withErrorBoundary } from '../presentation/SpinErrorBoundary';

export const SLACK_COMPONENT = 'spinnaker.application.slackChannelSelector.component';

module(SLACK_COMPONENT, []).component(
  'slackChannelSelector',
  react2angular(withErrorBoundary(SlackChannelSelector, 'slackChannelSelector'), ['channel', 'callback']),
);


text:
package com.b2international.snowowl.snomed.datastore.request.rf2.importer;

import java.util.Map;
import java.util.Set;

import com.b2international.collections.PrimitiveMaps;
import com.b2international.collections.longs.LongKeyMap;
import com.b2international.collections.longs.LongSet;
import com.b2international.snowowl.core.ResourceURI;
import com.b2international.snowowl.core.domain.BranchContext;
import com.b2international.snowowl.core.request.io.ImportDefectAcceptor.ImportDefectBuilder;
import com.b2international.snowowl.core.uri.ComponentURI;
import com.google.common.collect.ImmutableSet.Builder;

/**
 * An {@link Rf2EffectiveTimeSlice} implementation that ignores every method call and it does not register the given read RF2 rows at all inside it, essentially skips all content.
 *
 * @since 8.0
 */
final class IgnoredRf2EffectiveTimeSlice extends BaseRf2EffectiveTimeSlice {

	private final LongKeyMap<LongSet> emptyDependencies = PrimitiveMaps.newLongKeyOpenHashMap();
	private final LongKeyMap<Set<String>> emptyMembers = PrimitiveMaps.newLongKeyOpenHashMap();

	private final String message;

	public IgnoredRf2EffectiveTimeSlice(String effectiveTimeToIgnore, String message) {
		super(effectiveTimeToIgnore);
		this.message = message;
	}

	@Override
	public void register(String containerId, Rf2ContentType<?> type, String[] values, ImportDefectBuilder defectBuilder) {
	}

	@Override
	public void registerDependencies(long componentId, LongSet dependencies) {
	}

	@Override
	public void flush() {
	}

	@Override
	public Map<String, String[]> getContent() {
		return Map.of();
	}

	@Override
	public void unregisterDependencies(String componentId) {
	}

	@Override
	public LongKeyMap<LongSet> getDependenciesByComponent() {
		return emptyDependencies;
	}

	@Override
	public LongKeyMap<Set<String>> getMembersByReferencedComponent() {
		return emptyMembers;
	}

	@Override
	public void doImport(BranchContext context, ResourceURI codeSystemUri, Rf2ImportConfiguration importConfig, Builder<ComponentURI> visitedComponents) throws Exception {
		context.log().info(message);
	}

}