text:
package org.ssgwt.client.ui.datagrid.column;

import org.ssgwt.client.i18n.DateTimeFormat;
import org.ssgwt.client.i18n.SSDate;
import org.ssgwt.client.ui.datagrid.column.ImageHoverColumn.AbstractImageColumnPopup;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.Window;

/**
 * A text cell that will display text in a cell with a tooltip with the
 * same text value as the cell
 *
 * @author Ruan Naude <nauderuan777@gmail.com>
 * @since 14 March 2013
 */
public class SSTextCell<T> extends AbstractCell<String> implements HasHandlers {

    /**
     * The format that the date is currently displayed in
     */
    String sDateFormat = "";

    /**
     * The format that the date value should be displayed in
     */
    String sDateDisplayTooltipFormat = "";

    /**
     * String used to store the styleName
     */
    String styleName = "";

    /**
     * The popup the will be displayed on hover
     */
    private AbstractImageColumnPopup<T> popup;

    /**
     * The handler manager used to handle events
     */
    private HandlerManager handlerManager;

    /**
     * The parent column
     */
    private SSTextColumn<T> column;

    /**
     * The parent element of the Cell
     */
    private Element parent;

    /**
     * The mouse over event cont
     */
    private final static String MOUSE_OVER = "mouseover";

    /**
     * The mouse out event cont
     */
    private final static String MOUSE_OUT = "mouseout";

    /**
     * Instance of the template
     */
    private static Template template;

    /**
     * The left position of the popup
     */
    int popupLeftPosition = 0;

    /**
     * The top position of the popup
     */
    int popupTopPosition = 0;

    /**
     * Template providing SafeHTML templates to build the widget
     *
     * @author Michael Barnard <michael.barnard@a24group.com>
     * @since  11 June 2013
     */
    interface Template extends SafeHtmlTemplates {
        @Template("
")
        SafeHtml openTag(String style, String title);

        @Template("
")
        SafeHtml closeTag();
    }

    /**
     * Class Constructor
     *
     * @author Michael Barnard <michael.barnard@a24group.com>
     * @since  10 June 2013
     */
    public SSTextCell() {
        super();
        if (template == null) {
            template = GWT.create(Template.class);
        }
    }

    /**
     * Class Constructor
     *
     * @author Michael Barnard <michael.barnard@a24group.com>
     * @since  20 June 2013
     *
     * @param sCustomStyle The style used for customisation
     */
    public SSTextCell(String sCustomStyle) {
        super();
        this.setStyleName(sCustomStyle);
    }

    /**
     * Class Constructor
     *
     * @author Michael Barnard <michael.barnard@a24group.com>
     * @since  10 June 2013
     *
     * @param sDateFormat - The format that the date is currently displayed in
     * @param sDateDisplayTooltip - The date format that you want to have the tooltip displayed
     */
    public SSTextCell(String sDateFormat, String sDateDisplayTooltip) {
        this();
        this.sDateFormat = sDateFormat;
        this.sDateDisplayTooltipFormat = sDateDisplayTooltip;
    }

    /**
     * Class Constructor for text cell with custom tool tip
     *
     * @author Alec Erasmus <alec.erasmus@a24group.com>
     * @since  17 June 2013
     *
     * @param popup - The custom popup to display on hover
     */
    public SSTextCell(AbstractImageColumnPopup<T> popup) {
        super(MOUSE_OVER, MOUSE_OUT);
        if (template == null) {
            template = GWT.create(Template.class);
        }
        this.popup = popup;
        this.handlerManager = new HandlerManager(this);
    }

    /**
     * Setter for the parent column
     *
     * @author Alec Erasmus <alec.erasmus@a24group.com>
     * @since  27 june 2013
     *
     * @param column - The parent column
     */
    public void setParentColumn(SSTextColumn<T> column) {
        this.column = column;
    }

    /**
     * This will create a label with text and a tooltip with the same text value
     *
     * @author Ruan Naude <nauderuan777@gmail.com>
     * @author Saurabh Chawla <saurabh.chawla@a24group.com>
     * @since 14 March 2013
     *
     * @param context -The context the cell is in
     * @param value - The value to be added in the cell
     * @param sb -The safe html builder.
     */
    @Override
    public void render(Context context, String value, SafeHtmlBuilder sb) {
        if (value == null) {
            value = "";
        }

        String tooltip = value;
        //html encoding the string
        value = SafeHtmlUtils.fromString(value).asString();

        if (this.sDateDisplayTooltipFormat != null && this.sDateDisplayTooltipFormat != ""
            && this.sDateFormat != null && this.sDateFormat != "") {
            try {
                // Convert date from sDateFormat to sDateDisplayTooltipFormat
                SSDate date = DateTimeFormat.getFormat(this.sDateFormat).parse(value);
                tooltip = date.format(this.sDateDisplayTooltipFormat);
            } catch (Exception e){
                // Ignore exception, resulting in default tooltip
            }
        }

        sb.append(template.openTag(styleName, tooltip));
        sb.appendHtmlConstant(value.replace(" ", " "));
        sb.append(template.closeTag());
    }

    /**
     * Handle a browser event that took place within the cell. The default
     * implementation returns null.
     *
     * @author Alec Erasmus <alec.erasmus@a24group.com>
     * @since  17 June 2013
     *
     * @param context - the {@link Context} of the cell
     * @param parent - the parent Element
     * @param value - the value associated with the cell
     * @param event - the native browser event
     * @param valueUpdater - a {@link ValueUpdater}, or null if not specified
     */
    @Override
    public void onBrowserEvent(
        Context context,
        Element parent,
        String value,
        NativeEvent event,
        ValueUpdater<String> valueUpdater
    ) {
        // All the already browser event should still behave as it use to
        super.onBrowserEvent(context, parent, value, event, valueUpdater);

        this.parent = parent;
        Element imageElement = getLabelElement(parent);
        if (event.getEventTarget().equals(imageElement)) {
            if (MOUSE_OVER.equals(event.getType())) { // The event is MOUSE_OVER
                // Display the popup only if it is allowed.
                if (column.showPopup(column.getRowData())) {
                    displayPopup();
                }
            } else if (MOUSE_OUT.equals(event.getType())) { // The event is MOUSE_OUT
                // Close the popup
                hidePopup();
            }
        }
    };

    /**
     * Displays the popup relative to the cell
     *
     * @author Alec Erasmus <alec.erasmus@a24group.com>
     * @since  17 June 2013
     */
    private void displayPopup() {
        this.popup.center();
        this.popup.setData(column.getRowData());

        calculatePopupPosition();

        this.popup.setPopupPosition(
            popupLeftPosition,
            popupTopPosition
        );
    }

    /**
     * Calculate the position of the popup.
     *
     * @author Ryno Hartzer <ryno.hartzer@a24group.com>
     * @since  19 June 2013
     */
    private void calculatePopupPosition() {
        int windowHeight = Window.getClientHeight() - 10;
        int windowWidth = Window.getClientWidth() - 10;
        boolean topPointer = false;

        // Now we need to determine the x and y position of the pointer
        int xPointerPosition = this.popup.getOffsetWidth() / 6;
        // -1 is used as it should be shown 1px above/below the border line of the popup
        int yPointerPosition = this.popup.getOffsetHeight() - 1;
        int parentCenterXPosition = getLabelElement(this.parent).getAbsoluteLeft()
            + (getLabelElement(this.parent).getOffsetWidth() / 3);

        // By default show the popup upwards if possible
        if (this.popup.getOffsetHeight() + this.parent.getAbsoluteTop() + 10 <= windowHeight) {
            popupTopPosition = this.parent.getAbsoluteTop() - this.popup.getOffsetHeight() - 10;
            topPointer = false;
        } else {
            popupTopPosition = this.parent.getAbsoluteTop() + this.parent.getOffsetHeight() + 10;
            // -10 as we used +10 above. -2 is needed to get the pointer to show perfectly
            yPointerPosition = -12;
            topPointer = true;
        }
        // maxX will be the reference point plus the width of the popup.
        // Used to determine if we are 'out' of the screen horizontally
        int maxX = this.parent.getAbsoluteLeft() + this.popup.getOffsetWidth();

        // We cannot show the popup as it is out of the screen.
        if (maxX >= windowWidth) {
            // parentCenterXPosition is the middle x position of the parent image.
            // xPointerPosition is a 1/6 of the popup width. Multiply this by 5
            // so that we get 5/6.
            // Subtract 6 to align the center of the pointer with the center of the parent image
            popupLeftPosition = parentCenterXPosition - (xPointerPosition * 5) - 6;
            this.popup.setPointerPosition(xPointerPosition * 5, yPointerPosition, topPointer);
        } else {
            popupLeftPosition = parentCenterXPosition - (xPointerPosition) - 6;
            this.popup.setPointerPosition(xPointerPosition, yPointerPosition, topPointer);
        }
    }

    /**
     * Hides the popup
     *
     * @author Alec Erasmus <alec.erasmus@a24group.com>
     * @since  17 June 2013
     */
    private void hidePopup() {
        this.popup.hide();
    }

    /**
     * Retrieves the element of the label displayed in the cell
     *
     * @author Alec Erasmus <alec.erasmus@a24group.com>
     * @since  17 June 2013
     *
     * @param parent - The top level container of the Cell
     *
     * @return The element object that represents the label in the cell
     */
    protected Element getLabelElement(Element parent) {
        return parent.getFirstChildElement();
    }

    /**
     * This is used to fire an event
     *
     * @author Alec Erasmus <alec.erasmus@a24group.com>
     * @since  17 June 2013
     *
     * @param event - The event that needs to be fired
     */
    @Override
    public void fireEvent(GwtEvent<?> event) {
        handlerManager.fireEvent(event);
    }

    /**
     * Used to set the style name for the cell
     *
     * @author Michael Barnard <michael.barnard@a24group.com>
     * @since  20 June 2013
     *
     * @param styleName The custom style for the internal div tag
     *
     * @return void
     */
    public void setStyleName(String styleName) {
        this.styleName = styleName;
    }

}


text:
 /************************************************************************/
 /*                                                                      */
 /*                Centre for Speech Technology Research                 */
 /*                     University of Edinburgh, UK                      */
 /*                       Copyright (c) 1996,1997                        */
 /*                        All Rights Reserved.                          */
 /*                                                                      */
 /*  Permission is hereby granted, free of charge, to use and distribute */
 /*  this software and its documentation without restriction, including  */
 /*  without limitation the rights to use, copy, modify, merge, publish, */
 /*  distribute, sublicense, and/or sell copies of this work, and to     */
 /*  permit persons to whom this work is furnished to do so, subject to  */
 /*  the following conditions:                                           */
 /*   1. The code must retain the above copyright notice, this list of   */
 /*      conditions and the following disclaimer.                        */
 /*   2. Any modifications must be clearly marked as such.               */
 /*   3. Original authors' names are not deleted.                        */
 /*   4. The authors' names are not used to endorse or promote products  */
 /*      derived from this software without specific prior written       */
 /*      permission.                                                     */
 /*                                                                      */
 /*  THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK       */
 /*  DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING     */
 /*  ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT  */
 /*  SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE    */
 /*  FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES   */
 /*  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN  */
 /*  AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,         */
 /*  ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF      */
 /*  THIS SOFTWARE.                                                      */
 /*                                                                      */
 /*************************************************************************/

#ifndef __MODULEDESCRIPTION_H__
#define __MODULEDESCRIPTION_H__

#include <cstdio>
#include <iostream>

using namespace std;

#include "EST_String.h"

/** Machine readable descriptions of modules. Useful for help messages
  * and for verifying that a  set of modules should work together.
  *
  * This is a struct rather than a class so that it can be initialised
  * in the source of the module.
  * @author Richard Caley <rjc@cstr,ed,ac,uk>
  * @version $Id: ModuleDescription.h,v 1.4 2014/11/25 14:32:04 robert Exp $
  */

struct ModuleDescription {

  /**@name limits */
//@{
/// Number of lines of descriptive text.
#define MD_MAX_DESCRIPTION_LINES (10)
/// Space for input streams.
#define MD_MAX_INPUT_STREAMS (5)
/// Space for optional streams.
#define MD_MAX_OPTIONAL_STREAMS (5)
/// Space for output streams.
#define MD_MAX_OUTPUT_STREAMS (5)
/// Space for parameters.
#define MD_MAX_PARAMETERS (10)
//@}

/**@name Parameter types
  * Use these for types to avoid typoes and to allow for a cleverer system
  * at a later date.
  */
//@{
/// t or nil
#define mpt_bool	"BOOL"
/// Positive integer
#define mpt_natnum	"NATNUM"
/// Integer
#define mpt_int		"INT"
/// Floating point number
#define mpt_float	"FLOAT"
/// Any string
#define mpt_string	"STRING"
/// A UnitDatabase
#define mpt_unitdatabase "UNITDATABASE"
/// Anything
#define mpt_other	"OTHER"
//@}

  /// name of module
  const char * name;
  /// version number of module
  float version;
  /// where it comes from
  const char * organisation;
  /// person(s) responsible
  const char * author;

  /// general description
  const char * description[MD_MAX_DESCRIPTION_LINES];

  /// streams affected.
  struct stream_parameter {
    /// default stream name
    const char * name;
    /// what itis used for
    const char * description;
  };

  /// Streams which must have values when the module is called.
  struct stream_parameter input_streams[MD_MAX_INPUT_STREAMS];
  /// Streams which may or not be defined.
  struct stream_parameter optional_streams[MD_MAX_OPTIONAL_STREAMS];
  /// Streams which will be defined after the module has run.
  struct stream_parameter output_streams[MD_MAX_OUTPUT_STREAMS];

  /// Record for a parameter.
  struct parameter {
    /// Name of parameter
    const char * name;
    /// Type of value.
    const char * type;
    /// Default value assumed.
    const char * default_val;
    /// Human readable description of effect.
    const char * description;
  };
  /// Parameters which effect the module.
  struct parameter parameters[MD_MAX_PARAMETERS];

  /// Create human readable string from description.
  static EST_String to_string(const ModuleDescription &desc);
  /// Create a module description, initialising it properly.
  static struct ModuleDescription *create();
  /// Print the description to the strream.
  static ostream &print(ostream &s, const ModuleDescription &desc);

  static int print(FILE *s, const ModuleDescription &desc);

};

/// Output operator for descriptions.
ostream &operator << (ostream &stream, const ModuleDescription &desc);

//VAL_REGISTER_CLASS_DCLS(moddesc,ModuleDescription) // clang/llvm complains about this (Rob)
//SIOD_REGISTER_CLASS_DCLS(moddesc,ModuleDescription)
VAL_REGISTER_TYPE_DCLS(moddesc,ModuleDescription)
SIOD_REGISTER_TYPE_DCLS(moddesc,ModuleDescription)

#endif

redpajama_set_name: RedPajamaGithub


text:
// This code is auto-generated, do not modify
package com.spectralogic.ds3client.commands.spectrads3;

import com.spectralogic.ds3client.networking.HttpVerb;
import com.spectralogic.ds3client.commands.interfaces.AbstractRequest;
import com.google.common.net.UrlEscapers;

public class GetS3TargetReadPreferenceSpectraS3Request extends AbstractRequest {

    // Variables

    private final String s3TargetReadPreference;

    // Constructor

    public GetS3TargetReadPreferenceSpectraS3Request(final String s3TargetReadPreference) {
        this.s3TargetReadPreference = s3TargetReadPreference;

    }

    @Override
    public HttpVerb getVerb() {
        return HttpVerb.GET;
    }

    @Override
    public String getPath() {
        return "/_rest_/s3_target_read_preference/" + s3TargetReadPreference;
    }

    public String getS3TargetReadPreference() {
        return this.s3TargetReadPreference;
    }

}


text:
import re

from trac.config import get_configinfo
from trac.core import *
from trac.loader import get_plugin_info
from trac.perm import IPermissionRequestor
from trac.util.html import tag
from trac.util.translation import _
from trac.web.api import IRequestHandler
from trac.web.chrome import Chrome, INavigationContributor, accesskey

class AboutModule(Component):
    """"About Trac" page provider, showing version information from
    third-party packages, as well as configuration information."""

    required = True

    implements(INavigationContributor, IPermissionRequestor, IRequestHandler)

    # INavigationContributor methods

    def get_active_navigation_item(self, req):
        return 'about'

    def get_navigation_items(self, req):
        yield ('metanav', 'about',
               tag.a(_("About Trac"), href=req.href.about(),
                     accesskey=accesskey(req, 9)))

    # IPermissionRequestor methods

    def get_permission_actions(self):
        return ['CONFIG_VIEW']

    # IRequestHandler methods

    def match_request(self, req):
        return re.match(r'/about(?:_trac)?$', req.path_info)

    def process_request(self, req):
        data = {'systeminfo': None, 'plugins': None,
                'config': None, 'interface': None}

        if 'CONFIG_VIEW' in req.perm('config', 'systeminfo'):
            # Collect system information
            data['system_info'] = self.env.system_info
            Chrome(self.env).add_jquery_ui(req)

        if 'CONFIG_VIEW' in req.perm('config', 'plugins'):
            # Collect plugin information
            data['plugins'] = get_plugin_info(self.env)

        if 'CONFIG_VIEW' in req.perm('config', 'interface'):
            data['interface'] = \
                Chrome(self.env).get_interface_customization_files()

        if 'CONFIG_VIEW' in req.perm('config', 'ini'):
            # Collect config information
            data['config'] = get_configinfo(self.env)

        return 'about.html', data


text:
using namespace std;

Edge::Edge() {

	directFace = Face();
	indirectFace = Face();

	return;
}

Edge::Edge(Face initDirect, Face initIndirect) {

	directFace = initDirect;
	indirectFace = initIndirect;

	return;
}

Edge::Edge(const Edge &other) {

	directFace = other.directFace;
	indirectFace = other.indirectFace;

	return;
}

Face Edge::getDFace() {

	return directFace;
}

Face Edge::getIFace() {

	return indirectFace;
}

void Edge::sayColor() {

	cout << "Edge direct color: "
	     << directFace.getColor() << " - "
			 << COLORS[directFace.getColor()] << endl;

	cout << "Edge indirect color: "
				<< indirectFace.getColor() << " - "
				<< COLORS[indirectFace.getColor()] << endl;

	return;
}


text:
+++
Title = "Aaron Rinehart"
#Twitter = "Ana_M_Medina"
image = "Aaron.png"
type = "speaker"
linktitle = "aaron-rinehart"
#Github = "AnaMMedina21"
#Website = ""
+++

CTO at Verica, Former Big Deal at UnitedHealth Group, NASA, DHS. Pioneered Chaos Engineering in Cyber Security, 1st Security Chaos Engineering OSS ChaoSlingr.

Aaron has been expanding the possibilities of Chaos Engineering in its application to other safety- critical portions of the IT domain notably cybersecurity. He began pioneering the application of Security in Chaos Engineering during his tenure as the Chief Security Architect at the largest private healthcare company in the world, UnitedHealth Group (UHG). While at UHG Aaron released ChaoSlingr, one of the first open source software releases focused on using Chaos Engineering in cybersecurity to build more resilient systems. Aaron recently founded the first Chaos Engineering Meetup in Washington DC and is a frequent author, consultant and speaker in the space.


text:
FOUNDATION_EXPORT double Pods_WeakUniqueCollection_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_WeakUniqueCollection_TestsVersionString[];


text:
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.execution;

import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.externalSystem.model.ExternalSystemException;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.StreamUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.*;
import com.intellij.util.containers.ContainerUtil;
import org.gradle.initialization.BuildLayoutParameters;
import org.gradle.internal.nativeintegration.services.NativeServices;
import org.gradle.process.internal.JvmOptions;
import org.gradle.tooling.*;
import org.gradle.tooling.internal.consumer.DefaultGradleConnector;
import org.gradle.tooling.model.build.BuildEnvironment;
import org.gradle.util.GradleVersion;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.service.project.DistributionFactoryExt;
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext;
import org.jetbrains.plugins.gradle.settings.DistributionType;
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings;
import org.jetbrains.plugins.gradle.tooling.internal.init.Init;
import org.jetbrains.plugins.gradle.util.GradleConstants;
import org.jetbrains.plugins.gradle.util.GradleEnvironment;
import org.jetbrains.plugins.gradle.util.GradleUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Denis Zhdanov
 * @since 3/14/13 5:11 PM
 */
public class GradleExecutionHelper {

  private static final Logger LOG = Logger.getInstance(GradleExecutionHelper.class);

  @SuppressWarnings("MethodMayBeStatic")
  @NotNull
  public <T> ModelBuilder<T> getModelBuilder(@NotNull Class<T> modelType,
                                             @NotNull final ExternalSystemTaskId id,
                                             @Nullable GradleExecutionSettings settings,
                                             @NotNull ProjectConnection connection,
                                             @NotNull ExternalSystemTaskNotificationListener listener) {
    ModelBuilder<T> result = connection.model(modelType);
    if (settings != null) {
      prepare(result, id, settings, listener, connection);
    }
    return result;
  }

  @SuppressWarnings("MethodMayBeStatic")
  @NotNull
  public BuildLauncher getBuildLauncher(@NotNull final ExternalSystemTaskId id,
                                        @NotNull ProjectConnection connection,
                                        @Nullable GradleExecutionSettings settings,
                                        @NotNull ExternalSystemTaskNotificationListener listener) {
    BuildLauncher result = connection.newBuild();
    if (settings != null) {
      prepare(result, id, settings, listener, connection);
    }
    return result;
  }

  @Nullable
  public static BuildEnvironment getBuildEnvironment(ProjectResolverContext projectResolverContext) {
    return getBuildEnvironment(projectResolverContext.getConnection(),
                               projectResolverContext.getExternalSystemTaskId(),
                               projectResolverContext.getListener(),
                               projectResolverContext.getCancellationTokenSource());
  }

  @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
  public static void prepare(@NotNull LongRunningOperation operation,
                             @NotNull final ExternalSystemTaskId id,
                             @NotNull GradleExecutionSettings settings,
                             @NotNull final ExternalSystemTaskNotificationListener listener,
                             @NotNull ProjectConnection connection) {
    prepare(operation, id, settings, listener, connection, new OutputWrapper(listener, id, true), new OutputWrapper(listener, id, false));
  }

  @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
  public static void prepare(@NotNull LongRunningOperation operation,
                             @NotNull final ExternalSystemTaskId id,
                             @NotNull GradleExecutionSettings settings,
                             @NotNull final ExternalSystemTaskNotificationListener listener,
                             @NotNull ProjectConnection connection,
                             @NotNull final OutputStream standardOutput,
                             @NotNull final OutputStream standardError) {
    Set<String> jvmArgs = settings.getVmOptions();
    BuildEnvironment buildEnvironment = getBuildEnvironment(connection, id, listener);

    String gradleVersion = buildEnvironment != null ? buildEnvironment.getGradle().getGradleVersion() : null;
    if (!jvmArgs.isEmpty()) {
      // merge gradle args e.g. defined in gradle.properties
      Collection<String> merged;
      if (buildEnvironment != null) {
        // the BuildEnvironment jvm arguments of the main build should be used for the 'buildSrc' import
        // to avoid spawning of the second gradle daemon
        List<String> buildJvmArguments = "buildSrc".equals(buildEnvironment.getBuildIdentifier().getRootDir().getName())
                                         ? ContainerUtil.emptyList()
                                         : buildEnvironment.getJava().getJvmArguments();
        merged = mergeJvmArgs(settings.getServiceDirectory(), buildJvmArguments, jvmArgs);
      }
      else {
        merged = jvmArgs;
      }

      // filter nulls and empty strings
      List<String> filteredArgs = ContainerUtil.mapNotNull(merged, s -> StringUtil.isEmpty(s) ? null : s);

      operation.setJvmArguments(ArrayUtil.toStringArray(filteredArgs));
    }

    if (settings.isOfflineWork()) {
      settings.withArgument(GradleConstants.OFFLINE_MODE_CMD_OPTION);
    }

    final Application application = ApplicationManager.getApplication();
    if (application != null && application.isUnitTestMode()) {
      if (!settings.getArguments().contains("--quiet") && !settings.getArguments().contains("--debug")) {
        settings.withArgument("--info");
      }
      settings.withArgument("--recompile-scripts");
    }

    if (!settings.getArguments().isEmpty()) {
      String loggableArgs = StringUtil.join(obfuscatePasswordParameters(settings.getArguments()), " ");
      LOG.info("Passing command-line args to Gradle Tooling API: " + loggableArgs);

      // filter nulls and empty strings
      List<String> filteredArgs = ContainerUtil.mapNotNull(settings.getArguments(), s -> StringUtil.isEmpty(s) ? null : s);

      // TODO remove this replacement when --tests option will become available for tooling API
      replaceTestCommandOptionWithInitScript(filteredArgs);
      operation.withArguments(ArrayUtil.toStringArray(filteredArgs));
    }
    setupEnvironment(operation, settings, gradleVersion, id, listener);

    final String javaHome = settings.getJavaHome();
    if (javaHome != null && new File(javaHome).isDirectory()) {
      operation.setJavaHome(new File(javaHome));
    }

    String buildRootDir = buildEnvironment == null ? null : buildEnvironment.getBuildIdentifier().getRootDir().getPath();
    GradleProgressListener gradleProgressListener = new GradleProgressListener(listener, id, buildRootDir);
    operation.addProgressListener((ProgressListener)gradleProgressListener);
    operation.addProgressListener((org.gradle.tooling.events.ProgressListener)gradleProgressListener);
    operation.setStandardOutput(standardOutput);
    operation.setStandardError(standardError);
    InputStream inputStream = settings.getUserData(ExternalSystemRunConfiguration.RUN_INPUT_KEY);
    if (inputStream != null) {
      operation.setStandardInput(inputStream);
    }
  }

  private static void setupEnvironment(@NotNull LongRunningOperation operation,
                                       @NotNull GradleExecutionSettings settings,
                                       @Nullable String gradleVersion,
                                       ExternalSystemTaskId taskId,
                                       ExternalSystemTaskNotificationListener listener) {
    boolean isEnvironmentCustomizationSupported =
      gradleVersion != null && GradleVersion.version(gradleVersion).getBaseVersion().compareTo(GradleVersion.version("3.5")) >= 0;
    if (!isEnvironmentCustomizationSupported) {
      if (!settings.isPassParentEnvs() || !settings.getEnv().isEmpty()) {
        listener.onTaskOutput(taskId, String.format(
          "The version of Gradle you are using%s does not support the environment variables customization feature. " +
          "Support for this is available in Gradle 3.5 and all later versions.\n",
          gradleVersion == null ? "" : (" (" + gradleVersion + ")")), false);
      }
      return;
    }
    GeneralCommandLine commandLine = new GeneralCommandLine();
    commandLine.withEnvironment(settings.getEnv());
    commandLine.withParentEnvironmentType(
      settings.isPassParentEnvs() ? GeneralCommandLine.ParentEnvironmentType.CONSOLE : GeneralCommandLine.ParentEnvironmentType.NONE);
    Map<String, String> effectiveEnvironment = commandLine.getEffectiveEnvironment();
    operation.setEnvironmentVariables(effectiveEnvironment);
  }

  public <T> T execute(@NotNull String projectPath, @Nullable GradleExecutionSettings settings, @NotNull Function<ProjectConnection, T> f) {

    final String projectDir;
    final File projectPathFile = new File(projectPath);
    if (projectPathFile.isFile() && projectPath.endsWith(GradleConstants.EXTENSION)
        && projectPathFile.getParent() != null) {
      projectDir = projectPathFile.getParent();
    }
    else {
      projectDir = projectPath;
    }

    String userDir = null;
    if (!GradleEnvironment.ADJUST_USER_DIR) {
      try {
        userDir = System.getProperty("user.dir");
        if (userDir != null) System.setProperty("user.dir", projectDir);
      }
      catch (Exception ignore) {
      }
    }
    ProjectConnection connection = getConnection(projectDir, settings);
    try {
      return f.fun(connection);
    }
    catch (ExternalSystemException e) {
      throw e;
    }
    catch (Throwable e) {
      LOG.debug("Gradle execution error", e);
      Throwable rootCause = ExceptionUtil.getRootCause(e);
      throw new ExternalSystemException(ExceptionUtil.getMessage(rootCause), e);
    }
    finally {
      try {
        connection.close();
        if (userDir != null) {
          // restore original user.dir property
          System.setProperty("user.dir", userDir);
        }
      }
      catch (Throwable e) {
        LOG.debug("Gradle connection close error", e);
      }
    }
  }

  public void ensureInstalledWrapper(@NotNull ExternalSystemTaskId id,
                                     @NotNull String projectPath,
                                     @NotNull GradleExecutionSettings settings,
                                     @NotNull ExternalSystemTaskNotificationListener listener,
                                     @NotNull CancellationToken cancellationToken) {

    if (!settings.getDistributionType().isWrapped()) return;

    if (settings.getDistributionType() == DistributionType.DEFAULT_WRAPPED &&
        GradleUtil.findDefaultWrapperPropertiesFile(projectPath) != null) {
      return;
    }

    final long ttlInMs = settings.getRemoteProcessIdleTtlInMs();
    ProjectConnection connection = getConnection(projectPath, settings);
    try {
      settings.setRemoteProcessIdleTtlInMs(100);
      try {
        final File wrapperFilesLocation = FileUtil.createTempDirectory("wrap", "loc");
        final String fileName = "gradle-wrapper";
        final File jarFile = new File(wrapperFilesLocation, fileName + ".jar");
        final File scriptFile = new File(wrapperFilesLocation, "gradlew");
        final File pathToProperties = new File(wrapperFilesLocation, "path.tmp");

        Runtime.getRuntime().addShutdownHook(new Thread(() -> FileUtil.delete(wrapperFilesLocation)));
        final String[] lines = {
          "",
          "gradle.projectsEvaluated { gr ->",
          "  def wrapper = gr.rootProject.tasks[\"wrapper\"]",
          "  if (wrapper != null) {",
          "    if (wrapper.jarFile.exists()) {",
          "      wrapper.jarFile = new File('" + StringUtil.escapeBackSlashes(jarFile.getCanonicalPath()) + "')",
          "      wrapper.scriptFile = new File('" + StringUtil.escapeBackSlashes(scriptFile.getCanonicalPath()) + "')",
          "    }",
          "    wrapper.doLast {",
          "      new File('" + StringUtil.escapeBackSlashes(pathToProperties.getCanonicalPath()) + "').write wrapper.propertiesFile.getCanonicalPath()",
          "    }",
          "  }",
          "}",
          "",
        };
        final File tempFile = writeToFileGradleInitScript(StringUtil.join(lines, SystemProperties.getLineSeparator()));
        settings.withArguments(GradleConstants.INIT_SCRIPT_CMD_OPTION, tempFile.getAbsolutePath());
        BuildLauncher launcher = getBuildLauncher(id, connection, settings, listener);
        launcher.withCancellationToken(cancellationToken);
        launcher.forTasks("wrapper");
        launcher.run();
        settings.setWrapperPropertyFile(FileUtil.loadFile(pathToProperties));
      }
      catch (IOException e) {
        LOG.warn("Can't update wrapper", e);
      }
    }
    catch (Throwable e) {
      LOG.warn("Can't update wrapper", e);
      Throwable rootCause = ExceptionUtil.getRootCause(e);
      throw new ExternalSystemException(ExceptionUtil.getMessage(rootCause));
    }
    finally {
      settings.setRemoteProcessIdleTtlInMs(ttlInMs);
      try {
        connection.close();
      }
      catch (Throwable e) {
        // ignore
      }
    }
  }

  private static List<String> mergeJvmArgs(String serviceDirectory, List<String> jvmArgs, Set<String> jvmArgsFromIdeSettings) {
    File gradleUserHomeDir = serviceDirectory != null ? new File(serviceDirectory) : new BuildLayoutParameters().getGradleUserHomeDir();
    LOG.debug("Gradle home: " + gradleUserHomeDir);
    NativeServices.initialize(gradleUserHomeDir);
    Map<String, String> mergedArgs = new LinkedHashMap<>();
    for (String jvmArg : ContainerUtil.concat(jvmArgs, jvmArgsFromIdeSettings)) {
      int i = jvmArg.indexOf('=');
      if (i <= 0) {
        mergedArgs.put(jvmArg, "");
      }
      else {
        mergedArgs.put(jvmArg.substring(0, i), jvmArg.substring(i));
      }
    }

    List<String> mergedList = new ArrayList<>();
    for (Map.Entry<String, String> entry : mergedArgs.entrySet()) {
      mergedList.add(entry.getKey() + entry.getValue());
    }
    JvmOptions jvmOptions = new JvmOptions(null);
    jvmOptions.setAllJvmArgs(mergedList);
    return jvmOptions.getAllJvmArgs();
  }

  /**
   * Allows to retrieve gradle api connection to use for the given project.
   *
   * @param projectPath target project path
   * @param settings    execution settings to use
   * @return connection to use
   * @throws IllegalStateException if it's not possible to create the connection
   */
  @NotNull
  private static ProjectConnection getConnection(@NotNull String projectPath,
                                                 @Nullable GradleExecutionSettings settings)
    throws IllegalStateException {
    File projectDir = new File(projectPath);
    GradleConnector connector = GradleConnector.newConnector();
    int ttl = -1;

    if (settings != null) {
      File serviceDirectory = settings.getServiceDirectory() == null ? null : new File(settings.getServiceDirectory());
      File gradleHome = settings.getGradleHome() == null ? null : new File(settings.getGradleHome());
      //noinspection EnumSwitchStatementWhichMissesCases
      switch (settings.getDistributionType()) {
        case LOCAL:
          if (gradleHome != null) {
            connector.useInstallation(gradleHome);
          }
          break;
        case WRAPPED:
          if (settings.getWrapperPropertyFile() != null) {
            DistributionFactoryExt.setWrappedDistribution(connector, settings.getWrapperPropertyFile(), serviceDirectory);
          }
          break;
      }

      // Setup service directory if necessary.
      if (serviceDirectory != null) {
        connector.useGradleUserHomeDir(serviceDirectory);
      }

      // Setup logging if necessary.
      if (settings.isVerboseProcessing() && connector instanceof DefaultGradleConnector) {
        ((DefaultGradleConnector)connector).setVerboseLogging(true);
      }
      ttl = (int)settings.getRemoteProcessIdleTtlInMs();
    }

    // do not spawn gradle daemons during test execution
    final Application app = ApplicationManager.getApplication();
    ttl = (app != null && app.isUnitTestMode()) ? 10000 : ttl;

    if (ttl > 0 && connector instanceof DefaultGradleConnector) {
      ((DefaultGradleConnector)connector).daemonMaxIdleTime(ttl, TimeUnit.MILLISECONDS);
    }
    connector.forProjectDirectory(projectDir);
    ProjectConnection connection = connector.connect();
    if (connection == null) {
      throw new IllegalStateException(String.format(
        "Can't create connection to the target project via gradle tooling api. Project path: '%s'", projectPath
      ));
    }
    return connection;
  }

  @Nullable
  public static File generateInitScript(boolean isBuildSrcProject, @NotNull Set<Class> toolingExtensionClasses) {
    InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/init/init.gradle");
    try {
      if (stream == null) {
        LOG.warn("Can't get init script template");
        return null;
      }
      final String toolingExtensionsJarPaths = getToolingExtensionsJarPaths(toolingExtensionClasses);
      String script = FileUtil.loadTextAndClose(stream).replaceFirst(Pattern.quote("${EXTENSIONS_JARS_PATH}"), toolingExtensionsJarPaths);
      if (isBuildSrcProject) {
        String buildSrcDefaultInitScript = getBuildSrcDefaultInitScript();
        if (buildSrcDefaultInitScript == null) return null;
        script += buildSrcDefaultInitScript;
      }

      return writeToFileGradleInitScript(script);
    }
    catch (Exception e) {
      LOG.warn("Can't generate IJ gradle init script", e);
      return null;
    }
    finally {
      StreamUtil.closeStream(stream);
    }
  }

  public static File writeToFileGradleInitScript(@NotNull String content) throws IOException {
    return writeToFileGradleInitScript(content, "ijinit");
  }

  public static File writeToFileGradleInitScript(@NotNull String content, @NotNull String filePrefix) throws IOException {
    File tempFile = new File(FileUtil.getTempDirectory(), filePrefix + '.' + GradleConstants.EXTENSION);
    if (tempFile.exists() && StringUtil.equals(content, FileUtil.loadFile(tempFile))) {
      return tempFile;
    }
    tempFile = FileUtil.findSequentNonexistentFile(tempFile.getParentFile(), filePrefix, GradleConstants.EXTENSION);
    FileUtil.writeToFile(tempFile, content);
    tempFile.deleteOnExit();
    return tempFile;
  }

  @Nullable
  public static String getBuildSrcDefaultInitScript() {
    InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/init/buildSrcInit.gradle");
    try {
      if (stream == null) return null;
      return FileUtil.loadTextAndClose(stream);
    }
    catch (Exception e) {
      LOG.warn("Can't use IJ gradle init script", e);
      return null;
    }
    finally {
      StreamUtil.closeStream(stream);
    }
  }

  @Deprecated // use the method with the cancellationTokenSource provided
  @Nullable
  public static GradleVersion getGradleVersion(@NotNull ProjectConnection connection,
                                               @NotNull ExternalSystemTaskId taskId,
                                               @NotNull ExternalSystemTaskNotificationListener listener) {
    return getGradleVersion(connection, taskId, listener, null);
  }

  @Nullable
  public static GradleVersion getGradleVersion(@NotNull ProjectConnection connection,
                                               @NotNull ExternalSystemTaskId taskId,
                                               @NotNull ExternalSystemTaskNotificationListener listener,
                                               @Nullable CancellationTokenSource cancellationTokenSource) {
    final BuildEnvironment buildEnvironment = getBuildEnvironment(connection, taskId, listener, cancellationTokenSource);

    GradleVersion gradleVersion = null;
    if (buildEnvironment != null) {
      gradleVersion = GradleVersion.version(buildEnvironment.getGradle().getGradleVersion());
    }
    return gradleVersion;
  }

  @Deprecated // use the method with the cancellationTokenSource provided
  @Nullable
  public static BuildEnvironment getBuildEnvironment(@NotNull ProjectConnection connection,
                                                     @NotNull ExternalSystemTaskId taskId,
                                                     @NotNull ExternalSystemTaskNotificationListener listener) {
    return getBuildEnvironment(connection, taskId, listener, null);
  }

  @Nullable
  public static BuildEnvironment getBuildEnvironment(@NotNull ProjectConnection connection,
                                                     @NotNull ExternalSystemTaskId taskId,
                                                     @NotNull ExternalSystemTaskNotificationListener listener,
                                                     @Nullable CancellationTokenSource cancellationTokenSource) {
    ModelBuilder<BuildEnvironment> modelBuilder = connection.model(BuildEnvironment.class);
    if (cancellationTokenSource != null) {
      modelBuilder.withCancellationToken(cancellationTokenSource.token());
    }
    // do not use connection.getModel methods since it doesn't allow to handle progress events
    // and we can miss gradle tooling client side events like distribution download.
    GradleProgressListener gradleProgressListener = new GradleProgressListener(listener, taskId);
    modelBuilder.addProgressListener((ProgressListener)gradleProgressListener);
    modelBuilder.addProgressListener((org.gradle.tooling.events.ProgressListener)gradleProgressListener);
    modelBuilder.setStandardOutput(new OutputWrapper(listener, taskId, true));
    modelBuilder.setStandardError(new OutputWrapper(listener, taskId, false));

    final BuildEnvironment buildEnvironment = modelBuilder.get();
    if (LOG.isDebugEnabled()) {
      try {
        LOG.debug("Gradle version: " + buildEnvironment.getGradle().getGradleVersion());
        LOG.debug("Gradle java home: " + buildEnvironment.getJava().getJavaHome());
        LOG.debug("Gradle jvm arguments: " + buildEnvironment.getJava().getJvmArguments());
      }
      catch (Throwable t) {
        LOG.debug(t);
      }
    }
    return buildEnvironment;
  }

  private static void replaceTestCommandOptionWithInitScript(@NotNull List<String> args) {
    Set<String> testIncludePatterns = ContainerUtil.newLinkedHashSet();
    Iterator<String> it = args.iterator();
    while (it.hasNext()) {
      final String next = it.next();
      if ("--tests".equals(next)) {
        it.remove();
        if (it.hasNext()) {
          testIncludePatterns.add(it.next());
          it.remove();
        }
      }
    }
    if (!testIncludePatterns.isEmpty()) {
      StringBuilder buf = new StringBuilder();
      buf.append('[');
      for (Iterator<String> iterator = testIncludePatterns.iterator(); iterator.hasNext(); ) {
        String pattern = iterator.next();
        buf.append('\'').append(pattern).append('\'');
        if (iterator.hasNext()) {
          buf.append(',');
        }
      }
      buf.append(']');

      String path = renderInitScript(buf.toString());
      if (path != null) {
        ContainerUtil.addAll(args, GradleConstants.INIT_SCRIPT_CMD_OPTION, path);
      }
    }
  }

  @Nullable
  public static String renderInitScript(@NotNull String testArgs) {
    InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/init/testFilterInit.gradle");
    try {
      if (stream == null) {
        LOG.error("Can't get test filter init script template");
        return null;
      }
      String script = FileUtil.loadTextAndClose(stream).replaceFirst(Pattern.quote("${TEST_NAME_INCLUDES}"), Matcher.quoteReplacement(testArgs));
      final File tempFile = writeToFileGradleInitScript(script, "ijtestinit");
      return tempFile.getAbsolutePath();
    }
    catch (Exception e) {
      LOG.warn("Can't generate IJ gradle test filter init script", e);
      return null;
    }
    finally {
      StreamUtil.closeStream(stream);
    }
  }

  @NotNull
  private static String getToolingExtensionsJarPaths(@NotNull Set<Class> toolingExtensionClasses) {
    final Set<String> jarPaths = ContainerUtil.map2SetNotNull(toolingExtensionClasses, aClass -> {
      String path = PathManager.getJarPathForClass(aClass);
      if (path != null) {
        if (FileUtil.getNameWithoutExtension(path).equals("gradle-api-" + GradleVersion.current().getBaseVersion())) {
          LOG.warn("The gradle api jar shouldn't be added to the gradle daemon classpath: {" + aClass + "," + path + "}");
          return null;
        }
        return PathUtil.getCanonicalPath(path);
      }
      return null;
    });
    StringBuilder buf = new StringBuilder();
    buf.append('[');
    for (Iterator<String> it = jarPaths.iterator(); it.hasNext(); ) {
      String jarPath = it.next();
      buf.append('\"').append(jarPath).append('\"');
      if (it.hasNext()) {
        buf.append(',');
      }
    }
    buf.append(']');
    return buf.toString();
  }

  /* deprecated methods to be removed in future version */

  /**
   * @deprecated {@link #getModelBuilder(Class, ExternalSystemTaskId, GradleExecutionSettings, ProjectConnection, ExternalSystemTaskNotificationListener)}
   */
  @Deprecated
  @SuppressWarnings("MethodMayBeStatic")
  @NotNull
  public <T> ModelBuilder<T> getModelBuilder(@NotNull Class<T> modelType,
                                             @NotNull final ExternalSystemTaskId id,
                                             @Nullable GradleExecutionSettings settings,
                                             @NotNull ProjectConnection connection,
                                             @NotNull ExternalSystemTaskNotificationListener listener,
                                             @NotNull List<String> extraJvmArgs) {
    ModelBuilder<T> result = connection.model(modelType);
    prepare(result, id, settings, listener, extraJvmArgs, ContainerUtil.newArrayList(), connection);
    return result;
  }

  /**
   * @deprecated {@link #getBuildLauncher(ExternalSystemTaskId, ProjectConnection, GradleExecutionSettings, ExternalSystemTaskNotificationListener)}
   */
  @Deprecated
  @SuppressWarnings("MethodMayBeStatic")
  @NotNull
  public BuildLauncher getBuildLauncher(@NotNull final ExternalSystemTaskId id,
                                        @NotNull ProjectConnection connection,
                                        @Nullable GradleExecutionSettings settings,
                                        @NotNull ExternalSystemTaskNotificationListener listener,
                                        @NotNull final List<String> vmOptions,
                                        @NotNull final List<String> commandLineArgs) {
    BuildLauncher result = connection.newBuild();
    prepare(result, id, settings, listener, vmOptions, commandLineArgs, connection);
    return result;
  }

  @NotNull
  static List<String> obfuscatePasswordParameters(@NotNull List<String> commandLineArguments) {
    List<String> replaced = new ArrayList<>(commandLineArguments.size());
    final String PASSWORD_PARAMETER_IDENTIFIER = ".password=";
    for (String option : commandLineArguments) {
      // Find parameters ending in "password", like:
      //   -Pandroid.injected.signing.store.password=
      //   -Pandroid.injected.signing.key.password=
      int index = option.indexOf(PASSWORD_PARAMETER_IDENTIFIER);
      if (index == -1) {
        replaced.add(option);
      }
      else {
        replaced.add(option.substring(0, index + PASSWORD_PARAMETER_IDENTIFIER.length()) + "*********");
      }
    }
    return replaced;
  }

  /**
   * @deprecated to be removed in future version
   */
  @Deprecated
  @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
  public static void prepare(@NotNull LongRunningOperation operation,
                             @NotNull final ExternalSystemTaskId id,
                             @Nullable GradleExecutionSettings settings,
                             @NotNull final ExternalSystemTaskNotificationListener listener,
                             @NotNull List<String> extraJvmArgs,
                             @NotNull ProjectConnection connection) {
    if (settings == null) return;
    settings.withVmOptions(extraJvmArgs);
    prepare(operation, id, settings, listener, connection, new OutputWrapper(listener, id, true), new OutputWrapper(listener, id, false));
  }

  /**
   * @deprecated use {@link #prepare(LongRunningOperation, ExternalSystemTaskId, GradleExecutionSettings, ExternalSystemTaskNotificationListener, ProjectConnection)}
   */
  @Deprecated
  @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
  public static void prepare(@NotNull LongRunningOperation operation,
                             @NotNull final ExternalSystemTaskId id,
                             @Nullable GradleExecutionSettings settings,
                             @NotNull final ExternalSystemTaskNotificationListener listener,
                             @NotNull List<String> extraJvmArgs,
                             @NotNull List<String> commandLineArgs,
                             @NotNull ProjectConnection connection) {
    if (settings == null) return;
    settings.withArguments(commandLineArgs).withVmOptions(extraJvmArgs);
    prepare(operation, id, settings, listener, connection, new OutputWrapper(listener, id, true), new OutputWrapper(listener, id, false));
  }

  /**
   * @deprecated use {@link #prepare(LongRunningOperation, ExternalSystemTaskId, GradleExecutionSettings, ExternalSystemTaskNotificationListener, ProjectConnection, OutputStream, OutputStream)}
   */
  @Deprecated
  @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
  public static void prepare(@NotNull LongRunningOperation operation,
                             @NotNull final ExternalSystemTaskId id,
                             @NotNull GradleExecutionSettings settings,
                             @NotNull final ExternalSystemTaskNotificationListener listener,
                             @NotNull List<String> extraJvmArgs,
                             @NotNull List<String> commandLineArgs,
                             @NotNull ProjectConnection connection,
                             @NotNull final OutputStream standardOutput,
                             @NotNull final OutputStream standardError) {
    settings.withArguments(commandLineArgs).withVmOptions(extraJvmArgs);
    prepare(operation, id, settings, listener, connection, standardOutput, standardError);
  }
}


text:
/* */
"format cjs";
"use strict";

var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; };

var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; };

exports.NullableTypeAnnotation = NullableTypeAnnotation;
exports.UpdateExpression = UpdateExpression;
exports.ObjectExpression = ObjectExpression;
exports.Binary = Binary;
exports.BinaryExpression = BinaryExpression;
exports.SequenceExpression = SequenceExpression;
exports.YieldExpression = YieldExpression;
exports.ClassExpression = ClassExpression;
exports.UnaryLike = UnaryLike;
exports.FunctionExpression = FunctionExpression;
exports.ConditionalExpression = ConditionalExpression;
exports.__esModule = true;

var each = _interopRequire(require("lodash/collection/each"));

var t = _interopRequireWildcard(require("../../types"));

var PRECEDENCE = {};

each([["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]], function (tier, i) {
  each(tier, function (op) {
    PRECEDENCE[op] = i;
  });
});

function NullableTypeAnnotation(node, parent) {
  return t.isArrayTypeAnnotation(parent);
}

exports.FunctionTypeAnnotation = NullableTypeAnnotation;

function UpdateExpression(node, parent) {
  if (t.isMemberExpression(parent) && parent.object === node) {
    // (foo++).test()
    return true;
  }
}

function ObjectExpression(node, parent) {
  if (t.isExpressionStatement(parent)) {
    // ({ foo: "bar" });
    return true;
  }

  if (t.isMemberExpression(parent) && parent.object === node) {
    // ({ foo: "bar" }).foo
    return true;
  }

  return false;
}

function Binary(node, parent) {
  if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) {
    return true;
  }

  if (t.isUnaryLike(parent)) {
    return true;
  }

  if (t.isMemberExpression(parent) && parent.object === node) {
    return true;
  }

  if (t.isBinary(parent)) {
    var parentOp = parent.operator;
    var parentPos = PRECEDENCE[parentOp];

    var nodeOp = node.operator;
    var nodePos = PRECEDENCE[nodeOp];

    if (parentPos > nodePos) {
      return true;
    }

    if (parentPos === nodePos && parent.right === node) {
      return true;
    }
  }
}

function BinaryExpression(node, parent) {
  if (node.operator === "in") {
    // var i = (1 in []);
    if (t.isVariableDeclarator(parent)) {
      return true;
    }

    // for ((1 in []);;);
    if (t.isFor(parent)) {
      return true;
    }
  }
}

function SequenceExpression(node, parent) {
  if (t.isForStatement(parent)) {
    // Although parentheses wouldn't hurt around sequence
    // expressions in the head of for loops, traditional style
    // dictates that e.g. i++, j++ should not be wrapped with
    // parentheses.
    return false;
  }

  if (t.isExpressionStatement(parent) && parent.expression === node) {
    return false;
  }

  // Otherwise err on the side of overparenthesization, adding
  // explicit exceptions above if this proves overzealous.
  return true;
}

function YieldExpression(node, parent) {
  return t.isBinary(parent) || t.isUnaryLike(parent) || t.isCallExpression(parent) || t.isMemberExpression(parent) || t.isNewExpression(parent) || t.isConditionalExpression(parent) || t.isYieldExpression(parent);
}

function ClassExpression(node, parent) {
  return t.isExpressionStatement(parent);
}

function UnaryLike(node, parent) {
  return t.isMemberExpression(parent) && parent.object === node;
}

function FunctionExpression(node, parent) {
  // function () {};
  if (t.isExpressionStatement(parent)) {
    return true;
  }

  // (function test() {}).name;
  if (t.isMemberExpression(parent) && parent.object === node) {
    return true;
  }

  // (function () {})();
  if (t.isCallExpression(parent) && parent.callee === node) {
    return true;
  }
}

function ConditionalExpression(node, parent) {
  if (t.isUnaryLike(parent)) {
    return true;
  }

  if (t.isBinary(parent)) {
    return true;
  }

  if (t.isCallExpression(parent) || t.isNewExpression(parent)) {
    if (parent.callee === node) {
      return true;
    }
  }

  if (t.isConditionalExpression(parent) && parent.test === node) {
    return true;
  }

  if (t.isMemberExpression(parent) && parent.object === node) {
    return true;
  }

  return false;
}

exports.AssignmentExpression = ConditionalExpression;


text:
package com.canchitodev.awm.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

public interface AwmService<T, ID extends Serializable> {

	public T findById(ID id);

	public List<T> findAll();

	public void save(T entity);

	public void update(T entity);

	public void delete(ID id);

	public Page<T> findAll(Pageable pageable);

	public Page<T> findAll(Specification<T> spec, Pageable pageable);

	public boolean exists(ID id);
}


text:
require 'spec_helper'

feature 'Dashboard shortcuts', :js do
  context 'logged in' do
    before do
      sign_in(create(:user))
      visit root_dashboard_path
    end

    scenario 'Navigate to tabs' do
      find('body').send_keys([:shift, 'I'])

      check_page_title('Issues')

      find('body').send_keys([:shift, 'M'])

      check_page_title('Merge Requests')

      find('body').send_keys([:shift, 'T'])

      check_page_title('Todos')

      find('body').send_keys([:shift, 'P'])

      check_page_title('Projects')
    end
  end

  context 'logged out' do
    before do
      visit explore_root_path
    end

    scenario 'Navigate to tabs' do
      find('body').send_keys([:shift, 'G'])

      find('.nothing-here-block')
      expect(page).to have_content('No public groups')

      find('body').send_keys([:shift, 'S'])

      find('.nothing-here-block')
      expect(page).to have_selector('.snippets-list-holder')

      find('body').send_keys([:shift, 'P'])

      find('.nothing-here-block')
      expect(page).to have_content('No projects found')
    end
  end

  def check_page_title(title)
    expect(find('.header-content .title')).to have_content(title)
  end
end


text:
module Notifiable
  include SuperExceptionNotifier::NotifiableHelper

  def self.included(base)
    base.extend ClassMethods

    # Verbosity of the gem
    base.cattr_accessor :notifiable_verbose
    base.notifiable_verbose = false
    # Do Not Ever send error notification emails for these Error Classes
    base.cattr_accessor :notifiable_silent_exceptions
    base.notifiable_silent_exceptions = SILENT_EXCEPTIONS
    # Notification Level
    base.cattr_accessor :notifiable_notification_level
    base.notifiable_notification_level = [:email, :web_hooks]

    # Since there is no concept of locality from a request here allow user to explicitly define which env's are noisy (send notifications)
    base.cattr_accessor :notifiable_noisy_environments
    base.notifiable_noisy_environments = [:production]
  end

  module ClassMethods
    # set the exception_data deliverer OR retrieve the exception_data
    def exception_data(deliverer = nil)
      if deliverer
        write_inheritable_attribute(:exception_data, deliverer)
      else
        read_inheritable_attribute(:exception_data)
      end
    end

    def be_silent_for_exception?(exception)
      self.notifiable_silent_exceptions.respond_to?(:any?) && self.notifiable_silent_exceptions.any? {|klass| klass === exception }
    end

  end

  # Usage:
  #   notifiable { Klass.some_method }
  # This will rescue any errors that occur within Klass.some_method
  def notifiable(&block)
    yield
  rescue => exception
    rescue_with_hooks(exception)
    raise
  end

  def be_silent_for_exception?(exception)
    self.class.be_silent_for_exception?(exception)
  end

  private

  def notification_level_sends_email?
    self.class.notifiable_notification_level.include?(:email)
  end

  def notification_level_sends_web_hooks?
    self.class.notifiable_notification_level.include?(:web_hooks)
  end

  def rescue_with_hooks(exception)
    verbose = self.class.notifiable_verbose
    puts "[RESCUE STYLE] rescue_with_hooks" if verbose
    data = get_exception_data
    # With ExceptionNotifiable you have an inherent request, and using a status code makes sense.
    # With Notifiable class to wrap around everything that doesn't have a request,
    #   the errors you want to be notified of need to be specified either positively or negatively
    # 1. positive eg. set ExceptionNotifier.config[:notify_error_classes] to an array of classes
    #               set ExceptionNotifier.config[:notify_other_errors] to false
    # 1. negative eg. set Klass.silent_exceptions to the ones to keep quiet
    #               set ExceptionNotifier.config[:notify_other_errors] to true
    status_code = nil
    #We only send email if it has been configured in environment
    send_email = should_email_on_exception?(exception, status_code, verbose)
    #We only send web hooks if they've been configured in environment
    send_web_hooks = should_web_hook_on_exception?(exception, status_code, verbose)
    the_blamed = ExceptionNotifier.config[:git_repo_path].nil? ? nil : lay_blame(exception)
    rejected_sections = %w(request session)
    verbose_output(exception, status_code, "rescued by handler", send_email, send_web_hooks, nil, the_blamed, rejected_sections) if verbose
    # Send the exception notification email
    perform_exception_notify_mailing(exception, data, nil, the_blamed, verbose, rejected_sections) if send_email
    # Send Web Hook requests
    HooksNotifier.deliver_exception_to_web_hooks(ExceptionNotifier.config, exception, self, request, data, the_blamed) if send_web_hooks
  end

  def is_local? #like asking is_silent?
    eenv = defined?(Rails) ? Rails.env : RAILS_ENV
    !self.notifiable_noisy_environments.include?(eenv)
  end

end


text:
<?php

/*
 * This file is part of Sulu.
 *
 * (c) MASSIVE ART WebServices GmbH
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Sulu\Bundle\WebsiteBundle\Twig\Meta;

use Sulu\Bundle\WebsiteBundle\Twig\Content\ContentPathInterface;
use Sulu\Component\Webspace\Analyzer\RequestAnalyzerInterface;

/**
 * Provides helper function to generate meta tags.
 *
 * @deprecated will be removed in 1.2
 */
class MetaTwigExtension extends \Twig_Extension
{
    /**
     * @var RequestAnalyzerInterface
     */
    private $requestAnalyzer;

    /**
     * @var ContentPathInterface
     */
    private $contentPath;

    /**
     * Constructor.
     */
    public function __construct(RequestAnalyzerInterface $requestAnalyzer, ContentPathInterface $contentPath)
    {
        $this->contentPath = $contentPath;
        $this->requestAnalyzer = $requestAnalyzer;
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'sulu_website_meta';
    }

    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('sulu_meta_alternate', [$this, 'getAlternateLinks']),
            new \Twig_SimpleFunction('sulu_meta_seo', [$this, 'getSeoMetaTags']),
        ];
    }

    /**
     * Returns alternate link HTML tags with href-lang attributes.
     *
     * @param array $urls
     *
     * @return string
     *
     * @deprecated since 1.1 use SeoTwigExtension::renderSeoTags - sulu_seo
     */
    public function getAlternateLinks($urls)
    {
        // determine default and current values
        $webspaceKey = $this->requestAnalyzer->getWebspace()->getKey();
        $currentPortal = $this->requestAnalyzer->getPortal();

        $defaultLocale = null;
        if ($currentPortal !== null && ($defaultLocale = $currentPortal->getXDefaultLocalization()) !== null) {
            $defaultLocale = $defaultLocale->getLocalization();
        }

        $result = [];
        foreach ($urls as $locale => $url) {
            // url = '/' means that there is no translation for this page
            // the only exception is the homepage where the requested resource-locator is '/'
            if ($url !== '/' || $this->requestAnalyzer->getResourceLocator() === '/') {
                if ($locale === $defaultLocale) {
                    $result[] = $this->getAlternate($url, $webspaceKey, $locale, true);
                }
                $result[] = $this->getAlternate($url, $webspaceKey, $locale);
            }
        }

        return implode(PHP_EOL, $result);
    }

    /**
     * Returns seo meta tags with fallbacks.
     *
     * @param array $extension
     * @param array $content
     *
     * @return string
     *
     * @deprecated since 1.1 use SeoTwigExtension::renderSeoTags - sulu_seo
     */
    public function getSeoMetaTags($extension, $content)
    {
        $seo = [];
        if (array_key_exists('seo', $extension)) {
            $seo = $extension['seo'];
        }
        $excerpt = [];
        if (array_key_exists('excerpt', $extension)) {
            $excerpt = $extension['excerpt'];
        }

        // fallback for seo description
        if (
            (!array_key_exists('description', $seo) || $seo['description'] === '') &&
            array_key_exists('description', $excerpt) && $excerpt['description'] !== ''
        ) {
            $seo['description'] = strip_tags($excerpt['description']);
        }

        $seo['description'] = substr($seo['description'], 0, 155);

        // generate robots content
        $robots = [];
        $robots[] = (array_key_exists('noIndex', $seo) && $seo['noIndex'] === true) ? 'noIndex' : 'index';
        $robots[] = (array_key_exists('noFollow', $seo) && $seo['noFollow'] === true) ? 'noFollow' : 'follow';

        // build meta tags
        $result = [];
        $result[] = $this->getMeta('description', $seo['description']);
        $result[] = $this->getMeta('keywords', $seo['keywords']);
        $result[] = $this->getMeta('robots', strtoupper(implode(', ', $robots)));

        return implode(PHP_EOL, $result);
    }

    /**
     * Returns link-alternate html tag
     *  - e.g. <link rel="alternate" href="http://sulu.lo/de/test-url" hreflang="de" />.
     *
     * @param string $url
     * @param string $webspaceKey
     * @param string $locale
     * @param bool $default
     *
     * @return string
     */
    private function getAlternate($url, $webspaceKey, $locale, $default = false)
    {
        $url = $this->contentPath->getContentPath($url, $webspaceKey, $locale);

        return sprintf(
            '<link rel="alternate" href="%s" hreflang="%s" />',
            $url,
            !$default ? str_replace('_', '-', $locale) : 'x-default'
        );
    }

    /**
     * Returns meta html tag
     *  - e.g. <meta name="description" content="That's a good example">.
     *
     * @param string $name
     * @param string $content
     *
     * @return string
     */
    private function getMeta($name, $content)
    {
        return sprintf('<meta name="%s" content="%s">', $name, $content);
    }
}


text:
<!DOCTYPE html>

        <title>Loading...</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" crossorigin="anonymous">

        <link href='https://fonts.googleapis.com/css?family=Pridi' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=BioRhyme:400,800' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.0/animate.min.css">
        <link rel="stylesheet" href="HTML/css/main.css">

                    Dashboard

GitHub Source

Author

        <displaytable>

                         Date Time
                         Action
                         Path
                         Size
                         Info
                         Notes

        </displaytable>

        <statusbar class="STATUS" id="DSUIHelperEL">

            Ready

        </statusbar>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.softhaxi.insofth.controller;

import com.softhaxi.insofth.enums.FinanceActivity;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.controlsfx.dialog.DialogStyle;
import org.controlsfx.dialog.Dialogs;

/**
 * FXML Controller class
 *
 * @author Hutasoit
 */
public class MainController implements Initializable {

    private ResourceBundle bundle;

    private FXMLLoader loader;
    private Scene scene;
    private Stage stage;

    @FXML
    private Button btnNewIncome;
    @FXML
    private Button btnNewExpense;
    @FXML
    private Button btnNewTransfer;
    @FXML
    private Button btnNewBudget;
    @FXML
    private Button btnNewRecurring;

    /**
     * Initializes the controller class.
     *
     * @param url
     * @param rb
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        bundle = rb;
    }

    @FXML
    private void handleNewActivity(ActionEvent e) {
        Button btn = (Button) e.getSource();
        Parent root = null;
        NewIncomeController ctrl = null;
        try {
            if (btn == btnNewIncome) {

                loader = new FXMLLoader(getClass().getResource("/fxml/NewIncomeScene.fxml"), bundle);
                root = (Parent) loader.load();
                ctrl = loader.getController();
                scene = new Scene(root);
                stage = new Stage();
                stage.setTitle(bundle.getString("new.income"));
                stage.getIcons().add(new Image("/images/in_logo.png"));
                stage.setScene(scene);
                stage.initModality(Modality.WINDOW_MODAL);
                stage.initOwner(btnNewIncome.getScene().getWindow());
                stage.setResizable(false);
                stage.showAndWait();
                stage.setOnCloseRequest((WindowEvent event) -> {
                    stage = null;
                    scene = null;
                    loader = null;
                });

                return;

            }

            if (btn == btnNewExpense) {
                Dialogs.create()
                        .owner(btnNewExpense.getScene().getWindow())
                        .style(DialogStyle.NATIVE)
                        .lightweight()
                        .title(bundle.getString("app.name"))
                        .message(FinanceActivity.EXPENSE.toString())
                        .showInformation();
                return;
            }

        } catch (IOException ex) {
            Logger.getLogger(MainController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}


text:
//===--- Dominance.cpp - SIL basic block dominance analysis ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/Dominance.h"
#include "llvm/Support/GenericDomTree.h"
#include "llvm/Support/GenericDomTreeConstruction.h"

using namespace swift;

template class llvm::DominatorTreeBase<SILBasicBlock>;
template class llvm::DominatorBase<SILBasicBlock>;
template class llvm::DomTreeNodeBase<SILBasicBlock>;

/// Compute the immmediate-dominators map.
DominanceInfo::DominanceInfo(SILFunction *F)
    : DominatorTreeBase(/*isPostDom*/ false) {
      assert(!F->isExternalDeclaration() &&
             "Make sure the function is a definition and not a declaration.");
  recalculate(*F);
}

bool DominanceInfo::properlyDominates(SILInstruction *a, SILInstruction *b) {
  auto aBlock = a->getParent(), bBlock = b->getParent();

  // If the blocks are different, it's as easy as whether A's block
  // dominates B's block.
  if (aBlock != bBlock)
    return properlyDominates(a->getParent(), b->getParent());

  // Otherwise, they're in the same block, and we just need to check
  // whether B comes after A.  This is a non-strict computation.
  SILInstruction *f = &*aBlock->begin();
  while (b != f) {
    b = b->getPrevNode();
    if (a == b) return true;
  }

  return false;
}

void DominanceInfo::verify() const {
  // Recompute.
  auto *F = getRoot()->getParent();
  DominanceInfo OtherDT(F);

  // And compare.
  if (errorOccuredOnComparison(OtherDT)) {
    llvm::errs() << "DominatorTree is not up to date!\nComputed:\n";
    print(llvm::errs());
    llvm::errs() << "\nActual:\n";
    OtherDT.print(llvm::errs());
    abort();
  }
}

/// Compute the immmediate-post-dominators map.
PostDominanceInfo::PostDominanceInfo(SILFunction *F)
  : DominatorTreeBase(/*isPostDom*/ true) {
  assert(!F->isExternalDeclaration() &&
         "Can not construct a post dominator tree for a declaration");
  recalculate(*F);
}

bool
PostDominanceInfo::
properlyDominates(SILInstruction *I1, SILInstruction *I2) {
  SILBasicBlock *BB1 = I1->getParent(), *BB2 = I2->getParent();

  // If the blocks are different, it's as easy as whether BB1 post dominates
  // BB2.
  if (BB1 != BB2)
    return properlyDominates(BB1, BB2);

  // Otherwise, they're in the same block, and we just need to check
  // whether A comes after B.
  for (auto II = I1->getIterator(), IE = BB1->end(); II != IE; ++II) {
    if (&*II == I2) {
      return false;
    }
  }

  return true;
}

void PostDominanceInfo::verify() const {
  // Recompute.
  //
  // Even though at the SIL level we have "one" return function, we can have
  // multiple exits provided by no-return functions.
  auto *F = getRoots()[0]->getParent();
  PostDominanceInfo OtherDT(F);

  // And compare.
  if (errorOccuredOnComparison(OtherDT)) {
    llvm::errs() << "PostDominatorTree is not up to date!\nComputed:\n";
    print(llvm::errs());
    llvm::errs() << "\nActual:\n";
    OtherDT.print(llvm::errs());
    abort();
  }
}


text:
package org.apache.deltaspike.jsf.impl.injection;

import javax.enterprise.context.RequestScoped;

//TODO merge with AbstractBeanStorage if ViewDependentBeanStorage isn't needed (see MYFACES-3805)
@RequestScoped
public class RequestDependentBeanStorage extends AbstractBeanStorage
{
}


text:
import { __asyncDelegator, __asyncGenerator, __asyncValues, __await } from "tslib";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
/// <reference lib="esnext.asynciterable" />
/** Class containing PrivateLinkResources operations. */
export class PrivateLinkResourcesImpl {
    /**
     * Initialize a new instance of the class PrivateLinkResources class.
     * @param client Reference to the service client
     */
    constructor(client) {
        this.client = client;
    }
    /**
     * Gets the private link resources for SQL server.
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain
     *                          this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param options The options parameters.
     */
    listByServer(resourceGroupName, serverName, options) {
        const iter = this.listByServerPagingAll(resourceGroupName, serverName, options);
        return {
            next() {
                return iter.next();
            },
            [Symbol.asyncIterator]() {
                return this;
            },
            byPage: () => {
                return this.listByServerPagingPage(resourceGroupName, serverName, options);
            }
        };
    }
    listByServerPagingPage(resourceGroupName, serverName, options) {
        return __asyncGenerator(this, arguments, function* listByServerPagingPage_1() {
            let result = yield __await(this._listByServer(resourceGroupName, serverName, options));
            yield yield __await(result.value || []);
            let continuationToken = result.nextLink;
            while (continuationToken) {
                result = yield __await(this._listByServerNext(resourceGroupName, serverName, continuationToken, options));
                continuationToken = result.nextLink;
                yield yield __await(result.value || []);
            }
        });
    }
    listByServerPagingAll(resourceGroupName, serverName, options) {
        return __asyncGenerator(this, arguments, function* listByServerPagingAll_1() {
            var e_1, _a;
            try {
                for (var _b = __asyncValues(this.listByServerPagingPage(resourceGroupName, serverName, options)), _c; _c = yield __await(_b.next()), !_c.done;) {
                    const page = _c.value;
                    yield __await(yield* __asyncDelegator(__asyncValues(page)));
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) yield __await(_a.call(_b));
                }
                finally { if (e_1) throw e_1.error; }
            }
        });
    }
    /**
     * Gets the private link resources for SQL server.
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain
     *                          this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param options The options parameters.
     */
    _listByServer(resourceGroupName, serverName, options) {
        return this.client.sendOperationRequest({ resourceGroupName, serverName, options }, listByServerOperationSpec);
    }
    /**
     * Gets a private link resource for SQL server.
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain
     *                          this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param groupName The name of the private link resource.
     * @param options The options parameters.
     */
    get(resourceGroupName, serverName, groupName, options) {
        return this.client.sendOperationRequest({ resourceGroupName, serverName, groupName, options }, getOperationSpec);
    }
    /**
     * ListByServerNext
     * @param resourceGroupName The name of the resource group that contains the resource. You can obtain
     *                          this value from the Azure Resource Manager API or the portal.
     * @param serverName The name of the server.
     * @param nextLink The nextLink from the previous successful call to the ListByServer method.
     * @param options The options parameters.
     */
    _listByServerNext(resourceGroupName, serverName, nextLink, options) {
        return this.client.sendOperationRequest({ resourceGroupName, serverName, nextLink, options }, listByServerNextOperationSpec);
    }
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByServerOperationSpec = {
    path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/privateLinkResources",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: Mappers.PrivateLinkResourceListResult
        },
        default: {}
    },
    queryParameters: [Parameters.apiVersion2],
    urlParameters: [
        Parameters.$host,
        Parameters.subscriptionId,
        Parameters.resourceGroupName,
        Parameters.serverName
    ],
    headerParameters: [Parameters.accept],
    serializer
};
const getOperationSpec = {
    path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/privateLinkResources/{groupName}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: Mappers.PrivateLinkResource
        },
        default: {}
    },
    queryParameters: [Parameters.apiVersion2],
    urlParameters: [
        Parameters.$host,
        Parameters.subscriptionId,
        Parameters.resourceGroupName,
        Parameters.serverName,
        Parameters.groupName
    ],
    headerParameters: [Parameters.accept],
    serializer
};
const listByServerNextOperationSpec = {
    path: "{nextLink}",
    httpMethod: "GET",
    responses: {
        200: {
            bodyMapper: Mappers.PrivateLinkResourceListResult
        },
        default: {}
    },
    queryParameters: [Parameters.apiVersion2],
    urlParameters: [
        Parameters.$host,
        Parameters.subscriptionId,
        Parameters.resourceGroupName,
        Parameters.serverName,
        Parameters.nextLink
    ],
    headerParameters: [Parameters.accept],
    serializer
};
//# sourceMappingURL=privateLinkResources.js.map


text:
<?xml version="1.0" encoding="utf-8" ?>
<resources>
  <style name="AppBaseTheme" parent="@style/Theme.AppCompat.Light">
    <item name="android:windowActionBarOverlay">true</item>
    <item name="windowActionBarOverlay">true</item>
  </style>

  <style name="AppTheme" parent="AppBaseTheme">
  </style>
</resources>


text:
<?php

namespace MyCLabs\Work\Dispatcher;

use MyCLabs\Work\Dispatcher\Event\DispatcherEventListener;

/**
 * Provides event methods for a work dispatcher.
 *
 * @author Matthieu Napoli <matthieu@mnapoli.fr>
 */
trait WorkDispatcherEventTrait
{
    /**
     * @var DispatcherEventListener[]
     */
    protected $listeners = [];

    /**
     * @param DispatcherEventListener $listener
     */
    public function registerEventListener(DispatcherEventListener $listener)
    {
        $this->listeners[] = $listener;
    }

    /**
     * Dispatch an event to all the listeners.
     *
     * @param string $event
     * @param array  $parameters
     */
    protected function triggerEvent($event, array $parameters = [])
    {
        foreach ($this->listeners as $listener) {
            call_user_func_array([$listener, $event], $parameters);
        }
    }
}


text:
import json
import logging
import multiprocessing as mp
from collections import Counter, defaultdict
from concurrent.futures import ProcessPoolExecutor
from contextlib import contextmanager
from functools import partial
from queue import Full
from typing import Tuple

from django.apps import apps
from django.conf import settings
from django.core.management.color import no_style
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.db import DatabaseError, connections, router, transaction

from corehq.apps.dump_reload.exceptions import DataLoadException
from corehq.apps.dump_reload.interface import DataLoader
from corehq.apps.dump_reload.util import get_model_label
from corehq.sql_db.routers import HINT_PARTITION_VALUE

logger = logging.getLogger("load_sql")

CHUNK_SIZE = 200
ENQUEUE_TIMEOUT = 10

class SqlDataLoader(DataLoader):
    slug = 'sql'

    def load_objects(self, object_strings, force=False, dry_run=False):
        if dry_run:
            dry_run_stats = Counter()
            for line in object_strings:
                obj = self.line_to_object(line)
                if obj is not None:
                    dry_run_stats[obj['model']] += 1
            return dry_run_stats

        def enqueue_object(dbalias_to_workerqueue, obj):
            db_alias = get_db_alias(obj)
            worker, queue = dbalias_to_workerqueue[db_alias]
            # add a timeout here otherwise this blocks forever if the worker dies / errors
            queue.put(obj, timeout=ENQUEUE_TIMEOUT)

        def collect_results(dbalias_to_workerqueue) -> Tuple[list, list]:
            load_stats = []
            exceptions = []
            terminate_workers(dbalias_to_workerqueue)
            for db_alias, (worker, __) in dbalias_to_workerqueue.items():
                try:
                    load_stats.append(worker.result())
                except Exception as err:
                    err.args += (f'Error in worker {db_alias!r}',)
                    exceptions.append(err)
            return load_stats, exceptions

        def terminate_workers(dbalias_to_workerqueue):
            for __, queue in dbalias_to_workerqueue.values():
                try:
                    queue.put(None, timeout=1)
                except Full:
                    # If the queue is full it's likely the worker is already terminated
                    pass

        num_aliases = len(settings.DATABASES)
        manager = mp.Manager()
        with ProcessPoolExecutor(max_workers=num_aliases) as executor:
            # Map each db_alias to a queue + a worker task to consume the queue
            worker_queue_factory = partial(get_worker_queue, executor, manager)
            # DefaultDictWithKey passes the key to its factory function so that
            # the worker knows its db_alias without having to figure it out
            dbalias_to_workerqueue = DefaultDictWithKey(worker_queue_factory)

            for line in object_strings:
                obj = self.line_to_object(line)
                if obj is not None:
                    try:
                        enqueue_object(dbalias_to_workerqueue, obj)
                    except Exception as err:
                        __, errors = collect_results(dbalias_to_workerqueue)
                        if not isinstance(err, Full):
                            errors.append(err)
                        break
            else:
                load_stats, errors = collect_results(dbalias_to_workerqueue)

        if errors:
            raise errors[0] if len(errors) == 1 else Exception(errors)
        _reset_sequences(load_stats)
        loaded_model_counts = Counter()
        for db_stats in load_stats:
            model_labels = (f'{get_model_label(model)}'
                            for model in db_stats.model_counter.elements())
            loaded_model_counts.update(model_labels)
        return loaded_model_counts

    def line_to_object(self, line):
        line = line.strip()
        if line:
            obj = json.loads(line)
            update_model_name(obj)
            if self.filter_object(obj):
                return obj
        return None

    def filter_object(self, object):
        if not self.object_filter:
            return True
        model_label = object['model']
        return self.object_filter.findall(model_label)

def get_worker_queue(process_pool_executor, manager, db_alias):
    """
    Instantiates a queue, and starts a worker task in its own process
    """
    queue = manager.JoinableQueue(maxsize=CHUNK_SIZE)
    worker_task = process_pool_executor.submit(worker, queue, db_alias)
    return worker_task, queue

def worker(queue, db_alias):
    """
    Pulls objects from queue and loads them into their DB.
    """
    coro = load_data_for_db(db_alias)
    next(coro)
    while True:
        obj = queue.get()
        if obj is None:
            load_stat = coro.send(None)
            queue.task_done()
            return load_stat
        coro.send(obj)
        queue.task_done()

def _reset_sequences(load_stats):
    """Reset DB sequences if needed"""
    for stat in load_stats:
        loaded_object_count = sum(stat.model_counter.values())
        if loaded_object_count > 0:
            connection = connections[stat.db_alias]
            models = list(stat.model_counter)
            sequence_sql = connection.ops.sequence_reset_sql(no_style(), models)
            if sequence_sql:
                with connection.cursor() as cursor:
                    for line in sequence_sql:
                        cursor.execute(line)

def load_data_for_db(db_alias):
    """
    A coroutine that is sent object dictionaries and loads them into the
    database identified by ``db_alias``. When it is terminated with
    ``None``, it yields a LoadStat object.
    """
    model_counter = Counter()
    with transaction.atomic(using=db_alias), \
         constraint_checks_deferred(db_alias):
        while True:
            obj_dict = yield
            if obj_dict is None:
                break
            for obj in PythonDeserializer([obj_dict], using=db_alias):
                Model = type(obj.object)
                if not router.allow_migrate_model(db_alias, Model):
                    continue
                model_counter.update([Model])
                try:
                    # Force insert here to prevent Django from attempting to do an update.
                    # We want to ensure that if there is already data in the DB that we don't
                    # save over it and rather error out.
                    obj.save(using=db_alias, force_insert=True)
                except DatabaseError as err:
                    logger.exception("Error saving data")
                    m = Model._meta
                    key = f"pk={obj.object.pk}"
                    if hasattr(obj.object, "natural_key"):
                        key = f"key={obj.object.natural_key()}"
                    raise type(err)(
                        f'Could not load {m.app_label}.{m.object_name}'
                        f'({key}) in DB {db_alias!r}'
                    ) from err
    print(f'Loading DB {db_alias!r} complete')
    yield LoadStat(db_alias, model_counter)

@contextmanager
def constraint_checks_deferred(db_alias):
    """
    PostgreSQL does not support disabling constraint checks like MySQL.
    But you can defer them until transaction commit. Django's
    ``DatabaseWrapper`` for PostgreSQL doesn't have a method for this,
    so we need to execute raw SQL.
    """
    connection = connections[db_alias]
    with connection.cursor() as cursor:
        cursor.execute('SET CONSTRAINTS ALL DEFERRED')
        try:
            yield
        finally:
            if not cursor.db.needs_rollback:
                cursor.execute('SET CONSTRAINTS ALL IMMEDIATE')

def get_db_alias(obj: dict) -> str:
    app_label = obj['model']
    model = apps.get_model(app_label)
    router_hints = {}
    if hasattr(model, 'partition_attr'):
        try:
            partition_value = obj['fields'][model.partition_attr]
        except KeyError:
            # in the case of foreign keys the serialized field name is the
            # name of the foreign key attribute
            field, = [
                field for field in model._meta.fields
                if field.column == model.partition_attr
            ]
            try:
                partition_value = obj['fields'][field.name]
            except KeyError:
                if model.partition_attr == model._meta.pk.attname:
                    partition_value = obj['pk']
                else:
                    raise DataLoadException(f"Unable to find field {app_label}.{model.partition_attr}")

        router_hints[HINT_PARTITION_VALUE] = partition_value
    return router.db_for_write(model, **router_hints)

class DefaultDictWithKey(defaultdict):
    """
    A defaultdict that passes ``key`` to its factory
    """
    def __missing__(self, key):
        self[key] = value = self.default_factory(key)
        return value

class LoadStat:
    """
    Simple object for keeping track of stats
    """
    def __init__(self, db_alias, model_counter):
        self.db_alias = db_alias
        self.model_counter = model_counter

    def update(self, stat: 'LoadStat'):
        assert self.db_alias == stat.db_alias
        self.model_counter += stat.model_counter

def update_model_name(obj):
    name = obj["model"]
    obj["model"] = RENAMED_MODELS.get(name, name)

RENAMED_MODELS = {
    "form_processor.xforminstancesql": "form_processor.xforminstance",
    "form_processor.xformoperationsql": "form_processor.xformoperation",
    "form_processor.commcarecasesql": "form_processor.commcarecase",
    "form_processor.commcarecaseindexsql": "form_processor.commcarecaseindex",
    "form_processor.caseattachmentsql": "form_processor.caseattachment",
}