text:
"""Displays the results of the analysis to the user, using images and plots."""
from interface.Qt import QtGui, QtCore
from interface.ui import AddBackendDialog, PreferencesDialog
from interface.ui import PlotWindow, ImageWindow
from interface.ui import Ui_mainWindow
from interface.recorder import H5Recorder
from interface import DataSource
import logging
import os

class GUI(QtGui.QMainWindow, Ui_mainWindow):
    """Main Window Class.

    Contains only menus and toolbars. The plots will be in their own windows.
    """
    instance = None
    def __init__(self, restore):
        QtGui.QMainWindow.__init__(self)
        self._data_windows = []
        self._data_sources = []
        self._recorder = None
        self.settings = None
        self.setupUi(self)
        self.restore_settings(restore)
        self._init_timer()
        GUI.instance = self

    # This is to fix a resizing bug on Mac
    def resizeEvent(self, event):
        QtGui.QMainWindow.resizeEvent(self, event)
        QtGui.QApplication.processEvents()

    def clear(self):
        """Closes all DataWindows and remove all DataSources"""
        # Need to copy self._data_windows before iterating
        # as the original list gets modified in the close() call
        # screwing a simple iteration
        for dw in list(self._data_windows):
            dw.close()
            del dw
        self._data_windows = []

        for ds in self._data_sources:
            del ds
        self._data_sources = []
        self.plotdata_widget.table.clearContents()
        self.plotdata_widget.table.setRowCount(0)
        actions = self._backends_menu.actions()
        for a in actions:
            # All the added backups have a data() element
            if(a.data()):
                # Remove them
                self._backends_menu.removeAction(a)

    def restore_settings(self, do_restore, filename = None):
        if(filename):
            s = QtCore.QSettings(filename, QtCore.QSettings.IniFormat)
        else:
            s = QtCore.QSettings()
        self._init_geometry(s)
        self._init_recorder(s)
        loaded_sources = []
        try:
            if do_restore:
                loaded_sources = self._init_data_sources(s)
        except (TypeError, KeyError):
            # raise
            # Be a bit more resilient against configuration problems
            logging.warning("Failed to load data source settings! Continuing...")
        if do_restore:
            try:
                self._restore_data_windows(s, loaded_sources)
            except (TypeError, KeyError):
                # raise
                # Be a bit more resilient against configuration problems
                logging.warning("Failed to load data windows settings! Continuing...")
            self.plotdata_widget.restore_state(s)
        self.settings = s

    def _init_geometry(self, settings):
        """Restores the geometry of the main window."""
        if(settings.contains("geometry")):
            self.restoreGeometry(settings.value("geometry"))
        if(settings.contains("windowState")):
            self.restoreState(settings.value("windowState"))

    def _init_recorder(self, settings):
        """Initializes the recorder"""
        if not settings.contains("outputPath"):
            settings.setValue("outputPath", ".")
        if not settings.contains("plotFontSize"):
            settings.setValue("plotFontSize", "13")
        self._recorder = H5Recorder(settings.value("outputPath"), 100)

    def _restore_data_windows(self, settings, data_sources):
        """Restores the geometry and data sources of the data windows."""
        if(settings.contains("dataWindows")):
            data_windows = settings.value("dataWindows")
            if data_windows is None:
                return
            for dw in data_windows:
                try:
                    if(dw['window_type'] == 'ImageWindow'):
                        w = ImageWindow(self)
                    elif(dw['window_type'] == 'PlotWindow'):
                        w = PlotWindow(self)
                    else:
                        raise ValueError(('window_type %s not supported' %(dw['window_type'])))
                    w.restore_from_state(dw, data_sources)
                    self._data_windows.append(w)
                    logging.debug("Loaded %s from settings", type(w).__name__)
                # Try to handle some version incompatibilities
                except KeyError:
                    raise
                    pass

    def _init_data_sources(self, settings):
        """Restore data sources from the settings."""
        loaded_sources = []
        pd_settings = []
        if(settings.contains("plotData") and
           settings.value("plotData") is not None):
            pd_settings = settings.value("plotData")

        if(settings.contains("dataSources") and
           settings.value("dataSources") is not None):
            for ds in settings.value("dataSources"):
                ds = DataSource(self, ds[0], ds[1], ds[2], ds[3])
                ds.restore_state(pd_settings)
                loaded_sources.append(ds)
                logging.debug("Loaded data source '%s' from settings", ds.name())
        return loaded_sources

    def _init_timer(self):
        """Initialize reploting timer."""
        self._replot_timer = QtCore.QTimer()
        self._replot_timer.setInterval(1000) # Replot every 1000 ms
        self._replot_timer.timeout.connect(self._replot)
        self._replot_timer.start()

    def add_backend(self, data_source):
        """Add backend to menu if it's not there yet
        and append to _data_sources"""
        actions = self._backends_menu.actions()
        unique = True
        for a in actions:
            if(a.text() == data_source.name()):
                unique = False
        if(not unique):
            QtGui.QMessageBox.warning(self, "Duplicate backend",
                                      "Duplicate backend. Ignoring %s" % data_source.name())
            return
        self._data_sources.append(data_source)
        logging.debug("Registering data source '%s' in the GUI", data_source.name())
        action = QtGui.QAction(data_source.name(), self)
        action.setData(data_source)
        action.setCheckable(True)
        action.setChecked(True)
        self._backends_menu.addAction(action)
        action.triggered.connect(self._data_source_triggered)
        self.plotdata_widget.add_source(data_source)
        data_source._recorder = self._recorder
        self._status_message("Backend '%s' connected." % (data_source.name()), 5000)

    def _add_backend_triggered(self):
        """Create and show the add backend dialog"""
        diag = AddBackendDialog(self)
        if(diag.exec_()):
            ssh_tunnel = None
            if(diag.checkBox.isChecked()):
                ssh_tunnel = diag.ssh.text()
            ds = DataSource(self, diag.hostname.text(),
                            diag.port.value(),
                            ssh_tunnel)
            logging.debug("Adding new data source '%s'", ds.name())

    def _reload_backend_triggered(self):
        """Reload backends, asking for brodcasts and configurations"""
        # Go through the data sources and ask for new keys
        self._status_message("Reloading backends...")
        for ds in self._data_sources:
            ds.query_configuration()
        self._status_message("Reloading backends...done.", 3000)

    def _reload_configuration_triggered(self):
        """Reloads the configuration in the backends"""
        for ds in self._data_sources:
            ds.query_reloading()
        self._status_message("Reloading configuration...done.", 3000)

    def _new_display_triggered(self):
        """Create a new Data Window to display data broadcasts"""
        if(self.sender() is self._new_plot_action):
            w = PlotWindow(self)
        elif(self.sender() is self._new_image_action):
            w = ImageWindow(self)
        w.show()
        self._data_windows.append(w)

    def _data_source_triggered(self):
        """Start/Stop listening to a particular data source"""
        action = self.sender()
        ds = action.data()
        if(action.isChecked()):
            self._data_sources.append(ds)
        else:
            self._data_sources.remove(ds)

    def _replot(self):
        """Replot content on all data windows"""
        if self._replot_timer is not None:
            pass
            #self._replot_timer.stop()

        for p in self._data_windows:
            p.replot()
        self.plotdata_widget.update()

        if self._replot_timer is not None:
            pass
            #self._replot_timer.start()

    def _preferences_clicked(self):
        """Open the preferences dialog"""
        diag = PreferencesDialog(self)
        if(diag.exec_()):
            v = diag.outputPath.text()
            self.settings.setValue("outputPath", v)
            size = diag.fontSize.value()
            self.settings.setValue("plotFontSize", size)
            for dw in self._data_windows:
                dw.updateFonts()
            self._recorder.outpath = v

    def _recorder_toggled(self, turn_on):
        """Start/Stop the recorder"""
        if self._recorder is None:
            self._recorder_action.setChecked(False)
            return
        if (turn_on):
            record_titles = self.plotdata_widget.record_titles(True)
            if not len(record_titles):
                return
            success = self._recorder.openfile()
            if not success:
                self._recorder_action.setChecked(False)
                return
            for ds in self._data_sources:
                if ds.name() in record_titles:
                    for title in record_titles[ds.name()]:
                        ds.subscribe_for_recording(title)
        else:
            self._recorder.closefile()
            record_titles = self.plotdata_widget.record_titles(False)
            for ds in self._data_sources:
                if ds.name() in record_titles:
                    for title in record_titles[ds.name()]:
                        ds.unsubscribe_for_recording(title)

    def save_data_windows(self):
        """Save data windows state and data sources to the settings file"""
        dw_settings = []
        for dw in self._data_windows:
            dw_settings.append(dw.get_state())
        return dw_settings

    def _on_save_settings_triggered(self):
        # We need a non native dialog to work around a Qt bug
        # https://bugreports.qt.io/browse/QTBUG-16722
        fname = QtGui.QFileDialog.getSaveFileName(self, "Save Settings", filter="Humminbird Settings (*.hum)",
                                                  options=QtGui.QFileDialog.DontUseNativeDialog)
        if(fname):
            self.save_settings(fname)

    def _on_load_settings_triggered(self):
        # We need a non native dialog to work around a Qt bug
        # https://bugreports.qt.io/browse/QTBUG-16722
        fname = QtGui.QFileDialog.getOpenFileName(self, "Load Settings", filter="Humminbird Settings (*.hum)",
                                                  options=QtGui.QFileDialog.DontUseNativeDialog)
        if(fname):
            self.clear()
            self.restore_settings(fname)

    def save_settings(self, filename=None):
        if(filename):
            s = QtCore.QSettings(filename, QtCore.QSettings.IniFormat)
        else:
            s = QtCore.QSettings()
        s.setValue("geometry", self.saveGeometry())
        s.setValue("windowState", self.saveState())
        # Save data sources
        ds_settings = []
        for ds in self._data_sources:
            ds_settings.append([ds.hostname, ds.port, ds.ssh_tunnel, ds.conf])
        s.setValue("dataSources", ds_settings)
        self.plotdata_widget.save_state(s)
        s.setValue("plotData", self.plotdata_widget.save_plotdata())
        s.setValue("dataWindows", self.save_data_windows())
        # Make sure settings are saved
        s.sync()

    def closeEvent(self, event): #pylint: disable=invalid-name
        """Save settings and exit nicely"""
        self.save_settings()
        # Force exit to prevent pyqtgraph from crashing, lingering windows
        QtGui.qApp.quit()
        # Never gets here, but anyway...
        event.accept()

    @property
    def data_sources(self):
        """Provide access to the GUI data sources"""
        return self._data_sources

    @property
    def data_windows(self):
        """Provide access to the GUI data widows"""
        return self._data_windows

    def _status_message(self, msg, timeout=0, process_events=True):
        """Set statusBar message and make sure to show it!"""
        self.statusbar.showMessage(msg, timeout)
        # Without this it might not actually be shown
        if(process_events):
            QtCore.QCoreApplication.processEvents()


text:
module Travis::API::V3
  class Services::SslKey::Find < Service
    def run!
      repository = check_login_and_find(:repository)
      result(query.find(repository) || not_found(false, :key_pair))
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
module RailsRedmineIssues
  VERSION = "0.0.4"
end


text:
package io.tabmo.aerospike

import scala.util.control.NonFatal

import org.scalatest._

import io.tabmo.aerospike.client._

class Factory extends FlatSpec with AerospikeClientTest {

  "An aerospike client" can "be created from one host" in {
    try {
      ReactiveAerospikeClient.connect(host, port).close()
    } catch {
      case NonFatal(ex) => fail(ex)
    }
  }

  "An aerospike client" can "be created from multiple hosts" in {
    try {
      val host1 = s"$host:$port"
      val host2 = "localhost:3000"
      ReactiveAerospikeClient(host1, host2).close()
    } catch {
      case NonFatal(ex) => fail(ex)
    }
  }

  "Invalid hostname" must "be rejected" in {
    intercept[IllegalArgumentException] {
      ReactiveAerospikeClient("localhost:port").close()
    }
  }

}


text:
package org.axonframework.eventhandling.saga;

import java.util.Set;
import java.util.function.Supplier;

/**
 * Interface towards the storage mechanism of Saga instances. Saga Repositories can find sagas either through the
 * values
 * they have been associated with (see {@link AssociationValue}) or via their unique identifier.
 *
 * @author Allard Buijze
 * @since 3.0
 */
public interface SagaRepository<T> {

    /**
     * Find saga instances of the given {@code type} that have been associated with the given
     * {@code associationValue}.
     * <p/>
     *
     * @param associationValue The value that the returned Sagas must be associated with
     * @return A Set containing the found Saga instances. If none are found, an empty Set is returned. Will never return
     * {@code null}.
     */
    Set<String> find(AssociationValue associationValue);

    /**
     * Loads a known Saga instance by its unique identifier.
     * Due to the concurrent nature of Sagas, it is not unlikely for a Saga to have ceased to exist after it has been
     * found based on associations. Therefore, a repository should return {@code null} in case a Saga doesn't
     * exists, as opposed to throwing an exception.
     *
     * @param sagaIdentifier The unique identifier of the Saga to load
     * @return The Saga instance, or {@code null} if no such saga exists
     */
    Saga<T> load(String sagaIdentifier);

    /**
     * Creates a new Saga instance. The returned Saga will delegate event handling to the instance supplied by the given
     * {@code factoryMethod}.
     *
     * @param factoryMethod Used to create a new Saga delegate
     * @return a new Saga instance wrapping an instance of type {@link T}
     */
    Saga<T> newInstance(Supplier<T> factoryMethod);

}


text:
#include "stdafx.h"

// materials/kdsubsurface.cpp*
#include "materials/kdsubsurface.h"
#include "textures/constant.h"
#include "spectrum.h"
#include "texture.h"
#include "paramset.h"
#include "interaction.h"

// KdSubsurfaceMaterial Method Definitions
void KdSubsurfaceMaterial::ComputeScatteringFunctions(
    SurfaceInteraction *si, MemoryArena &arena, TransportMode mode,
    bool allowMultipleLobes) const {
    // Perform bump mapping with _bumpMap_, if present
    if (bumpMap) Bump(bumpMap, si);
    si->bsdf = ARENA_ALLOC(arena, BSDF)(*si, eta);
    Spectrum R = Kr->Evaluate(*si).Clamp();
    Spectrum T = Kt->Evaluate(*si).Clamp();

    if (allowMultipleLobes && (!R.IsBlack() || !T.IsBlack()))
        si->bsdf->Add(
            ARENA_ALLOC(arena, FresnelSpecular)(1., 1., 1.f, eta, mode));
    else {
        if (!R.IsBlack())
            si->bsdf->Add(ARENA_ALLOC(arena, SpecularReflection)(
                R, ARENA_ALLOC(arena, FresnelDielectric)(1.f, eta)));
        if (!T.IsBlack())
            si->bsdf->Add(
                ARENA_ALLOC(arena, SpecularTransmission)(T, 1.f, eta, mode));
    }

    Spectrum sig_t = scale * sigma_t->Evaluate(*si).Clamp();
    Spectrum kd = Kd->Evaluate(*si).Clamp();
    Spectrum sig_a, sig_s;
    SubsurfaceFromDiffuse(table, kd, sig_t, &sig_a, &sig_s);
    si->bssrdf = ARENA_ALLOC(arena, TabulatedBSSRDF)(*si, this, mode, eta,
                                                     sig_a, sig_s, table);
}

KdSubsurfaceMaterial *CreateKdSubsurfaceMaterial(const TextureParams &mp) {
    Float Kd[3] = {.5, .5, .5};
    std::shared_ptr<Texture<Spectrum>> kd =
        mp.GetSpectrumTexture("Kd", Spectrum::FromRGB(Kd));
    std::shared_ptr<Texture<Spectrum>> sigma_t =
        mp.GetSpectrumTexture("sigma_t", Spectrum::FromRGB(Kd));
    std::shared_ptr<Texture<Spectrum>> kr =
        mp.GetSpectrumTexture("Kr", Spectrum(1.f));
    std::shared_ptr<Texture<Spectrum>> kt =
        mp.GetSpectrumTexture("Kt", Spectrum(1.f));
    std::shared_ptr<Texture<Float>> bumpMap =
        mp.GetFloatTextureOrNull("bumpmap");
    Float eta = mp.FindFloat("eta", 1.33f);
    Float scale = mp.FindFloat("scale", 1.0f);
    Float g = mp.FindFloat("g", 0.0f);
    return new KdSubsurfaceMaterial(scale, kd, kr, kt, sigma_t, g, eta,
                                    bumpMap);
}


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

// polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
// using the polyfill specifically to avoid the call to `Object.defineProperty` for performance reasons
function fastFilter(fun/*, thisArg*/) {
	'use strict';

	if (this === void 0 || this === null) {
		throw new TypeError();
	}

	var t = Object(this);
	var len = t.length >>> 0;
	if (typeof fun !== 'function') {
		throw new TypeError();
	}

	var res = [];
	var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
	for (var i = 0; i < len; i++) {
		if (i in t) {
			var val = t[i];

			// NOTE: Technically this should Object.defineProperty at
			//       the next index, as push can be affected by
			//       properties on Object.prototype and Array.prototype.
			//       But that method's new, and collisions should be
			//       rare, so use the more-compatible alternative.
			if (fun.call(thisArg, val, i, t)) {
				res.push(val);
			}
		}
	}

	return res;
}

function Tapable() {
	this._plugins = {};
}
module.exports = Tapable;

function copyProperties(from, to) {
	for(var key in from)
		to[key] = from[key];
	return to;
}

Tapable.mixin = function mixinTapable(pt) {
	copyProperties(Tapable.prototype, pt);
};

Tapable.prototype.applyPlugins = function applyPlugins(name) {
	if(!this._plugins[name]) return;
	var args = Array.prototype.slice.call(arguments, 1);
	var plugins = this._plugins[name];
	for(var i = 0; i < plugins.length; i++)
		plugins[i].apply(this, args);
};

Tapable.prototype.applyPlugins0 = function applyPlugins0(name) {
	var plugins = this._plugins[name];
	if(!plugins) return;
	for(var i = 0; i < plugins.length; i++)
		plugins[i].call(this);
};

Tapable.prototype.applyPlugins1 = function applyPlugins1(name, param) {
	var plugins = this._plugins[name];
	if(!plugins) return;
	for(var i = 0; i < plugins.length; i++)
		plugins[i].call(this, param);
};

Tapable.prototype.applyPlugins2 = function applyPlugins2(name, param1, param2) {
	var plugins = this._plugins[name];
	if(!plugins) return;
	for(var i = 0; i < plugins.length; i++)
		plugins[i].call(this, param1, param2);
};

Tapable.prototype.applyPluginsWaterfall = function applyPluginsWaterfall(name, init) {
	if(!this._plugins[name]) return init;
	var args = Array.prototype.slice.call(arguments, 1);
	var plugins = this._plugins[name];
	var current = init;
	for(var i = 0; i < plugins.length; i++) {
		args[0] = current;
		current = plugins[i].apply(this, args);
	}
	return current;
};

Tapable.prototype.applyPluginsWaterfall0 = function applyPluginsWaterfall0(name, init) {
	var plugins = this._plugins[name];
	if(!plugins) return init;
	var current = init;
	for(var i = 0; i < plugins.length; i++)
		current = plugins[i].call(this, current);
	return current;
};

Tapable.prototype.applyPluginsWaterfall1 = function applyPluginsWaterfall1(name, init, param) {
	var plugins = this._plugins[name];
	if(!plugins) return init;
	var current = init;
	for(var i = 0; i < plugins.length; i++)
		current = plugins[i].call(this, current, param);
	return current;
};

Tapable.prototype.applyPluginsWaterfall2 = function applyPluginsWaterfall2(name, init, param1, param2) {
	var plugins = this._plugins[name];
	if(!plugins) return init;
	var current = init;
	for(var i = 0; i < plugins.length; i++)
		current = plugins[i].call(this, current, param1, param2);
	return current;
};

Tapable.prototype.applyPluginsBailResult = function applyPluginsBailResult(name) {
	if(!this._plugins[name]) return;
	var args = Array.prototype.slice.call(arguments, 1);
	var plugins = this._plugins[name];
	for(var i = 0; i < plugins.length; i++) {
		var result = plugins[i].apply(this, args);
		if(typeof result !== "undefined") {
			return result;
		}
	}
};

Tapable.prototype.applyPluginsBailResult1 = function applyPluginsBailResult1(name, param) {
	if(!this._plugins[name]) return;
	var plugins = this._plugins[name];
	for(var i = 0; i < plugins.length; i++) {
		var result = plugins[i].call(this, param);
		if(typeof result !== "undefined") {
			return result;
		}
	}
};

Tapable.prototype.applyPluginsBailResult2 = function applyPluginsBailResult2(name, param1, param2) {
	if(!this._plugins[name]) return;
	var plugins = this._plugins[name];
	for(var i = 0; i < plugins.length; i++) {
		var result = plugins[i].call(this, param1, param2);
		if(typeof result !== "undefined") {
			return result;
		}
	}
};

Tapable.prototype.applyPluginsBailResult3 = function applyPluginsBailResult3(name, param1, param2, param3) {
	if(!this._plugins[name]) return;
	var plugins = this._plugins[name];
	for(var i = 0; i < plugins.length; i++) {
		var result = plugins[i].call(this, param1, param2, param3);
		if(typeof result !== "undefined") {
			return result;
		}
	}
};

Tapable.prototype.applyPluginsBailResult4 = function applyPluginsBailResult4(name, param1, param2, param3, param4) {
	if(!this._plugins[name]) return;
	var plugins = this._plugins[name];
	for(var i = 0; i < plugins.length; i++) {
		var result = plugins[i].call(this, param1, param2, param3, param4);
		if(typeof result !== "undefined") {
			return result;
		}
	}
};

Tapable.prototype.applyPluginsBailResult5 = function applyPluginsBailResult5(name, param1, param2, param3, param4, param5) {
	if(!this._plugins[name]) return;
	var plugins = this._plugins[name];
	for(var i = 0; i < plugins.length; i++) {
		var result = plugins[i].call(this, param1, param2, param3, param4, param5);
		if(typeof result !== "undefined") {
			return result;
		}
	}
};

Tapable.prototype.applyPluginsAsyncSeries = Tapable.prototype.applyPluginsAsync = function applyPluginsAsyncSeries(name) {
	var args = Array.prototype.slice.call(arguments, 1);
	var callback = args.pop();
	var plugins = this._plugins[name];
	if(!plugins || plugins.length === 0) return callback();
	var i = 0;
	var _this = this;
	args.push(copyProperties(callback, function next(err) {
		if(err) return callback(err);
		i++;
		if(i >= plugins.length) {
			return callback();
		}
		plugins[i].apply(_this, args);
	}));
	plugins[0].apply(this, args);
};

Tapable.prototype.applyPluginsAsyncSeries1 = function applyPluginsAsyncSeries1(name, param, callback) {
	var plugins = this._plugins[name];
	if(!plugins || plugins.length === 0) return callback();
	var i = 0;
	var _this = this;
	var innerCallback = copyProperties(callback, function next(err) {
		if(err) return callback(err);
		i++;
		if(i >= plugins.length) {
			return callback();
		}
		plugins[i].call(_this, param, innerCallback);
	});
	plugins[0].call(this, param, innerCallback);
};

Tapable.prototype.applyPluginsAsyncSeriesBailResult = function applyPluginsAsyncSeriesBailResult(name) {
	var args = Array.prototype.slice.call(arguments, 1);
	var callback = args.pop();
	if(!this._plugins[name] || this._plugins[name].length === 0) return callback();
	var plugins = this._plugins[name];
	var i = 0;
	var _this = this;
	args.push(copyProperties(callback, function next() {
		if(arguments.length > 0) return callback.apply(null, arguments);
		i++;
		if(i >= plugins.length) {
			return callback();
		}
		plugins[i].apply(_this, args);
	}));
	plugins[0].apply(this, args);
};

Tapable.prototype.applyPluginsAsyncSeriesBailResult1 = function applyPluginsAsyncSeriesBailResult1(name, param, callback) {
	var plugins = this._plugins[name];
	if(!plugins || plugins.length === 0) return callback();
	var i = 0;
	var _this = this;
	var innerCallback = copyProperties(callback, function next(err, result) {
		if(arguments.length > 0) return callback(err, result);
		i++;
		if(i >= plugins.length) {
			return callback();
		}
		plugins[i].call(_this, param, innerCallback);
	});
	plugins[0].call(this, param, innerCallback);
};

Tapable.prototype.applyPluginsAsyncWaterfall = function applyPluginsAsyncWaterfall(name, init, callback) {
	if(!this._plugins[name] || this._plugins[name].length === 0) return callback(null, init);
	var plugins = this._plugins[name];
	var i = 0;
	var _this = this;
	var next = copyProperties(callback, function(err, value) {
		if(err) return callback(err);
		i++;
		if(i >= plugins.length) {
			return callback(null, value);
		}
		plugins[i].call(_this, value, next);
	});
	plugins[0].call(this, init, next);
};

Tapable.prototype.applyPluginsParallel = function applyPluginsParallel(name) {
	var args = Array.prototype.slice.call(arguments, 1);
	var callback = args.pop();
	if(!this._plugins[name] || this._plugins[name].length === 0) return callback();
	var plugins = this._plugins[name];
	var remaining = plugins.length;
	args.push(copyProperties(callback, function(err) {
		if(remaining < 0) return; // ignore
		if(err) {
			remaining = -1;
			return callback(err);
		}
		remaining--;
		if(remaining === 0) {
			return callback();
		}
	}));
	for(var i = 0; i < plugins.length; i++) {
		plugins[i].apply(this, args);
		if(remaining < 0) return;
	}
};

Tapable.prototype.applyPluginsParallelBailResult = function applyPluginsParallelBailResult(name) {
	var args = Array.prototype.slice.call(arguments, 1);
	var callback = args[args.length - 1];
	if(!this._plugins[name] || this._plugins[name].length === 0) return callback();
	var plugins = this._plugins[name];
	var currentPos = plugins.length;
	var currentResult;
	var done = [];
	for(var i = 0; i < plugins.length; i++) {
		args[args.length - 1] = (function(i) {
			return copyProperties(callback, function() {
				if(i >= currentPos) return; // ignore
				done.push(i);
				if(arguments.length > 0) {
					currentPos = i + 1;
					done = fastFilter.call(done, function(item) {
						return item <= i;
					});
					currentResult = Array.prototype.slice.call(arguments);
				}
				if(done.length === currentPos) {
					callback.apply(null, currentResult);
					currentPos = 0;
				}
			});
		}(i));
		plugins[i].apply(this, args);
	}
};

Tapable.prototype.applyPluginsParallelBailResult1 = function applyPluginsParallelBailResult1(name, param, callback) {
	var plugins = this._plugins[name];
	if(!plugins || plugins.length === 0) return callback();
	var currentPos = plugins.length;
	var currentResult;
	var done = [];
	for(var i = 0; i < plugins.length; i++) {
		var innerCallback = (function(i) {
			return copyProperties(callback, function() {
				if(i >= currentPos) return; // ignore
				done.push(i);
				if(arguments.length > 0) {
					currentPos = i + 1;
					done = fastFilter.call(done, function(item) {
						return item <= i;
					});
					currentResult = Array.prototype.slice.call(arguments);
				}
				if(done.length === currentPos) {
					callback.apply(null, currentResult);
					currentPos = 0;
				}
			});
		}(i));
		plugins[i].call(this, param, innerCallback);
	}
};

Tapable.prototype.hasPlugins = function hasPlugins(name) {
	var plugins = this._plugins[name];
	return plugins && plugins.length > 0;
};

Tapable.prototype.plugin = function plugin(name, fn) {
	if(Array.isArray(name)) {
		name.forEach(function(name) {
			this.plugin(name, fn);
		}, this);
		return;
	}
	if(!this._plugins[name]) this._plugins[name] = [fn];
	else this._plugins[name].push(fn);
};

Tapable.prototype.apply = function apply() {
	for(var i = 0; i < arguments.length; i++) {
		arguments[i].apply(this);
	}
};


text:
import firebase,{ firebaseRef,githubProvider,googleAuthProvider } from '../firebase'

export const addNote = (payload) => {
    return {
        type : 'ADD_NOTE',
        payload
    }
}

export const startAddNote = (payload) => {
    return (dispatch,getState) => {
        var userNotesRef = firebaseRef.child(`${getState().auth.uid}/notes`).push(payload)

        return userNotesRef.then(()=>{
            dispatch(addNote({
                ...payload,
                id : userNotesRef.key
            }))
        })
    }
}

export const addNotes = (payload) => {
    return {
        type : 'ADD_NOTES',
        payload
    }
}

export const deleteNote = (payload) => {
    return {
        type : 'DELETE_NOTE',
        payload
    }
}

export const startDeleteNote = (payload) => {
    return (dispatch,getState) =>{
        return firebaseRef.child(`${getState().auth.uid}/notes/${payload.id}`).remove().then(()=>{
            dispatch(deleteNote({id:payload.id}))
        })
    }
}

export const updateNote = (payload) => {
    return {
        type : 'UPDATE_NOTE',
        payload
    }
}

export const startUpdateNote = (payload) => {
    return (dispatch,getState) => {
        return firebaseRef.child(`${getState().auth.uid}/notes/${payload.id}`).update({note:payload.note}).then(()=>{
            dispatch(updateNote(payload))
        })
    }
}

export const login = (payload) => {
    return {
        type : 'LOGIN',
        payload
    }
}

export const logout = (payload) => {
    return {
        type : 'LOGOUT',
        payload
    }
}

export const startLogin = (provider) =>{
    return (dispatch,getState) => {
        var loginInProvider

        switch(provider){
            case 'github':
                loginInProvider = githubProvider
                break
            case 'google':
                loginInProvider = googleAuthProvider
                break
            default :
                loginInProvider = googleAuthProvider
        }

        return firebase.auth().signInWithPopup(loginInProvider).then((result) => {
            console.log("auth worked",result)
        },(error) => {
            console.log("auth error")
        })
    }
}

export const startLogout = () => {
    return (dispatch,getState) => {
        return firebase.auth().signOut().then(()=>{
            console.log('successfully signed out')
        })
    }
}

export const startGetNotes = () => {
    return(dispatch,getState) => {
        var notesRef =  firebaseRef.child(`${getState().auth.uid}/notes`)

        return notesRef.once('value').then((snapshot)=>{
            var notes = snapshot.val() || {}
            var notesHolder = []

            Object.keys(notes).forEach((noteKey)=>{
                notesHolder.push({
                    id:noteKey,
                    ...notes[noteKey]
                })
            })
            dispatch(addNotes(notesHolder))

        })
    }
}


text:
import React from 'react';

const CamperListItem = ({ camper, number }) => {
  return (

      {number}
      <a href={`https://freecodecamp.com/${camper.username}`} target="_blank">{camper.username}
      {camper.recent}
      {camper.alltime}

  );
}

export default CamperListItem;


text:
<?php

namespace DTS\eBaySDK\MerchantData\Enums\Test;

use DTS\eBaySDK\MerchantData\Enums\GalleryStatusCodeType;

class GalleryStatusCodeTypeTest extends \PHPUnit_Framework_TestCase
{
    private $obj;

    protected function setUp()
    {
        $this->obj = new GalleryStatusCodeType();
    }

    public function testCanBeCreated()
    {
        $this->assertInstanceOf('\DTS\eBaySDK\MerchantData\Enums\GalleryStatusCodeType', $this->obj);
    }
}


text:
/**
* PathManager controls a list of Paths and a list of PathFollowers.
* It is the central control for the majority of the Pathing API.
*
* @class Phaser.Plugin.PathManager
* @constructor
* @param {Phaser.Game} game - A reference to the current Phaser.Game instance.
* @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin.
*/
Phaser.Plugin.PathManager = function (game, parent) {

    Phaser.Plugin.call(this, game, parent);

    /**
     * @property {array} _list - list of paths
     * @private
     */
    this._list = [];

    /**
     * @property {array} _followers - list of path followers
     * @private
     */
    this._followers = [];

    this._branchRegistry = {};

};

Phaser.Plugin.PathManager.prototype = Object.create(Phaser.Plugin.prototype);
Phaser.Plugin.PathManager.prototype.constructor = Phaser.Plugin.PathManager;

/**
 * create a new Path from JSON data
 *
 * JSON data format:
 * required: "coordinateSystem":, "smoothness":, "loops":, "speed":, "pointList":[ {"x":, "y":}, ... ]
 * optional: "branchFrom": { "path":, "point": }, "joinTo": { "path":, "point": }
 */
Phaser.Plugin.PathManager.prototype.createPathsFromJSON = function(jsonKey) {

    var parse = this.game.cache.getJSON(jsonKey);
    var path;
    var createdPaths = [];
    var branchList = [];

    parse.paths.forEach(function(config) {
        path = new Phaser.Path(config.coordinateSystem, config.loops);
        path.name = config.name;
        this.addPoints(path, config.pointList, config.speed);
        this._list.push(path);
        createdPaths.push(path);
        config.pointList.reduce(function(list, pnt, index) {
            if (pnt.branchType === Phaser.Path.BranchTypes.ATTACHED) {
                list.push({
                    path: path.name,
                    branchPath: pnt.branchPath,
                    pointIndex: index,
                    type: pnt.branchType
                });
            } else if (pnt.branchType === Phaser.Path.BranchTypes.JOINED) {
                list.push({
                    path: pnt.branchPath,
                    branchPath: path.name,
                    pointIndex: pnt.branchPointIndex,
                    type: pnt.branchType
                });
            }
            return list;
        }, branchList);
    }, this);
    branchList.forEach(function(branch) {
        var mainPath = this.findPathByName(branch.path);
        var branchPath = this.findPathByName(branch.branchPath);
        var mainPathPointIndex = branch.pointIndex;
        if (branch.type === Phaser.Path.BranchTypes.ATTACHED) {
            this.attachBranch(branchPath, mainPath, mainPathPointIndex);
        } else if (branch.type === Phaser.Path.BranchTypes.JOINED) {
            this.joinBranch(branchPath, mainPath, mainPathPointIndex, false);
        }
    }, this);

    return createdPaths;
};

Phaser.Plugin.PathManager.prototype.addPath = function(path) {

    //  if path has points then addPoints, otherwise don't
    // this.addPoints(path, parse.pointList, parse.speed);

    this._list.push(path);

    return path;

};

// create a branching path and attach the start to an existing path
// when a PathFollower encounters the attachment point, it will be able to switch onto this new branch
//
// @param: count {value, optional}, make this branch counted (it won't be taken until a follower has passed it enough times)
Phaser.Plugin.PathManager.prototype.attachBranch = function(branchPath, mainPath, mainPathPointIndex, count) {

    if (typeof mainPath === 'string') {
        mainPath = this.findPathByName(mainPath);
    }

    var branchFromPoint = new Phaser.PathPoint();

    if (mainPath.getPathPoint(mainPathPointIndex, branchFromPoint)) {
        // move the first point of the branchPath to the branchFromPoint location
        branchPath.origin = branchFromPoint;
        var branchToPoint = branchPath.getPathPointReference(0);

        // attach the branch (use point reference so the changes go into the path)
        var branchFromPointRef = mainPath.getPathPointReference(mainPathPointIndex);

        this._branchAttach(branchFromPointRef, branchPath, 0);
        branchFromPointRef.branchType = Phaser.Path.BranchTypes.ATTACHED;

        // attach the branch's first point back to where it branched off from (for path reversal)
        branchToPoint.branchPath = mainPath;

        branchToPoint.branchPointIndex = mainPathPointIndex;

        // make sure this branch knows that it's using offset coordinates based on the first path point location
        branchPath.coordinateSystem = Phaser.Path.CoordinateSystems.OFFSET;
        branchPath.type = Phaser.Path.PathTypes.BRANCH;

        // set up counted branches data
        if (count !== undefined) {
            branchFromPointRef.data = {
                type: Phaser.PathPoint.DATA_COUNTER,
                value: count
            };
        }

        if (this._branchRegistry[branchPath.name]) {
            this._branchRegistry[branchPath.name].push(branchFromPointRef);
        } else {
            this._branchRegistry[branchPath.name] = [branchFromPointRef];
        }
    }

};

// attach the end of a path to an existing path
// when a PathFollower encounters the attachment point, it will automatically switch onto the attached path
Phaser.Plugin.PathManager.prototype.joinBranch = function(branchPath, mainPath, mainPathPointIndex, addPoint) {
    if (typeof addPoint === 'undefined') {
        addPoint = true;
    }
    if (typeof mainPath === 'string') {
        mainPath = this.findPathByName(mainPath);
    }

    var mainPathJoinPoint, branchLastPoint;

    mainPathJoinPoint = new Phaser.PathPoint();
    mainPath.getPathPoint(mainPathPointIndex, mainPathJoinPoint);

    if (mainPathJoinPoint) {
        if (addPoint) {

            var newBranchPoint = new Phaser.PathPoint();
            if (branchPath.getPathPoint(0, newBranchPoint)) {
                // make sure the newly added last path point is relative to the previously added first path point for the branch path by subtracting it out
                branchLastPoint = branchPath.addPathPoint(mainPathJoinPoint.x - newBranchPoint.x, mainPathJoinPoint.y - newBranchPoint.y, mainPathJoinPoint.vx, mainPathJoinPoint.vy, 1.0);
                this._branchAttach(branchLastPoint, mainPath, mainPathPointIndex);
            }
        } else {
            branchLastPoint = branchPath.getPathPointReference(branchPath.length - 1);
            this._branchAttach(branchLastPoint, mainPath, mainPathPointIndex);
        }
        branchLastPoint.branchType = Phaser.Path.BranchTypes.JOINED;
    }
    if (this._branchRegistry[branchPath.name]) {
        this._branchRegistry[branchPath.name].push(branchLastPoint);
    } else {
        this._branchRegistry[branchPath.name] = [branchLastPoint];
    }
};

// internal function, set the branching parameters of a PathPoint
Phaser.Plugin.PathManager.prototype._branchAttach = function(attachPoint, branchingPath, branchToPointIndex) {
    attachPoint.branchPath = branchingPath;
    attachPoint.branchPointIndex = branchToPointIndex;
};

Phaser.Plugin.PathManager.prototype._branchDetach = function(attachedPoint) {
    attachedPoint.branchPath = null;
    attachedPoint.branchPointIndex = null;
};

Phaser.Plugin.PathManager.prototype.removeBranch = function(branch) {
    if (typeof branch === 'string') {
        branch = this.findPathByName(branch);
    }
    this._branchRegistry[branch.name].forEach(function(point) {
        this._branchDetach(point);
    }, this);
    this._branchRegistry[branch.name] = null;
    this.removePath(this.pathIndex(branch));

};

// @return: the Path object which is at 'index' in the list
Phaser.Plugin.PathManager.prototype.getPath = function(index) {
    return this._list[index];
};

// add a list of points to a Path
Phaser.Plugin.PathManager.prototype.addPoints = function(path, pointList, speed) {
    if (speed === undefined) speed = 1.0;

    for (var i = 0; i < pointList.length; i++) {
        path.addPathPoint(pointList[i].x, pointList[i].y, pointList[i].vx, pointList[i].vy, speed, pointList[i].data);
    }

    return path.numPoints();
};

// @return: the Path object matching 'name' in the list
Phaser.Plugin.PathManager.prototype.findPathByName = function(name) {
    for (var i = 0; i < this._list.length; i++) {
        if (this._list[i].name == name) {
            return this._list[i];
        }
    }

    return null;

};

Phaser.Plugin.PathManager.prototype.findPathByPoint = function(point) {
    var l = this._list.length;

    for (var i = 0; i < l; i++) {
        if (this._list[i].pointIndex(point) > -1) {
            return this._list[i];
        }
    }

};

/*
 *  FOLLOWERS
 *
 *  the following functions control PathFollower objects
 *
 */

// create a new PathFollower and add it to the list
// @param: physicsAdjustTime - how quickly does a physics object attempt to get back to the path's virtual particle position (milliseconds), 0 = it's not a physics object
// @return: the new PathFollower object
Phaser.Plugin.PathManager.prototype.addFollower = function(path, follower, speed, rotationOffset, angularOffset, callbackAtEnd, physicsAdjustTime) {

    var f = new Phaser.PathFollower(path, follower, speed, rotationOffset, angularOffset, callbackAtEnd, physicsAdjustTime);

    this._followers.push(f);

    return f;

};

// update all PathFollower objects in the _followers list
// this will automatically move them along the Paths
//  was called updateFollowers
Phaser.Plugin.PathManager.prototype.update = function() {

    //  move this to a plugin var
    //var elapsedTime = 1.0;

    for (var i = this._followers.length - 1; i >= 0; --i) {
        var f = this._followers[i];

        // when a follower's update returns false, kill it
        if (!f.update(this.game.time.elpased)) {
            // callback for this follower when it dies
            if (f.callbackAtEnd) {
                f.callbackAtEnd(f.follower);
            }

            // destroy the follower
            f.destroy();

            // remove the follower from the list
            this._followers.splice(i, 1);
        }
    }

};

// remove all PathFollowers on this path without destroying their attached graphic objects
// (eg. a long line of enemies use a path to enter, then switch to AI control on arrival maintaining their relative positions)
Phaser.Plugin.PathManager.prototype.removeAllFollowers = function(path) {
    for (var i = this._followers.length - 1; i >= 0; --i) {
        var f = this._followers[i];

        if (f.path == path) {
            // callback for this follower when it dies
            if (f.callbackAtEnd) {
                f.callbackAtEnd(f.follower);
            }

            // destroy the follower
            f.destroy();

            // remove the follower from the list
            this._followers.splice(i, 1);
        }
    }

};

Phaser.Plugin.PathManager.prototype.pathIndex = function(path) {
    return this._list.indexOf(path);
};

Phaser.Plugin.PathManager.prototype.removePath = function(pathIndex) {
    this.removeAllFollowers(this.getPath(pathIndex));
    if (pathIndex < this._list.length) {
        return this._list.splice(pathIndex, 1);
    } else {
        throw new Error("ERROR: Cannot remove non-existent path");
    }
};

/*
 *  DEBUG DRAWING OF ALL PATHS
 */

// draw all paths
Phaser.Plugin.PathManager.prototype.drawPaths = function(graphics) {
    for (var i = 0; i < this._list.length; i++) {
        this._list[i].debug(graphics);
    }
};


text:
package io.sundr.examples.validation;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

import io.sundr.builder.annotations.Buildable;

@Buildable(validationEnabled = true)
public interface Address {

  @NotNull
  String getStreet();

  @Min(1)
  int getNumber();

  @Pattern(regexp = "[0-9]*")
  @Size(min = 4, max = 6)
  String getZipCode();
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Threading.Tasks;
using Microsoft.Common.Core.Shell;
using Microsoft.R.Components.InteractiveWorkflow;
using Microsoft.VisualStudio.ProjectSystem;
using Microsoft.VisualStudio.ProjectSystem.FileSystemMirroring;
using Microsoft.VisualStudio.R.Package.Commands;

namespace Microsoft.VisualStudio.R.Package.ProjectSystem.Commands {
    [ExportCommandGroup("AD87578C-B324-44DC-A12A-B01A6ED5C6E3")]
    [AppliesTo(ProjectConstants.RtvsProjectCapability)]
    internal sealed class SetAsStartUpRScriptCommand : IAsyncCommandGroupHandler {
        private readonly ConfiguredProject _configuredProject;
        private readonly IRInteractiveWorkflowProvider _interactiveWorkflowProvider;
        private readonly ICoreShell _coreShell;

        [ImportingConstructor]
        public SetAsStartUpRScriptCommand(ConfiguredProject configuredProject, IRInteractiveWorkflowProvider interactiveWorkflowProvider, ICoreShell coreShell) {
            _configuredProject = configuredProject;
            _interactiveWorkflowProvider = interactiveWorkflowProvider;
            _coreShell = coreShell;
        }

        public Task<CommandStatusResult> GetCommandStatusAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, string commandText, CommandStatus progressiveStatus) {
            if (commandId == RPackageCommandId.icmdSetAsStartUpRScript && nodes.IsSingleNodePath()) {
                return Task.FromResult(new CommandStatusResult(true, commandText, CommandStatus.Enabled | CommandStatus.Supported));
            }
            return Task.FromResult(CommandStatusResult.Unhandled);
        }

        public async Task<bool> TryHandleCommandAsync(IImmutableSet<IProjectTree> nodes, long commandId, bool focused, long commandExecuteOptions, IntPtr variantArgIn, IntPtr variantArgOut) {
            _coreShell.AssertIsOnMainThread();
            if (commandId != RPackageCommandId.icmdSetAsStartUpRScript) {
                return false;
            }
            var properties = _configuredProject.Services.ExportProvider.GetExportedValue<ProjectProperties>();
            var path = nodes.GetSingleNodePath();
            var relativePath = _configuredProject.UnconfiguredProject.MakeRelative(path);
            await properties.SetStartupFileAsync(relativePath);
            return true;
        }
    }
}


text:
package com.newsblur.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.DialogFragment;
import android.text.TextUtils;

import com.newsblur.R;
import com.newsblur.util.AppConstants;
import com.newsblur.util.FeedUtils;

import javax.inject.Inject;

import dagger.hilt.android.AndroidEntryPoint;

@AndroidEntryPoint
public class DeleteFolderFragment extends DialogFragment {

    @Inject
    FeedUtils feedUtils;

    private static final String FOLDER_NAME = "folder_name";
    private static final String FOLDER_PARENT = "folder_parent";

    public static DeleteFolderFragment newInstance(String folderName, String folderParent) {
        DeleteFolderFragment frag = new DeleteFolderFragment();
        Bundle args = new Bundle();
        args.putString(FOLDER_NAME, folderName);
        args.putString(FOLDER_PARENT, folderParent);
        frag.setArguments(args);
        return frag;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
        final String folderName = getArguments().getString(FOLDER_NAME);
        final String folderParent = getArguments().getString(FOLDER_PARENT);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.delete_folder_message, folderName));
        builder.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String inFolder = "";
                if (!TextUtils.isEmpty(folderParent) && !folderParent.equals(AppConstants.ROOT_FOLDER)) {
                    inFolder = folderParent;
                }
                feedUtils.deleteFolder(folderName, inFolder, getActivity());
                DeleteFolderFragment.this.dismiss();
            }
        });
        builder.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                DeleteFolderFragment.this.dismiss();
            }
        });
        return builder.create();
    }
}


text:
// PluginWrite.cpp

#include "StdAfx.h"

#include <stdio.h>

#include "Plugin.h"

#include "../../../Common/StringConvert.h"
#include "../../../Common/Wildcard.h"

#include "../../../Windows/FileName.h"
#include "../../../Windows/FileFind.h"

#include "../Common/ZipRegistry.h"

#include "../Agent/Agent.h"

#include "ProgressBox.h"
#include "Messages.h"
#include "UpdateCallbackFar.h"

using namespace NWindows;
using namespace NFile;
using namespace NDir;
using namespace NFar;

using namespace NUpdateArchive;

static const char *kHelpTopic = "Update";

static const char *kArchiveHistoryKeyName = "7-ZipArcName";

static const UInt32 g_MethodMap[] = { 0, 1, 3, 5, 7, 9 };

static HRESULT SetOutProperties(IOutFolderArchive *outArchive, UInt32 method)
{
  CMyComPtr<ISetProperties> setProperties;
  if (outArchive->QueryInterface(IID_ISetProperties, (void **)&setProperties) == S_OK)
  {
    UStringVector realNames;
    realNames.Add(UString(L"x"));
    NCOM::CPropVariant value = (UInt32)method;
    CRecordVector<const wchar_t *> names;
    FOR_VECTOR (i, realNames)
      names.Add(realNames[i]);
    RINOK(setProperties->SetProperties(&names.Front(), &value, names.Size()));
  }
  return S_OK;
}

/*
HRESULT CPlugin::AfterUpdate(CWorkDirTempFile &tempFile, const UStringVector &pathVector)
{
  _folder.Release();
  m_ArchiveHandler->Close();

  RINOK(tempFile.MoveToOriginal(true));

  RINOK(m_ArchiveHandler->ReOpen(NULL)); // check it

  m_ArchiveHandler->BindToRootFolder(&_folder);
  FOR_VECTOR (i, pathVector)
  {
    CMyComPtr<IFolderFolder> newFolder;
    _folder->BindToFolder(pathVector[i], &newFolder);
    if (!newFolder)
      break;
    _folder = newFolder;
  }
  return S_OK;
}
*/

NFileOperationReturnCode::EEnum CPlugin::PutFiles(
  struct PluginPanelItem *panelItems, int numItems,
  int moveMode, int opMode)
{
  /*
  if (moveMode != 0)
  {
    g_StartupInfo.ShowMessage(NMessageID::kMoveIsNotSupported);
    return NFileOperationReturnCode::kError;
  }
  */

  if (numItems == 0)
    return NFileOperationReturnCode::kError;

  if (_agent->IsThereReadOnlyArc())
  {
    g_StartupInfo.ShowMessage(NMessageID::kUpdateNotSupportedForThisArchive);
    return NFileOperationReturnCode::kError;
  }

  const int kYSize = 14;
  const int kXMid = 38;

  NCompression::CInfo compressionInfo;
  compressionInfo.Load();

  int methodIndex = 0;
  int i;
  for (i = ARRAY_SIZE(g_MethodMap) - 1; i >= 0; i--)
    if (compressionInfo.Level >= g_MethodMap[i])
    {
      methodIndex = i;
      break;
    }

  const int kMethodRadioIndex = 2;
  const int kModeRadioIndex = kMethodRadioIndex + 7;

  struct CInitDialogItem initItems[]={
    { DI_DOUBLEBOX, 3, 1, 72, kYSize - 2, false, false, 0, false, NMessageID::kUpdateTitle, NULL, NULL },

    { DI_SINGLEBOX, 4, 2, kXMid - 2, 2 + 7, false, false, 0, false, NMessageID::kUpdateMethod, NULL, NULL },

    { DI_RADIOBUTTON, 6, 3, 0, 0, methodIndex == 0, methodIndex == 0, DIF_GROUP, false, NMessageID::kUpdateMethod_Store, NULL, NULL },
    { DI_RADIOBUTTON, 6, 4, 0, 0, methodIndex == 1, methodIndex == 1, 0, false, NMessageID::kUpdateMethod_Fastest, NULL, NULL },
    { DI_RADIOBUTTON, 6, 5, 0, 0, methodIndex == 2, methodIndex == 2, 0, false, NMessageID::kUpdateMethod_Fast, NULL, NULL },
    { DI_RADIOBUTTON, 6, 6, 0, 0, methodIndex == 3, methodIndex == 3, 0, false, NMessageID::kUpdateMethod_Normal, NULL, NULL },
    { DI_RADIOBUTTON, 6, 7, 0, 0, methodIndex == 4, methodIndex == 4, 0, false, NMessageID::kUpdateMethod_Maximum, NULL, NULL },
    { DI_RADIOBUTTON, 6, 8, 0, 0, methodIndex == 5, methodIndex == 5, 0, false, NMessageID::kUpdateMethod_Ultra, NULL, NULL },

    { DI_SINGLEBOX, kXMid, 2, 70, 2 + 5, false, false, 0, false, NMessageID::kUpdateMode, NULL, NULL },

    { DI_RADIOBUTTON, kXMid + 2, 3, 0, 0, false, true, DIF_GROUP, false, NMessageID::kUpdateMode_Add, NULL, NULL },
    { DI_RADIOBUTTON, kXMid + 2, 4, 0, 0, false, false,        0, false, NMessageID::kUpdateMode_Update, NULL, NULL },
    { DI_RADIOBUTTON, kXMid + 2, 5, 0, 0, false, false,        0, false, NMessageID::kUpdateMode_Fresh, NULL, NULL },
    { DI_RADIOBUTTON, kXMid + 2, 6, 0, 0, false, false,        0, false, NMessageID::kUpdateMode_Sync, NULL, NULL },

    { DI_TEXT, 3, kYSize - 4, 0, 0, false, false, DIF_BOXCOLOR|DIF_SEPARATOR, false, -1, "", NULL  },

    { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, true, NMessageID::kUpdateAdd, NULL, NULL  },
    { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL  }
  };

  const int kNumDialogItems = ARRAY_SIZE(initItems);
  const int kOkButtonIndex = kNumDialogItems - 2;
  FarDialogItem dialogItems[kNumDialogItems];
  g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems);
  int askCode = g_StartupInfo.ShowDialog(76, kYSize,
      kHelpTopic, dialogItems, kNumDialogItems);
  if (askCode != kOkButtonIndex)
    return NFileOperationReturnCode::kInterruptedByUser;

  compressionInfo.Level = g_MethodMap[0];
  for (i = 0; i < ARRAY_SIZE(g_MethodMap); i++)
    if (dialogItems[kMethodRadioIndex + i].Selected)
      compressionInfo.Level = g_MethodMap[i];

  const CActionSet *actionSet;

       if (dialogItems[kModeRadioIndex    ].Selected) actionSet = &k_ActionSet_Add;
  else if (dialogItems[kModeRadioIndex + 1].Selected) actionSet = &k_ActionSet_Update;
  else if (dialogItems[kModeRadioIndex + 2].Selected) actionSet = &k_ActionSet_Fresh;
  else if (dialogItems[kModeRadioIndex + 3].Selected) actionSet = &k_ActionSet_Sync;
  else throw 51751;

  compressionInfo.Save();

  CWorkDirTempFile tempFile;;
  if (tempFile.CreateTempFile(m_FileName) != S_OK)
    return NFileOperationReturnCode::kError;

  /*
  CSysStringVector fileNames;
  for (int i = 0; i < numItems; i++)
  {
    const PluginPanelItem &panelItem = panelItems[i];
    CSysString fullName;
    if (!MyGetFullPathName(panelItem.FindData.cFileName, fullName))
      return NFileOperationReturnCode::kError;
    fileNames.Add(fullName);
  }
  */

  CScreenRestorer screenRestorer;
  CProgressBox progressBox;
  CProgressBox *progressBoxPointer = NULL;
  if ((opMode & OPM_SILENT) == 0 && (opMode & OPM_FIND ) == 0)
  {
    screenRestorer.Save();

    progressBoxPointer = &progressBox;
    progressBox.Init(
        // g_StartupInfo.GetMsgString(NMessageID::kWaitTitle),
        g_StartupInfo.GetMsgString(NMessageID::kUpdating));
  }

  UStringVector pathVector;
  GetPathParts(pathVector);

  UStringVector fileNames;
  fileNames.ClearAndReserve(numItems);
  for (i = 0; i < numItems; i++)
    fileNames.AddInReserved(MultiByteToUnicodeString(panelItems[i].FindData.cFileName, CP_OEMCP));
  CObjArray<const wchar_t *> fileNamePointers(numItems);
  for (i = 0; i < numItems; i++)
    fileNamePointers[i] = fileNames[i];

  CMyComPtr<IOutFolderArchive> outArchive;
  HRESULT result = m_ArchiveHandler.QueryInterface(IID_IOutFolderArchive, &outArchive);
  if (result != S_OK)
  {
    g_StartupInfo.ShowMessage(NMessageID::kUpdateNotSupportedForThisArchive);
    return NFileOperationReturnCode::kError;
  }

  /*
  BYTE actionSetByte[NUpdateArchive::NPairState::kNumValues];
  for (i = 0; i < NUpdateArchive::NPairState::kNumValues; i++)
    actionSetByte[i] = (BYTE)actionSet->StateActions[i];
  */

  CUpdateCallback100Imp *updateCallbackSpec = new CUpdateCallback100Imp;
  CMyComPtr<IFolderArchiveUpdateCallback> updateCallback(updateCallbackSpec );

  updateCallbackSpec->Init(/* m_ArchiveHandler, */ progressBoxPointer);

  if (SetOutProperties(outArchive, compressionInfo.Level) != S_OK)
    return NFileOperationReturnCode::kError;

  /*
  outArchive->SetFolder(_folder);
  outArchive->SetFiles(L"", fileNamePointers, numItems);
  // FStringVector requestedPaths;
  // FStringVector processedPaths;
  result = outArchive->DoOperation2(
      // &requestedPaths, &processedPaths,
      NULL, NULL,
      tempFile.OutStream, actionSetByte, NULL, updateCallback);
  updateCallback.Release();
  outArchive.Release();

  if (result == S_OK)
  {
    result = AfterUpdate(tempFile, pathVector);
  }
  */

  {
    result = _agent->SetFiles(L"", fileNamePointers, numItems);
    if (result == S_OK)
    {
      CAgentFolder *agentFolder = NULL;
      {
        CMyComPtr<IArchiveFolderInternal> afi;
        _folder.QueryInterface(IID_IArchiveFolderInternal, &afi);
        if (afi)
          afi->GetAgentFolder(&agentFolder);
      }
      if (agentFolder)
        result = agentFolder->CommonUpdateOperation(AGENT_OP_Uni,
            (moveMode != 0), NULL, actionSet, NULL, 0, updateCallback);
      else
        result = E_FAIL;
    }
  }

  if (result != S_OK)
  {
    ShowSysErrorMessage(result);
    return NFileOperationReturnCode::kError;
  }

  return NFileOperationReturnCode::kSuccess;
}

namespace NPathType
{
  enum EEnum
  {
    kLocal,
    kUNC
  };
  EEnum GetPathType(const UString &path);
}

struct CParsedPath
{
  UString Prefix; // Disk or UNC with slash
  UStringVector PathParts;
  void ParsePath(const UString &path);
  UString MergePath() const;
};

static const wchar_t kDirDelimiter = WCHAR_PATH_SEPARATOR;
static const wchar_t kDiskDelimiter = L':';

namespace NPathType
{
  EEnum GetPathType(const UString &path)
  {
    if (path.Len() <= 2)
      return kLocal;
    if (path[0] == kDirDelimiter && path[1] == kDirDelimiter)
      return kUNC;
    return kLocal;
  }
}

void CParsedPath::ParsePath(const UString &path)
{
  int curPos = 0;
  switch (NPathType::GetPathType(path))
  {
    case NPathType::kLocal:
    {
      int posDiskDelimiter = path.Find(kDiskDelimiter);
      if (posDiskDelimiter >= 0)
      {
        curPos = posDiskDelimiter + 1;
        if ((int)path.Len() > curPos)
          if (path[curPos] == kDirDelimiter)
            curPos++;
      }
      break;
    }
    case NPathType::kUNC:
    {
      // the bug was fixed:
      curPos = path.Find(kDirDelimiter, 2);
      if (curPos < 0)
        curPos = path.Len();
      else
        curPos++;
    }
  }
  Prefix = path.Left(curPos);
  SplitPathToParts(path.Ptr(curPos), PathParts);
}

UString CParsedPath::MergePath() const
{
  UString result = Prefix;
  FOR_VECTOR (i, PathParts)
  {
    if (i != 0)
      result += kDirDelimiter;
    result += PathParts[i];
  }
  return result;
}

static void SetArcName(UString &arcName, const CArcInfoEx &arcInfo)
{
  if (!arcInfo.Flags_KeepName())
  {
    int dotPos = arcName.ReverseFind_Dot();
    int slashPos = arcName.ReverseFind_PathSepar();
    if (dotPos > slashPos + 1)
      arcName.DeleteFrom(dotPos);
  }
  arcName += L'.';
  arcName += arcInfo.GetMainExt();
}

HRESULT CompressFiles(const CObjectVector<PluginPanelItem> &pluginPanelItems)
{
  if (pluginPanelItems.Size() == 0)
    return E_FAIL;

  UStringVector fileNames;
  {
    FOR_VECTOR (i, pluginPanelItems)
    {
      const PluginPanelItem &panelItem = pluginPanelItems[i];
      if (strcmp(panelItem.FindData.cFileName, "..") == 0 &&
          NFind::NAttributes::IsDir(panelItem.FindData.dwFileAttributes))
        return E_FAIL;
      if (strcmp(panelItem.FindData.cFileName, ".") == 0 &&
          NFind::NAttributes::IsDir(panelItem.FindData.dwFileAttributes))
        return E_FAIL;
      FString fullPath;
      FString fileNameUnicode = us2fs(MultiByteToUnicodeString(panelItem.FindData.cFileName, CP_OEMCP));
      if (!MyGetFullPathName(fileNameUnicode, fullPath))
        return E_FAIL;
      fileNames.Add(fs2us(fullPath));
    }
  }

  NCompression::CInfo compressionInfo;
  compressionInfo.Load();

  int archiverIndex = -1;

  /*
  CCodecs *codecs = new CCodecs;
  CMyComPtr<ICompressCodecsInfo> compressCodecsInfo = codecs;
  if (codecs->Load() != S_OK)
    throw "Can't load 7-Zip codecs";
  */

  if (LoadGlobalCodecs() != S_OK)
    throw "Can't load 7-Zip codecs";

  CCodecs *codecs = g_CodecsObj;

  {
    FOR_VECTOR (i, codecs->Formats)
    {
      const CArcInfoEx &arcInfo = codecs->Formats[i];
      if (arcInfo.UpdateEnabled)
      {
        if (archiverIndex == -1)
          archiverIndex = i;
        if (MyStringCompareNoCase(arcInfo.Name, compressionInfo.ArcType) == 0)
          archiverIndex = i;
      }
    }
  }

  if (archiverIndex < 0)
    throw "there is no output handler";

  UString resultPath;
  {
    CParsedPath parsedPath;
    parsedPath.ParsePath(fileNames.Front());
    if (parsedPath.PathParts.Size() == 0)
      return E_FAIL;
    if (fileNames.Size() == 1 || parsedPath.PathParts.Size() == 1)
    {
      // CSysString pureName, dot, extension;
      resultPath = parsedPath.PathParts.Back();
    }
    else
    {
      parsedPath.PathParts.DeleteBack();
      resultPath = parsedPath.PathParts.Back();
    }
  }
  UString archiveNameSrc = resultPath;
  UString arcName = archiveNameSrc;

  int prevFormat = archiverIndex;
  SetArcName(arcName, codecs->Formats[archiverIndex]);

  const CActionSet *actionSet = &k_ActionSet_Add;

  for (;;)
  {
    AString archiveNameA = UnicodeStringToMultiByte(arcName, CP_OEMCP);
    const int kYSize = 16;
    const int kXMid = 38;

    const int kArchiveNameIndex = 2;
    const int kMethodRadioIndex = kArchiveNameIndex + 2;
    const int kModeRadioIndex = kMethodRadioIndex + 7;

    char updateAddToArchiveString[512];
    {
      const CArcInfoEx &arcInfo = codecs->Formats[archiverIndex];
      const AString s = UnicodeStringToMultiByte(arcInfo.Name, CP_OEMCP);
      sprintf(updateAddToArchiveString,
        g_StartupInfo.GetMsgString(NMessageID::kUpdateAddToArchive), (const char *)s);
    }

    int methodIndex = 0;
    int i;
    for (i = ARRAY_SIZE(g_MethodMap) - 1; i >= 0; i--)
      if (compressionInfo.Level >= g_MethodMap[i])
      {
        methodIndex = i;
        break;
      }

    const struct CInitDialogItem initItems[]=
    {
      { DI_DOUBLEBOX, 3, 1, 72, kYSize - 2, false, false, 0, false, NMessageID::kUpdateTitle, NULL, NULL },

      { DI_TEXT, 5, 2, 0, 0, false, false, 0, false, -1, updateAddToArchiveString, NULL },

      { DI_EDIT, 5, 3, 70, 3, true, false, DIF_HISTORY, false, -1, archiveNameA, kArchiveHistoryKeyName},
      // { DI_EDIT, 5, 3, 70, 3, true, false, 0, false, -1, arcName, NULL},

      { DI_SINGLEBOX, 4, 4, kXMid - 2, 4 + 7, false, false, 0, false, NMessageID::kUpdateMethod, NULL, NULL },

      { DI_RADIOBUTTON, 6, 5, 0, 0, false, methodIndex == 0, DIF_GROUP, false, NMessageID::kUpdateMethod_Store, NULL, NULL },
      { DI_RADIOBUTTON, 6, 6, 0, 0, false, methodIndex == 1, 0, false, NMessageID::kUpdateMethod_Fastest, NULL, NULL },
      { DI_RADIOBUTTON, 6, 7, 0, 0, false, methodIndex == 2, 0, false, NMessageID::kUpdateMethod_Fast, NULL, NULL },
      { DI_RADIOBUTTON, 6, 8, 0, 0, false, methodIndex == 3, 0, false, NMessageID::kUpdateMethod_Normal, NULL, NULL },
      { DI_RADIOBUTTON, 6, 9, 0, 0, false, methodIndex == 4, 0, false, NMessageID::kUpdateMethod_Maximum, NULL, NULL },
      { DI_RADIOBUTTON, 6,10, 0, 0, false, methodIndex == 5, 0, false, NMessageID::kUpdateMethod_Ultra, NULL, NULL },

      { DI_SINGLEBOX, kXMid, 4, 70, 4 + 5, false, false, 0, false, NMessageID::kUpdateMode, NULL, NULL },

      { DI_RADIOBUTTON, kXMid + 2, 5, 0, 0, false, actionSet == &k_ActionSet_Add, DIF_GROUP, false, NMessageID::kUpdateMode_Add, NULL, NULL },
      { DI_RADIOBUTTON, kXMid + 2, 6, 0, 0, false, actionSet == &k_ActionSet_Update,      0, false, NMessageID::kUpdateMode_Update, NULL, NULL },
      { DI_RADIOBUTTON, kXMid + 2, 7, 0, 0, false, actionSet == &k_ActionSet_Fresh,       0, false, NMessageID::kUpdateMode_Fresh, NULL, NULL },
      { DI_RADIOBUTTON, kXMid + 2, 8, 0, 0, false, actionSet == &k_ActionSet_Sync,        0, false, NMessageID::kUpdateMode_Sync, NULL, NULL },

      { DI_TEXT, 3, kYSize - 4, 0, 0, false, false, DIF_BOXCOLOR|DIF_SEPARATOR, false, -1, "", NULL  },

      { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, true, NMessageID::kUpdateAdd, NULL, NULL  },
      { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kUpdateSelectArchiver, NULL, NULL  },
      { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL  }
    };

    const int kNumDialogItems = ARRAY_SIZE(initItems);

    const int kOkButtonIndex = kNumDialogItems - 3;
    const int kSelectarchiverButtonIndex = kNumDialogItems - 2;

    FarDialogItem dialogItems[kNumDialogItems];
    g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems);
    int askCode = g_StartupInfo.ShowDialog(76, kYSize,
        kHelpTopic, dialogItems, kNumDialogItems);

    archiveNameA = dialogItems[kArchiveNameIndex].Data;
    archiveNameA.Trim();
    MultiByteToUnicodeString2(arcName, archiveNameA, CP_OEMCP);

    compressionInfo.Level = g_MethodMap[0];
    for (i = 0; i < ARRAY_SIZE(g_MethodMap); i++)
      if (dialogItems[kMethodRadioIndex + i].Selected)
        compressionInfo.Level = g_MethodMap[i];

         if (dialogItems[kModeRadioIndex    ].Selected) actionSet = &k_ActionSet_Add;
    else if (dialogItems[kModeRadioIndex + 1].Selected) actionSet = &k_ActionSet_Update;
    else if (dialogItems[kModeRadioIndex + 2].Selected) actionSet = &k_ActionSet_Fresh;
    else if (dialogItems[kModeRadioIndex + 3].Selected) actionSet = &k_ActionSet_Sync;
    else throw 51751;

    if (askCode == kSelectarchiverButtonIndex)
    {
      CIntVector indices;
      CSysStringVector archiverNames;
      FOR_VECTOR (k, codecs->Formats)
      {
        const CArcInfoEx &arc = codecs->Formats[k];
        if (arc.UpdateEnabled)
        {
          indices.Add(k);
          archiverNames.Add(GetSystemString(arc.Name, CP_OEMCP));
        }
      }

      int index = g_StartupInfo.Menu(FMENU_AUTOHIGHLIGHT,
          g_StartupInfo.GetMsgString(NMessageID::kUpdateSelectArchiverMenuTitle),
          NULL, archiverNames, archiverIndex);
      if (index >= 0)
      {
        const CArcInfoEx &prevArchiverInfo = codecs->Formats[prevFormat];
        if (prevArchiverInfo.Flags_KeepName())
        {
          const UString &prevExtension = prevArchiverInfo.GetMainExt();
          const unsigned prevExtensionLen = prevExtension.Len();
          if (arcName.Len() >= prevExtensionLen &&
              MyStringCompareNoCase(arcName.RightPtr(prevExtensionLen), prevExtension) == 0)
          {
            int pos = arcName.Len() - prevExtensionLen;
            if (pos > 2)
            {
              if (arcName[pos - 1] == '.')
                arcName.DeleteFrom(pos - 1);
            }
          }
        }

        archiverIndex = indices[index];
        const CArcInfoEx &arcInfo = codecs->Formats[archiverIndex];
        prevFormat = archiverIndex;

        if (arcInfo.Flags_KeepName())
          arcName = archiveNameSrc;
        SetArcName(arcName, arcInfo);
      }
      continue;
    }

    if (askCode != kOkButtonIndex)
      return E_ABORT;

    break;
  }

  const CArcInfoEx &archiverInfoFinal = codecs->Formats[archiverIndex];
  compressionInfo.ArcType = archiverInfoFinal.Name;
  compressionInfo.Save();

  NWorkDir::CInfo workDirInfo;
  workDirInfo.Load();

  FString fullArcName;
  if (!MyGetFullPathName(us2fs(arcName), fullArcName))
    return E_FAIL;

  CWorkDirTempFile tempFile;
  RINOK(tempFile.CreateTempFile(fullArcName));

  CScreenRestorer screenRestorer;
  CProgressBox progressBox;
  CProgressBox *progressBoxPointer = NULL;

  screenRestorer.Save();

  progressBoxPointer = &progressBox;
  progressBox.Init(
      // g_StartupInfo.GetMsgString(NMessageID::kWaitTitle),
      g_StartupInfo.GetMsgString(NMessageID::kUpdating));

  NFind::CFileInfo fileInfo;

  CMyComPtr<IOutFolderArchive> outArchive;

  CMyComPtr<IInFolderArchive> archiveHandler;
  if (fileInfo.Find(fullArcName))
  {
    if (fileInfo.IsDir())
      throw "There is Directory with such name";

    CAgent *agentSpec = new CAgent;
    archiveHandler = agentSpec;
    // CLSID realClassID;
    CMyComBSTR archiveType;
    RINOK(agentSpec->Open(NULL,
        GetUnicodeString(fullArcName, CP_OEMCP), UString(),
        // &realClassID,
        &archiveType,
        NULL));

    if (MyStringCompareNoCase(archiverInfoFinal.Name, (const wchar_t *)archiveType) != 0)
      throw "Type of existing archive differs from specified type";
    HRESULT result = archiveHandler.QueryInterface(
        IID_IOutFolderArchive, &outArchive);
    if (result != S_OK)
    {
      g_StartupInfo.ShowMessage(NMessageID::kUpdateNotSupportedForThisArchive);
      return E_FAIL;
    }
  }
  else
  {
    // HRESULT result = outArchive.CoCreateInstance(classID);
    CAgent *agentSpec = new CAgent;
    outArchive = agentSpec;

    /*
    HRESULT result = outArchive.CoCreateInstance(CLSID_CAgentArchiveHandler);
    if (result != S_OK)
    {
      g_StartupInfo.ShowMessage(NMessageID::kUpdateNotSupportedForThisArchive);
      return E_FAIL;
    }
    */
  }

  CObjArray<const wchar_t *> fileNamePointers(fileNames.Size());

  unsigned i;
  for (i = 0; i < fileNames.Size(); i++)
    fileNamePointers[i] = fileNames[i];

  outArchive->SetFolder(NULL);
  outArchive->SetFiles(L"", fileNamePointers, fileNames.Size());
  BYTE actionSetByte[NUpdateArchive::NPairState::kNumValues];
  for (i = 0; i < NUpdateArchive::NPairState::kNumValues; i++)
    actionSetByte[i] = (BYTE)actionSet->StateActions[i];

  CUpdateCallback100Imp *updateCallbackSpec = new CUpdateCallback100Imp;
  CMyComPtr<IFolderArchiveUpdateCallback> updateCallback(updateCallbackSpec );

  updateCallbackSpec->Init(/* archiveHandler, */ progressBoxPointer);

  RINOK(SetOutProperties(outArchive, compressionInfo.Level));

  // FStringVector requestedPaths;
  // FStringVector processedPaths;
  HRESULT result = outArchive->DoOperation(
      // &requestedPaths, &processedPaths,
      NULL, NULL,
      codecs, archiverIndex,
      tempFile.OutStream, actionSetByte,
      NULL, updateCallback);
  updateCallback.Release();
  outArchive.Release();

  if (result != S_OK)
  {
    ShowSysErrorMessage(result);
    return result;
  }

  if (archiveHandler)
  {
    archiveHandler->Close();
  }

  result = tempFile.MoveToOriginal(archiveHandler != NULL);
  if (result != S_OK)
  {
    ShowSysErrorMessage(result);
    return result;
  }
  return S_OK;
}

static const char *k_CreateFolder_History = "NewFolder"; // we use default FAR folder name

HRESULT CPlugin::CreateFolder()
{
  if (_agent->IsThereReadOnlyArc())
  {
    g_StartupInfo.ShowMessage(NMessageID::kUpdateNotSupportedForThisArchive);
    return TRUE;
  }

  UString destPathU;
  {
    const int kXSize = 60;
    const int kYSize = 8;
    const int kPathIndex = 2;

    AString destPath = "New Folder";

    const struct CInitDialogItem initItems[]={
      { DI_DOUBLEBOX, 3, 1, kXSize - 4, kYSize - 2, false, false, 0, false,
          -1, "Create Folder", NULL },

      { DI_TEXT, 5, 2, 0, 0, false, false, 0, false, -1, "Folder name:", NULL },

      { DI_EDIT, 5, 3, kXSize - 6, 3, true, false, DIF_HISTORY, false, -1, destPath, k_CreateFolder_History },

      { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, true, NMessageID::kOk, NULL, NULL },
      { DI_BUTTON, 0, kYSize - 3, 0, 0, false, false, DIF_CENTERGROUP, false, NMessageID::kCancel, NULL, NULL }
    };

    const int kNumDialogItems = ARRAY_SIZE(initItems);
    const int kOkButtonIndex = kNumDialogItems - 2;

    FarDialogItem dialogItems[kNumDialogItems];
    g_StartupInfo.InitDialogItems(initItems, dialogItems, kNumDialogItems);
    for (;;)
    {
      int askCode = g_StartupInfo.ShowDialog(kXSize, kYSize,
          NULL, // kHelpTopic
          dialogItems, kNumDialogItems);
      if (askCode != kOkButtonIndex)
        return E_ABORT;
      destPath = dialogItems[kPathIndex].Data;
      destPathU = GetUnicodeString(destPath, CP_OEMCP);
      destPathU.Trim();
      if (!destPathU.IsEmpty())
        break;
      g_StartupInfo.ShowErrorMessage("You must specify folder name");
    }

  }

  CScreenRestorer screenRestorer;
  CProgressBox progressBox;
  CProgressBox *progressBoxPointer = NULL;
  // if ((opMode & OPM_SILENT) == 0 && (opMode & OPM_FIND ) == 0)
  {
    screenRestorer.Save();

    progressBoxPointer = &progressBox;
    progressBox.Init(
        // g_StartupInfo.GetMsgString(NMessageID::kWaitTitle),
        g_StartupInfo.GetMsgString(NMessageID::kDeleting));
  }

  CUpdateCallback100Imp *updateCallbackSpec = new CUpdateCallback100Imp;
  CMyComPtr<IFolderArchiveUpdateCallback> updateCallback(updateCallbackSpec);

  updateCallbackSpec->Init(/* m_ArchiveHandler, */ progressBoxPointer);

  HRESULT result;
  {
    CMyComPtr<IFolderOperations> folderOperations;
    result = _folder.QueryInterface(IID_IFolderOperations, &folderOperations);
    if (folderOperations)
      result = folderOperations->CreateFolder(destPathU, updateCallback);
    else if (result != S_OK)
      result = E_FAIL;
  }

  if (result != S_OK)
  {
    ShowSysErrorMessage(result);
    return result;
  }

  g_StartupInfo.Control(this, FCTL_UPDATEPANEL, (void *)1);
  g_StartupInfo.Control(this, FCTL_REDRAWPANEL, NULL);

  PanelInfo panelInfo;

  if (g_StartupInfo.ControlGetActivePanelInfo(panelInfo))
  {
    AString destPath = GetOemString(destPathU);

    for (int i = 0; i < panelInfo.ItemsNumber; i++)
    {
      const PluginPanelItem &pi = panelInfo.PanelItems[i];
      if (strcmp(destPath, pi.FindData.cFileName) == 0)
      {
        PanelRedrawInfo panelRedrawInfo;
        panelRedrawInfo.CurrentItem = i;
        panelRedrawInfo.TopPanelItem = 0;
        g_StartupInfo.Control(this, FCTL_REDRAWPANEL, &panelRedrawInfo);
        break;
      }
    }
  }

  SetCurrentDirVar();
  return S_OK;
}


text:
/**
 * @param {number} n
 * @return {number}
 */
const bulbSwitch = function (n) {
    // Only squares will be toggled odd times
    return Math.floor(Math.sqrt(n));
};

module.exports = bulbSwitch;


text:
package com.ak.yahoonewsreader.data;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ak.yahoonewsreader.data.NewsItem.NewsItemImage;
import com.ak.yahoonewsreader.util.Logger;

public class NewsItemsParser {

	private static final String TAG_RESULTS = "result";
	private static final String TAG_ITEMS = "items";
	private static final String TAG_TITLE = "title";
	private static final String TAG_PUBLISHED = "published";
	private static final String TAG_UUID = "uuid";
	private static final String TAG_PUBLISHER = "publisher";
	private static final String TAG_IMAGES = "images";
	private static final String TAG_WIDTH = "width";
	private static final String TAG_HEIGTH = "height";
	private static final String TAG_URL = "url";
	private static final String TAG_LINK = "link";
	private static final String TAG_SUMMARY = "summary";

	public static List<NewsItem> parse(String jsonString){

		JSONObject jsonObject = null;
		List<NewsItem> newsItemslist = null;

		try {
			jsonObject = new JSONObject(jsonString.toString());
		} catch (JSONException e) {
			Logger.error("Invalid JSON 1 - Skipping parsing", e);
			e.printStackTrace();
			return null;
		}

		if(jsonObject != null){
			try {
				JSONObject results = jsonObject.getJSONObject(TAG_RESULTS);
				JSONArray items = results.getJSONArray(TAG_ITEMS);
				newsItemslist = new ArrayList<NewsItem>();
				for (int i = 0; i < items.length(); i++) {
					try{
						JSONObject item = items.getJSONObject(i);
						String title = item.getString(TAG_TITLE);
						String uuid = item.getString(TAG_UUID);
						NewsItem newsItem = new NewsItem(title, uuid);
						newsItem.setPublished(item.getString(TAG_PUBLISHED));
						newsItem.setPublisher(item.getString(TAG_PUBLISHER));
						newsItem.setSummary(item.getString(TAG_SUMMARY));
						newsItem.setLink(item.getString(TAG_LINK));
						List<NewsItemImage> images = new ArrayList<NewsItem.NewsItemImage>();
						JSONArray imagelist = item.getJSONArray(TAG_IMAGES);
						for (int j = 0; j < imagelist.length(); j++) {
							try{
								JSONObject image = imagelist.getJSONObject(i);
								int width = Integer.valueOf(image.getString(TAG_WIDTH));
								int heigth = Integer.valueOf(image.getString(TAG_HEIGTH));
								URL url = new URL(image.getString(TAG_URL));
								NewsItemImage imageObj = new NewsItemImage(width, heigth, url);
								images.add(imageObj);
							}catch(JSONException e){
								Logger.error("Invalid Image JSON object - Skipping Image", e);
								continue;
							}catch (NumberFormatException e) {
								Logger.error("Invalid Image SIZE - Skipping Image", e);
								continue;
							} catch (MalformedURLException e) {
								Logger.error("Invalid Image URL - Skipping Image", e);
								continue;
							}
						}
						newsItemslist.add(newsItem);
					}catch (JSONException e) {
						Logger.error("Invalid News Item JSON Object - Skipping News Item", e);
						e.printStackTrace();
						continue;
					}
				}
			} catch (JSONException e) {
				Logger.error("Invalid JSON 2 - Skipping parsing", e);
				e.printStackTrace();
			}
		}
		return newsItemslist;
	}

}


text:
package RemoveDuplicatesfromSortedListII;

/**
 * Definition for singly-linked list.
 */
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

/**
 * Given a sorted linked list, delete all nodes that have duplicate
 * numbers, leaving only distinct numbers from the original list.
 * <p>
 * For example,
 * Given 1->2->3->3->4->4->5, return 1->2->5.
 * Given 1->1->1->2->3, return 2->3.
 */
class Solution {

    public ListNode deleteDuplicates(ListNode head) {
        if (head == null)
            return null;
        ListNode nh = null, ptr = null;

        while (head != null) {
            int val = head.val, count = 0;
            ListNode node = head;

            while (node != null && node.val == val) {
                count++;
                node = node.next;
            }
            if (count == 1) {
                if (nh == null) {
                    nh = ptr = head;
                } else {
                    ptr.next = head;
                    ptr = ptr.next;
                }
                ptr.next = null;
            }
            head = node;
        }
        return nh;
    }
}


text:
package org.anyline.data.prepare.auto;

public interface TablePrepare extends AutoPrepare{
}