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

namespace RepetierHost.model
{
    public class LogLine
    {
        public string text;
        public bool response; // is it response or send data
        public int level = 0; // Info level 0 = normal, 1 = warning, 2 = error, 3 = info, 4 = Skeinforge
        public DateTime time;

        public LogLine(string _text, bool _response, int _level)
        {
            time = DateTime.Now;
            text = Time()+" : "+_text;
            response = _response;
            level = _level;
        }
        public string Time()
        {
            return time.Hour.ToString("00") + ":" + time.Minute.ToString("00") + ":" +
                time.Second.ToString("00") + "." + time.Millisecond.ToString("000");
        }
    }
    public class RLog
    {
        public static void info(string text)
        {
            Main.conn.log(text, false, 3);
        }
        public static void message(string text)
        {
            Main.conn.log(text, false, 0);
        }
        public static void warning(string text)
        {
            Main.conn.log(text, false, 1);
        }
        public static void error(string text)
        {
            Main.conn.log(text, false, 2);
        }
    }
}


text:
// Copyright 2000-2021 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 com.intellij.openapi.options.ex;

import com.intellij.CommonBundle;
import com.intellij.ide.SaveAndSyncHandler;
import com.intellij.ide.actions.ShowSettingsUtilImpl;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.IndexNotReadyException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.wm.ex.IdeFocusTraversalPolicy;
import com.intellij.ui.IdeUICustomization;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;

public class SingleConfigurableEditor extends DialogWrapper {
  private static final Logger LOG = Logger.getInstance(SingleConfigurableEditor.class);
  private Project myProject;
  private Configurable myConfigurable;
  private JComponent myCenterPanel;
  private final String myDimensionKey;
  private final boolean myShowApplyButton;
  private boolean mySaveAllOnClose;

  public SingleConfigurableEditor(@Nullable Project project,
                                  @NotNull Configurable configurable,
                                  String dimensionKey,
                                  boolean showApplyButton,
                                  @NotNull IdeModalityType ideModalityType) {
    super(project, true, ideModalityType);
    myDimensionKey = dimensionKey;
    myShowApplyButton = showApplyButton;
    String title = createTitleString(configurable);
    if (project != null && project.isDefault()) {
      title = IdeUICustomization.getInstance().projectMessage("title.for.new.projects", title);
    }

    setTitle(title);

    myProject = project;
    myConfigurable = configurable;
    init();
    myConfigurable.reset();
  }

  public SingleConfigurableEditor(Component parent,
                                  @NotNull Configurable configurable,
                                  String dimensionServiceKey,
                                  boolean showApplyButton,
                                  @NotNull IdeModalityType ideModalityType) {
    super(null, parent, true, ideModalityType);
    myDimensionKey = dimensionServiceKey;
    myShowApplyButton = showApplyButton;
    setTitle(createTitleString(configurable));

    myConfigurable = configurable;
    init();
    myConfigurable.reset();
  }

  public SingleConfigurableEditor(@Nullable Project project, Configurable configurable, String dimensionKey, boolean showApplyButton) {
    this(project, configurable, dimensionKey, showApplyButton, IdeModalityType.IDE);
  }

  public SingleConfigurableEditor(Component parent, Configurable configurable, String dimensionServiceKey, boolean showApplyButton) {
    this(parent, configurable, dimensionServiceKey, showApplyButton, IdeModalityType.IDE);
  }

  public SingleConfigurableEditor(@Nullable Project project, Configurable configurable, String dimensionKey, @NotNull IdeModalityType ideModalityType) {
    this(project, configurable, dimensionKey, true, ideModalityType);
  }

  public SingleConfigurableEditor(@Nullable Project project, Configurable configurable, String dimensionKey) {
    this(project, configurable, dimensionKey, true);
  }

  public SingleConfigurableEditor(Component parent, Configurable configurable, String dimensionServiceKey) {
    this(parent, configurable, dimensionServiceKey, true);
  }

  public SingleConfigurableEditor(@Nullable Project project, Configurable configurable, @NotNull IdeModalityType ideModalityType) {
    this(project, configurable, ShowSettingsUtilImpl.createDimensionKey(configurable), ideModalityType);
  }

  public SingleConfigurableEditor(@Nullable Project project, Configurable configurable) {
    this(project, configurable, ShowSettingsUtilImpl.createDimensionKey(configurable));
  }

  public SingleConfigurableEditor(Component parent, Configurable configurable) {
    this(parent, configurable, ShowSettingsUtilImpl.createDimensionKey(configurable));
  }

  public Configurable getConfigurable() {
    return myConfigurable;
  }

  public Project getProject() {
    return myProject;
  }

  private static @NlsContexts.DialogTitle String createTitleString(@NotNull Configurable configurable) {
    String displayName = configurable.getDisplayName();
    LOG.assertTrue(displayName != null, configurable.getClass().getName());
    return displayName.replaceAll("\n", " ");
  }

  @Override
  protected String getDimensionServiceKey() {
    return myDimensionKey != null ? myDimensionKey : super.getDimensionServiceKey();
  }

  @Override
  protected Action @NotNull [] createActions() {
    List<Action> actions = new ArrayList<>();
    actions.add(getOKAction());
    actions.add(getCancelAction());
    if (myShowApplyButton) {
      actions.add(new ApplyAction());
    }
    if (getHelpId() != null) {
      actions.add(getHelpAction());
    }
    return actions.toArray(new Action[0]);
  }

  @Nullable
  @Override
  protected String getHelpId() {
    return myConfigurable.getHelpTopic();
  }

  @Override
  protected void doOKAction() {
    try {
      if (myConfigurable.isModified()) {
        myConfigurable.apply();
        mySaveAllOnClose = true;
      }
    }
    catch (ConfigurationException e) {
      if (e.getMessage() != null) {
        if (myProject != null) {
          Messages.showMessageDialog(myProject, e.getMessage(), e.getTitle(), Messages.getErrorIcon());
        }
        else {
          Messages.showMessageDialog(getRootPane(), e.getMessage(), e.getTitle(), Messages.getErrorIcon());
        }
      }
      return;
    }

    super.doOKAction();
  }

  protected static String createDimensionKey(Configurable configurable) {
    String displayName = configurable.getDisplayName();
    displayName = displayName.replaceAll("\n", "_").replaceAll(" ", "_");
    return "#" + displayName;
  }

  protected class ApplyAction extends AbstractAction {
    private final Alarm myUpdateAlarm = new Alarm(getDisposable());

    public ApplyAction() {
      super(CommonBundle.getApplyButtonText());
      setEnabled(false); // should be disabled initially. the same as com.intellij.openapi.options.newEditor.ConfigurableEditor.init
      final Runnable updateRequest = new Runnable() {
        @Override
        public void run() {
          if (!isShowing()) return;
          try {
            setEnabled(myConfigurable != null && myConfigurable.isModified());
          }
          catch (IndexNotReadyException ignored) { }
          addUpdateRequest(this);
        }
      };

      // invokeLater necessary to make sure dialog is already shown so we calculate modality state correctly.
      SwingUtilities.invokeLater(() -> {
        // schedule if not already disposed
        if (myConfigurable != null) addUpdateRequest(updateRequest);
      });
    }

    private void addUpdateRequest(final Runnable updateRequest) {
      Window window = getWindow();
      myUpdateAlarm.addRequest(updateRequest, 500, window == null ? ModalityState.NON_MODAL : ModalityState.stateForComponent(window));
    }

    @Override
    public void actionPerformed(ActionEvent event) {
      if (myPerformAction) return;
      try {
        myPerformAction = true;
        if (myConfigurable.isModified()) {
          myConfigurable.apply();
          mySaveAllOnClose = true;
          setCancelButtonText(CommonBundle.getCloseButtonText());
        }
      }
      catch (ConfigurationException e) {
        if (myProject != null) {
          Messages.showMessageDialog(myProject, e.getMessage(), e.getTitle(), Messages.getErrorIcon());
        }
        else {
          Messages.showMessageDialog(getRootPane(), e.getMessage(), e.getTitle(), Messages.getErrorIcon());
        }
      }
      finally {
        myPerformAction = false;
      }
    }
  }

  @Override
  protected JComponent createCenterPanel() {
    myCenterPanel = myConfigurable.createComponent();
    return myCenterPanel;
  }

  @Override
  public JComponent getPreferredFocusedComponent() {
    Configurable configurable = myConfigurable;
    JComponent preferred = configurable == null ? null : configurable.getPreferredFocusedComponent();
    return preferred == null ? IdeFocusTraversalPolicy.getPreferredFocusedComponent(myCenterPanel) : preferred;
  }

  @Override
  public void dispose() {
    super.dispose();
    myConfigurable.disposeUIResources();
    myConfigurable = null;

    if (mySaveAllOnClose) {
      SaveAndSyncHandler.getInstance().scheduleSave(new SaveAndSyncHandler.SaveTask(myProject, /* forceSavingAllSettings = */ true));
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
"use strict";

const idlUtils = require("../generated/utils");

const ElementImpl = require("./Element-impl").implementation;
const MouseEvent = require("../generated/MouseEvent");
const GlobalEventHandlersImpl = require("./GlobalEventHandlers-impl").implementation;
const focusing = require("../helpers/focusing.js");
const conversions = require("webidl-conversions");
const isDisabled = require("../helpers/form-controls").isDisabled;

class HTMLElementImpl extends ElementImpl {
  constructor(args, privateData) {
    super(args, privateData);
    this._initGlobalEvents();

    this._tabIndex = 0;

    this._settingCssText = false;
    this._clickInProgress = false;

    this._style = new this._core.CSSStyleDeclaration(newCssText => {
      if (!this._settingCssText) {
        this._settingCssText = true;
        this.setAttribute("style", newCssText);
        this._settingCssText = false;
      }
    });
  }

  // Add default event behavior (click link to navigate, click button to submit
  // form, etc). We start by wrapping dispatchEvent so we can forward events to
  // the element's default functions (only events that did not incur
  // preventDefault).
  dispatchEvent(event) {
    if (event.type === "click") {
      callEventBehaviorHook(event, "_preClickActivationSteps", this);
    }

    const outcome = super.dispatchEvent(event);

    if (event.type === "click") {
      if (event.defaultPrevented) {
        callEventBehaviorHook(event, "_canceledActivationSteps");
      } else {
        callEventBehaviorHook(event, "_activationBehavior");
      }
    }

    return outcome;
  }

  focus() {
    if (!focusing.isFocusableAreaElement(this)) {
      return;
    }

    const previous = this._ownerDocument._lastFocusedElement;

    focusing.fireFocusEventWithTargetAdjustment("blur", previous, this);
    this._ownerDocument._lastFocusedElement = this;
    focusing.fireFocusEventWithTargetAdjustment("focus", this, previous);

    if (this._ownerDocument._defaultView._frameElement) {
      this._ownerDocument._defaultView._frameElement.focus();
    }
  }

  blur() {
    if (this._ownerDocument._lastFocusedElement !== this || !focusing.isFocusableAreaElement(this)) {
      return;
    }

    focusing.fireFocusEventWithTargetAdjustment("blur", this, this._ownerDocument);
    this._ownerDocument._lastFocusedElement = null;
    focusing.fireFocusEventWithTargetAdjustment("focus", this._ownerDocument, this);
  }

  click() {
    // https://html.spec.whatwg.org/multipage/interaction.html#dom-click
    // https://html.spec.whatwg.org/multipage/interaction.html#run-synthetic-click-activation-steps
    // Not completely spec compliant due to e.g. incomplete implementations of disabled for form controls, or no
    // implementation at all of isTrusted.

    if (this._clickInProgress) {
      return;
    }

    this._clickInProgress = true;

    if (isDisabled(this)) {
      return;
    }

    const event = MouseEvent.createImpl(["click", { bubbles: true, cancelable: true }], {});

    // Run synthetic click activation steps. According to the spec,
    // this should not be calling dispatchEvent, but it matches browser behavior.
    // See: https://www.w3.org/Bugs/Public/show_bug.cgi?id=12230
    // See also: https://github.com/whatwg/html/issues/805
    this.dispatchEvent(event);

    this._clickInProgress = false;
  }

  get dir() {
    let dirValue = this.getAttribute("dir");
    if (dirValue !== null) {
      dirValue = dirValue.toLowerCase();

      if (["ltr", "rtl", "auto"].includes(dirValue)) {
        return dirValue;
      }
    }
    return "";
  }
  set dir(value) {
    this.setAttribute("dir", value);
  }

  get style() {
    return this._style;
  }
  set style(value) {
    this._style.cssText = value;
  }

  _attrModified(name, value, oldValue) {
    if (name === "style" && value !== oldValue && !this._settingCssText) {
      this._settingCssText = true;
      this._style.cssText = value;
      this._settingCssText = false;
    } else if (name.startsWith("on")) {
      this._globalEventChanged(name.substring(2));
    }

    super._attrModified.apply(this, arguments);
  }

  // TODO this should be [Reflect]able if we added default value support to webidl2js's [Reflect]
  get tabIndex() {
    if (!this.hasAttribute("tabindex")) {
      return focusing.isFocusableAreaElement(this) ? 0 : -1;
    }
    return conversions.long(this.getAttribute("tabindex"));
  }

  set tabIndex(value) {
    this.setAttribute("tabIndex", String(value));
  }

  get offsetParent() {
    return null;
  }

  get offsetTop() {
    return 0;
  }

  get offsetLeft() {
    return 0;
  }

  get offsetWidth() {
    return 0;
  }

  get offsetHeight() {
    return 0;
  }
}

function callEventBehaviorHook(event, name, targetOverride) {
  if (event) {
    const target = targetOverride || event.target;
    if (target && typeof target[name] === "function") {
      target[name]();
    }
  }
}

idlUtils.mixin(HTMLElementImpl.prototype, GlobalEventHandlersImpl.prototype);

module.exports = {
  implementation: HTMLElementImpl
};


text:
from pyquery import PyQuery

class QueryMiss(Exception):
    pass

def query_op(d, spec):
    """ Example query:
    {"$query": "a"}

    or

    {"$query": "a",
     "$op": ["attr", "href"]}
    """

    query = spec['$query']

    if "$op" in spec:
        op = spec['$op']
    else:
        op = ['html']

    match = d(query)

    if len(match) == 0:
        raise QueryMiss(query)

    # Get the op details

    # If the length of the match is only 1, apply the operation and return
    # the result
    if len(match) == 1:
        func = getattr(match, op[0])
        args = op[1:]

        return func(*args)

    # If the length of the match is greater than 1, apply the opperation to
    # each element
    else:
        result = []

        for el in match:
            item = PyQuery(el)
            func = getattr(item, op[0])
            args = op[1:]

            result.append(func(*args))
        return result

OPERATION_MAP = {
    '$query': query_op,
}

def find_op(spec):
    operation = None
    for op in OPERATION_MAP.keys():
        if op in spec:
            operation = OPERATION_MAP[op]
            break
    return operation

def extract(d, spec):
    result = {}
    for key, val in spec.iteritems():
        if type(val) is dict:
            # Locate which operator to use
            operation = find_op(val)

            if operation is not None:
                val = operation(d, val)

        result[key] = val

    return result


text:
package ru.job4j.task;

/**
 * SimpleVictory class.
 * @author agavrikov
 * @since 28.08.2017
 * @version 1
 */
public class SimpleVictory implements Victory {

    /**
     * Method for find victory on board.
     * @param board board
     * @param lastI row
     * @param lastJ col
     * @return true? if victory founded< else false
     */
    @Override
    public boolean playerIsWin(Board board, int lastI, int lastJ) {
        boolean result = false;
        SimpleField[][] fields = board.fields();
        char charPlayer = fields[lastI][lastJ].mark.view;

        char[][] combinations = createCombinations(fields);

        for (int i = 0; i < combinations.length; i++){
            result = true;
            for(int j = 0; j < combinations[i].length; j++) {
                if (combinations[i][j] != charPlayer) {
                    result = false;
                    break;
                }
            }
            if (result) {
                break;
            }
        }

        return result;
    }

    /**
     * Additional method for create arrays of win positions.
     * @param fields fields
     * @return array of win positions
     */
    private char[][] createCombinations(SimpleField[][] fields) {
        char[][] combinations = new char[fields.length * 2 + 2][fields.length];
        for (int i = 0; i < fields.length; i++) {
            for (int j = 0; j < fields.length; j++) {
                combinations[i][j] = fields[i][j].mark.view;
                combinations[j + fields[i].length][j] = fields[j][i].mark.view;
            }
            if(i + 1 < fields.length) {
                combinations[fields[i].length * 2 + 1][i] = fields[i][i + 1].mark.view;
            }
            int curCol = fields.length - 1 - i;
            combinations[fields[i].length * 2 + 1][i] = fields[i][curCol].mark.view;
        }
        return combinations;
    }
}


text:
<?xml version='1.0' encoding='utf-8' ?>

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    android:paddingBottom="12dp"
    android:paddingLeft="8dp"
    android:paddingRight="8dp"
    android:paddingTop="12dp"
    android:textSize="16sp"
    android:textColor="@color/black" />


text:
local awful = require("awful")
local noti = require("utils.noti")
local table = require("gears.table")
local icons = require("config.icons")
local button = require("utils.button")
local font = require("utils.font")

-- widget creation
local scrot_icon = button({
  fg_icon = M.x.on_background,
  icon = font.button(icons.widget.scrot),
  layout = "horizontal"
})

function take_scrot(time)
  local time = time or 0
  local title = "Screenshot is taken." -- default
  if time >= 1 then
    title = "Screenshot taken in "..time.." sec(s)..."
  end
  awful.spawn.with_shell("scrot -d "..time.." -q 100")
  noti.info(title)
end

scrot_icon:buttons(table.join(
  awful.button({ }, 1, function() -- left click
    take_scrot()
  end),
  awful.button({}, 2, function() -- middle click
    take_scrot(3)
  end),
  awful.button({}, 3, function() -- right
    take_scrot(1)
  end)
))

return scrot_icon


text:
package net.aeten.core;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface ModuleInfo {
	String name();

	String version();

	String copyright();
}


text:
from typing import Dict, List
from sqlalchemy import MetaData, create_engine, inspect
from sqlalchemy.engine import Engine
from sqlalchemy.engine.reflection import Inspector

from ._config import SQLALCHEMY_DATABASE_URI, SQLALCHEMY_ENGINE_OPTIONS

engine: Engine = create_engine(SQLALCHEMY_DATABASE_URI, **SQLALCHEMY_ENGINE_OPTIONS)
metadata = MetaData(bind=engine)

TABLE_OPTIONS = dict(
    mysql_engine="InnoDB",
    # mariadb_engine="InnoDB",
    mysql_charset="utf8mb4",
    # mariadb_charset="utf8",
)

def sql_table_has_columns(table: str, columns: List[str]) -> bool:
    """
    checks whether the given table has all the given columns defined
    """
    inspector: Inspector = inspect(engine)
    table_columns: List[Dict] = inspector.get_columns(table)
    table_column_names = set(str(d.get("name", "")).lower() for d in table_columns)
    return all(c.lower() in table_column_names for c in columns)


text:
package eventstore
package core
package cluster

import scala.collection.immutable.SortedSet

sealed trait NodeState extends Ordered[NodeState] {
  def id: Int
  def isAllowedToConnect: Boolean
  def compare(that: NodeState) = this.id compare that.id
}

object NodeState {
  val values: SortedSet[NodeState] = SortedSet(
    Initializing,
    ReadOnlyLeaderless,
    DiscoverLeader,
    Unknown,
    PreReadOnlyReplica,
    PreReplica,
    CatchingUp,
    Clone,
    ReadOnlyReplica,
    Follower,
    PreLeader,
    Leader,
    Manager,
    ShuttingDown,
    Shutdown,
    ResigningLeader
  )

  final val oldTerminology: Map[String, NodeState] = Map(
    "Slave"     -> NodeState.Follower,
    "Master"    -> NodeState.Leader,
    "PreMaster" -> NodeState.PreLeader
  )

  private val map: Map[String, NodeState] =
    values.map(x => x.toString -> x).toMap ++ oldTerminology

  def apply(x: String): NodeState =
    map.getOrElse(x, throw new IllegalArgumentException(s"No NodeState found for $x"))

  // id value and order derived from:
  // https://github.com/EventStore/EventStoreDB-Client-Dotnet-Legacy/blob/24cacecb6f003df5015258b05d8356e12c6b694f/src/EventStore.ClientAPI/Messages/ClusterMessages.cs#L74

  @SerialVersionUID(1L) case object Initializing extends NodeState {
    def id = 0
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object ReadOnlyLeaderless extends NodeState {
    def id = 1
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object DiscoverLeader extends NodeState {
    def id = 2
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object Unknown extends NodeState {
    def id = 3
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object PreReadOnlyReplica extends NodeState {
    def id = 4
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object PreReplica extends NodeState {
    def id = 5
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object CatchingUp extends NodeState {
    def id = 6
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object Clone extends NodeState {
    def id = 7
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object ReadOnlyReplica extends NodeState {
    def id = 8
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object Follower extends NodeState {
    def id = 9
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object PreLeader extends NodeState {
    def id = 10
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object Leader extends NodeState {
    def id = 11
    def isAllowedToConnect = true
  }

  @SerialVersionUID(1L) case object Manager extends NodeState {
    def id = 12
    def isAllowedToConnect = false
  }

  @SerialVersionUID(1L) case object ShuttingDown extends NodeState {
    def id = 13
    def isAllowedToConnect = false
  }

  @SerialVersionUID(1L) case object Shutdown extends NodeState {
    def id = 14
    def isAllowedToConnect = false
  }

   @SerialVersionUID(1L) case object ResigningLeader extends NodeState {
    def id = 15
    def isAllowedToConnect = false
  }

}


text:
package com.android.tools.build.bundletool.mergers;

import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.androidManifest;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.androidManifestForAssetModule;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.androidManifestForFeature;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.androidManifestForMlModule;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.withFeatureCondition;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.withInstallTimeDelivery;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.withInstallTimeRemovableElement;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.withMetadataValue;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.withMinSdkVersion;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.withOnDemandDelivery;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.withSplitNameActivity;
import static com.android.tools.build.bundletool.testing.ManifestProtoUtils.withSplitNameService;
import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static com.google.common.truth.extensions.proto.ProtoTruth.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;

import com.android.aapt.Resources.XmlNode;
import com.android.bundle.Config.BundleConfig;
import com.android.tools.build.bundletool.TestData;
import com.android.tools.build.bundletool.io.ZipBuilder;
import com.android.tools.build.bundletool.model.AppBundle;
import com.android.tools.build.bundletool.model.BundleModuleName;
import com.android.tools.build.bundletool.model.ZipPath;
import com.android.tools.build.bundletool.model.exceptions.InvalidBundleException;
import com.android.tools.build.bundletool.testing.BundleConfigBuilder;
import com.google.common.truth.Correspondence;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Path;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipFile;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for the {@link BundleModuleMerger} class. */
@RunWith(JUnit4.class)
public class BundleModuleMergerTest {
  private static final byte[] TEST_CONTENT = new byte[1];
  private static final byte[] TEST_CONTENT_2 = new byte[2];
  private static final BundleConfig BUNDLE_CONFIG_1_0_0 =
      BundleConfigBuilder.create().setVersion("1.0.0").build();
  private static final BundleConfig BUNDLE_CONFIG_1_8_0 =
      BundleConfigBuilder.create().setVersion("1.8.0").build();
  private static final BundleConfig BUNDLE_CONFIG_0_14_0 =
      BundleConfigBuilder.create().setVersion("0.14.0").build();
  private static final XmlNode MANIFEST = androidManifest("com.test.app.detail");

  @Rule public TemporaryFolder tmp = new TemporaryFolder();

  private Path bundleFile;

  @Before
  public void setUp() {
    bundleFile = tmp.getRoot().toPath().resolve("bundle.aab");
  }

  @Test
  public void testMultipleModulesWithInstallTime_implicitMerging() throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);
      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_implicitMerging_duplicateModuleEntries()
      throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail1/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail1/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail2/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail2/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("detail2/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);
      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_throws_duplicateModuleEntriesWithDifferentContent()
      throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail1/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail1/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail2/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail2/assets/baseAssetfile.txt"), TEST_CONTENT_2)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      InvalidBundleException exception =
          assertThrows(
              InvalidBundleException.class,
              () ->
                  BundleModuleMerger.mergeNonRemovableInstallTimeModules(
                      AppBundle.buildFromZip(appBundleZip),
                      /* overrideBundleToolVersion = */ false));
      assertThat(exception)
          .hasMessageThat()
          .contains("Existing module entry 'assets/baseAssetfile.txt' with different contents.");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_noMergingIfBuiltWithOlderBundleTool()
      throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_0_14_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);
      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base", "detail");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_bundleToolVersionOverride() throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_0_14_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ true);

      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base");
    }
  }

  // Override ignored for bundles built by bundletool version >= 1.0.0. Allows developers to
  // selectively merge modules.
  @Test
  public void testMultipleModulesWithInstallTime_bundleToolVersionOverrideIgnored()
      throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeDelivery());
    XmlNode installTimeNonRemovableModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeRemovableElement(false));
    XmlNode installTimeRemovableModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeRemovableElement(true));
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        // merged by default
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail2/manifest/AndroidManifest.xml"),
            installTimeNonRemovableModuleManifest)
        .addFileWithContent(ZipPath.create("detail2/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail3/manifest/AndroidManifest.xml"),
            installTimeRemovableModuleManifest)
        .addFileWithContent(ZipPath.create("detail3/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ true);

      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base", "detail3");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_notMergingAssetModules() throws Exception {
    XmlNode assetModuleManifest =
        androidManifestForAssetModule("com.test.app.detail", withInstallTimeDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), assetModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);

      assertThat(appBundle.getAssetModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("detail");
      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_notMergingMlModules() throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForMlModule("com.test.app.detail", withInstallTimeDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);

      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base", "detail");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_explicitMerging() throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeRemovableElement(false));
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundlePreMerge = AppBundle.buildFromZip(appBundleZip);
      AppBundle appBundlePostMerge =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              appBundlePreMerge, /* overrideBundleToolVersion = */ false);

      assertThat(
              appBundlePreMerge.getModules().values().stream()
                  .mapToLong(module -> module.getEntries().size())
                  .sum())
          .isEqualTo(
              appBundlePostMerge.getModules().values().stream()
                  .mapToLong(module -> module.getEntries().size())
                  .sum());
      assertThat(appBundlePostMerge.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_mergingOptedOut() throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeRemovableElement(true));
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);

      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base", "detail");
    }
  }

  @Test
  public void testDoNotMergeIfNotInstallTime() throws Exception {
    XmlNode onDemandModuleManifest =
        androidManifestForFeature("com.test.app.detail", withOnDemandDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), onDemandModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);

      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base", "detail");
    }
  }

  @Test
  public void testDoNotMergeIfConditionalModule() throws Exception {
    XmlNode conditionalModuleManifest =
        androidManifest(
            "com.test.app.detail", withMinSdkVersion(24), withFeatureCondition("android.feature"));
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), conditionalModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);

      assertThat(appBundle.getFeatureModules().keySet())
          .comparingElementsUsing(equalsBundleModuleName())
          .containsExactly("base", "detail");
    }
  }

  @Test
  public void testMultipleModulesWithInstallTime_implicitMergingDexRenaming() throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature("com.test.app.detail", withInstallTimeDelivery());
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithContent(ZipPath.create("base/dex/classes.dex"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("base/assets/baseAssetfile.txt"), TEST_CONTENT)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .addFileWithContent(ZipPath.create("detail/assets/detailsAssetfile.txt"), TEST_CONTENT)
        .addFileWithContent(ZipPath.create("detail/dex/classes.dex"), TEST_CONTENT)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundlePreMerge = AppBundle.buildFromZip(appBundleZip);
      AppBundle appBundlePostMerge =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              appBundlePreMerge, /* overrideBundleToolVersion = */ false);
      assertThat(appBundlePostMerge.getModules().keySet().stream().map(BundleModuleName::getName))
          .containsExactly("base");
      assertThat(
              appBundlePreMerge.getModules().values().stream()
                  .mapToLong(module -> module.getEntries().size())
                  .sum())
          .isEqualTo(
              appBundlePostMerge.getModules().values().stream()
                  .mapToLong(module -> module.getEntries().size())
                  .sum());
      assertThat(appBundlePostMerge.getBaseModule().getEntry(ZipPath.create("dex/classes.dex")))
          .isPresent();
      assertThat(appBundlePostMerge.getBaseModule().getEntry(ZipPath.create("dex/classes2.dex")))
          .isPresent();
    }
  }

  @Test
  public void testRealBundle() throws Exception {
    File file = tmp.newFile();
    try (FileOutputStream os = new FileOutputStream(file)) {
      // This bundle has a base module and 3 feature modules: java, assets and initialInstall.
      // initialInstall should be merged into base.
      os.write(TestData.readBytes("testdata/bundle/install-time-permanent-modules.aab"));
    }
    Path bundleFile = file.toPath();

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundlePreMerge = AppBundle.buildFromZip(appBundleZip);
      AppBundle appBundlePostMerge =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              appBundlePreMerge, /* overrideBundleToolVersion = */ false);

      assertThat(appBundlePostMerge.getModules().keySet().stream().map(BundleModuleName::getName))
          .containsExactly("base", "java", "assets");
      assertEntriesPreserved(appBundlePreMerge, appBundlePostMerge);
      assertThat(appBundlePostMerge.getBaseModule().getEntry(ZipPath.create("dex/classes.dex")))
          .isPresent();
      assertThat(appBundlePostMerge.getBaseModule().getEntry(ZipPath.create("dex/classes2.dex")))
          .isPresent();
    }
  }

  @Test
  public void fuseApplicationElementsInManifest_1_8_0() throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature(
            "com.test.app.detail",
            withInstallTimeDelivery(),
            withSplitNameActivity("activity1", "detail"),
            withSplitNameService("service", "detail"));
    createBasicZipBuilder(BUNDLE_CONFIG_1_8_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);

      XmlNode fusedManifest =
          androidManifest(
              "com.test.app.detail",
              withSplitNameActivity("activity1", "detail"),
              withSplitNameService("service", "detail"),
              withMetadataValue("com.android.dynamic.apk.fused.modules", "base,detail"));
      assertThat(appBundle.getBaseModule().getAndroidManifest().getManifestRoot().getProto())
          .isEqualTo(fusedManifest);
    }
  }

  @Test
  public void fuseOnlyActivitiesInManifest_1_0_0() throws Exception {
    XmlNode installTimeModuleManifest =
        androidManifestForFeature(
            "com.test.app.detail",
            withInstallTimeDelivery(),
            withSplitNameActivity("activity1", "detail"),
            withSplitNameService("service", "detail"));
    createBasicZipBuilder(BUNDLE_CONFIG_1_0_0)
        .addFileWithProtoContent(ZipPath.create("base/manifest/AndroidManifest.xml"), MANIFEST)
        .addFileWithProtoContent(
            ZipPath.create("detail/manifest/AndroidManifest.xml"), installTimeModuleManifest)
        .writeTo(bundleFile);

    try (ZipFile appBundleZip = new ZipFile(bundleFile.toFile())) {
      AppBundle appBundle =
          BundleModuleMerger.mergeNonRemovableInstallTimeModules(
              AppBundle.buildFromZip(appBundleZip), /* overrideBundleToolVersion = */ false);

      XmlNode fusedManifest =
          androidManifest(
              "com.test.app.detail",
              withSplitNameActivity("activity1", "detail"),
              withMetadataValue("com.android.dynamic.apk.fused.modules", "base,detail"));
      assertThat(appBundle.getBaseModule().getAndroidManifest().getManifestRoot().getProto())
          .isEqualTo(fusedManifest);
    }
  }

  private static Correspondence<BundleModuleName, String> equalsBundleModuleName() {
    return Correspondence.from(
        (BundleModuleName bundleModuleName, String moduleName) ->
            bundleModuleName.getName().equals(moduleName),
        "equals");
  }

  private static void assertEntriesPreserved(
      AppBundle appBundlePreMerge, AppBundle appBundlePostMerge) {
    assertThat(
            appBundlePreMerge.getModules().values().stream()
                .mapToLong(module -> module.getEntries().size())
                .sum())
        .isEqualTo(
            appBundlePostMerge.getModules().values().stream()
                .mapToLong(module -> module.getEntries().size())
                .sum());

    // Doesn't account for classes2.dex. Verified later.
    assertThat(
            appBundlePostMerge.getModule(BundleModuleName.create("base")).getEntries().stream()
                .map(moduleEntry -> moduleEntry.getPath().toString())
                .collect(Collectors.toSet()))
        .containsAtLeastElementsIn(
            Stream.concat(
                    appBundlePreMerge
                        .getModule(BundleModuleName.create("base"))
                        .getEntries()
                        .stream()
                        .map(moduleEntry -> moduleEntry.getPath().toString()),
                    appBundlePreMerge
                        .getModule(BundleModuleName.create("initialInstall"))
                        .getEntries()
                        .stream()
                        .map(moduleEntry -> moduleEntry.getPath().toString()))
                .collect(Collectors.toSet()));

    assertThat(
            appBundlePreMerge.getModule(BundleModuleName.create("java")).getEntries().stream()
                .map(moduleEntry -> moduleEntry.getPath().toString())
                .collect(Collectors.toSet()))
        .containsExactlyElementsIn(
            appBundlePostMerge.getModule(BundleModuleName.create("java")).getEntries().stream()
                .map(moduleEntry -> moduleEntry.getPath().toString())
                .collect(Collectors.toSet()));
    assertThat(
            appBundlePreMerge.getModule(BundleModuleName.create("assets")).getEntries().stream()
                .map(moduleEntry -> moduleEntry.getPath().toString())
                .collect(Collectors.toSet()))
        .containsExactlyElementsIn(
            appBundlePostMerge.getModule(BundleModuleName.create("assets")).getEntries().stream()
                .map(moduleEntry -> moduleEntry.getPath().toString())
                .collect(Collectors.toSet()));
  }

  private static ZipBuilder createBasicZipBuilder(BundleConfig config) {
    ZipBuilder zipBuilder = new ZipBuilder();
    return zipBuilder.addFileWithContent(ZipPath.create("BundleConfig.pb"), config.toByteArray());
  }
}


text:
import React, {Component} from 'react'
import {string} from 'prop-types'
import {connect} from 'react-redux'
import withReduxSaga from '..'
import Layout from '../components/layout'

import {
  GET_SYNC_REDUX_PROP_TYPE,
  GET_ASYNC_REDUX_SAGA_PROP_TYPE,
  STATIC_PROP_TEXT,
  SYNC_REDUX_PROP_TEXT,
} from '../test/constants'

class AsyncExample extends Component {
  static propTypes = {
    staticProp: string,
    syncReduxProp: string,
    asyncReduxSagaProp: string,
  }

  static getInitialProps({ctx: {store}}) {
    store.dispatch({
      type: GET_SYNC_REDUX_PROP_TYPE,
      data: SYNC_REDUX_PROP_TEXT,
    })

    store.dispatch({type: GET_ASYNC_REDUX_SAGA_PROP_TYPE})
    return {staticProp: STATIC_PROP_TEXT}
  }

  render() {
    const {staticProp, syncReduxProp, asyncReduxSagaProp} = this.props

    return (
      <Layout>

          Received static prop:

            {staticProp}

          Received synchronous Redux prop:

            {syncReduxProp}

          Received asynchronous Redux-Saga prop:

            {asyncReduxSagaProp || 'loading...'}

      </Layout>
    )
  }
}

export default withReduxSaga(connect(state => state)(AsyncExample))


text:
package com.android.heightmapprofiler;

import android.graphics.Bitmap;
import android.graphics.Color;

// This class generates vertex arrays based on grayscale images.
// It defines 1.0 (white) as the tallest point and 0.0 (black) as the lowest point,
// and builds a mesh that represents that topology.
public class HeightMapMeshMaker {

	public static final Grid makeGrid(Bitmap drawable, Bitmap lightmap, int subdivisions, float width, float height, float scale, boolean fixedPoint) {
    	Grid grid = null;

    	final float subdivisionRange = subdivisions - 1;

    	final float vertexSizeX = width / subdivisionRange;
    	final float vertexSizeZ = height / subdivisionRange;

    	if (drawable != null) {
    		grid = new Grid(subdivisions, subdivisions, fixedPoint);
    		final float heightMapScaleX = drawable.getWidth() / subdivisionRange;
    		final float heightMapScaleY = drawable.getHeight() / subdivisionRange;
    		final float lightMapScaleX = lightmap != null ? lightmap.getWidth() / subdivisions : 0.0f;
    		final float lightMapScaleY = lightmap != null ? lightmap.getHeight() / subdivisions : 0.0f;

    		final float[] vertexColor = { 1.0f, 1.0f, 1.0f, 1.0f };
    		for (int i = 0; i < subdivisions; i++) {
    			final float u = (float)(i + 1) / subdivisions;
    			for (int j = 0; j < subdivisions; j++) {
    				final float v = (float)(j + 1) / subdivisions;

    				final float vertexHeight = getBilinearFilteredHeight(drawable, (heightMapScaleX * i), (heightMapScaleY * j), scale);

    				if (lightmap != null) {
    					final int lightColor = lightmap.getPixel((int)(lightMapScaleX * i), (int)(lightMapScaleY * j));
    					final float colorScale = 1.0f / 255.0f;
    					vertexColor[0] = colorScale * Color.red(lightColor);
    					vertexColor[1] = colorScale * Color.green(lightColor);
    					vertexColor[2] = colorScale * Color.blue(lightColor);
    					vertexColor[3] = colorScale * Color.alpha(lightColor);

    				}
    				grid.set(i, j, i * vertexSizeX, vertexHeight, j * vertexSizeZ, u, v, vertexColor);
    			}
    		}
      	}
    	return grid;
    }

	// In order to get a smooth gradation between pixels from a low-resolution height map,
	// this function uses a bilinear filter to calculate a weighted average of four pixels
	// surrounding the requested point.
	public static final float getBilinearFilteredHeight(Bitmap drawable, float x, float y, float scale) {
		final int topLeftPixelX = clamp((int)Math.floor(x), 0, drawable.getWidth() - 1);
		final int topLeftPixelY = clamp((int)Math.floor(y), 0, drawable.getHeight() - 1);
		final int bottomRightPixelX = clamp((int)Math.ceil(x), 0, drawable.getWidth() - 1);
		final int bottomRightPixelY = clamp((int)Math.ceil(y), 0, drawable.getHeight() - 1);
		final float topLeftWeightX = x - topLeftPixelX;
		final float topLeftWeightY = y - topLeftPixelY;
		final float bottomRightWeightX = 1.0f - topLeftWeightX;
		final float bottomRightWeightY = 1.0f - topLeftWeightY;

		final int topLeft = drawable.getPixel(topLeftPixelX, topLeftPixelY);
		final int topRight = drawable.getPixel(bottomRightPixelX, topLeftPixelY);
		final int bottomLeft = drawable.getPixel(topLeftPixelX, bottomRightPixelY);
		final int bottomRight = drawable.getPixel(bottomRightPixelX, bottomRightPixelY);

		final float red1 = bottomRightWeightX * Color.red(topLeft) + topLeftWeightX * Color.red(topRight);
		final float red2 = bottomRightWeightX * Color.red(bottomLeft) + topLeftWeightX * Color.red(bottomRight);
		final float red = bottomRightWeightY * red1 + topLeftWeightY * red2;

		final float height = red * scale;
		return height;

	}

	private static final int clamp(int value, int min, int max) {
		return value < min ? min : (value > max ? max : value);
	}
}


text:
        Mi cuenta

Mis datos personales

<?php echo anchor('login/logout','Salir'); ?>


text:
//==============================================================================
//         Copyright 2009 - 2013 LRI    UMR 8623 CNRS/Univ Paris Sud XI
//         Copyright 2012 - 2013 MetaScale SAS
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_SDK_BENCH_BENCHMARK_HPP_INCLUDED
#define NT2_SDK_BENCH_BENCHMARK_HPP_INCLUDED

#include <nt2/sdk/config/type_lists.hpp>
#include <nt2/sdk/bench/config.hpp>
#include <nt2/sdk/bench/suite.hpp>
#include <nt2/sdk/bench/args.hpp>
#include <nt2/sdk/bench/details/bench.hpp>

#define NT2_UNIT_MAIN_SUITE nt2::details::benchmarks

#include <nt2/sdk/unit/module.hpp>
#include <nt2/sdk/unit/details/base_case.hpp>
#include <boost/preprocessor/seq/for_each.hpp>

/*
  Note: We use the factorized TEST_BASE_* macro but without any suffix so the
  display and the speedup identification works without any changes
*/

/*!
  @brief Single benchmark registration

  Create and register a function as a benchmark by creating all the needed
  boilerplate code around the body of the benchmark function itself.

  @param Name Experiment type used in this benchmark
**/
#define NT2_REGISTER_BENCHMARK(Name)                                           \
NT2_TEST_BASE_CASE(Name,nt2::details::bench,nt2::details::benchmarks,)         \
/**/

/*!
  @brief Template benchmarks registration

  Create and register a template function as benchmarks by creating all the
  needed boilerplate code around the body of the benchmark function itself so
  that every instantiation of said function for a type inside the preprocessor
  sequence TYPES is run independently.

  @param Name   Experiment type used in this benchmark
  @param Types  Preprocessor sequence of type to pass to the benchmark function
**/
#define NT2_REGISTER_BENCHMARK_TPL(Name, Types)                                \
NT2_TEST_BASE_CASE_TPL( Name, Types                                            \
                      , nt2::details::bench                                    \
                      , nt2::details::benchmarks                               \
                      ,                                                        \
                      )                                                        \
/**/

#endif


text:
package org.patricbrc.Workspace;

import java.io.*;
import java.util.*;
import org.codehaus.jackson.map.*;
import org.codehaus.jackson.map.annotate.*;
import org.codehaus.jackson.type.*;
import org.codehaus.jackson.*;

public class return_get_download_url_deserializer extends JsonDeserializer<return_get_download_url>
{
    public return_get_download_url deserialize(JsonParser p, DeserializationContext ctx)
	throws IOException, JsonProcessingException
    {
	return_get_download_url res = new return_get_download_url();
	if (!p.isExpectedStartArrayToken())
	{
		System.out.println("Bad parse in return_get_download_url_deserializer: " + p.getCurrentToken());
		return null;
	}
	p.nextToken();
	res.urls = p.readValueAs(new TypeReference<List<String>>(){});
	JsonToken t = p.nextToken();
//	System.out.println("exit return_get_download_url_deserializer with token " + t);

	return res;
    }
}


text:
<?php

namespace machour\yii2\google\apiclient\commands;

use Google_Auth_Exception;
use Google_Client;
use Yii;
use yii\console\Controller;
use yii\console\Exception;
use yii\helpers\Json;

/**
 * This command interacts with Google API in order to set up your environment.
 *
 * @author Mehdi Achour <machour@gmail.com>
 * @since 1.0
 */
class GoogleController extends Controller
{

    /**
     * Google API discovery backend
     */
    const DISCOVERY_URL = 'https://www.googleapis.com/discovery/v1/apis';

    /**
     * @var array Api cache for the {getApis} getter
     */
    private $theApis = [];

    /**
     * @var string The access tokens directory
     */
    public $configPath = '@runtime/google-apiclient/';

    /**
     * @var string
     */
    public $clientSecretPath = '@runtime/google-apiclient/secret.json';

    /**
     * Prints this help message
     */
    public function actionIndex()
    {
        $this->run('/help', ['google_apiclient']);
    }

    /**
     * Configures a Google API
     *
     * @param string $clientSecretPath The client secret file path
     * @param string $api The api identifier. Will be prompted for if not provided.
     * @throws Exception
     */
    public function actionConfigure($clientSecretPath, $api = '')
    {

        $this->clientSecretPath = Yii::getAlias($clientSecretPath);
        if (!file_exists($this->clientSecretPath)) {
            throw new Exception("The client secret file \"{$this->clientSecretPath}\" does not exist!");
        }

        if (!$api || !isset($this->apis[$api])) {
            if ($api) {
                $this->stderr("Error: Unknown API requested: $api, prompting for the correct one..\n");
            }
            // prompt for the api to use
            $options = [];
            foreach ($this->apis as $id => $versions) {
                foreach ($versions as $version => $_api) {
                    $options[$id] = $_api->title;
                    break;
                }
            }
            $api = $this->select("\nPick an API to connect to", $options);
        }

        $version = false;
        if (count($this->apis[$api]) > 1) {
            if ($this->prompt("\nThe $api API has several versions. Install preferred version?")) {
                foreach ($this->apis[$api] as $_api) {
                    if ($_api->preferred) {
                        $version = $_api->version;
                    }
                }
            } else {
                $versions = [];
                foreach ($this->apis[$api] as $version => $_api) {
                    $versions[$version] = $version;
                }
                $version = $this->select("\nPick the desired version number", $versions);
            }
        } else {
            $version = array_keys($this->apis[$api])[0];
        }

        if ($version) {
            // Discover the API
            $discovery = $this->apis[$api][$version];

            $response = Json::decode(file_get_contents($discovery->discoveryRestUrl), false);

            $scopes = [];
            // Prompt for scopes if any
            if (isset($response->auth->oauth2->scopes)) {
                $this->stdout("\nAvailable scopes :\n");
                $availableScopes = [];
                foreach ($response->auth->oauth2->scopes as $scope => $desc) {
                    $availableScopes[] = $scope;
                    $this->stdout("  $scope\t\t{$desc->description}\n");
                }

                $done = false;
                while (!$done) {
                    $inputs = explode(',', $this->prompt("Please enter the required scopes separated by a comma:"));
                    $scopes = [];

                    foreach ($inputs as $input) {
                        $input = trim($input);
                        if ($input) {
                            if (!in_array($input, $availableScopes)) {
                                $this->stderr("Error in the input string, prompting again...\n\n");
                                continue 2;
                            } else {
                                $scopes[] = $input;
                            }
                        }
                    }

                    if (!empty($scopes)) {
                        $done = true;
                    }
                }
            }

            $credentialsPath = $this->generateCredentialsFile($api, $scopes);
            $this->stdout(sprintf("Credentials saved to %s\n\n", $credentialsPath));

        } else {
            $this->stderr("Something went terribly wrong..\n");
        }
    }

    /**
     * List all the available APIs
     *
     * @param bool|false $showAllVersions Whether to show all versions of each API
     */
    public function actionList($showAllVersions = false)
    {
        foreach ($this->apis as $id => $versions) {
            foreach ($versions as $version => $api) {
                if (!$showAllVersions) {
                    $this->stdout($api->name . ' - ' . $api->title . "\n");
                    break;
                } else {
                    $this->stdout($api->id . ' - ' . $api->title . "\n");
                }
            }
        }
    }

    /**
     * Fetches the Google API list
     *
     * @return array
     */
    public function getApis()
    {
        if (empty($this->theApis)) {
            $response = Json::decode(file_get_contents(self::DISCOVERY_URL), false);

            $theApis = [];
            foreach ($response->items as $item) {
                if (!isset($theApis[$item->name])) {
                    $theApis[$item->name] = [];
                }
                $theApis[$item->name][$item->version] = $item;
            }
            ksort($theApis);

            $this->theApis = $theApis;
        }

        return $this->theApis;
    }

    /**
     * Generates the credential file, prompting the user for the verification code
     * @param string $api The API name
     * @param Array $scopes The desired scopes
     * @return string
     */
    private function generateCredentialsFile($api, $scopes) {

        $credentialsPath = Yii::getAlias($this->configPath) . '/' . $api . '_' . $this->getUuid() . '.json';

        $client = new Google_Client();
        $client->setAuthConfigFile($this->clientSecretPath);
        $client->setAccessType('offline');
        $client->setScopes(implode(' ', $scopes));

        // Request authorization from the user.
        $authUrl = $client->createAuthUrl();
        $this->stdout(sprintf("Open the following link in your browser:\n  %s\n", $authUrl));

        $authenticated = false;

        while (!$authenticated) {
            $authCode = $this->prompt("Enter the verification code: ");

            // Exchange authorization code for an access token.
            try {
                $accessToken = $client->authenticate($authCode);
                $authenticated = true;
            } catch (Google_Auth_Exception $e) {
                $this->stderr($e->getMessage() . "\n");
            }
        }

        // Store the credentials to disk.
        if (!is_dir(dirname($credentialsPath))) {
            mkdir(dirname($credentialsPath), 0700, true);
        }
        /** @var string $accessToken */
        file_put_contents($credentialsPath, $accessToken);

        return $credentialsPath;

    }

    /**
     * Generates a v4 UUID
     *
     * @return string
     */
    private function getUuid() {
        return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',

            // 32 bits for "time_low"
            mt_rand(0, 0xffff), mt_rand(0, 0xffff),

            // 16 bits for "time_mid"
            mt_rand(0, 0xffff),

            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 4
            mt_rand(0, 0x0fff) | 0x4000,

            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            mt_rand(0, 0x3fff) | 0x8000,

            // 48 bits for "node"
            mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
        );
    }
}