text:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using PhotoResizeLib;
using System.Drawing;

namespace PhotoResizer
{

    public partial class frmHome : Form
    {
        // This delegate enables asynchronous calls for setting
        // the text property on a TextBox control.
        delegate void SetLblProgressCallback(ProcessingResult result);
        delegate void SetProgressDelegate(ProgressEventArgs e);
        delegate void ProcessingCancelledDelegate();
        delegate void SetCurrentProgressDelegate(ProgressEventArgs e);

        private int[] comboTxtDefaults = { 50, 1000, 2000 };
        private int comboLastIdx = 0;
        private CancellationTokenSource cancelSource = new CancellationTokenSource();
        private MediaProcessor MP = new MediaProcessor();

        public frmHome()
        {
            InitializeComponent();

            this.cbxOutputType.Items.AddRange(OutputStringTypes.GetImageTypes());
            this.cbxVideoOutputType.Items.AddRange(OutputStringTypes.GetVideoTypes());
            this.cbxResizeType.SelectedIndex = 0;
            this.cbxOutputType.SelectedIndex = 0;
            this.txtResize.Text = this.comboTxtDefaults[this.cbxResizeType.SelectedIndex].ToString();
            this.cbxVideoOutputType.SelectedIndex = 0;
            this.cbxVideoResizeType.SelectedIndex = 0;

            this.lblDragFiles.DragEnter += new DragEventHandler(lblDragFiles_DragEnter);
            this.lblDragFiles.DragDrop += new DragEventHandler(lblDragFiles_DragDrop);
            this.lblDragTrimVideo.DragEnter += new DragEventHandler(lblDragTrimVideo_DragEnter);
            this.lblDragTrimVideo.DragDrop += new DragEventHandler(lblDragTrimVideo_DragDrop);

            string[] imageExt = MediaProcessor.GetAllAllowedImageExtensions();
            string[] videoExt = MediaProcessor.GetAllAllowedVideoExtensions();
            string allTooltip = "";
            string videoTooltip = "";
            for (int ii = 0; ii < imageExt.Length; ii++)
            {
                allTooltip += (imageExt[ii] + " ");
            }
            allTooltip += "\r\n";
            for (int ii = 0; ii < videoExt.Length; ii++)
            {
                allTooltip += (videoExt[ii] + " ");
                videoTooltip += (videoExt[ii] + " ");
            }
            this.toolTip1.SetToolTip(this.lblDragFiles, allTooltip);
            this.toolTip1.SetToolTip(this.lblDragTrimVideo, videoTooltip);
        }

        private bool TryReadDefaultCropRatio(out float? defaultCropRatio)
        {
            bool success = true;
            defaultCropRatio = null;
            if (this.txtRatio1.Text.Length > 0 && this.txtRatio2.Text.Length > 0)
            {
                float cropRatio;
                success = MediaProcessorOptions.TryParseCropRatio(this.txtRatio1.Text + ":" + this.txtRatio2.Text, out cropRatio);
                if (success)
                {
                    defaultCropRatio = cropRatio;
                }
            }
            return success;
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {

            if (MP.isProcessing)
            {
                this.cancelSource.Cancel();
                return;
            }
            if (MP.GetNumFiles() == 0)
            {
                MessageBox.Show("No files selected.", "No files selected", MessageBoxButtons.OK);
                return;
            }
            int resizeValue = 0;
            bool success = MediaProcessorOptions.TryParseResizeValue(this.txtResize.Text, (comboOptions)this.cbxResizeType.SelectedIndex, out resizeValue);
            if (!success)
            {
                MessageBox.Show("Invalid value entered for resizing images to.", "Invalid entry", MessageBoxButtons.OK);
                return;
            }
            int videoResizeValue = 0;
            success = MediaProcessorOptions.TryParseResizeValue(this.txtVideoResize.Text, (comboOptions)this.cbxVideoResizeType.SelectedIndex, out videoResizeValue);
            if (!success)
            {
                MessageBox.Show("Invalid value entered for resizing videos to.", "Invalid entry", MessageBoxButtons.OK);
                return;
            }

            success = this.TryReadDefaultCropRatio(out float? defaultCropRatio);
            if (!success)
            {
                MessageBox.Show("Invalid value entered for crop ratio.", "Invalid entry", MessageBoxButtons.OK);
                return;
            }

            MediaProcessorOptions options = new MediaProcessorOptions(
                (comboOptions)this.cbxResizeType.SelectedIndex,
                (comboOptions)this.cbxVideoResizeType.SelectedIndex,
                (outTypeOptions)this.cbxOutputType.SelectedIndex,
                (videoOutTypeOptions)this.cbxVideoOutputType.SelectedIndex,
                resizeValue,
                videoResizeValue,
                (int)nudQuality.Value,
                (int)nudVideoQuality.Value,
                defaultCropRatio
            );
            MP.SetOptions(options);
            MP.SetFileSuffix(txtSuffix.Text);

            FileValidationResult val = MP.ValidateFileList();
            if (val.noInputList.Count > 0 || val.folderFailedList.Count > 0)
            {
                MessageBox.Show(val.message, "Invalid file list", MessageBoxButtons.OK);
                return;
            }
            if (val.outputExistsList.Count > 0)
            {
                DialogResult res = MessageBox.Show("Overwrite these files?\r\n\r\n" + val.message, "Files already exist", MessageBoxButtons.YesNo);
                if (res == DialogResult.No)
                {
                    return;
                }
            }

            CancellationToken token = this.cancelSource.Token;
            this.OnProcessingStart();
            Task processingTask = Task.Factory.StartNew(() =>
            {
                MP.Run(token, UpdateOnProgress);
                if (token.IsCancellationRequested)
                {
                    this.OnProcessingCancelled();
                }
                else
                {
                    this.OnProcessingComplete(MP.GetResult());
                }

            }, token);

        }

        private bool ShouldContinueWhenFileExists(string message)
        {
            DialogResult result = MessageBox.Show("File " + message + ". \r\nYes to overwrite\r\nNo to skip this file\r\nCancel to stop processing", "File already exists", MessageBoxButtons.YesNoCancel);
            switch (result)
            {
                case DialogResult.Yes:
                    return true;
                case DialogResult.No:
                    return false;
                case DialogResult.Cancel:
                    this.cancelSource.Cancel();
                    return false;
                default:
                    return false;
            }
        }

        private void OnProcessingStart()
        {
            // Does any tasks which should be done when processing begins
            this.btnProcess.Text = "Cancel";
            SetControlsEnable(false);
        }

        private void SetControlsEnable(bool enbl)
        {
            this.btnClearFiles.Enabled = enbl;
            this.btnShowSelected.Enabled = enbl;

            this.txtResize.Enabled = enbl;
            this.cbxOutputType.Enabled = enbl;
            this.cbxResizeType.Enabled = enbl;
            this.nudQuality.Enabled = enbl;

            this.txtVideoResize.Enabled = enbl;
            this.cbxVideoOutputType.Enabled = enbl;
            this.cbxVideoResizeType.Enabled = enbl;
            this.nudVideoQuality.Enabled = enbl;
        }

        private void OnProcessingComplete(ProcessingResult result)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.lblProgress.InvokeRequired)
            {
                SetLblProgressCallback d = new SetLblProgressCallback(OnProcessingComplete);
                this.Invoke(d, new object[] { result });
            }
            else
            {
                lblProgress.Text = string.Format("Processing complete on {0} of {1} files. {2} files failed.",
                                result.numComplete.ToString(),
                                result.numTotal.ToString(),
                                result.numFailed.ToString());

                if (result.lastError != null)
                {
                    MessageBox.Show(String.Format("One or more files failed.\nLast exception: {0}\n{1}", result.lastError.Message, result.lastError.StackTrace),
                        "File processing error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }

                this.btnProcess.Text = "Process Files";
                SetControlsEnable(true);
                MP.ClearFiles();
                SetFileCount();
            }
        }
        private void OnProcessingCancelled()
        {
            if (this.lblProgress.InvokeRequired)
            {
                ProcessingCancelledDelegate d = new ProcessingCancelledDelegate(OnProcessingCancelled);
                this.Invoke(d, new object[] { });
            }
            else
            {
                lblProgress.Text += " (cancelled)";
                this.btnProcess.Text = "Process Files";
                SetControlsEnable(true);
                this.cancelSource = new CancellationTokenSource(); // reset cancel token
            }
        }

        private void SetFileCount()
        {
            lblNumFiles.Text = MP.GetNumFiles().ToString() + " files selected.";
        }

        private void UpdateOnProgress(object sender, ProgressEventArgs e)
        {
            SetProgress(e);
            SetCurrentProgress(e);
        }

        private void SetProgress(ProgressEventArgs e)
        {
            if (this.lblProgress.InvokeRequired)
            {
                SetProgressDelegate d = new SetProgressDelegate(SetProgress);
                this.Invoke(d, new object[] { e });
            }
            else
            {
                lblProgress.Text = "Processed " + e.filesComplete.ToString() + " of " + e.totalFiles.ToString() + " files.";
                if (e.totalFiles == 0)
                {
                    pbar1.Value = 0;
                }
                else
                {
                    pbar1.Value = Convert.ToInt32(e.totalProgress * pbar1.Maximum / 100);
                }
            }
        }
        private void SetCurrentProgress(ProgressEventArgs e)
        {
            if (this.lblFileProgress.InvokeRequired)
            {
                SetCurrentProgressDelegate d = new SetCurrentProgressDelegate(SetCurrentProgress);
                this.Invoke(d, new object[] { e });
            }
            else
            {
                int numTotal = MP.GetNumFiles();
                lblFileProgress.Text = "Processing file " + e.currentFile;
                pbar2.Value = Convert.ToInt32(e.fileProgress);
            }
        }

        private void cbxResizeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            int resizeValue = 0;
            bool success = MediaProcessorOptions.TryParseResizeValue(this.txtResize.Text, (comboOptions)this.comboLastIdx, out resizeValue);
            if (!success)
            {
                this.comboTxtDefaults[this.comboLastIdx] = resizeValue;
            }
            this.txtResize.Text = this.comboTxtDefaults[this.cbxResizeType.SelectedIndex].ToString();
            this.comboLastIdx = this.cbxResizeType.SelectedIndex;
        }

        private void lblDragFiles_DragEnter(object sender, DragEventArgs e)
        {
            if (MP.isProcessing)
            {
                return;
            }
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }
        private void lblDragFiles_DragDrop(object sender, DragEventArgs e)
        {
            if (MP.isProcessing)
            {
                return;
            }
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            int oldCount = MP.GetNumFiles();
            MP.AddFiles(files);

            int numNew = MP.GetNumFiles() - oldCount;
            int numIgnored = files.Length - numNew;
            this.statusInfo.Text = numNew.ToString() + " new files were added.";
            if (numIgnored > 0)
            {
                this.statusInfo.Text += (" " + numIgnored.ToString() + " were ignored due to already being in the list or having an unsupported file type.");
            }
            SetFileCount();
        }
        private void lblDragTrimVideo_DragEnter(object sender, DragEventArgs e)
        {
            if (MP.isProcessing)
            {
                return;
            }
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                e.Effect = DragDropEffects.Copy;
            }
        }
        private void lblDragTrimVideo_DragDrop(object sender, DragEventArgs e)
        {
            if (MP.isProcessing)
            {
                return;
            }
            string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            string[] allowedFiles = MP.GetAllowedVideoFiles(files);
            if (allowedFiles.Length == 0)
            {
                this.statusInfo.Text = "None of the dragged files were supported video files.";
                return;
            }

            string filename = allowedFiles[0];
            if (MP.IsInList(filename))
            {
                this.statusInfo.Text = "Dragged file is already in the list.";
                return;
            }

            using (frmVideoTrim trimmer = new frmVideoTrim(filename))
            {
                DialogResult dialogResult = trimmer.ShowDialog(this);
                switch (dialogResult)
                {
                    case DialogResult.OK:
                        Tuple<double, double> startStop = trimmer.GetTimeRange();
                        MP.AddTrimmedVideo(filename, startStop);
                        this.statusInfo.Text = "1 new file was added.";
                        SetFileCount();
                        break;
                    default:
                        this.statusInfo.Text = "0 new files were added. Trimming was cancelled.";
                        break;
                }
            }
        }

        private void btnClearFiles_Click(object sender, EventArgs e)
        {
            MP.ClearFiles();
            SetFileCount();
            SetProgress(new ProgressEventArgs(0, 0, 0, ""));
            SetCurrentProgress(new ProgressEventArgs(0, 0, 0, "(processing not started)"));
        }

        private void cbxOutputType_SelectedIndexChanged(object sender, EventArgs e)
        {
            outTypeOptions currentOption = (outTypeOptions)this.cbxOutputType.SelectedIndex;
            if (currentOption == outTypeOptions.match ||
                currentOption == outTypeOptions.JPG)
            {
                this.lblQuality.Visible = true;
                this.nudQuality.Visible = true;
            }
            else
            {
                this.lblQuality.Visible = false;
                this.nudQuality.Visible = false;
            }
        }

        private void btnShowSelected_Click(object sender, EventArgs e)
        {
            List<string> fileList = MP.GetFileList();
            string dispString = "";
            int count = 0;
            foreach (string filename in fileList)
            {
                dispString += (filename + "\r\n");
                count++;
                if (count >= 50)
                {
                    dispString += String.Format("...and {0} more files.", (fileList.Count - count).ToString());
                    break;
                }
            }
            MessageBox.Show(dispString, "Currently Selected Files", MessageBoxButtons.OK);
        }

        private void btnSetCropBoundaries_Click(object sender, EventArgs e)
        {
            if (this.MP.GetNumFiles() == 0)
            {
                MessageBox.Show("No files selected", "No files selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            bool success = this.TryReadDefaultCropRatio(out float? defaultCropRatio);
            if (!success)
            {
                MessageBox.Show("Invalid default crop ratio entered", "Invalid default crop ratio", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            using (frmImageCrop cropper = new frmImageCrop(this.MP.GetFileList(), this.MP.GetCropBoundaries(), defaultCropRatio))
            {
                DialogResult dialogResult = cropper.ShowDialog(this);
                if (dialogResult == DialogResult.OK)
                {
                    var setBoundaries = cropper.GetCropBoundaries();
                    foreach (KeyValuePair<string, Rectangle> p in setBoundaries)
                    {
                        MP.SetCropBoundaryForFile(p.Key, p.Value);
                    }
                    this.statusInfo.Text = "Updated custom crop areas.";
                }
                else
                {
                    this.statusInfo.Text = "Custom crop areas were not updated. Cropping was cancelled.";
                }
            }
        }
    }
}


text:
package org.jbpm.workflow.instance.node;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.drools.core.common.InternalAgenda;
import org.drools.core.common.InternalKnowledgeRuntime;
import org.drools.core.util.MVELSafeHelper;
import org.jbpm.process.core.Context;
import org.jbpm.process.core.ContextContainer;
import org.jbpm.process.core.context.exception.ExceptionScope;
import org.jbpm.process.core.context.variable.Variable;
import org.jbpm.process.core.context.variable.VariableScope;
import org.jbpm.process.core.datatype.DataType;
import org.jbpm.process.core.impl.DataTransformerRegistry;
import org.jbpm.process.instance.ContextInstance;
import org.jbpm.process.instance.ContextInstanceContainer;
import org.jbpm.process.instance.ProcessInstance;
import org.jbpm.process.instance.context.exception.ExceptionScopeInstance;
import org.jbpm.process.instance.context.variable.VariableScopeInstance;
import org.jbpm.process.instance.impl.ContextInstanceFactory;
import org.jbpm.process.instance.impl.ContextInstanceFactoryRegistry;
import org.jbpm.util.PatternConstants;
import org.jbpm.workflow.core.node.DataAssociation;
import org.jbpm.workflow.core.node.RuleSetNode;
import org.jbpm.workflow.core.node.Transformation;
import org.jbpm.workflow.instance.WorkflowRuntimeException;
import org.jbpm.workflow.instance.impl.NodeInstanceResolverFactory;
import org.kie.api.runtime.KieRuntime;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.process.DataTransformer;
import org.kie.api.runtime.process.EventListener;
import org.kie.api.runtime.process.NodeInstance;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.dmn.api.core.DMNContext;
import org.kie.dmn.api.core.DMNMessage.Severity;
import org.kie.dmn.api.core.DMNModel;
import org.kie.dmn.api.core.DMNResult;
import org.kie.dmn.api.core.DMNRuntime;
import org.kie.internal.runtime.StatefulKnowledgeSession;
import org.mvel2.integration.impl.MapVariableResolverFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Runtime counterpart of a ruleset node.
 *
 */
public class RuleSetNodeInstance extends StateBasedNodeInstance implements EventListener, ContextInstanceContainer {

    private static final long serialVersionUID = 510l;
    private static final Logger logger = LoggerFactory.getLogger(RuleSetNodeInstance.class);

    private static final String ACT_AS_WAIT_STATE_PROPERTY = "org.jbpm.rule.task.waitstate";

    private Map<String, FactHandle> factHandles = new HashMap<String, FactHandle>();
    private String ruleFlowGroup;

    // NOTE: ContetxInstances are not persisted as current functionality (exception scope) does not require it
    private Map<String, ContextInstance> contextInstances = new HashMap<String, ContextInstance>();
    private Map<String, List<ContextInstance>> subContextInstances = new HashMap<String, List<ContextInstance>>();

    protected RuleSetNode getRuleSetNode() {
        return (RuleSetNode) getNode();
    }

    public void internalTrigger(final NodeInstance from, String type) {
        try {
            super.internalTrigger(from, type);
            // if node instance was cancelled, abort
            if (getNodeInstanceContainer().getNodeInstance(getId()) == null) {
                return;
            }
            if (!org.jbpm.workflow.core.Node.CONNECTION_DEFAULT_TYPE.equals(type)) {
                throw new IllegalArgumentException("A RuleSetNode only accepts default incoming connections!");
            }
            RuleSetNode ruleSetNode = getRuleSetNode();
            KieRuntime kruntime = getProcessInstance().getKnowledgeRuntime();
            Map<String, Object> inputs = evaluateParameters(ruleSetNode);

            if (ruleSetNode.isDMN()) {
                String namespace = resolveVariable(ruleSetNode.getNamespace());
                String model = resolveVariable(ruleSetNode.getModel());
                String decision = resolveVariable(ruleSetNode.getDecision());

                DMNRuntime runtime = ((KieSession) kruntime).getKieRuntime(DMNRuntime.class);
                DMNModel dmnModel = runtime.getModel(namespace, model);
                if (dmnModel == null) {
                    throw new IllegalArgumentException("DMN model '" + model + "' not found with namespace '" + namespace + "'");
                }
                DMNResult dmnResult = null;
                DMNContext context = runtime.newContext();

                for (Entry<String, Object> entry : inputs.entrySet()) {
                    context.set(entry.getKey(), entry.getValue());
                }

                if (decision != null && !decision.isEmpty()) {
                    dmnResult = runtime.evaluateDecisionByName(dmnModel, decision, context);
                } else {
                    dmnResult = runtime.evaluateAll(dmnModel, context);
                }

                if (dmnResult.hasErrors()) {
                    String errors = dmnResult.getMessages(Severity.ERROR).stream()
                            .map(message -> message.toString())
                            .collect(Collectors.joining(", "));

                    throw new RuntimeException("DMN result errors:: " + errors);
                }
                processOutputs(dmnResult.getContext().getAll());
                triggerCompleted();
            } else {

                // first set rule flow group
                setRuleFlowGroup(resolveRuleFlowGroup(ruleSetNode.getRuleFlowGroup()));

                //proceed
                for (Entry<String, Object> entry : inputs.entrySet()) {
                    String inputKey = getRuleFlowGroup() + "_" + getProcessInstance().getId() + "_" + entry.getKey();

                    factHandles.put(inputKey, kruntime.insert(entry.getValue()));
                }

                if (actAsWaitState()) {
                    addRuleSetListener();
                    ((InternalAgenda) getProcessInstance().getKnowledgeRuntime().getAgenda())
                            .activateRuleFlowGroup(getRuleFlowGroup(), getProcessInstance().getId(), getUniqueId());

                } else {
                    ((InternalAgenda) getProcessInstance().getKnowledgeRuntime().getAgenda())
                            .activateRuleFlowGroup(getRuleFlowGroup(), getProcessInstance().getId(), getUniqueId());

                    ((KieSession) getProcessInstance().getKnowledgeRuntime()).fireAllRules();

                    removeEventListeners();
                    retractFacts();
                    triggerCompleted();
                }
            }
        } catch (Exception e) {
            handleException(e);
        }
    }

    private void handleException(Throwable e) {
        ExceptionScopeInstance exceptionScopeInstance = getExceptionScopeInstance(e);
        if(exceptionScopeInstance != null) {
            exceptionScopeInstance.handleException(e.getClass().getName(), e);
        } else {
            if(ExceptionUtils.getRootCause(e) != null) {
                handleException(ExceptionUtils.getRootCause(e));
            } else {
                throw new WorkflowRuntimeException(this, getProcessInstance(), "Unable to execute Action: " + e.getMessage(), e);
            }
        }
    }

    private ExceptionScopeInstance getExceptionScopeInstance(Throwable e) {
        return (ExceptionScopeInstance) resolveContextInstance(ExceptionScope.EXCEPTION_SCOPE, e.getClass().getName());
    }

    public void addEventListeners() {
        super.addEventListeners();
        addRuleSetListener();
    }

    private String getRuleSetEventType() {
        InternalKnowledgeRuntime kruntime = getProcessInstance().getKnowledgeRuntime();
        if (kruntime instanceof StatefulKnowledgeSession) {
            return "RuleFlowGroup_" + getRuleFlowGroup() + "_" + ((StatefulKnowledgeSession) kruntime).getIdentifier();
        } else {
            return "RuleFlowGroup_" + getRuleFlowGroup();
        }
    }

    private void addRuleSetListener() {
        getProcessInstance().addEventListener(getRuleSetEventType(), this, true);
    }

    public void removeEventListeners() {
        super.removeEventListeners();
        getProcessInstance().removeEventListener(getRuleSetEventType(), this, true);

    }

    public void cancel() {
        super.cancel();
        ((InternalAgenda) getProcessInstance().getKnowledgeRuntime().getAgenda()).deactivateRuleFlowGroup(getRuleFlowGroup());
    }

    public void signalEvent(String type, Object event) {
        if (getRuleSetEventType().equals(type)) {
            removeEventListeners();
            retractFacts();
            triggerCompleted();
        }
    }

	public void retractFacts() {
	    Map<String, Object> objects = new HashMap<String, Object>();
        KieRuntime kruntime = getProcessInstance().getKnowledgeRuntime();

	    for (Entry<String, FactHandle> entry : factHandles.entrySet()) {

            Object object = ((StatefulKnowledgeSession)kruntime).getObject(entry.getValue());
            String key = entry.getKey();
            key = key.replaceAll(getRuleFlowGroup()+"_", "");
            key = key.replaceAll(getProcessInstance().getId()+"_", "");
            objects.put(key , object);

            kruntime.delete(entry.getValue());

	    }

	    processOutputs(objects);
        factHandles.clear();
	}

	private void processOutputs(Map<String, Object> objects) {
	    RuleSetNode ruleSetNode = getRuleSetNode();
        if (ruleSetNode != null) {
            for (Iterator<DataAssociation> iterator = ruleSetNode.getOutAssociations().iterator(); iterator.hasNext(); ) {
                DataAssociation association = iterator.next();
                if (association.getTransformation() != null) {
                    Transformation transformation = association.getTransformation();
                    DataTransformer transformer = DataTransformerRegistry.get().find(transformation.getLanguage());
                    if (transformer != null) {
                        Object parameterValue = transformer.transform(transformation.getCompiledExpression(), objects);
                        VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
                        resolveContextInstance(VariableScope.VARIABLE_SCOPE, association.getTarget());
                        if (variableScopeInstance != null && parameterValue != null) {

                            variableScopeInstance.setVariable(association.getTarget(), parameterValue);
                        } else {
                            logger.warn("Could not find variable scope for variable {}", association.getTarget());
                            logger.warn("Continuing without setting variable.");
                        }
                        if (parameterValue != null) {
                            variableScopeInstance.setVariable(association.getTarget(), parameterValue);
                        }
                    }
                } else if (association.getAssignments() == null || association.getAssignments().isEmpty()) {
                    VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
                    resolveContextInstance(VariableScope.VARIABLE_SCOPE, association.getTarget());
                    if (variableScopeInstance != null) {
                        Object value = objects.get(association.getSources().get(0));
                        if (value == null) {
                            try {
                                value = MVELSafeHelper.getEvaluator().eval(association.getSources().get(0), new MapVariableResolverFactory(objects));
                            } catch (Throwable t) {
                                // do nothing
                            }
                        }
                        Variable varDef = variableScopeInstance.getVariableScope().findVariable(association.getTarget());
                        DataType dataType = varDef.getType();
                        // exclude java.lang.Object as it is considered unknown type
                        if (!dataType.getStringType().endsWith("java.lang.Object") && value instanceof String) {
                            value = dataType.readValue((String) value);
                        }
                        variableScopeInstance.setVariable(association.getTarget(), value);
                    } else {
                        logger.warn("Could not find variable scope for variable {}", association.getTarget());
                    }

                }
            }
        }

    }

    protected Map<String, Object> evaluateParameters(RuleSetNode ruleSetNode) {
	    Map<String, Object> replacements = new HashMap<String, Object>();

        for (Iterator<DataAssociation> iterator = ruleSetNode.getInAssociations().iterator(); iterator.hasNext(); ) {
            DataAssociation association = iterator.next();
            if (association.getTransformation() != null) {
            	Transformation transformation = association.getTransformation();
            	DataTransformer transformer = DataTransformerRegistry.get().find(transformation.getLanguage());
            	if (transformer != null) {
            		Object parameterValue = transformer.transform(transformation.getCompiledExpression(), getSourceParameters(association));
            		if (parameterValue != null) {
            			replacements.put(association.getTarget(), parameterValue);
                    }
            	}
            } else if (association.getAssignments() == null || association.getAssignments().isEmpty()) {
                Object parameterValue = null;
                VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
                resolveContextInstance(VariableScope.VARIABLE_SCOPE, association.getSources().get(0));
                if (variableScopeInstance != null) {
                    parameterValue = variableScopeInstance.getVariable(association.getSources().get(0));
                } else {
                    try {
                        parameterValue = MVELSafeHelper.getEvaluator().eval(association.getSources().get(0), new NodeInstanceResolverFactory(this));
                    } catch (Throwable t) {
                        logger.error("Could not find variable scope for variable {}", association.getSources().get(0));
                        logger.error("when trying to execute RuleSetNode {}", ruleSetNode.getName());
                        logger.error("Continuing without setting parameter.");
                    }
                }
                if (parameterValue != null) {
                	replacements.put(association.getTarget(), parameterValue);
                }
            }
        }

        for (Map.Entry<String, Object> entry: ruleSetNode.getParameters().entrySet()) {
            if (entry.getValue() instanceof String) {

                Object value = resolveVariable(entry.getValue());
                if (value != null) {
                    replacements.put(entry.getKey(), value);
                }

            }
        }

        return replacements;
	}

	private Object resolveVariable(Object s) {

	    if (s instanceof String) {
            Matcher matcher = PatternConstants.PARAMETER_MATCHER.matcher((String) s);
            while (matcher.find()) {
                String paramName = matcher.group(1);

                VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
                    resolveContextInstance(VariableScope.VARIABLE_SCOPE, paramName);
                if (variableScopeInstance != null) {
                    Object variableValue = variableScopeInstance.getVariable(paramName);
                    if (variableValue != null) {
                        return variableValue;
                    }
                } else {
                    try {
                        Object variableValue = MVELSafeHelper.getEvaluator().eval(paramName, new NodeInstanceResolverFactory(this));
                        if (variableValue != null) {
                            return variableValue;
                        }
                    } catch (Throwable t) {
                        logger.error("Could not find variable scope for variable {}", paramName);
                    }
                }
            }
	    }

        return s;

    }

    protected Map<String, Object> getSourceParameters(DataAssociation association) {
    	Map<String, Object> parameters = new HashMap<String, Object>();
    	for (String sourceParam : association.getSources()) {
	    	Object parameterValue = null;
	        VariableScopeInstance variableScopeInstance = (VariableScopeInstance)
	        resolveContextInstance(VariableScope.VARIABLE_SCOPE, sourceParam);
	        if (variableScopeInstance != null) {
	            parameterValue = variableScopeInstance.getVariable(sourceParam);
	        } else {
	            try {
	                parameterValue = MVELSafeHelper.getEvaluator().eval(sourceParam, new NodeInstanceResolverFactory(this));
	            } catch (Throwable t) {
	                logger.warn("Could not find variable scope for variable {}", sourceParam);
	            }
	        }
	        if (parameterValue != null) {
	        	parameters.put(association.getTarget(), parameterValue);
	        }
    	}

    	return parameters;
    }

	private String resolveRuleFlowGroup(String origin) {
	    return (String) resolveVariable(origin);
	}

    public Map<String, FactHandle> getFactHandles() {
        return factHandles;
    }

    public void setFactHandles(Map<String, FactHandle> factHandles) {
        this.factHandles = factHandles;
    }

    public String getRuleFlowGroup() {
        if (ruleFlowGroup == null || ruleFlowGroup.trim().length() == 0) {
            ruleFlowGroup = getRuleSetNode().getRuleFlowGroup();
        }
        return ruleFlowGroup;
    }

    public void setRuleFlowGroup(String ruleFlowGroup) {

        this.ruleFlowGroup = ruleFlowGroup;
    }

    protected boolean actAsWaitState() {
        Object asWaitState = getProcessInstance().getKnowledgeRuntime().getEnvironment().get(ACT_AS_WAIT_STATE_PROPERTY);
        if (asWaitState != null) {
            return Boolean.parseBoolean(asWaitState.toString());
        }

        return false;
    }

    @Override
    public List<ContextInstance> getContextInstances(String contextId) {
        return this.subContextInstances.get(contextId);
    }

    @Override
    public void addContextInstance(String contextId, ContextInstance contextInstance) {
        List<ContextInstance> list = this.subContextInstances.get(contextId);
        if (list == null) {
            list = new ArrayList<ContextInstance>();
            this.subContextInstances.put(contextId, list);
        }
        list.add(contextInstance);
    }

    @Override
    public void removeContextInstance(String contextId, ContextInstance contextInstance) {
        List<ContextInstance> list = this.subContextInstances.get(contextId);
        if (list != null) {
            list.remove(contextInstance);
        }
    }

    @Override
    public ContextInstance getContextInstance(String contextId, long id) {
        List<ContextInstance> contextInstances = subContextInstances.get(contextId);
        if (contextInstances != null) {
            for (ContextInstance contextInstance: contextInstances) {
                if (contextInstance.getContextId() == id) {
                    return contextInstance;
                }
            }
        }
        return null;
    }

    @Override
    public ContextInstance getContextInstance(Context context) {
        ContextInstanceFactory conf = ContextInstanceFactoryRegistry.INSTANCE.getContextInstanceFactory(context);
        if (conf == null) {
            throw new IllegalArgumentException("Illegal context type (registry not found): " + context.getClass());
        }
        ContextInstance contextInstance = (ContextInstance) conf.getContextInstance(context, this, (ProcessInstance) getProcessInstance());
        if (contextInstance == null) {
            throw new IllegalArgumentException("Illegal context type (instance not found): " + context.getClass());
        }
        return contextInstance;
    }

    @Override
    public ContextContainer getContextContainer() {
        return getRuleSetNode();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package br.edu.fatecsbc.sigapi.coletor.selenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import com.machinepublishers.jbrowserdriver.JBrowserDriver;
import com.machinepublishers.jbrowserdriver.Settings;

import br.edu.fatecsbc.sigapi.coletor.service.CredenciaisInvalidasException;
import br.edu.fatecsbc.sigapi.coletor.service.SigaInacessivelException;
import br.edu.fatecsbc.sigapi.coletor.service.SigapiException;

public class SigaClient
    extends JBrowserDriver {

    private static final int DEFAULT_TIMEOUT = 30;
    private static final int DEFAULT_IMPLICITY_TIMEOUT = 30;

    private static final String URL_LOGIN = "https://www.sigacentropaulasouza.com.br/aluno/login.aspx";

    private static final String PAGE_HOME = "home.aspx";

    private static final String ELEMENT_ID_LOGIN_INPUT_SENHA = "vSIS_USUARIOSENHA";
    private static final String ELEMENT_ID_LOGIN_INPUT_USUARIO = "vSIS_USUARIOID";
    private static final String ELEMENT_NAME_LOGIN_BT_CONFIRMA = "BTCONFIRMA";

    private static final String ELEMENT_ID_LOGIN_TXT_ERROR = "gxErrorViewer";

    private static final String ERROR_MESSAGE_LOGIN = "Não confere Login e Senha";

    public enum PAGE {

        AVISOS("Avisos", "home.aspx"),

        EMAILS(By.name("Embpage1"), AVISOS),

        CALENDARIO_PROVAS("Calendário de Provas", "calendarioprovas.aspx"),

        FALTAS_PARCIAIS("Faltas Parciais", "faltasparciais.aspx"),

        HISTORICO_GRADE("Histórico (Grade)", "historicograde.aspx"),

        HISTORICO_COMPLETO("Histórico Completo", "historicocompleto.aspx"),

        HISTORICO("Histórico", "historico.aspx"),

        HORARIO("Horário", "horario.aspx"),

        NOTAS_PARCIAIS("Notas Parciais", "notasparciais.aspx");

        private final By frame;
        private final PAGE parentPage;
        private final String label;
        private final String url;

        private PAGE(final By frame, final PAGE parentPage) {
            this(frame, parentPage, null, null);
        }

        private PAGE(final String label, final String url) {
            this(null, null, label, url);
        }

        private PAGE(final By frame, final PAGE parentPage, final String label, final String url) {
            this.frame = frame;
            this.parentPage = parentPage;
            this.label = label;
            this.url = url;
        }

        public By getFrame() {
            return frame;
        }

        public PAGE getParentPage() {
            return parentPage;
        }

        public String getLabel() {
            return label;
        }

        public String getUrl() {
            return url;
        }

        public boolean isFrame() {
            return frame != null;
        }

    }

    private static final ExpectedCondition<Boolean> ERROR_CONDITION_LOGIN = ExpectedConditions
        .textToBe(By.id(ELEMENT_ID_LOGIN_TXT_ERROR), ERROR_MESSAGE_LOGIN);

    private static final ExpectedCondition<Boolean> CONDITION_PAGE_IS_HOME = ExpectedConditions.urlContains(PAGE_HOME);

    private static final ExpectedCondition<Boolean> CONDITION_AFTER_LOGIN = ExpectedConditions
        .or(CONDITION_PAGE_IS_HOME, ERROR_CONDITION_LOGIN);

    private final int implicityTimeout;
    private PAGE currentPage;
    private boolean logged = false;

    public SigaClient() {
        this(DEFAULT_IMPLICITY_TIMEOUT);
    }

    public SigaClient(final int implicityTimeout) {
        super(createSettings());
        this.implicityTimeout = implicityTimeout;
        turnOnImplicitWaits();
    }

    private static Settings createSettings() {
        // @formatter:off
        return Settings.builder()
            .cache(false)
            .logger(null)
            .build();
        // @formatter:on
    }

    public void login(final String usuario, final String senha) throws SigapiException {

        currentPage = null;
        go(URL_LOGIN);

        if (!isElementVisibleById(ELEMENT_ID_LOGIN_INPUT_USUARIO)) {
            throw new SigaInacessivelException("Não foi possível acessar a página inicial");
        }

        sendKeysElementById(ELEMENT_ID_LOGIN_INPUT_USUARIO, usuario);
        sendKeysElementById(ELEMENT_ID_LOGIN_INPUT_SENHA, senha);
        clickElementByName(ELEMENT_NAME_LOGIN_BT_CONFIRMA);

        try {
            wait(CONDITION_AFTER_LOGIN);
        } catch (final WaitException e) {
            throw new SigaInacessivelException("Erro inesperado após o login", e);
        }

        if (ERROR_CONDITION_LOGIN.apply(this)) {
            throw new CredenciaisInvalidasException();
        }

        currentPage = PAGE.AVISOS;
        logged = true;

    }

    public void go(final PAGE newPage) throws SigaInacessivelException {

        if (!logged) {
            throw new IllegalStateException("Não está logado");
        }

        if (currentPage.isFrame()) {
            switchTo().defaultContent();
        }

        PAGE destination = newPage;
        if (newPage.isFrame()) {
            destination = newPage.getParentPage();
        }

        if (currentPage != destination) {

            // Clica no link
            findElementByLinkText(destination.getLabel()).click();
            try {
                // Aguarda o carregamento da URL
                wait(ExpectedConditions.urlContains(newPage.getUrl()));
            } catch (final WaitException e) {
                throw new SigaInacessivelException("Erro inesperado indo para a página " + newPage.name(), e);
            }

        }

        if (newPage.isFrame()) {

            try {
                wait(ExpectedConditions.frameToBeAvailableAndSwitchToIt(newPage.getFrame()));
            } catch (final WaitException e) {
                throw new SigaInacessivelException(
                    "Erro inesperado tentando obter o conteúdo de um frame da página " + newPage.name(), e);
            }

        }

        currentPage = newPage;

    }

    public void wait(final ExpectedCondition<?> condition) throws WaitException {
        wait(condition, DEFAULT_TIMEOUT);
    }

    public void wait(final ExpectedCondition<?> condition, final int timeout) throws WaitException {

        final WebDriverWait wait = new WebDriverWait(this, timeout);
        turnOffImplicitWaits();
        try {
            wait.until(condition);
        } catch (final Exception e) {
            throw new WaitException(e);
        } finally {
            turnOnImplicitWaits();
        }

    }

    public void sendKeysElementById(final String id, final String keys) {
        findElement(By.id(id)).sendKeys(keys);
    }

    public void clickElementByName(final String name) {
        findElement(By.name(name)).click();
    }

    public void go(final String url) {
        navigate().to(url);
    }

    public boolean isElementVisibleById(final String id) {
        return isElementVisible(By.id(id));
    }

    public boolean isElementVisible(final By by) {

        turnOffImplicitWaits();
        try {
            return ExpectedConditions.visibilityOfElementLocated(by).apply(this) != null;
        } catch (final NoSuchElementException e) {
            return false;
        } finally {
            turnOnImplicitWaits();
        }

    }

    @Override
    public void quit() {
        logged = false;
        super.quit();
    }

    private void turnOffImplicitWaits() {
        updateImplicityTimeout(0);
    }

    private void turnOnImplicitWaits() {
        updateImplicityTimeout(implicityTimeout);
    }

    private void updateImplicityTimeout(final int newTimeout) {
        manage().timeouts().implicitlyWait(newTimeout, TimeUnit.SECONDS);
    }

}


text:
package org.apache.ignite.internal.processors.query.h2;

import java.util.List;
import java.util.Random;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteSystemProperties;
import org.apache.ignite.cache.query.SqlFieldsQuery;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.internal.IgniteEx;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 */
public class GridSubqueryJoinOptimizerSelfTest extends GridCommonAbstractTest {
    /** */
    private static final String CACHE_NAME = "cache";

    /** */
    private static IgniteEx ignite;

    /** */
    private static IgniteCache<Integer, Integer> cache;

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        super.beforeTestsStarted();

        ignite = (IgniteEx)startGridsMultiThreaded(2);
        cache = ignite.getOrCreateCache(new CacheConfiguration<>(CACHE_NAME));

        prepare();
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        super.afterTestsStopped();

        stopAllGrids();
    }

    /**
     * Very simple case: all tables have an alias, all columns referred
     * through tables' alias.
     */
    @Test
    public void testSelectExpression1() {
        String outerSqlTemplate = "select e.name, (%s) from emp e order by 1";
        String subSql = "select d.name from dep d where d.id = e.dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case when tables has no aliases, but they are different.
     */
    @Test
    public void testSelectExpression2() {
        String outerSqlTemplate = "select name, (%s) dname from emp e order by 1";
        String subSql = "select name from dep where id = dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case when tables are the same, inner table has an alias.
     */
    @Test
    public void testSelectExpression3() {
        String outerSqlTemplate = "select name, (%s) ename from emp order by 1";
        String subSql = "select name from emp e where e.id = emp.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case when tables are the same, outer table has an alias.
     */
    @Test
    public void testSelectExpression4() {
        String outerSqlTemplate = "select name, (%s) ename from emp e order by 1";
        String subSql = "select name from emp where e.id = id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case when tables are the same, the outer table has an alias, the inner has an additional filter.
     */
    @Test
    public void testSelectExpression5() {
        String outerSqlTemplate = "select name, (%s) ename from emp e order by 1";
        String subSql = "select name from emp where e.id = id and name = 'emp1'";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case like {@link #testSelectExpression1()}, but PK of the inner table is compound.
     */
    @Test
    public void testSelectExpressionCompoundPk() {
        String outerSqlTemplate = "select e.name, (%s) from emp e order by 1";
        String subSql = "select d.name from dep2 d where d.id = e.dep_id and d.id2 = e.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case where several subqueries used as several indeoendent columns.
     */
    @Test
    public void testSelectExpressionMultiple1() {
        String outerSqlTemplate = "select (%s), (%s), (%s) from emp e1 order by 2, 3";

        String subSql1 = "select 42";
        String subSql2 = "select e2.name from emp e2 where e2.id = e1.id";
        String subSql3 = "select d.name from dep d where d.id = dep_id";

        String resSql = String.format(outerSqlTemplate, subSql1, subSql2, subSql3);

        check(resSql, 2);
    }

    /**
     * Case where several subqueries used within a function.
     */
    @Test
    public void testSelectExpressionMultiple2() {
        String outerSqlTemplate = "select name, (%s) as lbl from emp e1 order by 1";
        String subSql = "(select 'prefix ' as pref_val) " +
            "|| (select name from dep2 dn where dn.id = dep_id and dn.id2 = dep_id)";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * Simple case to ensure subqueries correctly pulled out from table list.
     */
    @Test
    public void testTableList1() {
        String outerSqlTemplate = "select e.name, d.name from emp e, (%s) d where e.dep_id = d.id order by 1, 2";
        String subSql = "select dd.name, dd.id from dep dd where dd.id < 100";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure subqueries correctly pulled out from table list, but tables the same.
     */
    @Test
    public void testTableList2() {
        String outerSqlTemplate = "select d1.name, d2.name from dep d1, (%s) d2 where d1.id = d2.id order by 1, 2";
        String subSql = "select d.name, d.id from dep d where d.id < 100";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * The same as {@link #testTableList2()}, but inner table has no alias.
     */
    @Test
    public void testTableList3() {
        String outerSqlTemplate = "select d1.name, d2.name from dep d1, (%s) d2 where d1.id = d2.id order by 1, 2";
        String subSql = "select name, id from dep where id < 100";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * The same as {@link #testTableList2()}, but both tables have no aliases.
     */
    @Test
    public void testTableList4() {
        String outerSqlTemplate = "select name from dep, (%s) d where dep.id = d.id order by 1";
        String subSql = "select id from dep where id < 100";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure subqueries correctly pulled out from table list, but inner table has no filters.
     */
    @Test
    public void testTableList5() {
        String outerSqlTemplate = "select name from dep, (%s) d where dep.id = (MOD(d.id, 7) + 1) order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure simple hierarchical subqueries properly pulled out from table list.
     */
    @Test
    public void testTableList6() {
        String outerSqlTemplate = "select name from (%s) d where d.id < 100 order by 1";
        String subSql = "select * from (select id, name from dep)";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure explicitly declared inner join with explicit join condition
     * properly pulled out from table list.
     */
    @Test
    public void testTableList7() {
        String outerSqlTemplate = "select e.name from emp e inner join (%s) d on e.id = d.id where d.id < 100 order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure explicitly declared inner join with implicit join condition
     * properly pulled out from table list.
     */
    @Test
    public void testTableList8() {
        String outerSqlTemplate = "select e.name from emp e inner join (%s) d where e.id = d.id and d.id < 100 order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure explicitly declared left join with explicit join condition
     * properly pulled out from table list.
     */
    @Test
    public void testTableList9() {
        String outerSqlTemplate = "select e.name from emp e left join (%s) d on e.id = d.id where d.id < 100 order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure explicitly declared left join without join condition
     * properly pulled out from table list.
     */
    @Test
    public void testTableList10() {
        String outerSqlTemplate = "select e.name from emp e left join (%s) d where e.id = d.id and d.id < 100 order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * The same as {@link #testTableList2()}, but both tables have no aliases.
     */
    @Test
    public void testTableListMultiple() {
        String outerSqlTemplate = "select name from dep, (%s) d, (%s) e where dep.id = d.id order by 1";
        String subSql1 = "select id from dep where id < 100";
        String subSql2 = "select id from emp where id < 100";

        String resSql = String.format(outerSqlTemplate, subSql1, subSql2);

        check(resSql, 1);
    }

    /**
     * Simple case where all tables have an alias, all columns referred
     * through tables' alias.
     */
    @Test
    public void testExistsClause1() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep d where d.id = e.dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but inner table has no alias.
     */
    @Test
    public void testExistsClause2() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep where id = e.dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but outer table has no alias.
     */
    @Test
    public void testExistsClause3() {
        String outerSqlTemplate = "select id, name from emp where exists (%s) order by 1";
        String subSql = "select 1 from dep d where d.id = dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but both tables have no aliases.
     */
    @Test
    public void testExistsClause4() {
        String outerSqlTemplate = "select id, name from emp where exists (%s) order by 1";
        String subSql = "select 1 from dep where id = dep_id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but tables are the same.
     */
    @Test
    public void testExistsClause5() {
        String outerSqlTemplate = "select id, name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from emp where id = e.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but inner table has coumpound PK.
     */
    @Test
    public void testExistsClauseCompoundPk() {
        String outerSqlTemplate = "select id, name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep2 where id = e.id and id2 = 12";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case with multiple EXISTS clauses.
     */
    @Test
    public void testExistsClauseMultiple() {
        String outerSqlTemplate = "select id, name from dep2 d where exists (%s) and exists (%s) order by 1";
        String subSql1 = "select 1 from emp where d.id = dep_id and id = 3";
        String subSql2 = "select 1 from emp where d.id2 = dep_id and id = 3";

        String resSql = String.format(outerSqlTemplate, subSql1, subSql2);

        check(resSql, 1);
    }

    /**
     * Simple case where all tables have an alias, all columns referred
     * through tables' alias.
     */
    @Test
    public void testInClause1() {
        String outerSqlTemplate = "select e.id, e.name from emp e where e.dep_id in (%s) order by 1";
        String subSql = "select d.id from dep d";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but inner table has no alias.
     */
    @Test
    public void testInClause2() {
        String outerSqlTemplate = "select e.id, e.name from emp e where e.dep_id in (%s) order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but outer table has no alias.
     */
    @Test
    public void testInClause3() {
        String outerSqlTemplate = "select id, name from emp where dep_id in (%s) order by 1";
        String subSql = "select d.id from dep d";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but both tables have no aliases.
     */
    @Test
    public void testInClause4() {
        String outerSqlTemplate = "select id, name from emp where dep_id in (%s) order by 1";
        String subSql = "select id from dep";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but tables are the same.
     */
    @Test
    public void testInClause5() {
        String outerSqlTemplate = "select id, name from emp e where id in (%s) order by 1";
        String subSql = "select id from emp";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure that array on the left of the IN clause is handled properly.
     */
    @Test
    public void testInClause6() {
        String outerSqlTemplate = "select id, name from emp e where (id, name) in (%s) order by 1";
        String subSql = "select (id, name) from emp";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case to ensure that expression on the left of the IN clause is handled properly.
     */
    @Test
    public void testInClause7() {
        String outerSqlTemplate = "select id, name from emp e where (2 + abs(id)) in (%s) order by 1";
        String subSql = "select id from emp";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Simple case, but inner table has coumpound PK.
     */
    @Test
    public void testInClauseCompoundPk() {
        String outerSqlTemplate = "select id, name from emp e where id in (%s) order by 1";
        String subSql = "select id from dep2 where id2 = 12";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 1);
    }

    /**
     * Case with multiple IN clauses.
     */
    @Test
    public void testInClauseMultiple() {
        String outerSqlTemplate = "select id, name from dep2 d where id in (%s) and id2 in (%s) order by 1";
        String subSql = "select id from emp";

        String resSql = String.format(outerSqlTemplate, subSql, subSql);

        check(resSql, 1);
    }

    /**
     * Test should verify cases with UNION ALL.
     */
    @Test
    public void testOptimizationAppliedToUnion() {
        String sql = "" +
            "select emp.name, d.id from emp, (select * from dep) d " +
            "union all " +
            "select (select name from dep2 where id = 1 and id2 = 1) as dep_name, d.id " +
            "from dep d where exists (select 1 from dep where id = d.id)";

        check(sql, 1);
    }

    /**
     * Test should verify all cases where subquery should not be rewrited.
     */
    @Test
    public void testOptimizationShouldNotBeApplied1() {
        String sql = "" +
            // follow should not be rewrited beacuse of aggregates
            "select (select max(id) from emp) f1," +
            "       (select sum(id) from emp) f2," +
            "       (select distinct id from emp where id = 1) f3," +
            "       (select distinct(id) from emp where id = 1) f4," +
            "       (select id from emp where id = 1 group by id) f5," +
            "       (select id from emp where id = 1 group by 1) f6," +
            "       (select id from emp limit 1) f7," +
            "       (select id from emp where id = 2 offset 2) f8," +
            // and this one because dep2 has compound pk (id, id2),
            // so predicate over 'id' could not guarantee uniqueness
            "       (select id from dep2 where id = 2) f9" +
            " from dep";

        check(sql, 10);
    }

    /**
     * Test should verify that optimization won't be applied when columns of the compound index
     * connect by OR.
     */
    @Test
    public void testOptimizationShouldNotBeApplied2() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep2 d2 where d2.id = e.id or d2.id2 = e.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * Case to ensure subquery with join won't be pulled out from table list.
     */
    @Test
    public void testOptimizationShouldNotBeApplied3() {
        String outerSqlTemplate = "select e.name from emp e, (%s) d order by 1 limit 10";
        String subSql = "select d1.id, d2.name from dep d1, dep d2";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2 + 1/* explain reports one additional SELECT in comments */);
    }

    /**
     * Case to ensure subquery with join won't be pulled out from EXISTS.
     */
    @Test
    public void testOptimizationShouldNotBeApplied4() {
        String outerSqlTemplate = "select e.name from emp e where exists (%s) order by 1 limit 10";
        String subSql = "select 1 from dep d1, dep d2 where d1.id = d2.id and d1.id = e.id";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * Test should verify that optimization won't be applied when columns of the compound index
     * connect by OR (ver 2).
     */
    @Test
    public void testOptimizationShouldNotBeApplied5() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep2 d2 where 1 = 1 and (d2.id = e.id or d2.id2 = e.id)";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * Test should verify that optimization won't be applied when columns of the compound index
     * connect by OR (ver 3).
     */
    @Test
    public void testOptimizationShouldNotBeApplied6() {
        String outerSqlTemplate = "select e.id, e.name from emp e where exists (%s) order by 1";
        String subSql = "select 1 from dep2 d2 where 1 = 1 and (d2.id = e.id and (d2.id2 = 1 or d2.id2 = 2))";

        String resSql = String.format(outerSqlTemplate, subSql);

        check(resSql, 2);
    }

    /**
     * @param sql Sql.
     * @param expSelectClauses Expected select clauses.
     */
    private void check(String sql, int expSelectClauses) {
        optimizationEnabled(false);

        List<List<?>> exp = cache.query(new SqlFieldsQuery(sql)).getAll();

        optimizationEnabled(true);

        List<List<?>> act = cache.query(new SqlFieldsQuery(sql).setEnforceJoinOrder(true)).getAll();

        Assert.assertEquals("Result set mismatch", exp, act);

        String plan = cache.query(new SqlFieldsQuery("explain " + sql)).getAll().get(0).get(0).toString();

        System.out.println(plan);

        int actCnt = countEntries(plan, "SELECT");

        Assert.assertEquals(String.format("SELECT-clause count mismatch: exp=%d, act=%d, plan=[%s]",
            expSelectClauses, actCnt, plan), expSelectClauses, actCnt);
    }

    /**
     * Creates all neccessary tables and inserts data.
     */
    private void prepare() {
        Random rnd = new Random();

        cache.query(new SqlFieldsQuery("CREATE TABLE dep (id LONG PRIMARY KEY, name VARCHAR, dep_name VARCHAR)"));
        cache.query(new SqlFieldsQuery("CREATE TABLE dep2 (id LONG, id2 LONG, name VARCHAR, PRIMARY KEY(id, id2))"));
        cache.query(new SqlFieldsQuery("CREATE TABLE emp (id LONG PRIMARY KEY, name VARCHAR, dep_id LONG)"));

        for (int i = 0; i < 20; i++) {
            cache.query(new SqlFieldsQuery("insert into dep (id, name, dep_name) values(?, ?, ?)")
                .setArgs(i, "dep" + i, "dep" + i));

            cache.query(new SqlFieldsQuery("insert into dep2 (id, id2, name) values(?, ?, ?)")
                .setArgs(i, i, "dep" + i));

            cache.query(new SqlFieldsQuery("insert into emp (id, name, dep_id) values(?, ?, ?)")
                .setArgs(i, "emp" + i, i < 10 ? rnd.nextInt(10) : null));
        }
    }

    /**
     * Count of entries of substring in string.
     *
     * @param where Where to search.
     * @param what What to search.
     * @return Count of entries or -1 if non is found.
     */
    private int countEntries(String where, String what) {
        return where.split(what).length - 1;
    }

    /** */
    private void optimizationEnabled(boolean enabled) {
        System.setProperty(IgniteSystemProperties.IGNITE_ENABLE_SUBQUERY_REWRITE_OPTIMIZATION, String.valueOf(enabled));

        GridTestUtils.setFieldValue(GridSubqueryJoinOptimizer.class, "optimizationEnabled", null);
    }
}


text:
package nl.knaw.dans.common.lang.search.simple;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import nl.knaw.dans.common.lang.search.Field;
import nl.knaw.dans.common.lang.search.FieldSet;
import nl.knaw.dans.common.lang.search.Index;
import nl.knaw.dans.common.lang.search.SearchQuery;
import nl.knaw.dans.common.lang.search.SearchRequest;
import nl.knaw.dans.common.lang.search.SortField;

public class SimpleSearchRequest implements SearchRequest
{
    private static final long serialVersionUID = -3624908538629551131L;

    @SuppressWarnings("unchecked")
    private FieldSet fieldQueries = new SimpleFieldSet();

    @SuppressWarnings("unchecked")
    private FieldSet filterQueries = new SimpleFieldSet();

    private SearchQuery query;

    private int limit = 10;

    private int offset;

    private List<SortField> sortFields;

    private Set<Class<?>> filterBeans;

    private Index index;

    private boolean highlightEnabled;

    private Set<String> facetFieldList;

    public SimpleSearchRequest()
    {
    }

    public SimpleSearchRequest(SearchQuery query)
    {
        this.query = query;
    }

    public SimpleSearchRequest(SearchQuery query, Index index)
    {
        this.index = index;
        this.query = query;
    }

    public SimpleSearchRequest(String queryString)
    {
        this.query = new SimpleSearchQuery(queryString);
    }

    public FieldSet<?> getFieldQueries()
    {
        return fieldQueries;
    }

    public void setFieldQueries(FieldSet<?> fieldQueries)
    {
        this.fieldQueries = fieldQueries;
    }

    public void clearFieldQueries()
    {
        fieldQueries.clear();
    }

    @SuppressWarnings("unchecked")
    public void addFieldQuery(Field<?> query)
    {
        fieldQueries.add(query);
    }

    public FieldSet<?> getFilterQueries()
    {
        return filterQueries;
    }

    @SuppressWarnings("unchecked")
    public void addFilterQuery(Field<?> query)
    {
        if (filterQueries == null)
            filterQueries = new SimpleFieldSet();
        filterQueries.add(query);
    }

    public void setFilterQueries(FieldSet<?> filterQueries)
    {
        this.filterQueries = filterQueries;
    }

    public void clearFilterQueries()
    {
        if (filterQueries != null)
            filterQueries.clear();
    }

    public Index getIndex()
    {
        return index;
    }

    public SearchQuery getQuery()
    {
        return query != null ? query : EmptySearchQuery.getInstance();
    }

    public void setQuery(SearchQuery query)
    {
        this.query = query;
    }

    public int getLimit()
    {
        return limit;
    }

    public int getOffset()
    {
        return offset;
    }

    public void setLimit(int limit)
    {
        this.limit = limit;
    }

    public void setOffset(int offset)
    {
        this.offset = offset;
    }

    public void addSortField(SortField orderField)
    {
        if (sortFields == null)
            sortFields = new ArrayList<SortField>();
        sortFields.add(orderField);
    }

    public void clearSortFields()
    {
        if (sortFields != null)
            sortFields.clear();
    }

    @SuppressWarnings("unchecked")
    public List<SortField> getSortFields()
    {
        return (List<SortField>) (sortFields != null ? sortFields : Collections.emptyList());
    }

    public void setSortFields(List<SortField> orderFields)
    {
        this.sortFields = orderFields;
    }

    public void addFilterBean(Class<?> filterBean)
    {
        if (filterBeans == null)
            filterBeans = new HashSet<Class<?>>();

        filterBeans.add(filterBean);
    }

    public void clearFilterBeans()
    {
        if (filterBeans != null)
            filterBeans.clear();
    }

    @SuppressWarnings("unchecked")
    public Set<Class<?>> getFilterBeans()
    {
        return filterBeans != null ? filterBeans : Collections.EMPTY_SET;
    }

    public void setFilterBeans(Set<Class<?>> filterBeans)
    {
        this.filterBeans = filterBeans;
    }

    public void setIndex(Index index)
    {
        this.index = index;
    }

    public boolean isHighlightingEnabled()
    {
        return highlightEnabled;
    }

    public void setHighlightingEnabled(boolean enabled)
    {
        highlightEnabled = enabled;
    }

    @SuppressWarnings("unchecked")
    public Set<String> getFacetFields()
    {
        return facetFieldList != null ? facetFieldList : Collections.EMPTY_SET;
    }

    public void setFacetFields(Set<String> facetField)
    {
        this.facetFieldList = facetField;
    }

}


text:
class User < ActiveRecord::Base
  def admin?
    true
  end
end


text:
using System;
using System.Collections.Concurrent;
using System.Linq;

namespace NElasticsearch
{
    class ClientsPool<T>
    {
        public class ElasticsearchEndpoint
        {
            public ElasticsearchEndpoint(T client)
            {
                RestClient = client;
            }

            public T RestClient { get; set; }
            public DateTime LatestFailure { get; set; }
            public int NumberOfFailures { get; set; }

            public void ResetFailures()
            {
                NumberOfFailures = 0;
                LatestFailure = DateTime.MinValue;
            }

            public void MarkFailure()
            {
                LatestFailure = DateTime.UtcNow;
                NumberOfFailures++;
            }
        }

        public ClientsPool()
        {
            ShouldUseFailedEndpoint = (numberOfFailures, lastFailure) =>
            {
                if (numberOfFailures > 5)
                    return false;
                if (lastFailure.AddMinutes(1) > DateTime.UtcNow)
                    return false;
                return true;
            };

            ShouldMarkEndpointAsDead = (numberOfFailures, lastFailure) => numberOfFailures > 5;
        }

        public Func<int, DateTime, bool> ShouldUseFailedEndpoint { get; set; }
        public Func<int, DateTime, bool> ShouldMarkEndpointAsDead { get; set; }

        private readonly ConcurrentQueue<ElasticsearchEndpoint> _clients = new ConcurrentQueue<ElasticsearchEndpoint>();
        private readonly ConcurrentQueue<ElasticsearchEndpoint> _deadClients = new ConcurrentQueue<ElasticsearchEndpoint>();

        public void Add(T client)
        {
            _clients.Enqueue(new ElasticsearchEndpoint(client));
        }

        public ElasticsearchEndpoint GetEndpoint()
        {
            var clientsCount = _clients.Count;
            while (!_clients.IsEmpty && clientsCount > 0)
            {
                ElasticsearchEndpoint endpoint;
                if (!_clients.TryDequeue(out endpoint))
                    // TODO try the dead queue
                    throw new ElasticsearchException("No clients found in the list");

                --clientsCount;

                if (endpoint.NumberOfFailures > 0 &&
                    ShouldMarkEndpointAsDead(endpoint.NumberOfFailures, endpoint.LatestFailure))
                {
                    _deadClients.Enqueue(endpoint);
                    continue;
                }

                if (endpoint.NumberOfFailures == 0 || ShouldUseFailedEndpoint(endpoint.NumberOfFailures, endpoint.LatestFailure))
                    return endpoint;

                _clients.Enqueue(endpoint);
            }
            throw new ElasticsearchException("No available Elasticsearch endpoints found");
        }

        public void ReleaseEndpoint(ElasticsearchEndpoint endpoint)
        {
            if (_clients.Contains(endpoint))
                _clients.Enqueue(endpoint);
        }
    }
}


text:
<!DOCTYPE html>

    <title></title>

        Having trouble viewing this email? Click here

        You may  unsubscribe  if you no longer wish to receive our emails.

        Uncle Harry's Appliance Academy

        Professional Business Start Up Training

Uncle Harry's Story Time

Getting a Job Over 50

<span style="font-size: 14pt; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;" color="#ff0000" face="Verdana,  Geneva,  Arial,  Helvetica,  sans-serif"Tired of Being Laid off,
Unterpaid

Dear [First Name],

Are you banging against the glass ceiling because of age or lack of valuable skills? Are you stuck in a low paying job and afraid to make a move? We talk to many folks exactly like you. The economy is no better and it is nearly impossible to learn a new career without financial help. What are you going to do?

We understand your problem. Would you like to do something about it? Check the following box and we will call.  ___.
   Uncle Harry


text:
Ext.define('KitchenSink.view.CodeContent', {
    extend: 'Ext.panel.Panel',
    alias: 'widget.codeContent',
    scrollable: true,

    cls: 'code-content',

    afterRender: function() {
        this.callParent(arguments);
        prettyPrint();
    }
});


text:
package econ.Mercury.Core;

public class Transaction {

    protected final Integer references;
    protected final String recipient;
    protected final String account;
    protected final Double Amount;
    protected final Long date = System.currentTimeMillis();

    public Transaction (String recipient, String accountName, Double amount, Econ eco) {
        this.references = eco.ReferencesID();
        this.recipient  = recipient;
        this.account    = accountName;
        this.Amount     = amount;
    }

    public Integer getReferencesID() {
        return this.references;
    }

    public String getRecipoent() {
        return this.recipient;
    }

    public String getAccount() {
        return this.account;
    }

    public Double getAmount() {
        return this.Amount;
    }

    public Long getDate() {
        return this.date;
    }
}


text:
// This file contains auto-generated code.

namespace Microsoft
{
    namespace Extensions
    {
        namespace Logging
        {
            // Generated from `Microsoft.Extensions.Logging.LoggingBuilderExtensions` in `Microsoft.Extensions.Logging, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60; Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
            public static partial class LoggingBuilderExtensions
            {
                public static Microsoft.Extensions.Logging.ILoggingBuilder AddConfiguration(this Microsoft.Extensions.Logging.ILoggingBuilder builder, Microsoft.Extensions.Configuration.IConfiguration configuration) => throw null;
            }

            namespace Configuration
            {
                // Generated from `Microsoft.Extensions.Logging.Configuration.ILoggerProviderConfiguration<>` in `Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
                public interface ILoggerProviderConfiguration<T>
                {
                    Microsoft.Extensions.Configuration.IConfiguration Configuration { get; }
                }

                // Generated from `Microsoft.Extensions.Logging.Configuration.ILoggerProviderConfigurationFactory` in `Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
                public interface ILoggerProviderConfigurationFactory
                {
                    Microsoft.Extensions.Configuration.IConfiguration GetConfiguration(System.Type providerType);
                }

                // Generated from `Microsoft.Extensions.Logging.Configuration.LoggerProviderOptions` in `Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
                public static class LoggerProviderOptions
                {
                    public static void RegisterProviderOptions<TOptions, TProvider>(Microsoft.Extensions.DependencyInjection.IServiceCollection services) where TOptions : class => throw null;
                }

                // Generated from `Microsoft.Extensions.Logging.Configuration.LoggerProviderOptionsChangeTokenSource<,>` in `Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
                public class LoggerProviderOptionsChangeTokenSource<TOptions, TProvider> : Microsoft.Extensions.Options.ConfigurationChangeTokenSource<TOptions>
                {
                    public LoggerProviderOptionsChangeTokenSource(Microsoft.Extensions.Logging.Configuration.ILoggerProviderConfiguration<TProvider> providerConfiguration) : base(default(Microsoft.Extensions.Configuration.IConfiguration)) => throw null;
                }

                // Generated from `Microsoft.Extensions.Logging.Configuration.LoggingBuilderConfigurationExtensions` in `Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60`
                public static class LoggingBuilderConfigurationExtensions
                {
                    public static void AddConfiguration(this Microsoft.Extensions.Logging.ILoggingBuilder builder) => throw null;
                }

            }
        }
    }
}
namespace System
{
    namespace Diagnostics
    {
        namespace CodeAnalysis
        {
            /* Duplicate type 'DynamicallyAccessedMemberTypes' is not stubbed in this assembly 'Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. */

            /* Duplicate type 'DynamicallyAccessedMembersAttribute' is not stubbed in this assembly 'Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. */

            /* Duplicate type 'RequiresUnreferencedCodeAttribute' is not stubbed in this assembly 'Microsoft.Extensions.Logging.Configuration, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. */

        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.jetel.collection</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

org.jetel.collection

Classes

Stack


text:
import { Controller, Req, Res, Route, Status } from '@ditsmod/core';
import { getParams, getContent, OasRoute } from '@ditsmod/openapi';

import { BasicGuard } from './basic.guard';
import { Model2 } from './models';
import { getMetaContent } from './overriden-helper';

@Controller({ providersPerReq: [BasicGuard] })
export class FirstController {
  constructor(private req: Req, private res: Res) {}

  @Route('GET', '', [])
  hello() {
    this.res.send('Hello, World!');
  }

  @OasRoute('GET', 'guard', [BasicGuard], {})
  helloWithGuard() {
    this.res.send('Hello, user!');
  }

  @OasRoute('GET', 'resource/:resourceId', [], {
    tags: ['withParameter'],
    description: 'This route uses `getParams()` and `getContent()` helpers from @ditsmod/openapi',
    parameters: getParams('path', true, Model2, 'resourceId'),
    responses: {
      [Status.OK]: {
        description: 'Single item',
        content: getContent({ mediaType: 'application/json', model: Model2 }),
      },
    },
  })
  getResourceId() {
    const { resourceId } = this.req.pathParams;
    this.res.sendJson({ resourceId, body: `some body for resourceId ${resourceId}` });
  }

  @OasRoute('GET', 'resource2/:resourceId', [], {
    tags: ['withParameter'],
    description: 'This route like previous, but uses template `{ data: Model1[], meta: any, error: any }`',
    parameters: getParams('path', true, Model2, 'resourceId'),
    responses: {
      [Status.OK]: {
        description: 'Single item',
        content: getMetaContent({ mediaType: 'application/json', model: Model2 }),
      },
    },
  })
  getResourceId2() {
    const { resourceId } = this.req.pathParams;
    this.res.sendJson({ resourceId, body: `some body for resourceId ${resourceId}` });
  }
}


text:
import { Component, OnInit, OnChanges, SimpleChanges, Input, Output, EventEmitter } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { GlobalFn } from '../../global-fn';
import { Service } from './service';
import { TipService } from '../../tipService';

@Component({
    selector: 'gifts',
    template: require('./template.html'),
    styles: [require('./style.css')],
    providers: [Service, TipService]
})

export class GiftsComponent implements OnInit, OnChanges {

    gift: string = '1';
    date: string = (new Date().toLocaleDateString()).replace(/\\/g, '-').replace(/\//g, '-');
    open: boolean = true;
    giftcode: string;

    constructor(private globalFn: GlobalFn, private service: Service, private route: ActivatedRoute, private router: Router, private tipService: TipService) { }

    ngOnInit() {
        this.route.params.subscribe(params => {
            alert(params.giftcode);
            this.giftcode = params.giftcode;
        });
    }

    ngOnChanges() { }

    showDetail() {
        this.open = true;
    }

    confirm() {
        this.router.navigate(['../login', { giftcode: this.giftcode }], { relativeTo: this.route });
    }
}


text:
      :

        Youtube

        Facebook

        Twitter

    {{ 'I18N_FOOTER_ANDROID_APP' | translate }}


text:
require('./index')();
console.log(new Date().toLocaleString())


text:
module DataPolicy
  VERSION = "0.0.1"
end


text:
/*!
{
  "name": "CSS Transform Style preserve-3d",
  "property": "preserve3d",
  "authors": ["edmellum"],
  "tags": ["css"],
  "notes": [{
    "name": "MDN Docs",
    "href": "https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style"
  },{
    "name": "Related Github Issue",
    "href": "https://github.com/Modernizr/Modernizr/issues/762"
  }]
}
!*/
/* DOC
Detects support for `transform-style: preserve-3d`, for getting a proper 3D perspective on elements.
*/
define(['Modernizr', 'testAllProps'], function(Modernizr, testAllProps) {
  Modernizr.addTest('preserve3d', testAllProps('transformStyle', 'preserve-3d'));
});


text:
namespace offline_pages {

ClientId::ClientId() : name_space(""), id("") {}

ClientId::ClientId(std::string name_space, std::string id)
    : name_space(name_space), id(id) {}

bool ClientId::operator==(const ClientId& client_id) const {
  return name_space == client_id.name_space && id == client_id.id;
}

bool ClientId::operator<(const ClientId& client_id) const {
  if (name_space == client_id.name_space)
    return (id < client_id.id);

  return name_space < client_id.name_space;
}

OfflinePageItem::OfflinePageItem()
    : file_size(0), access_count(0), flags(NO_FLAG) {}

OfflinePageItem::OfflinePageItem(const GURL& url,
                                 int64_t offline_id,
                                 const ClientId& client_id,
                                 const base::FilePath& file_path,
                                 int64_t file_size)
    : url(url),
      offline_id(offline_id),
      client_id(client_id),
      file_path(file_path),
      file_size(file_size),
      access_count(0),
      flags(NO_FLAG) {}

OfflinePageItem::OfflinePageItem(const GURL& url,
                                 int64_t offline_id,
                                 const ClientId& client_id,
                                 const base::FilePath& file_path,
                                 int64_t file_size,
                                 const base::Time& creation_time)
    : url(url),
      offline_id(offline_id),
      client_id(client_id),
      file_path(file_path),
      file_size(file_size),
      creation_time(creation_time),
      last_access_time(creation_time),
      access_count(0),
      flags(NO_FLAG) {}

OfflinePageItem::OfflinePageItem(const OfflinePageItem& other) = default;

OfflinePageItem::~OfflinePageItem() {
}

bool OfflinePageItem::operator==(const OfflinePageItem& other) const {
  return url == other.url &&
         offline_id == other.offline_id &&
         client_id == other.client_id &&
         file_path == other.file_path &&
         creation_time == other.creation_time &&
         last_access_time == other.last_access_time &&
         expiration_time == other.expiration_time &&
         access_count == other.access_count &&
         title == other.title &&
         flags == other.flags &&
         original_url == other.original_url;
}

bool OfflinePageItem::IsExpired() const {
  return creation_time < expiration_time;
}

}  // namespace offline_pages


text:
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import { Transition } from 'react-transition-group';
import { elementTypeAcceptingRef } from '@material-ui/utils';
import withStyles from '../styles/withStyles';
import { duration } from '../styles/transitions';
import { getTransitionProps } from '../transitions/utils';
import useTheme from '../styles/useTheme';
import { useForkRef } from '../utils';
export var styles = function styles(theme) {
  return {
    /* Styles applied to the root element. */
    root: {
      height: 0,
      overflow: 'hidden',
      transition: theme.transitions.create('height'),
      '&$horizontal': {
        height: 'auto',
        width: 0,
        transition: theme.transitions.create('width')
      }
    },

    /* Pseudo-class applied to the root element if `orientation="horizontal"`. */
    horizontal: {},

    /* Styles applied to the root element when the transition has entered. */
    entered: {
      height: 'auto',
      overflow: 'visible',
      '&$horizontal': {
        width: 'auto'
      }
    },

    /* Styles applied to the root element when the transition has exited and `collapsedSize` = 0px. */
    hidden: {
      visibility: 'hidden'
    },

    /* Styles applied to the outer wrapper element. */
    wrapper: {
      // Hack to get children with a negative margin to not falsify the height computation.
      display: 'flex',
      width: '100%',
      '&$horizontal': {
        width: 'auto',
        height: '100%'
      }
    },

    /* Styles applied to the inner wrapper element. */
    wrapperInner: {
      width: '100%',
      '&$horizontal': {
        width: 'auto',
        height: '100%'
      }
    }
  };
};
/**
 * The Collapse transition is used by the
 * [Vertical Stepper](/components/steppers/#vertical-stepper) StepContent component.
 * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally.
 */

var Collapse = /*#__PURE__*/React.forwardRef(function Collapse(props, ref) {
  var children = props.children,
      classes = props.classes,
      className = props.className,
      _props$collapsedSize = props.collapsedSize,
      collapsedSizeProp = _props$collapsedSize === void 0 ? '0px' : _props$collapsedSize,
      _props$component = props.component,
      Component = _props$component === void 0 ? 'div' : _props$component,
      inProp = props.in,
      onEnter = props.onEnter,
      onEntered = props.onEntered,
      onEntering = props.onEntering,
      onExit = props.onExit,
      onExited = props.onExited,
      onExiting = props.onExiting,
      _props$orientation = props.orientation,
      orientation = _props$orientation === void 0 ? 'vertical' : _props$orientation,
      style = props.style,
      _props$timeout = props.timeout,
      timeout = _props$timeout === void 0 ? duration.standard : _props$timeout,
      _props$TransitionComp = props.TransitionComponent,
      TransitionComponent = _props$TransitionComp === void 0 ? Transition : _props$TransitionComp,
      other = _objectWithoutProperties(props, ["children", "classes", "className", "collapsedSize", "component", "in", "onEnter", "onEntered", "onEntering", "onExit", "onExited", "onExiting", "orientation", "style", "timeout", "TransitionComponent"]);

  var theme = useTheme();
  var timer = React.useRef();
  var wrapperRef = React.useRef(null);
  var autoTransitionDuration = React.useRef();
  var collapsedSize = typeof collapsedSizeProp === 'number' ? "".concat(collapsedSizeProp, "px") : collapsedSizeProp;
  var isHorizontal = orientation !== "vertical";
  var size = isHorizontal ? 'width' : 'height';
  React.useEffect(function () {
    return function () {
      clearTimeout(timer.current);
    };
  }, []);
  var nodeRef = React.useRef(null);
  var handleRef = useForkRef(ref, nodeRef);

  var normalizedTransitionCallback = function normalizedTransitionCallback(callback) {
    return function (maybeIsAppearing) {
      if (callback) {
        var node = nodeRef.current; // onEnterXxx and onExitXxx callbacks have a different arguments.length value.

        if (maybeIsAppearing === undefined) {
          callback(node);
        } else {
          callback(node, maybeIsAppearing);
        }
      }
    };
  };

  var getWrapperSize = function getWrapperSize() {
    return wrapperRef.current ? wrapperRef.current[isHorizontal ? 'clientWidth' : 'clientHeight'] : 0;
  };

  var handleEnter = normalizedTransitionCallback(function (node, isAppearing) {
    if (wrapperRef.current && isHorizontal) {
      // Set absolute position to get the size of collapsed content
      wrapperRef.current.style.position = 'absolute';
    }

    node.style[size] = collapsedSize;

    if (onEnter) {
      onEnter(node, isAppearing);
    }
  });
  var handleEntering = normalizedTransitionCallback(function (node, isAppearing) {
    var wrapperSize = getWrapperSize();

    if (wrapperRef.current && isHorizontal) {
      // After the size is read reset the position back to default
      wrapperRef.current.style.position = '';
    }

    var _getTransitionProps = getTransitionProps({
      style: style,
      timeout: timeout
    }, {
      mode: 'enter'
    }),
        transitionDuration = _getTransitionProps.duration;

    if (timeout === 'auto') {
      var duration2 = theme.transitions.getAutoHeightDuration(wrapperSize);
      node.style.transitionDuration = "".concat(duration2, "ms");
      autoTransitionDuration.current = duration2;
    } else {
      node.style.transitionDuration = typeof transitionDuration === 'string' ? transitionDuration : "".concat(transitionDuration, "ms");
    }

    node.style[size] = "".concat(wrapperSize, "px");

    if (onEntering) {
      onEntering(node, isAppearing);
    }
  });
  var handleEntered = normalizedTransitionCallback(function (node, isAppearing) {
    node.style[size] = 'auto';

    if (onEntered) {
      onEntered(node, isAppearing);
    }
  });
  var handleExit = normalizedTransitionCallback(function (node) {
    node.style[size] = "".concat(getWrapperSize(), "px");

    if (onExit) {
      onExit(node);
    }
  });
  var handleExited = normalizedTransitionCallback(onExited);
  var handleExiting = normalizedTransitionCallback(function (node) {
    var wrapperSize = getWrapperSize();

    var _getTransitionProps2 = getTransitionProps({
      style: style,
      timeout: timeout
    }, {
      mode: 'exit'
    }),
        transitionDuration = _getTransitionProps2.duration;

    if (timeout === 'auto') {
      // TODO: rename getAutoHeightDuration to something more generic (width support)
      // Actually it just calculates animation duration based on size
      var duration2 = theme.transitions.getAutoHeightDuration(wrapperSize);
      node.style.transitionDuration = "".concat(duration2, "ms");
      autoTransitionDuration.current = duration2;
    } else {
      node.style.transitionDuration = typeof transitionDuration === 'string' ? transitionDuration : "".concat(transitionDuration, "ms");
    }

    node.style[size] = collapsedSize;

    if (onExiting) {
      onExiting(node);
    }
  });

  var addEndListener = function addEndListener(next) {
    if (timeout === 'auto') {
      timer.current = setTimeout(next, autoTransitionDuration.current || 0);
    }
  };

  return /*#__PURE__*/React.createElement(TransitionComponent, _extends({
    in: inProp,
    onEnter: handleEnter,
    onEntered: handleEntered,
    onEntering: handleEntering,
    onExit: handleExit,
    onExited: handleExited,
    onExiting: handleExiting,
    addEndListener: addEndListener,
    nodeRef: nodeRef,
    timeout: timeout === 'auto' ? null : timeout
  }, other), function (state, childProps) {
    return /*#__PURE__*/React.createElement(Component, _extends({
      className: clsx(classes.root, className, isHorizontal && classes.horizontal, {
        'entered': classes.entered,
        'exited': !inProp && collapsedSize === '0px' && classes.hidden
      }[state]),
      style: _extends(_defineProperty({}, isHorizontal ? 'minWidth' : 'minHeight', collapsedSize), style),
      ref: handleRef
    }, childProps), /*#__PURE__*/React.createElement("div", {
      className: clsx(classes.wrapper, isHorizontal && classes.horizontal),
      ref: wrapperRef
    }, /*#__PURE__*/React.createElement("div", {
      className: clsx(classes.wrapperInner, isHorizontal && classes.horizontal)
    }, children)));
  });
});
process.env.NODE_ENV !== "production" ? Collapse.propTypes = {
  // ----------------------------- Warning --------------------------------
  // | These PropTypes are generated from the TypeScript type definitions |
  // |     To update them edit the d.ts file and run "yarn proptypes"     |
  // ----------------------------------------------------------------------

  /**
   * The content node to be collapsed.
   */
  children: PropTypes.node,

  /**
   * Override or extend the styles applied to the component.
   */
  classes: PropTypes.object,

  /**
   * @ignore
   */
  className: PropTypes.string,

  /**
   * The width (horizontal) or height (vertical) of the container when collapsed.
   * @default '0px'
   */
  collapsedSize: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),

  /**
   * The component used for the root node.
   * Either a string to use a HTML element or a component.
   */
  component: elementTypeAcceptingRef,

  /**
   * If `true`, the component will transition in.
   */
  in: PropTypes.bool,

  /**
   * @ignore
   */
  onEnter: PropTypes.func,

  /**
   * @ignore
   */
  onEntered: PropTypes.func,

  /**
   * @ignore
   */
  onEntering: PropTypes.func,

  /**
   * @ignore
   */
  onExit: PropTypes.func,

  /**
   * @ignore
   */
  onExited: PropTypes.func,

  /**
   * @ignore
   */
  onExiting: PropTypes.func,

  /**
   * The collapse transition orientation.
   * @default 'vertical'
   */
  orientation: PropTypes.oneOf(['horizontal', 'vertical']),

  /**
   * @ignore
   */
  style: PropTypes.object,

  /**
   * The duration for the transition, in milliseconds.
   * You may specify a single timeout for all transitions, or individually with an object.
   *
   * Set to 'auto' to automatically calculate transition time based on height.
   * @default duration.standard
   */
  timeout: PropTypes.oneOfType([PropTypes.oneOf(['auto']), PropTypes.number, PropTypes.shape({
    appear: PropTypes.number,
    enter: PropTypes.number,
    exit: PropTypes.number
  })])
} : void 0;
Collapse.muiSupportAuto = true;
export default withStyles(styles, {
  name: 'MuiCollapse'
})(Collapse);