{"dataset": "schnappinger", "name": "Schnappinger", "kind": "human-rated", "samples": [{"task_id": "Schnappinger/aoi/artofillusion.animation.ActorEditorWindow", "source": "/* Copyright (C) 2002-2006 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport artofillusion.*;\nimport artofillusion.animation.Actor.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\n\nimport javax.swing.table.*;\nimport javax.swing.*;\nimport java.awt.*;\n\n/** The ActorEditorWindow class represents the window for editing Actor objects. */\n\npublic class ActorEditorWindow extends BDialog\n{\n  private Actor theObject, oldObject;\n  private ObjectInfo objInfo;\n  private EditingWindow theWindow;\n  private BList gestureList;\n  private BTable currentPoseTable;\n  private CurrentPoseTableModel tableModel;\n  private BButton addButton, removeButton, saveButton, extractButton;\n  private BButton editButton, renameButton, copyButton, deleteButton;\n  private BButton okButton, cancelButton;\n  private ActionProcessor processor;\n  private ActorKeyframe currentPose, key;\n  private ObjectPreviewCanvas preview;\n  private Runnable onClose;\n  private boolean canModifyGestures;\n\n  /** Display a window for editing a pose of an Actor.  If key is null, the\n      Actor's current pose will be edited.  Otherwise, the specified keyframe\n      will be edited. */\n\n  public ActorEditorWindow(EditingWindow parent, ObjectInfo info, Actor obj, ActorKeyframe key, Runnable cb)\n  {\n    super(parent.getFrame(), (key == null ? info.getName() : Translate.text(\"editKeyframeFor\", info.getName())), false);\n    objInfo = info;\n    oldObject = obj;\n    theObject = (Actor) obj.duplicate();\n    theWindow = parent;\n    this.key = key;\n    if (key != null)\n      theObject.applyPoseKeyframe(key);\n    currentPose = (ActorKeyframe) theObject.getPoseKeyframe();\n    onClose = cb;\n    processor = new ActionProcessor();\n    canModifyGestures = (info.getObject() == obj);\n    for (int i = currentPose.id.length-1; i >= 0; i--)\n    {\n      int which = theObject.findPoseIndex(currentPose.id[i]);\n      if (which == -1)\n        currentPose.deleteGesture(i);\n    }\n\n    // Layout the components in the window.\n\n    FormContainer content = new FormContainer(new double [] {0, 0, 1}, new double [] {1, 0, 0});\n    setContent(content);\n    content.setDefaultLayout(new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.BOTH, null, null));\n\n    // The list of gestures.\n\n    content.add(UIUtilities.createScrollingList(gestureList = new BList()), 0, 0, new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.BOTH));\n    gestureList.setPreferredVisibleRows(10);\n    for (int i = 0; i < theObject.gestureName.length; i++)\n      gestureList.add(theObject.gestureName[i]);\n    gestureList.setMultipleSelectionEnabled(false);\n    gestureList.addEventLink(SelectionChangedEvent.class, this, \"updateComponents\");\n    gestureList.addEventLink(MouseClickedEvent.class, new Object() {\n      void processEvent(MouseClickedEvent ev)\n      {\n        if (ev.getClickCount() == 2)\n          doEdit();\n      }\n    });\n\n    // The buttons for editing them.\n\n    FormContainer leftPanel = new FormContainer(new double [] {1}, new double [] {0, 0, 0, 0, 0, 1, 0, 0});\n    content.add(leftPanel, 0, 1);\n    leftPanel.setDefaultLayout(new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.HORIZONTAL, new Insets(2, 2, 2, 2), null));\n    leftPanel.add(editButton = Translate.button(\"edit\", this, \"doEdit\"), 0, 1);\n    leftPanel.add(renameButton = Translate.button(\"rename\", this, \"doRename\"), 0, 2);\n    leftPanel.add(copyButton = Translate.button(\"duplicate\", this, \"doDuplicate\"), 0, 3);\n    leftPanel.add(deleteButton = Translate.button(\"delete\", this, \"doDelete\"), 0, 4);\n    leftPanel.add(saveButton = Translate.button(\"save\", \"...\", this, \"doSave\"), 0, 6);\n    leftPanel.add(extractButton = Translate.button(\"extract\", \"...\", this, \"doExtract\"), 0, 7);\n\n    // The Add and Remove buttons.\n\n    ColumnContainer addRemovePanel = new ColumnContainer();\n    content.add(addRemovePanel, 1, 0);\n    addRemovePanel.setDefaultLayout(new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.HORIZONTAL, new Insets(2, 2, 2, 2), null));\n    addRemovePanel.add(addButton = Translate.button(\"add\", \">>\", this, \"doAdd\"));\n    addRemovePanel.add(removeButton = new BButton(\"<< \"+Translate.text(\"button.remove\")));\n    removeButton.addEventLink(CommandEvent.class, this, \"doRemove\");\n\n    // The current pose.\n\n    tableModel = new CurrentPoseTableModel();\n    currentPoseTable = new BTable(tableModel);\n    currentPoseTable.setMultipleSelectionEnabled(false);\n    currentPoseTable.addEventLink(SelectionChangedEvent.class, this, \"updateComponents\");\n    TableColumn column = ((JTable) currentPoseTable.getComponent()).getColumnModel().getColumn(1);\n    column.setCellEditor(new ValueEditor());\n    ValueRenderer renderer = new ValueRenderer();\n    column.setCellRenderer(renderer);\n    column.setMinWidth(renderer.getPreferredSize().width);\n    column.setMaxWidth(renderer.getPreferredSize().width);\n    ((JTable) currentPoseTable.getComponent()).setRowHeight(renderer.getPreferredSize().height);\n    BScrollPane tableScrollPane = new BScrollPane(currentPoseTable, BScrollPane.SCROLLBAR_NEVER, BScrollPane.SCROLLBAR_ALWAYS);\n    tableScrollPane.setPreferredViewSize(new Dimension(250, 5*renderer.getPreferredSize().height));\n    content.add(BOutline.createBevelBorder(tableScrollPane, false), 2, 0);\n\n    // The object previewer.\n\n    content.add(preview = new ObjectPreviewCanvas(new ObjectInfo(theObject, new CoordinateSystem(), \"\")), 1, 1, 2, 1,\n        new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.BOTH, null, null));\n    preview.setPreferredSize(new Dimension(300, 300));\n\n    // The buttons at the bottom.\n\n    RowContainer bottomPanel = new RowContainer();\n    content.add(bottomPanel, 0, 2, 3, 1, new LayoutInfo());\n    bottomPanel.add(okButton = Translate.button(\"ok\", this, \"doOk\"));\n    bottomPanel.add(cancelButton = Translate.button(\"cancel\", this, \"dispose\"));\n    pack();\n    UIUtilities.centerDialog(this, parent.getFrame());\n    updateComponents();\n    setVisible(true);\n  }\n\n  /** Add a new gesture to the current pose. */\n\n  private void doAdd()\n  {\n    currentPose.addGesture(theObject.gestureID[gestureList.getSelectedIndex()], 1.0);\n    tableModel.fireTableDataChanged();\n    updateComponents();\n    updateDisplay();\n  }\n\n  /** Remove a gesture from the current pose. */\n\n  private void doRemove()\n  {\n    currentPose.deleteGesture(currentPoseTable.getSelectedRows()[0]);\n    tableModel.fireTableDataChanged();\n    updateComponents();\n    updateDisplay();\n  }\n\n  /** Save the current pose as a new gesture. */\n\n  private void doSave()\n  {\n    BStandardDialog dlg = new BStandardDialog(\"\", Translate.text(\"savePoseAsGesture\"), BStandardDialog.PLAIN);\n    String name = dlg.showInputDialog(this, null, \"New Gesture\");\n    if (name == null)\n      return;\n    theObject.addGesture((Gesture) theObject.getWrappedObject().getPoseKeyframe(), name);\n    gestureList.add(name);\n    gestureList.setSelected(gestureList.getItemCount()-1, true);\n    updateComponents();\n  }\n\n  /** Save the current pose as a new object. */\n\n  private void doExtract()\n  {\n    BStandardDialog dlg = new BStandardDialog(\"\", Translate.text(\"savePoseAsObject\"), BStandardDialog.PLAIN);\n    String name = dlg.showInputDialog(this, null, \"Extracted Pose\");\n    if (name == null)\n      return;\n    ObjectInfo info = new ObjectInfo(theObject.getWrappedObject().duplicate(),\n      new CoordinateSystem(new Vec3(), Vec3.vz(), Vec3.vy()), name);\n    info.addTrack(new PositionTrack(info), 0);\n    info.addTrack(new RotationTrack(info), 1);\n    if (theWindow instanceof LayoutWindow)\n      ((LayoutWindow) theWindow).addObject(info, null);\n    else\n      theWindow.getScene().addObject(info, null);\n    theWindow.updateImage();\n  }\n\n  /** Edit the currently selected gesture. */\n\n  private void doEdit()\n  {\n    if (canModifyGestures)\n      editGesture(gestureList.getSelectedIndex());\n  }\n\n  /** Rename a gesture. */\n\n  private void doRename()\n  {\n    int which = gestureList.getSelectedIndex();\n    BStandardDialog dlg = new BStandardDialog(\"\", Translate.text(\"enterNewNameForGesture\"), BStandardDialog.PLAIN);\n    String name = dlg.showInputDialog(this, null, theObject.gestureName[which]);\n    if (name == null)\n      return;\n    theObject.gestureName[which] = name;\n    gestureList.replace(which, theObject.gestureName[which]);\n    gestureList.setSelected(which, true);\n  }\n\n  /** Duplicate a gesture. */\n\n  private void doDuplicate()\n  {\n    int which = gestureList.getSelectedIndex();\n    BStandardDialog dlg = new BStandardDialog(\"\", Translate.text(\"enterNameForNewGesture\"), BStandardDialog.PLAIN);\n    String name = dlg.showInputDialog(this, null, \"Copy of \"+theObject.gestureName[which]);\n    if (name == null)\n      return;\n    theObject.addGesture((Gesture) theObject.gesture[which].duplicate(theObject.getWrappedObject()), name);\n    gestureList.add(name);\n    gestureList.setSelected(gestureList.getItemCount()-1, true);\n    updateComponents();\n    editGesture(gestureList.getItemCount()-1);\n  }\n\n  /** Delete a gesture. */\n\n  private void doDelete()\n  {\n    int which = gestureList.getSelectedIndex();\n    String options[] = new String [] {Translate.text(\"Yes\"), Translate.text(\"No\")};\n    int choice = new BStandardDialog(\"\", Translate.text(\"deleteGesture\", theObject.gestureName[which]), BStandardDialog.QUESTION).showOptionDialog(this, options, options[0]);\n    if (choice== 1)\n      return;\n    for (int i = 0; i < currentPose.id.length; i++)\n      if (currentPose.id[i] == theObject.gestureID[which])\n      {\n        currentPose.deleteGesture(i);\n        i--;\n        updateDisplay();\n      }\n    theObject.deleteGestureWithID(theObject.gestureID[which]);\n    gestureList.remove(which);\n    tableModel.fireTableDataChanged();\n    updateComponents();\n  }\n\n  /** Save the edits. */\n\n  private void doOk()\n  {\n    oldObject.copyObject(theObject);\n    if (key != null)\n    {\n      key.copy(currentPose);\n      theWindow.getScene().applyTracksToObject(objInfo);\n      theWindow.updateImage();\n    }\n    dispose();\n    if (onClose != null)\n      onClose.run();\n  }\n\n  /** Display a window to let the user edit a gesture. */\n\n  private void editGesture(int which)\n  {\n    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));\n    Object3D editObj = theObject.getWrappedObject().duplicate();\n    editObj.applyPoseKeyframe(theObject.gesture[which]);\n    EditCallback cb = new EditCallback(editObj, theObject.gestureID[which]);\n    ObjectInfo info = objInfo.duplicate(editObj);\n    info.setName(theObject.gestureName[which]);\n    editObj.editGesture(theWindow, info, cb, objInfo);\n    setCursor(Cursor.getDefaultCursor());\n  }\n\n  /** Update the status of the buttons and weight field. */\n\n  private void updateComponents()\n  {\n    int i, id, selected = gestureList.getSelectedIndex();\n\n    if (selected == -1)\n    {\n      addButton.setEnabled(false);\n      editButton.setEnabled(false);\n      renameButton.setEnabled(false);\n      copyButton.setEnabled(false);\n      deleteButton.setEnabled(false);\n    }\n    else\n    {\n      editButton.setEnabled(canModifyGestures);\n      renameButton.setEnabled(canModifyGestures && selected > 0);\n      copyButton.setEnabled(canModifyGestures);\n      deleteButton.setEnabled(canModifyGestures && selected > 0);\n      id = theObject.gestureID[gestureList.getSelectedIndex()];\n      for (i = 0; i < currentPose.id.length && currentPose.id[i] != id; i++);\n      addButton.setEnabled(selected > 0 && i == currentPose.id.length);\n    }\n    int rows[] = currentPoseTable.getSelectedRows();\n    removeButton.setEnabled(rows.length > 0);\n    saveButton.setEnabled(canModifyGestures);\n  }\n\n  /** Reapply the current pose and update the preview. */\n\n  private void updateDisplay()\n  {\n    theObject.applyPoseKeyframe(currentPose);\n    preview.objectChanged();\n    preview.repaint();\n  }\n\n  /** This is an inner class which is called when a keyframe has been edited. */\n\n  private class EditCallback implements Runnable\n  {\n    public Object3D editObject;\n    public int editID;\n\n    public EditCallback(Object3D obj, int id)\n    {\n      editObject = obj;\n      editID = id;\n    }\n\n    public void run()\n    {\n      int which = theObject.findPoseIndex(editID);\n      theObject.getWrappedObject().copyObject(editObject);\n      theObject.gesture[which] = (Gesture) theObject.getWrappedObject().getPoseKeyframe();\n\n      // Update the skeletons for all other poses, in case a joint has been added or deleted.\n\n      Skeleton s = theObject.gesture[which].getSkeleton();\n      if (s != null)\n        for (int i = 0; i < theObject.gesture.length; i++)\n        {\n          if (i == which)\n            continue;\n          Skeleton olds = theObject.gesture[i].getSkeleton();\n          Skeleton news = s.duplicate();\n          Joint joint[] = news.getJoints();\n          for (int j = 0; j < joint.length; j++)\n          {\n            Joint j2 = olds.getJoint(joint[j].id);\n            if (j2 != null)\n              joint[j].copy(j2);\n          }\n          theObject.gesture[i].setSkeleton(news);\n        }\n      updateDisplay();\n    }\n  }\n\n  /**\n   * This is the model for the table describing the current pose.\n   */\n\n  private class CurrentPoseTableModel extends AbstractTableModel\n  {\n    public int getRowCount()\n    {\n      return currentPose.getNumGestures();\n    }\n\n    public int getColumnCount()\n    {\n      return 2;\n    }\n\n    public Object getValueAt(int rowIndex, int columnIndex)\n    {\n      if (columnIndex == 0)\n        return theObject.gestureName[theObject.findPoseIndex(currentPose.getGestureID(rowIndex))];\n      return new Double(currentPose.getGestureWeight(rowIndex));\n    }\n\n    public String getColumnName(int column)\n    {\n      return (Translate.text(column == 0 ? \"Gesture\" : \"Weight\"));\n    }\n\n    public boolean isCellEditable(int rowIndex, int columnIndex)\n    {\n      return (columnIndex == 1);\n    }\n  }\n\n  /**\n   * This is the renderer for values in the Weight column of the table.\n   */\n\n  private class ValueRenderer extends BuoyComponent implements TableCellRenderer\n  {\n    private ValueSelector selector;\n\n    public ValueRenderer()\n    {\n      super(new ValueSelector(0.0, -Double.MAX_VALUE, Double.MAX_VALUE, 0.005));\n      selector = (ValueSelector) getWidget();\n    }\n\n    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)\n    {\n      selector.setValue(((Double) value).doubleValue());\n      selector.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());\n      return this;\n    }\n\n    public void validate()\n    {\n      super.validate();\n      selector.layoutChildren();\n    }\n  }\n\n  /**\n   * This is the editor for values in the Weight column of the table.\n   */\n\n  private class ValueEditor extends AbstractCellEditor implements TableCellEditor\n  {\n    private ValueSelector selector;\n    private BuoyComponent component;\n    private int currentRow;\n\n    public ValueEditor()\n    {\n      selector = new ValueSelector(0.0, -Double.MAX_VALUE, Double.MAX_VALUE, 0.005);\n      component = new BuoyComponent(selector) {\n        public void validate()\n        {\n          super.validate();\n          selector.layoutChildren();\n        }\n      };\n      selector.setBackground(((JTable) currentPoseTable.getComponent()).getSelectionBackground());\n      selector.addEventLink(ValueChangedEvent.class, new Object() {\n        void processEvent()\n        {\n          processor.addEvent(new Runnable() {\n            public void run()\n            {\n              currentPose.weight[currentRow] = selector.getValue();\n              updateDisplay();\n            }\n          });\n        }\n      });\n    }\n\n    public Object getCellEditorValue()\n    {\n      return new Double(selector.getValue());\n    }\n\n    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)\n    {\n      selector.setValue(((Double) value).doubleValue());\n      currentRow = row;\n      return component;\n    }\n  }\n}\n", "human_rating": 2.8482677868907, "metadata": {"project": "aoi", "class": "artofillusion.animation.ActorEditorWindow", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/ActorEditorWindow.java", "label_probabilities": {"readability": [4.38897e-07, 0.848266, 0.151734, 3.13027e-08], "understandability": [4.80515e-06, 0.165522, 0.834105, 0.000368564], "complexity": [0.0384024, 0.242482, 0.719054, 6.09142e-05], "modularization": [0.000933063, 0.754034, 0.245033, 2.1247e-08], "overall": [2.81463e-08, 0.237515, 0.762485, 2.48766e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.AnimationPreviewer", "source": "/* Copyright (C) 2001-2012 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport artofillusion.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport artofillusion.view.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.awt.image.*;\nimport java.io.ByteArrayInputStream;\nimport java.io.ByteArrayOutputStream;\nimport java.io.IOException;\nimport java.text.*;\n\nimport javax.imageio.ImageIO;\n\n/** This class generates a wireframe preview of an animation. */\n\npublic class AnimationPreviewer implements Runnable\n{\n  private LayoutWindow window;\n  private double originalTime;\n  private ValueField widthField, heightField, startField, endField, fpsField;\n  private BLabel timeLabel, frameLabel;\n  private Scene theScene;\n  private ObjectInfo sceneCamera;\n  private BComboBox camChoice, modeChoice;\n  private SceneViewer canvas;\n  private Thread previewThread;\n  private BDialog display;\n  private byte imageData[][];\n  private NumberFormat format;\n  \n  static int currentCamera = 0, width = 320, height = 240, fps = 15, mode = 2;\n  static double startTime = 0.0, endTime = 1.0;\n\n  public AnimationPreviewer(LayoutWindow parent)\n  {\n    window = parent;\n    theScene = window.getScene();\n\n    // Find all the cameras in the scene.\n    \n    ObjectInfo obj;\n    int i, count;\n    \n    for (i = 0, count = 0; i < theScene.getNumObjects(); i++)\n    {\n      obj = theScene.getObject(i);\n      if (obj.getObject() instanceof SceneCamera)\n        count++;\n    }\n    if (count == 0)\n    {\n      new BStandardDialog(\"\", Translate.text(\"noCameraError\"), BStandardDialog.INFORMATION).showMessageDialog(window);\n      return;\n    }\n    if (count <= currentCamera)\n      currentCamera = 0;\n    ObjectInfo cameras[] = new ObjectInfo [count];\n    for (i = 0, count = 0; i < theScene.getNumObjects(); i++)\n    {\n      obj = theScene.getObject(i);\n      if (obj.getObject() instanceof SceneCamera)\n        cameras[count++] = obj;\n    }\n\n    // Create the components.\n\n    camChoice = new BComboBox();\n    for (i = 0; i < cameras.length; i++)\n      camChoice.add(cameras[i].getName());\n    camChoice.setSelectedIndex(currentCamera);\n    modeChoice = new BComboBox(new Object [] {\n       Translate.text(\"menu.wireframeDisplay\"), \n       Translate.text(\"menu.shadedDisplay\"), \n       Translate.text(\"menu.smoothDisplay\"), \n       Translate.text(\"menu.texturedDisplay\"),\n        Translate.text(\"menu.transparentDisplay\")\n    });\n    modeChoice.setSelectedIndex(mode);\n    widthField = new ValueField((double) width, ValueField.POSITIVE+ValueField.INTEGER);\n    heightField = new ValueField((double) height, ValueField.POSITIVE+ValueField.INTEGER);\n    startField = new ValueField(startTime, ValueField.NONE);\n    endField = new ValueField(endTime, ValueField.NONE);\n    fpsField = new ValueField(fps, ValueField.POSITIVE+ValueField.INTEGER);\n    \n    // Display a dialog with the various options.\n    \n    ComponentsDialog dlg = new ComponentsDialog(window, Translate.text(\"renderPreview\"),\n      new Widget [] {camChoice, modeChoice, startField, endField, widthField, heightField, fpsField},\n      new String [] {Translate.text(\"Camera\"), Translate.text(\"menu.displayMode\"), Translate.text(\"StartTime\"), \n      Translate.text(\"EndTime\"), Translate.text(\"Width\"), Translate.text(\"Height\"),\n      Translate.text(\"FramesPerSec\")});\n    if (!dlg.clickedOk())\n      return;\n    currentCamera = camChoice.getSelectedIndex();\n    sceneCamera = cameras[currentCamera];\n    mode = modeChoice.getSelectedIndex();\n    width = (int) widthField.getValue();\n    height = (int) heightField.getValue();\n    startTime = startField.getValue();\n    endTime = endField.getValue();\n    fps = (int) fpsField.getValue();\n    originalTime = theScene.getTime();\n    \n    // Display a dialog to show the preview.\n    \n    display = new BDialog(window, Translate.text(\"Preview\"), true);\n    format = NumberFormat.getNumberInstance();\n    format.setMaximumFractionDigits(3);\n    ColumnContainer content = new ColumnContainer();\n    display.setContent(BOutline.createEmptyBorder(content, UIUtilities.getStandardDialogInsets()));\n    content.setDefaultLayout(new LayoutInfo(LayoutInfo.WEST, LayoutInfo.HORIZONTAL, new Insets(2, 0, 2, 0), null));\n    content.add(timeLabel = new BLabel());\n    content.add(frameLabel = new BLabel());\n    setLabels(0.0, 0);\n    content.add(canvas = new SceneViewer(theScene, new RowContainer(), parent, true));\n    canvas.setPreferredSize(new Dimension(AnimationPreviewer.width, AnimationPreviewer.height));\n    canvas.setRenderMode(mode);\n    canvas.setBoundCamera(sceneCamera);\n    canvas.setPerspective(true);\n    canvas.setTool(new EditingTool(parent) {\n      public boolean hilightSelection()\n      {\n        return false;\n      }\n    });\n    content.add(Translate.button(\"close\", this, \"doClose\"), new LayoutInfo());\n    display.pack();\n    UIUtilities.centerDialog(display, window);\n    display.setResizable(false);\n    previewThread = new Thread(this);\n    previewThread.setPriority(Thread.NORM_PRIORITY-1);\n    previewThread.start();\n    display.setVisible(true);\n  }\n  \n  /** Generate and display all of the frames in a loop. */\n\n  public void run()\n  {\n    int totalFrames = (int) Math.ceil((endTime-startTime)*fps);\n    if (totalFrames <= 0)\n      totalFrames = 1;\n    imageData = new byte [totalFrames][];\n    Camera cam = canvas.getCamera();\n    long lastUpdate = 0L, ms, delay = 1000/fps;\n    \n    // In the first loop, we render all of the images.\n    \n    try\n    {\n      for (int i = 0; i < totalFrames; i++)\n      {\n        final double time = startTime+i/(double) fps;\n        theScene.setTime(time);\n        SceneCamera sc = (SceneCamera) sceneCamera.getObject();\n        cam.setCameraCoordinates(sceneCamera.getCoords().duplicate());\n        cam.setScreenTransform(sc.getScreenTransform(width, height), width, height);\n        final int frame = i;\n        try\n        {\n          EventQueue.invokeAndWait(new Runnable() {\n            public void run()\n            {\n              setLabels(time, frame);\n              SoftwareCanvasDrawer drawer = (SoftwareCanvasDrawer) canvas.getCanvasDrawer();\n              Graphics2D canvasGraphics = (Graphics2D) canvas.getComponent().getGraphics();\n              drawer.paint(new RepaintEvent(canvas, canvasGraphics));\n              canvasGraphics.dispose();\n              imageData[frame] = recordImage(drawer.getImage());\n            }\n          });\n        }\n        catch (Exception ex)\n        {\n          return;\n        }\n        if (Thread.currentThread().isInterrupted())\n          return;\n        ms = System.currentTimeMillis();\n        if (ms < lastUpdate+delay)\n        {\n          try\n          {\n            Thread.sleep(lastUpdate+delay-ms);\n          }\n          catch (InterruptedException ex)\n          {\n            return;\n          }\n        }\n        lastUpdate = System.currentTimeMillis();\n      }\n      \n      // In later loops, we simply retrieve the data from the array.\n      \n      while (!Thread.currentThread().isInterrupted())\n      {\n        for (int i = 0; i < totalFrames; i++)\n        {\n          final double time = startTime+i/(double) fps;\n          final int frame = i;\n          final Image image = retrieveImage(imageData[i]);\n          try\n          {\n            EventQueue.invokeAndWait(new Runnable() {\n              public void run()\n              {\n                setLabels(time, frame);\n                Graphics2D canvasGraphics = (Graphics2D) canvas.getComponent().getGraphics();\n                canvasGraphics.drawImage(image, 0, 0, null);\n                canvasGraphics.dispose();\n              }\n            });\n          }\n          catch (Exception ex)\n          {\n            return;\n          }\n          ms = System.currentTimeMillis();\n          if (ms < lastUpdate+delay)\n          {\n            try\n            {\n              Thread.sleep(lastUpdate+delay-ms);\n            }\n            catch (InterruptedException ex)\n            {\n              return;\n            }\n          }\n          lastUpdate = System.currentTimeMillis();\n        }\n      }\n    }\n    catch (IOException ex)\n    {\n      ex.printStackTrace();\n    }\n  }\n  \n  /** Close the window. */\n  \n  private void doClose()\n  {\n    previewThread.interrupt();\n    try\n    {\n      previewThread.join();\n    }\n    catch (InterruptedException ex)\n    {\n    }\n    theScene.setTime(originalTime);\n    display.dispose();\n  }\n\n  /** Set the labels for the current time and frame. */\n  \n  private void setLabels(double time, int frame)\n  {\n    timeLabel.setText(Translate.text(\"Time\")+\": \"+format.format(time));\n    frameLabel.setText(Translate.text(\"Frame\")+\": \"+(frame+1));\n  }\n  \n  /** Record the bitmap for an image. */\n  \n  private byte [] recordImage(BufferedImage image)\n  {\n    try\n    {\n      ByteArrayOutputStream baos = new ByteArrayOutputStream();\n      ImageIO.write(image, \"png\", baos);\n      return baos.toByteArray();\n    }\n    catch (IOException ex)\n    {\n      return null;\n    }\n  }\n\n  /** Copy a bitmap into the image. */\n  \n  private Image retrieveImage(byte bytes[]) throws IOException\n  {\n    return ImageIO.read(new ByteArrayInputStream(bytes));\n  }\n}", "human_rating": 2.0315201899999997, "metadata": {"project": "aoi", "class": "artofillusion.animation.AnimationPreviewer", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/AnimationPreviewer.java", "label_probabilities": {"readability": [2.28e-18, 0.0385996, 0.954321, 0.00707939], "understandability": [1.808e-11, 0.0220584, 0.972453, 0.0054887], "complexity": [1.11763e-05, 0.856708, 0.143281, 4.3631e-10], "modularization": [0.0169976, 0.983002, 1e-20, 0.0], "overall": [0.0, 2.55598e-05, 0.33632, 0.663654]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.distortion.CustomDistortion", "source": "/* Copyright (C) 2002-2012 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation.distortion;\n\nimport artofillusion.math.*;\nimport artofillusion.procedural.*;\nimport artofillusion.object.*;\n\n/** This is a distortion which uses a procedure to distort an object. */\n\npublic class CustomDistortion extends Distortion\n{\n  private Procedure proc;\n  private int procVersion;\n  PointInfo point;\n  private double weight;\n  private Mat4 preTransform, postTransform;\n\n  public CustomDistortion(Procedure proc, int procVersion, PointInfo point, double weight, Mat4 preTransform, Mat4 postTransform)\n  {\n    this.proc = proc;\n    this.procVersion = procVersion;\n    this.point = point;\n    this.weight = weight;\n    this.preTransform = preTransform;\n    this.postTransform = postTransform;\n  }\n\n  /** Determine whether this distortion is identical to another one. */\n  \n  public boolean isIdenticalTo(Distortion d)\n  {\n    if (!(d instanceof CustomDistortion))\n      return false;\n    CustomDistortion s = (CustomDistortion) d;\n    if (previous != null && !previous.isIdenticalTo(s.previous))\n      return false;\n    if (previous == null && s.previous != null)\n      return false;\n    if (weight != s.weight || proc != s.proc || procVersion != s.procVersion)\n      return false;\n    if (point.t != s.point.t)\n      return false;\n    if (point.param == null)\n      {\n        if (s.point.param != null)\n          return false;\n      }\n    else\n      {\n        if (s.point.param == null || point.param.length != s.point.param.length)\n          return false;\n        for (int i = 0; i < point.param.length; i++)\n          if (point.param[i] != s.point.param[i])\n            return false;\n      }\n    if (preTransform == s.preTransform && postTransform == s.postTransform)\n      return true;\n    return (preTransform != null && preTransform.equals(s.preTransform) &&\n      postTransform != null && postTransform.equals(s.postTransform));\n  }\n  \n  /** Create a duplicate of this object. */\n  \n  public Distortion duplicate()\n  {\n    CustomDistortion d = new CustomDistortion(proc, procVersion, point, weight, preTransform, postTransform);\n    if (previous != null)\n      d.previous = previous.duplicate();\n    return d;\n  }\n  \n  /** Apply the Distortion, and return a transformed mesh. */\n\n  public Mesh transform(Mesh obj)\n  {\n    if (previous != null)\n      obj = previous.transform(obj);\n    Mesh newmesh = (Mesh) obj.duplicate();\n    MeshVertex[] vert = newmesh.getVertices();\n    Vec3 newvert[] = new Vec3 [vert.length];\n    OutputModule output[] = proc.getOutputModules();\n    double w2 = 1.0-weight;\n    \n    for (int i = 0; i < newvert.length; i++)\n      {\n        newvert[i] = vert[i].r;\n        if (preTransform != null)\n          preTransform.transform(newvert[i]);\n        point.x = newvert[i].x;\n        point.y = newvert[i].y;\n        point.z = newvert[i].z;\n        proc.initForPoint(point);\n        if (output[0].inputConnected(0))\n          newvert[i].x = weight*output[0].getAverageValue(0, 0.0) + w2*newvert[i].x;\n        if (output[1].inputConnected(0))\n          newvert[i].y = weight*output[1].getAverageValue(0, 0.0) + w2*newvert[i].y;\n        if (output[2].inputConnected(0))\n          newvert[i].z = weight*output[2].getAverageValue(0, 0.0) + w2*newvert[i].z;\n        if (postTransform != null)\n          postTransform.transform(newvert[i]);\n      }\n    newmesh.setVertexPositions(newvert);\n    return newmesh;\n  }\n}", "human_rating": 2.98662020396798, "metadata": {"project": "aoi", "class": "artofillusion.animation.distortion.CustomDistortion", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/distortion/CustomDistortion.java", "label_probabilities": {"readability": [0.0, 0.986621, 0.0133786, 3.96798e-09], "understandability": [0.0, 0.0, 0.0750067, 0.924993], "complexity": [0.0, 1.0, 8.728e-17, 0.0], "modularization": [0.0, 1.0, 0.0, 0.0], "overall": [0.0, 0.0, 0.718747, 0.281253]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.FilterParameterTrack", "source": "/* Copyright (C) 2003-2009 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.image.filter.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.io.*;\nimport java.util.*;\n\n/** This is a Track which allows the parameters of an ImageFilter to be keyframed. */\n\npublic class FilterParameterTrack extends Track\n{\n  private Object parent;\n  private ImageFilter filter;\n  private Timecourse tc;\n  private int smoothingMethod;\n  \n  /** Create a new FilterParameterTrack. */\n  \n  public FilterParameterTrack(Object parent, ImageFilter filter)\n  {\n    super(filter.getName());\n    this.parent = parent;\n    this.filter = filter;\n    tc = new Timecourse(new Keyframe [0], new double [0], new Smoothness [0]);\n    smoothingMethod = Timecourse.INTERPOLATING;\n  }\n  \n  /** Get the filter corresponding to this track. */\n  \n  public ImageFilter getFilter()\n  {\n    return filter;\n  }\n  \n  /** Modify the pose of the object. */\n  \n  public void apply(double time)\n  {\n    ArrayKeyframe k = (ArrayKeyframe) tc.evaluate(time, smoothingMethod);\n\n    if (k == null)\n      return;\n    int index = 0;\n    Property[] properties = filter.getProperties();\n    for (int i = 0; i < properties.length; i++)\n    {\n      if (properties[i].getType() == Property.DOUBLE)\n        filter.setPropertyValue(i, k.val[index++]);\n      else if (properties[i].getType() == Property.COLOR)\n        filter.setPropertyValue(i, new RGBColor(k.val[index++], k.val[index++], k.val[index++]));\n    }\n  }\n  \n  /** Create a duplicate of this track. */\n  \n  public Track duplicate(Object obj)\n  {\n    FilterParameterTrack t = new FilterParameterTrack(obj, filter);\n    t.name = name;\n    t.enabled = enabled;\n    t.quantized = quantized;\n    t.smoothingMethod = smoothingMethod;\n    t.tc = tc.duplicate(filter);\n    return t;\n  }\n  \n  /** Make this track identical to another one. */\n  \n  public void copy(Track tr)\n  {\n    FilterParameterTrack t = (FilterParameterTrack) tr;\n    \n    name = t.name;\n    enabled = t.enabled;\n    quantized = t.quantized;\n    smoothingMethod = t.smoothingMethod;\n    tc = t.tc.duplicate(filter);\n  }\n  \n  /** Get a list of all keyframe times for this track. */\n  \n  public double [] getKeyTimes()\n  {\n    return tc.getTimes();\n  }\n\n  /** Get the timecourse describing this track. */\n  \n  public Timecourse getTimecourse()\n  {\n    return tc;\n  }\n  \n  /** Set a keyframe at the specified time. */\n  \n  public void setKeyframe(double time, Keyframe k, Smoothness s)\n  {\n    tc.addTimepoint(k, time, s);\n  }\n  \n  /** Set a keyframe at the specified time, based on the current state of the Scene. */\n  \n  public Keyframe setKeyframe(double time, Scene sc)\n  {\n    double key[] = getCurrentValues();\n    Keyframe k = new ArrayKeyframe(key);\n    tc.addTimepoint(k, time, new Smoothness());\n    return k;\n  }\n\n  /** Set a keyframe at the specified time, based on the current state of the Scene,\n      if and only if the Scene does not match the current state of the track.  Return\n      the new Keyframe, or null if none was set. */\n  \n  public Keyframe setKeyframeIfModified(double time, Scene sc)\n  {\n    if (tc.getTimes().length == 0)\n      return setKeyframe(time, sc);\n    double val1[] = ((ArrayKeyframe) tc.evaluate(time, smoothingMethod)).val;\n    double val2[] = getCurrentValues();\n    for (int i = 0; i < val1.length; i++)\n      if (val1[i] != val2[i])\n        return setKeyframe(time, sc);\n    return null;\n  }\n\n  /** Look up the current values from the filter. */\n\n  private double[] getCurrentValues()\n  {\n    ArrayList<Double> values = new ArrayList<Double>();\n    Property properties[] = filter.getProperties();\n    for (int i = 0; i < properties.length; i++)\n    {\n      if (properties[i].getType() == Property.DOUBLE)\n        values.add((Double) filter.getPropertyValue(i));\n      else if (properties[i].getType() == Property.COLOR)\n      {\n        RGBColor color = (RGBColor) filter.getPropertyValue(i);\n        values.add(Double.valueOf(color.getRed()));\n        values.add(Double.valueOf(color.getGreen()));\n        values.add(Double.valueOf(color.getBlue()));\n      }\n    }\n    double val[] = new double[values.size()];\n    for (int i = 0; i < values.size(); i++)\n      val[i] = values.get(i);\n    return val;\n  }\n\n  /** Move a keyframe to a new time, and return its new position in the list. */\n  \n  public int moveKeyframe(int which, double time)\n  {\n    return tc.moveTimepoint(which, time);\n  }\n  \n  /** Delete the specified keyframe. */\n  \n  public void deleteKeyframe(int which)\n  {\n    tc.removeTimepoint(which);\n  }\n  \n  /** This track is null if it has no keyframes. */\n  \n  public boolean isNullTrack()\n  {\n    return (tc.getTimes().length == 0);\n  }\n  \n  /** This has no child tracks. */\n  \n  public Track [] getSubtracks()\n  {\n    return new Track [0];\n  }\n\n  /** Determine whether this track can be added as a child of an object. */\n  \n  public boolean canAcceptAsParent(Object obj)\n  {\n    return false;\n  }\n  \n  /** Get the parent object of this track. */\n  \n  public Object getParent()\n  {\n    return parent;\n  }\n  \n  /** Set the parent object of this track. */\n  \n  public void setParent(Object obj)\n  {\n    parent = obj;\n  }\n  \n  /** Get the smoothing method for this track. */\n  \n  public int getSmoothingMethod()\n  {\n    return smoothingMethod;\n  }\n  \n  /** Set the smoothing method for this track. */\n  \n  public void setSmoothingMethod(int method)\n  {\n    smoothingMethod = method;\n  }\n  \n  /** Get the names of all graphable values for this track. */\n  \n  public String [] getValueNames()\n  {\n    ArrayList<String> names = new ArrayList<String>();\n    for (Property property : filter.getProperties())\n    {\n      if (property.getType() == Property.DOUBLE)\n        names.add(property.getName());\n      else if (property.getType() == Property.COLOR)\n      {\n        names.add(property.getName()+\" (\"+Translate.text(\"Red\")+\")\");\n        names.add(property.getName()+\" (\"+Translate.text(\"Green\")+\")\");\n        names.add(property.getName()+\" (\"+Translate.text(\"Blue\")+\")\");\n      }\n    }\n    return names.toArray(new String[names.size()]);\n  }\n\n  /** Get the default list of graphable values (for a track which has no keyframes). */\n  \n  public double [] getDefaultGraphValues()\n  {\n    return getCurrentValues();\n  }\n  \n  /** Get the allowed range for graphable values.  This returns a 2D array, where elements\n      [n][0] and [n][1] are the minimum and maximum allowed values, respectively, for\n      the nth graphable value. */\n  \n  public double[][] getValueRange()\n  {\n    ArrayList<double[]> ranges = new ArrayList<double[]>();\n    for (Property property : filter.getProperties())\n    {\n      if (property.getType() == Property.DOUBLE)\n        ranges.add(new double[] {property.getMinimum(), property.getMaximum()});\n      else if (property.getType() == Property.COLOR)\n      {\n        ranges.add(new double[] {0.0, Double.MAX_VALUE});\n        ranges.add(new double[] {0.0, Double.MAX_VALUE});\n        ranges.add(new double[] {0.0, Double.MAX_VALUE});\n      }\n    }\n    return ranges.toArray(new double[ranges.size()][]);\n  }\n\n  /** Write a serialized representation of this track to a stream. */\n  \n  public void writeToStream(DataOutputStream out, Scene sc) throws IOException\n  {\n    double t[] = tc.getTimes();\n    Smoothness s[] = tc.getSmoothness();\n    Keyframe v[] = tc.getValues();\n\n    out.writeShort(0); // Version number\n    out.writeUTF(name);\n    out.writeBoolean(enabled);\n    out.writeInt(smoothingMethod);\n    out.writeInt(t.length);\n    for (int i = 0; i < t.length; i++)\n      {\n        out.writeDouble(t[i]);\n        v[i].writeToStream(out); \n        s[i].writeToStream(out); \n      }\n  }\n  \n  /** Initialize this tracked based on its serialized representation as written by writeToStream(). */\n  \n  public void initFromStream(DataInputStream in, Scene scene) throws IOException, InvalidObjectException\n  {\n    short version = in.readShort();\n    \n    if (version != 0)\n      throw new InvalidObjectException(\"\");\n    name = in.readUTF();\n    enabled = in.readBoolean();\n    smoothingMethod = in.readInt();\n    int keys = in.readInt();\n    double t[] = new double [keys];\n    Smoothness s[] = new Smoothness [keys];\n    Keyframe v[] = new Keyframe [keys];\n    for (int i = 0; i < keys; i++)\n      {\n        t[i] = in.readDouble();\n        v[i] = new ArrayKeyframe(in, filter);\n        s[i] = new Smoothness(in);\n      }\n    tc = new Timecourse(v, t, s);\n  }\n  \n  /** Present a window in which the user can edit the specified keyframe. */\n  \n  public void editKeyframe(LayoutWindow win, int which)\n  {\n    ArrayKeyframe key = (ArrayKeyframe) tc.getValues()[which];\n    Smoothness s = tc.getSmoothness()[which];\n    double time = tc.getTimes()[which];\n    ValueField timeField = new ValueField(time, ValueField.NONE, 5);\n    ValueSlider s1Slider = new ValueSlider(0.0, 1.0, 100, s.getLeftSmoothness());\n    final ValueSlider s2Slider = new ValueSlider(0.0, 1.0, 100, s.getRightSmoothness());\n    final BCheckBox sameBox = new BCheckBox(Translate.text(\"separateSmoothness\"), !s.isForceSame());\n    Property properties[] = filter.getProperties();\n    ArrayList<PropertyEditor> editors = new ArrayList<PropertyEditor>();\n\n    int index = 0;\n    for (Property property : properties)\n    {\n      if (property.getType() == Property.DOUBLE)\n        editors.add(new PropertyEditor(property, key.val[index++]));\n      else if (property.getType() == Property.COLOR)\n        editors.add(new PropertyEditor(property, new RGBColor(key.val[index++], key.val[index++], key.val[index++])));\n    }\n    Widget widget[] = new Widget [editors.size()+5];\n    String label[] = new String [editors.size()+5];\n    for (int i = 0; i < editors.size(); i++)\n    {\n      widget[i] = editors.get(i).getWidget();\n      label[i] = editors.get(i).getLabel();\n    }\n    sameBox.addEventLink(ValueChangedEvent.class, new Object() {\n      void processEvent()\n      {\n        s2Slider.setEnabled(sameBox.getState());\n      }\n    });\n    s2Slider.setEnabled(sameBox.getState());\n    int n = editors.size();\n    widget[n] = timeField;\n    widget[n+1] = sameBox;\n    widget[n+2] = new BLabel(Translate.text(\"Smoothness\")+':');\n    widget[n+3] = s1Slider;\n    widget[n+4] = s2Slider;\n    label[n] = Translate.text(\"Time\");\n    label[n+3] = \"(\"+Translate.text(\"left\")+\")\";\n    label[n+4] = \"(\"+Translate.text(\"right\")+\")\";\n    ComponentsDialog dlg = new ComponentsDialog(win, Translate.text(\"editKeyframe\"), widget, label);\n    if (!dlg.clickedOk())\n      return;\n    win.setUndoRecord(new UndoRecord(win, false, UndoRecord.COPY_TRACK, new Object [] {this, duplicate(filter)}));\n    index = 0;\n    for (PropertyEditor editor : editors)\n    {\n      if (editor.getProperty().getType() == Property.DOUBLE)\n        key.val[index++] = (Double) editor.getValue();\n      else\n      {\n        RGBColor color = (RGBColor) editor.getValue();\n        key.val[index++] = color.getRed();\n        key.val[index++] = color.getGreen();\n        key.val[index++] = color.getBlue();\n      }\n    }\n    if (sameBox.getState())\n      s.setSmoothness(s1Slider.getValue(), s2Slider.getValue());\n    else\n      s.setSmoothness(s1Slider.getValue());\n    moveKeyframe(which, timeField.getValue());\n  }\n\n  /** This method presents a window in which the user can edit the track. */\n  \n  public void edit(LayoutWindow win)\n  {\n    BTextField nameField = new BTextField(FilterParameterTrack.this.getName());\n    BComboBox smoothChoice = new BComboBox(new String [] {\n      Translate.text(\"Discontinuous\"),\n      Translate.text(\"Linear\"),\n      Translate.text(\"Interpolating\"),\n      Translate.text(\"Approximating\")\n    });\n    smoothChoice.setSelectedIndex(smoothingMethod);\n    ComponentsDialog dlg = new ComponentsDialog(win, Translate.text(\"filterTrackTitle\"), new Widget []\n        {nameField, smoothChoice}, new String [] {Translate.text(\"trackName\"), Translate.text(\"SmoothingMethod\")});\n    if (!dlg.clickedOk())\n      return;\n    win.setUndoRecord(new UndoRecord(win, false, UndoRecord.COPY_TRACK, new Object [] {this, duplicate(filter)}));\n    this.setName(nameField.getText());\n    smoothingMethod = smoothChoice.getSelectedIndex();\n  }\n}\n", "human_rating": 2.99487487042, "metadata": {"project": "aoi", "class": "artofillusion.animation.FilterParameterTrack", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/FilterParameterTrack.java", "label_probabilities": {"readability": [2.10594e-05, 0.994837, 0.00513738, 4.87282e-06], "understandability": [4.96097e-11, 0.000594478, 0.982747, 0.0166586], "complexity": [7.97478e-11, 0.998797, 0.00120278, 5.41849e-13], "modularization": [0.954571, 0.0454259, 2.63485e-06, 1.9e-19], "overall": [3e-20, 1.52735e-05, 0.621429, 0.378556]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.IKTrack", "source": "/* Copyright (C) 2003-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport artofillusion.*;\nimport artofillusion.animation.distortion.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.io.*;\nimport java.util.*;\n\n/** This is a Track which modifies the shape of an object using inverse kinematics. */\n\npublic class IKTrack extends Track\n{\n  private ObjectInfo info;\n  private Vector constraints;\n  private boolean useGestures;\n  private WeightTrack theWeight;\n  \n  public IKTrack(ObjectInfo info)\n  {\n    super(\"Inverse Kinematics\");\n    this.info = info;\n    theWeight = new WeightTrack(this);\n    constraints = new Vector();\n    useGestures = true;\n  }\n  \n  /** Get whether to reshape the mesh based on its gestures. */\n  \n  public boolean getUseGestures()\n  {\n    return useGestures;\n  }\n  \n  /** Set whether to reshape the mesh based on its gestures. */\n  \n  public void setUseGestures(boolean use)\n  {\n    useGestures = use;\n  }\n\n  /** This method presents a window in which the user can edit the track. */\n  \n  public void edit(LayoutWindow win)\n  {\n    if (info.getSkeleton() == null)\n      new BStandardDialog(\"\", Translate.text(\"ikNotApplyWarning\"), BStandardDialog.INFORMATION).showMessageDialog(win);\n    else\n      new Editor(win);\n  }\n  \n  /** Modify the position of the object. */\n  \n  public void apply(double time)\n  {\n    double weight = theWeight.getWeight(time);\n    Skeleton skeleton = info.getSkeleton();\n    if (skeleton == null)\n      return;\n    Joint joint[] = skeleton.getJoints();\n    if (joint.length == 0)\n      return;\n    boolean locked[] = new boolean [joint.length];\n    Vec3 target[] = new Vec3 [joint.length];\n    Mat4 toLocal = info.getCoords().toLocal();\n    \n    for (int i = 0; i < constraints.size(); i++)\n    {\n      Constraint c = (Constraint) constraints.elementAt(i);\n      int index = skeleton.findJointIndex(c.jointID);\n      if (index == -1)\n        continue;\n      if (c.target == null)\n        locked[index] = true;\n      else\n      {\n        CoordinateSystem coords = c.target.getCoords();\n        if (coords == null)\n          locked[index] = true;\n        else\n          target[index] = toLocal.times(coords.getOrigin());\n      }\n    }\n    Actor actor = Actor.getActor(info.getObject());\n    info.addDistortion(new IKDistortion(locked, target, weight, actor));\n  }\n  \n  /** Create a duplicate of this track. */\n  \n  public Track duplicate(Object obj)\n  {\n    IKTrack t = new IKTrack((ObjectInfo) obj);\n    \n    t.name = name;\n    t.enabled = enabled;\n    t.quantized = quantized;\n    t.constraints = new Vector();\n    for (int i = 0; i < constraints.size(); i++)\n    {\n      Constraint c = (Constraint) constraints.elementAt(i);\n      t.constraints.addElement(c.duplicate());\n    }\n    t.theWeight = (WeightTrack) theWeight.duplicate(t);\n    return t;\n  }\n  \n  /** Make this track identical to another one. */\n  \n  public void copy(Track tr)\n  {\n    IKTrack t = (IKTrack) tr;\n    \n    name = t.name;\n    enabled = t.enabled;\n    quantized = t.quantized;\n    constraints = new Vector();\n    for (int i = 0; i < t.constraints.size(); i++)\n    {\n      Constraint c = (Constraint) t.constraints.elementAt(i);\n      constraints.addElement(c.duplicate());\n    }\n    theWeight = (WeightTrack) t.theWeight.duplicate(t);\n  }\n  \n  /** Get a list of all keyframe times for this track. */\n  \n  public double [] getKeyTimes()\n  {\n    return new double [0];\n  }\n\n  /** Move a keyframe to a new time, and return its new position in the list. */\n  \n  public int moveKeyframe(int which, double time)\n  {\n    return -1;\n  }\n  \n  /** Delete the specified keyframe. */\n  \n  public void deleteKeyframe(int which)\n  {\n  }\n  \n  /** This track is null if it has no targets. */\n  \n  public boolean isNullTrack()\n  {\n    for (int i = 0; i < constraints.size(); i++)\n      if (((Constraint) constraints.elementAt(i)).target != null)\n        return false;\n    return true;\n  }\n  \n  /** This has a single child track. */\n  \n  public Track [] getSubtracks()\n  {\n    return new Track [] {theWeight};\n  }\n\n  /** Determine whether this track can be added as a child of an object. */\n  \n  public boolean canAcceptAsParent(Object obj)\n  {\n    return (obj instanceof ObjectInfo && ((ObjectInfo) obj).getObject() instanceof Mesh);\n  }\n  \n  /** Get the parent object of this track. */\n  \n  public Object getParent()\n  {\n    return info;\n  }\n  \n  /** Set the parent object of this track. */\n  \n  public void setParent(Object obj)\n  {\n    info = (ObjectInfo) obj;\n  }\n  \n  /** Get an array of any objects which this track depends on (and which therefore must\n      be updated before this track is applied). */ \n  \n  public ObjectInfo [] getDependencies()\n  {\n    Vector v = new Vector();\n    for (int i = 0; i < constraints.size(); i++)\n    {\n      Constraint c = (Constraint) constraints.elementAt(i);\n      if (c.target != null)\n        v.addElement(c.target.getObject());\n    }\n    ObjectInfo ref[] = new ObjectInfo [v.size()];\n    v.copyInto(ref);\n    return ref;\n  }\n  \n  /** Delete all references to the specified object from this track.  This is used when an\n      object is deleted from the scene. */\n  \n  public void deleteDependencies(ObjectInfo obj)\n  {\n    for (int i = constraints.size()-1; i >= 0; i--)\n    {\n      Constraint c = (Constraint) constraints.elementAt(i);\n      if (c.target != null && c.target.getObject() == obj)\n        constraints.removeElementAt(i);\n    }\n  }\n\n  public void updateObjectReferences(Map<ObjectInfo, ObjectInfo> objectMap)\n  {\n    for (int i = constraints.size()-1; i >= 0; i--)\n    {\n      Constraint c = (Constraint) constraints.elementAt(i);\n      if (c.target != null && objectMap.containsKey(c.target.getObject()))\n      {\n        ObjectInfo newObject = objectMap.get(c.target.getObject());\n        if (c.target.getJoint() == null)\n          c.target = new ObjectRef(newObject);\n        else\n          c.target = new ObjectRef(newObject, newObject.getSkeleton().getJoint(c.target.getJoint().id));\n      }\n    }\n  }\n\n  /** Write a serialized representation of this track to a stream. */\n  \n  public void writeToStream(DataOutputStream out, Scene scene) throws IOException\n  {\n    out.writeShort(1); // Version number\n    out.writeUTF(name);\n    out.writeBoolean(enabled);\n    out.writeBoolean(useGestures);\n    out.writeInt(constraints.size());\n    for (int i = 0; i < constraints.size(); i++)\n    {\n      Constraint c = (Constraint) constraints.elementAt(i);\n      out.writeInt(c.jointID);\n      out.writeBoolean(c.target != null);\n      if (c.target != null)\n        c.target.writeToStream(out);\n    }\n    theWeight.writeToStream(out, scene);\n  }\n  \n  /** Initialize this tracked based on its serialized representation as written by writeToStream(). */\n  \n  public void initFromStream(DataInputStream in, Scene scene) throws IOException, InvalidObjectException\n  {\n    short version = in.readShort();\n    \n    if (version < 0 || version > 1)\n      throw new InvalidObjectException(\"\");\n    name = in.readUTF();\n    enabled = in.readBoolean();\n    if (version > 0)\n      useGestures = in.readBoolean();\n    int numConstraints = in.readInt();\n    constraints = new Vector();\n    for (int i = 0; i < numConstraints; i++)\n    {\n      Constraint c = new Constraint(in.readInt(), in.readBoolean() ? new ObjectRef(in, scene) : null);\n      constraints.addElement(c);\n    }\n    theWeight.initFromStream(in, scene);\n  }\n  \n  /** This inner class represents a single constraint. */\n  \n  private class Constraint\n  {\n    public int jointID;\n    public ObjectRef target;\n    \n    public Constraint(int id, ObjectRef t)\n    {\n      jointID = id;\n      target = t;\n    }\n    \n    public Constraint duplicate()\n    {\n      if (target == null)\n        return new Constraint(jointID, null);\n      return new Constraint(jointID, target.duplicate());\n    }\n  }\n\n  /** Inner class for editing constraint tracks. */\n  \n  private class Editor extends BDialog\n  {\n    LayoutWindow window;\n    BList constraintList;\n    BTextField nameField;\n    BCheckBox gesturesBox;\n    Vector tempConstraints;\n    int tempJointID[];\n    ObjectRef tempTarget[];\n    BButton editButton, deleteButton;\n    \n    public Editor(LayoutWindow win)\n    {\n      super(win, Translate.text(\"ikTrackTitle\"), true);\n      window = win;\n      tempConstraints = new Vector();\n      for (int i = 0; i < constraints.size(); i++)\n        tempConstraints.addElement(((Constraint) constraints.elementAt(i)).duplicate());\n      \n      // Layout the dialog.\n      \n      FormContainer content = new FormContainer(new double [] {0.0, 1.0}, new double [] {0.0, 1.0, 0.0, 0.0});\n      setContent(content);\n      content.setDefaultLayout(new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.BOTH, null, null));\n      content.add(Translate.label(\"trackName\"), 0, 0);\n      content.add(Translate.label(\"constraints\"), 0, 1);\n      content.add(nameField = new BTextField(IKTrack.this.getName(), 30), 1, 0);\n      content.add(UIUtilities.createScrollingList(constraintList = new BList()), 1, 1);\n      constraintList.setPreferredVisibleRows(5);\n      constraintList.addEventLink(SelectionChangedEvent.class, this, \"selectionChanged\");\n      constraintList.addEventLink(MouseClickedEvent.class, this, \"mouseClicked\");\n      buildConstraintList();\n      content.add(gesturesBox = new BCheckBox(Translate.text(\"useGesturesToShapeMesh\"), useGestures), 0, 2, 2, 1);\n      gesturesBox.setEnabled(Actor.getActor(info.getObject()) != null);\n      RowContainer buttons = new RowContainer();\n      content.add(buttons, 0, 3, 2, 1, new LayoutInfo());\n      buttons.add(Translate.button(\"add\", \"...\", this, \"doAdd\"));\n      buttons.add(editButton = Translate.button(\"edit\", \"...\", this, \"doEdit\"));\n      buttons.add(deleteButton = Translate.button(\"delete\", this, \"doDelete\"));\n      buttons.add(Translate.button(\"ok\", this, \"doOk\"));\n      buttons.add(Translate.button(\"cancel\", this, \"dispose\"));\n      pack();\n      UIUtilities.centerDialog(this, win);\n      editButton.setEnabled(false);\n      deleteButton.setEnabled(false);\n      setVisible(true);\n    }\n    \n    /** Fill in the list of constraints. */\n    \n    private void buildConstraintList()\n    {\n      Skeleton skeleton = info.getSkeleton();\n      constraintList.removeAll();\n      if (tempConstraints.size() == 0)\n      {\n        constraintList.add(\"(No Constraints)\");\n        constraintList.setEnabled(false);\n        return;\n      }\n      constraintList.setEnabled(true);\n      for (int i = 0; i < tempConstraints.size(); i++)\n      {\n        Constraint c = (Constraint) tempConstraints.elementAt(i);\n        Joint j = skeleton.getJoint(c.jointID);\n        if (c.target == null)\n          constraintList.add(Translate.text(\"jointIsLocked\", j.name));\n        else\n          constraintList.add(Translate.text(\"jointFollowsTarget\", j.name, c.target.toString()));\n      }\n    }\n    \n    private void doAdd()\n    {\n      Constraint c = new Constraint(-1, null);\n      if (editConstraint(c))\n      {\n        tempConstraints.addElement(c);\n        buildConstraintList();\n      }\n    }\n    \n    private void doEdit()\n    {\n      if (constraintList.getSelectedIndex() > -1)\n      {\n        Constraint c = (Constraint) tempConstraints.elementAt(constraintList.getSelectedIndex());\n        if (editConstraint(c))\n          buildConstraintList();\n      }\n    }\n    \n    private void doDelete()\n    {\n      if (constraintList.getSelectedIndex() > -1)\n        tempConstraints.removeElementAt(constraintList.getSelectedIndex());\n      buildConstraintList();\n    }\n    \n    private void doOk()\n    {\n      window.setUndoRecord(new UndoRecord(window, false, UndoRecord.COPY_OBJECT_INFO, new Object [] {info, info.duplicate()}));\n      IKTrack.this.setName(nameField.getText());\n      IKTrack.this.setUseGestures(gesturesBox.getState());\n      constraints = tempConstraints;\n      window.getScore().repaintAll();\n      dispose();\n    }\n\n    private void mouseClicked(MouseClickedEvent ev)\n    {\n      if (ev.getClickCount() == 2)\n        doEdit();\n    }\n    \n    /** Update the components when a selection changes. */\n    \n    private void selectionChanged()\n    {\n      editButton.setEnabled(constraintList.getSelectedIndex() > -1);\n      deleteButton.setEnabled(constraintList.getSelectedIndex() > -1);\n    }\n    \n    /** Display a window for editing a single constraint. */\n    \n    private boolean editConstraint(Constraint c)\n    {\n      Skeleton skeleton = info.getSkeleton();\n      Joint joint[] = skeleton.getJoints();\n      BList jointList = new BList();\n      for (int i = 0; i < joint.length; i++)\n        jointList.add(joint[i].name);\n      if (skeleton.findJointIndex(c.jointID) > -1)\n        jointList.setSelected(skeleton.findJointIndex(c.jointID), true);\n      jointList.setPreferredVisibleRows(8);\n      RadioButtonGroup group = new RadioButtonGroup();\n      BRadioButton lockedBox = new BRadioButton(Translate.text(\"locked\"), c.target == null, group);\n      final BRadioButton targetBox = new BRadioButton(Translate.text(\"followsTarget\"), c.target != null, group);\n      RowContainer targetRow = new RowContainer();\n      targetRow.add(lockedBox);\n      targetRow.add(targetBox);\n      ObjectRef tempRef = (c.target == null ? new ObjectRef() : c.target);\n      final ObjectRefSelector selector = new ObjectRefSelector(tempRef, window, Translate.text(\"targetForJoint\"), info);\n      Object listener = new Object() {\n        private void processEvent(ValueChangedEvent ev)\n        {\n          selector.setEnabled(ev.getWidget() == targetBox);\n        }\n      };\n      lockedBox.addEventLink(ValueChangedEvent.class, listener);\n      targetBox.addEventLink(ValueChangedEvent.class, listener);\n      selector.setEnabled(c.target != null);\n      ComponentsDialog dlg = new ComponentsDialog(window, Translate.text(\"editConstraint\"), new Widget []\n          {UIUtilities.createScrollingList(jointList), targetRow, selector}, new String [] {Translate.text(\"applyConstraintTo\"), Translate.text(\"constraintType\"),\n          Translate.text(\"targetForJoint\")});\n      if (!dlg.clickedOk() || jointList.getSelectedIndex() == -1)\n        return false;\n      if (jointList.getSelectedIndex() > -1)\n        c.jointID = joint[jointList.getSelectedIndex()].id;\n      if (lockedBox.getState())\n        c.target = null;\n      else\n        c.target = selector.getSelection();\n      return true;\n    }\n  }\n}\n", "human_rating": 2.9979672800059096, "metadata": {"project": "aoi", "class": "artofillusion.animation.IKTrack", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/IKTrack.java", "label_probabilities": {"readability": [0.00148014, 0.995007, 0.00351286, 5.91009e-12], "understandability": [0.00246177, 0.0365374, 0.960852, 0.000148336], "complexity": [0.0218853, 0.89388, 0.0214254, 0.0628096], "modularization": [0.961592, 0.0384083, 2.25749e-09, 0.0], "overall": [8.98743e-10, 0.00424964, 0.98226, 0.0134906]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.NullKeyframe", "source": "/* Copyright (C) 2001-2002 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport java.io.*;\n\n/** This is a keyframes which contains no information.  It is occasionally useful as a\n    placeholder. */\n\npublic class NullKeyframe implements Keyframe\n{\n  public NullKeyframe()\n  {\n  }\n\n  /* Create a duplicate of this keyframe. */\n  \n  public Keyframe duplicate()\n  {\n    return new NullKeyframe();\n  }\n\n  /* Create a duplicate of this keyframe for a (possibly different) object. */\n  \n  public Keyframe duplicate(Object owner)\n  {\n    return new NullKeyframe();\n  }\n  \n  /* Get the list of graphable values for this keyframe. */\n  \n  public double [] getGraphValues()\n  {\n    return new double [0];\n  }\n  \n  /* Set the list of graphable values for this keyframe. */\n  \n  public void setGraphValues(double values[])\n  {\n  }\n\n  /* These methods return a new Keyframe which is a weighted average of this one and one,\n     two, or three others. */\n  \n  public Keyframe blend(Keyframe o2, double weight1, double weight2)\n  {\n    return new NullKeyframe();\n  }\n\n  public Keyframe blend(Keyframe o2, Keyframe o3, double weight1, double weight2, double weight3)\n  {\n    return new NullKeyframe();\n  }\n\n  public Keyframe blend(Keyframe o2, Keyframe o3, Keyframe o4, double weight1, double weight2, double weight3, double weight4)\n  {\n    return new NullKeyframe();\n  }\n\n  /* Determine whether this keyframe is identical to another one. */\n  \n  public boolean equals(Keyframe k)\n  {\n    return (k instanceof NullKeyframe);\n  }\n  \n  /* Write out a representation of this keyframe to a stream. */\n  \n  public void writeToStream(DataOutputStream out) throws IOException\n  {\n  }\n\n  /* Reconstructs the keyframe from its serialized representation. */\n\n   public NullKeyframe(DataInputStream in, Object parent) throws IOException\n   {\n   }\n}", "human_rating": 4.0, "metadata": {"project": "aoi", "class": "artofillusion.animation.NullKeyframe", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/NullKeyframe.java", "label_probabilities": {"readability": [1.0, 1.1349e-16, 0.0, 0.0], "understandability": [1.63e-18, 0.997988, 0.00201219, 0.0], "complexity": [0.0, 0.0, 0.0, 1.0], "modularization": [0.0, 7.456e-13, 0.200522, 0.799478], "overall": [1.0, 0.0, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.PositionTrack", "source": "/* Copyright (C) 2001-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.io.*;\nimport java.util.*;\n\n/** This is a Track which controls the position of an object. */\n\npublic class PositionTrack extends Track\n{\n  ObjectInfo info;\n  Timecourse tc;\n  int smoothingMethod, mode, relCoords, joint;\n  ObjectRef relObject;\n  WeightTrack theWeight;\n  boolean enablex, enabley, enablez;\n  \n  public static final int ABSOLUTE = 0;\n  public static final int RELATIVE = 1;\n\n  public static final int WORLD = 0;\n  public static final int PARENT = 1;\n  public static final int OBJECT = 2;\n  public static final int LOCAL = 3;\n  \n  public PositionTrack(ObjectInfo info)\n  {\n    this(info, \"Position\", true, true, true);\n  }\n  \n  public PositionTrack(ObjectInfo info, String name, boolean affectX, boolean affectY, boolean affectZ)\n  {\n    super(name);\n    this.info = info;\n    tc = new Timecourse(new Keyframe [0], new double [0], new Smoothness [0]);\n    smoothingMethod = Timecourse.INTERPOLATING;\n    mode = ABSOLUTE;\n    relCoords = PARENT;\n    relObject = new ObjectRef();\n    theWeight = new WeightTrack(this);\n    enablex = affectX;\n    enabley = affectY;\n    enablez = affectZ;\n    joint = -1;\n  }\n  \n  /** Modify the position of the object. */\n  \n  public void apply(double time)\n  {\n    Vec3 pos = (VectorKeyframe) tc.evaluate(time, smoothingMethod);\n    double weight = theWeight.getWeight(time);\n\n    if (pos == null)\n      return;\n    Vec3 v = info.getCoords().getOrigin();\n    if (mode == ABSOLUTE)\n      {\n        double w = 1.0-weight;\n        if (enablex)\n          v.x *= w;\n        if (enabley)\n          v.y *= w;\n        if (enablez)\n          v.z *= w;\n      }\n    if (mode == ABSOLUTE && relCoords == PARENT)\n      {\n        if (info.getParent() != null)\n          pos = info.getParent().getCoords().fromLocal().times(pos);\n      }\n    else if (mode == ABSOLUTE && relCoords == OBJECT)\n      {\n        CoordinateSystem coords = relObject.getCoords();\n        if (coords != null)\n          pos = coords.fromLocal().times(pos);\n      }\n    else if (mode == RELATIVE && relCoords == PARENT)\n      {\n        if (info.getParent() != null)\n          pos = info.getParent().getCoords().fromLocal().timesDirection(pos);\n      }\n    else if (mode == RELATIVE && relCoords == OBJECT)\n      {\n        CoordinateSystem coords = relObject.getCoords();\n        if (coords != null)\n          pos = coords.fromLocal().timesDirection(pos);\n      }\n    else if (mode == RELATIVE && relCoords == LOCAL)\n      pos = info.getCoords().fromLocal().timesDirection(pos);\n    if (joint > -1 && mode == ABSOLUTE)\n      {\n        Joint j = info.getSkeleton().getJoint(joint);\n        if (j != null)\n          {\n            if (info.getPose() != null && !info.getPose().equals(info.getObject().getPoseKeyframe()))\n              {\n                info.getObject().applyPoseKeyframe(info.getPose());\n                j = info.getSkeleton().getJoint(joint);\n              }\n            pos = pos.minus(new ObjectRef(info, j).getCoords().getOrigin());\n            pos.add(info.getCoords().getOrigin());\n          }\n      }\n    if (enablex)\n      v.x += pos.x*weight;\n    if (enabley)\n      v.y += pos.y*weight;\n    if (enablez)\n      v.z += pos.z*weight;\n    info.getCoords().setOrigin(v);\n  }\n  \n  /** Create a duplicate of this track. */\n  \n  public Track duplicate(Object obj)\n  {\n    PositionTrack t = new PositionTrack((ObjectInfo) obj);\n    \n    t.name = name;\n    t.enabled = enabled;\n    t.quantized = quantized;\n    t.mode = mode;\n    t.relCoords = relCoords;\n    t.smoothingMethod = smoothingMethod;\n    t.tc = tc.duplicate((ObjectInfo) obj);\n    t.relObject = relObject.duplicate();\n    t.theWeight = (WeightTrack) theWeight.duplicate(t);\n    t.enablex = enablex;\n    t.enabley = enabley;\n    t.enablez = enablez;\n    t.joint = joint;\n    return t;\n  }\n  \n  /** Make this track identical to another one. */\n  \n  public void copy(Track tr)\n  {\n    PositionTrack t = (PositionTrack) tr;\n    \n    name = t.name;\n    enabled = t.enabled;\n    quantized = t.quantized;\n    mode = t.mode;\n    relCoords = t.relCoords;\n    smoothingMethod = t.smoothingMethod;\n    tc = t.tc.duplicate(info);\n    relObject = t.relObject.duplicate();\n    theWeight = (WeightTrack) t.theWeight.duplicate(this);\n    enablex = t.enablex;\n    enabley = t.enabley;\n    enablez = t.enablez;\n    joint = t.joint;\n  }\n  \n  /** Get a list of all keyframe times for this track. */\n  \n  public double [] getKeyTimes()\n  {\n    return tc.getTimes();\n  }\n\n  /** Get the timecourse describing this track. */\n  \n  public Timecourse getTimecourse()\n  {\n    return tc;\n  }\n  \n  /** Set a keyframe at the specified time. */\n  \n  public void setKeyframe(double time, Keyframe k, Smoothness s)\n  {\n    tc.addTimepoint(k, time, s);\n  }\n  \n  /** Set a keyframe at the specified time, based on the current state of the Scene. */\n  \n  public Keyframe setKeyframe(double time, Scene sc)\n  {\n    Vec3 pos = info.getCoords().getOrigin();\n\n    if (joint > -1 && mode == ABSOLUTE)\n      {\n        Joint j = info.getSkeleton().getJoint(joint);\n        if (j != null)\n          pos = new ObjectRef(info, j).getCoords().getOrigin();\n      }\n    if (relCoords == PARENT)\n      {\n        if (info.getParent() != null)\n          pos = info.getParent().getCoords().toLocal().times(pos);\n      }\n    else if (relCoords == OBJECT)\n      {\n        CoordinateSystem coords = relObject.getCoords();\n        if (coords != null)\n          pos = coords.toLocal().times(pos);\n      }\n    Keyframe k = new VectorKeyframe(pos);\n    tc.addTimepoint(k, time, new Smoothness());\n    return k;\n  }\n\n  /** Set a keyframe at the specified time, based on the current state of the Scene,\n      if and only if the Scene does not match the current state of the track.  Return\n      the new Keyframe, or null if none was set. */\n  \n  public Keyframe setKeyframeIfModified(double time, Scene sc)\n  {\n    if (tc.getTimes().length == 0)\n      return setKeyframe(time, sc);\n    VectorKeyframe pos = (VectorKeyframe) tc.evaluate(time, smoothingMethod);\n    Vec3 current = info.getCoords().getOrigin();\n\n    if (joint > -1 && mode == ABSOLUTE)\n      {\n        Joint j = info.getSkeleton().getJoint(joint);\n        if (j != null)\n          current = new ObjectRef(info, j).getCoords().getOrigin();\n      }\n    if (relCoords == PARENT)\n      {\n        if (info.getParent() != null)\n          current = info.getParent().getCoords().toLocal().times(current);\n      }\n    else if (relCoords == OBJECT)\n      {\n        CoordinateSystem coords = relObject.getCoords();\n        if (coords != null)\n          current = coords.toLocal().times(current);\n      }\n    if ((enablex && Math.abs(pos.x-current.x) > 1e-10) ||\n        (enabley && Math.abs(pos.y-current.y) > 1e-10) ||\n        (enablez && Math.abs(pos.z-current.z) > 1e-10))\n      return setKeyframe(time, sc);\n    return null;\n  }\n\n  /** Move a keyframe to a new time, and return its new position in the list. */\n  \n  public int moveKeyframe(int which, double time)\n  {\n    return tc.moveTimepoint(which, time);\n  }\n  \n  /** Delete the specified keyframe. */\n  \n  public void deleteKeyframe(int which)\n  {\n    tc.removeTimepoint(which);\n  }\n  \n  /** This track is null if it has no keyframes. */\n  \n  public boolean isNullTrack()\n  {\n    return (tc.getTimes().length == 0);\n  }\n  \n  /** Determine whether this track affects the X coordinate. */\n  \n  public boolean affectsX()\n  {\n    return enablex;\n  }\n  \n  /** Determine whether this track affects the Y coordinate. */\n  \n  public boolean affectsY()\n  {\n    return enabley;\n  }\n  \n  /** Determine whether this track affects the Z coordinate. */\n  \n  public boolean affectsZ()\n  {\n    return enablez;\n  }\n  \n  /** This has a single child track. */\n  \n  public Track [] getSubtracks()\n  {\n    return new Track [] {theWeight};\n  }\n\n  /** Determine whether this track can be added as a child of an object. */\n  \n  public boolean canAcceptAsParent(Object obj)\n  {\n    return (obj instanceof ObjectInfo);\n  }\n  \n  /** Get the parent object of this track. */\n  \n  public Object getParent()\n  {\n    return info;\n  }\n  \n  /** Set the parent object of this track. */\n  \n  public void setParent(Object obj)\n  {\n    info = (ObjectInfo) obj;\n  }\n  \n  /** Get the smoothing method for this track. */\n  \n  public int getSmoothingMethod()\n  {\n    return smoothingMethod;\n  }\n  \n  /** Set the smoothing method for this track. */\n  \n  public void setSmoothingMethod(int method)\n  {\n    smoothingMethod = method;\n  }\n  \n  /** Determine whether this track is in absolute or relative mode. */\n  \n  public boolean isRelative()\n  {\n    return (mode == RELATIVE);\n  }\n  \n  /** Set whether this track is in absolute or relative mode. */\n  \n  public void setRelative(boolean rel)\n  {\n    mode = (rel ? RELATIVE : ABSOLUTE);\n  }\n  \n  /** Get the coordinate system of this track (WORLD, PARENT, OBJECT, or LOCAL). */\n  \n  public int getCoordinateSystem()\n  {\n    return relCoords;\n  }\n  \n  /** Set the coordinate system of this track (WORLD, PARENT, OBJECT, or LOCAL). */\n  \n  public void setCoordinateSystem(int system)\n  {\n    relCoords = system;\n  }\n  \n  /** Get the object reference for the parent coordinate system.  The return\n      value is undefined if getCoordinateSystem() does not return OBJECT. */\n  \n  public ObjectRef getCoordsObject()\n  {\n    return relObject;\n  }\n  \n  /** Set the object reference for the parent coordinate system.  This causes\n      the coordinate system to be set to OBJECT. */\n  \n  public void setCoordsObject(ObjectRef obj)\n  {\n    relObject = obj;\n    relCoords = OBJECT;\n  }\n  \n  /** Get the ID of the joint this track applies to, or -1 if it applies to the\n      object origin. */\n  \n  public int getApplyToJoint()\n  {\n    return joint;\n  }\n  \n  /** Set the ID of the joint this track applies to.  Specify -1 if it should\n      apply to the object origin. */\n  \n  public void setApplyToJoint(int jointID)\n  {\n    joint = jointID;\n  }\n  \n  /** Get the names of all graphable values for this track. */\n  \n  public String [] getValueNames()\n  {\n    return new String [] {\"X\", \"Y\", \"Z\"};\n  }\n\n  /** Get the default list of graphable values (for a track which has no keyframes). */\n  \n  public double [] getDefaultGraphValues()\n  {\n    Vec3 pos = info.getCoords().getOrigin();\n    return new double [] {pos.x, pos.y, pos.z};\n  }\n  \n  /** Get the allowed range for graphable values.  This returns a 2D array, where elements\n      [n][0] and [n][1] are the minimum and maximum allowed values, respectively, for\n      the nth graphable value. */\n  \n  public double[][] getValueRange()\n  {\n    double range[][] = new double [3][2];\n    for (int i = 0; i < range.length; i++)\n      {\n        range[i][0] = -Double.MAX_VALUE;\n        range[i][1] = Double.MAX_VALUE;\n      }\n    return range;\n  }\n  \n  /** Get an array of any objects which this track depends on (and which therefore must\n      be updated before this track is applied). */ \n  \n  public ObjectInfo [] getDependencies()\n  {\n    if (relCoords == OBJECT)\n    {\n      ObjectInfo relInfo = relObject.getObject();\n      if (relInfo != null)\n        return new ObjectInfo [] {relInfo};\n    }\n    else if (relCoords == PARENT && info.getParent() != null)\n      return new ObjectInfo [] {info.getParent()};\n    return new ObjectInfo [0];\n  }\n  \n  /** Delete all references to the specified object from this track.  This is used when an\n      object is deleted from the scene. */\n  \n  public void deleteDependencies(ObjectInfo obj)\n  {\n    if (relObject.getObject() == obj)\n      relObject = new ObjectRef();\n  }\n\n  public void updateObjectReferences(Map<ObjectInfo, ObjectInfo> objectMap)\n  {\n    if (objectMap.containsKey(relObject.getObject()))\n    {\n      ObjectInfo newObject = objectMap.get(relObject.getObject());\n      if (relObject.getJoint() == null)\n        relObject = new ObjectRef(newObject);\n      else\n        relObject = new ObjectRef(newObject, newObject.getSkeleton().getJoint(relObject.getJoint().id));\n    }\n  }\n\n  /** Write a serialized representation of this track to a stream. */\n  \n  public void writeToStream(DataOutputStream out, Scene scene) throws IOException\n  {\n    double t[] = tc.getTimes();\n    Smoothness s[] = tc.getSmoothness();\n    Keyframe v[] = tc.getValues();\n\n    out.writeShort(1); // Version number\n    out.writeUTF(name);\n    out.writeBoolean(enabled);\n    out.writeInt(smoothingMethod);\n    out.writeInt(mode);\n    out.writeInt(relCoords);\n    out.writeInt(joint);\n    out.writeBoolean(enablex);\n    out.writeBoolean(enabley);\n    out.writeBoolean(enablez);\n    out.writeInt(t.length);\n    for (int i = 0; i < t.length; i++)\n      {\n        out.writeDouble(t[i]);\n        ((VectorKeyframe) v[i]).writeToFile(out); \n        s[i].writeToStream(out); \n      }\n    if (relCoords == OBJECT)\n      relObject.writeToStream(out);\n    theWeight.writeToStream(out, scene);\n  }\n  \n  /** Initialize this tracked based on its serialized representation as written by writeToStream(). */\n  \n  public void initFromStream(DataInputStream in, Scene scene) throws IOException, InvalidObjectException\n  {\n    short version = in.readShort();\n    if (version < 0 || version > 1)\n      throw new InvalidObjectException(\"\");\n    name = in.readUTF();\n    enabled = in.readBoolean();\n    smoothingMethod = in.readInt();\n    mode = in.readInt();\n    relCoords = in.readInt();\n    joint = (version == 0 ? -1 : in.readInt());\n    enablex = in.readBoolean();\n    enabley = in.readBoolean();\n    enablez = in.readBoolean();\n    int keys = in.readInt();\n    double t[] = new double [keys];\n    Smoothness s[] = new Smoothness [keys];\n    Keyframe v[] = new Keyframe [keys];\n    for (int i = 0; i < keys; i++)\n      {\n        t[i] = in.readDouble();\n        v[i] = new VectorKeyframe(new Vec3(in));\n        s[i] = new Smoothness(in);\n      }\n    tc = new Timecourse(v, t, s);\n    if (relCoords == OBJECT)\n      relObject = new ObjectRef(in, scene);\n    else\n      relObject = new ObjectRef();\n    theWeight.initFromStream(in, scene);\n  }\n\n  /** Present a window in which the user can edit the specified keyframe. */\n  \n  public void editKeyframe(LayoutWindow win, int which)\n  {\n    VectorKeyframe key = (VectorKeyframe) tc.getValues()[which];\n    Smoothness s = tc.getSmoothness()[which];\n    double time = tc.getTimes()[which];\n    ValueField xField = new ValueField(key.x, ValueField.NONE, 5);\n    ValueField yField = new ValueField(key.y, ValueField.NONE, 5);\n    ValueField zField = new ValueField(key.z, ValueField.NONE, 5);\n    ValueField timeField = new ValueField(time, ValueField.NONE, 5);\n    ValueSlider s1Slider = new ValueSlider(0.0, 1.0, 100, s.getLeftSmoothness());\n    final ValueSlider s2Slider = new ValueSlider(0.0, 1.0, 100, s.getRightSmoothness());\n    final BCheckBox sameBox = new BCheckBox(Translate.text(\"separateSmoothness\"), !s.isForceSame());\n    \n    sameBox.addEventLink(ValueChangedEvent.class, new Object() {\n      void processEvent()\n      {\n        s2Slider.setEnabled(sameBox.getState());\n      }\n    });\n    s2Slider.setEnabled(sameBox.getState());\n    ComponentsDialog dlg = new ComponentsDialog(win, Translate.text(\"editKeyframe\"), new Widget []\n        {xField, yField, zField, timeField, sameBox, new BLabel(Translate.text(\"Smoothness\")+':'), s1Slider, s2Slider},\n        new String [] {\"X\", \"Y\", \"Z\", Translate.text(\"Time\"), null, null, \"(\"+Translate.text(\"left\")+\")\", \"(\"+Translate.text(\"right\")+\")\"});\n    if (!dlg.clickedOk())\n      return;\n    win.setUndoRecord(new UndoRecord(win, false, UndoRecord.COPY_TRACK, new Object [] {this, duplicate(info)}));\n    key.x = xField.getValue();\n    key.y = yField.getValue();\n    key.z = zField.getValue();\n    if (sameBox.getState())\n      s.setSmoothness(s1Slider.getValue(), s2Slider.getValue());\n    else\n      s.setSmoothness(s1Slider.getValue());\n    moveKeyframe(which, timeField.getValue());\n  }\n\n  /** This method presents a window in which the user can edit the track. */\n  \n  public void edit(LayoutWindow win)\n  {\n    Skeleton s = info.getSkeleton();\n    Joint j[] = (s == null ? null : s.getJoints());\n    BTextField nameField = new BTextField(getName());\n    BComboBox smoothChoice = new BComboBox(new String [] {\n      Translate.text(\"Discontinuous\"),\n      Translate.text(\"Linear\"),\n      Translate.text(\"Interpolating\"),\n      Translate.text(\"Approximating\")\n    });\n    smoothChoice.setSelectedIndex(smoothingMethod);\n    final BComboBox modeChoice = new BComboBox(new String [] {\n      Translate.text(\"Absolute\"),\n      Translate.text(\"Relative\")\n    });\n    modeChoice.setSelectedIndex(mode);\n    final BComboBox coordsChoice = new BComboBox(new String [] {\n      Translate.text(\"World\"),\n      Translate.text(\"Parent\"),\n      Translate.text(\"OtherObject\")\n    });\n    if (mode == 1)\n      coordsChoice.add(Translate.text(\"Local\"));\n    coordsChoice.setSelectedIndex(relCoords);\n    BComboBox jointChoice = new BComboBox();\n    jointChoice.add(Translate.text(\"objectOrigin\"));\n    if (j != null)\n    {\n      for (int i = 0; i < j.length; i++)\n        jointChoice.add(j[i].name);\n      for (int i = 0; i < j.length; i++)\n        if (j[i].id == joint)\n          jointChoice.setSelectedIndex(i+1);\n    }\n    final ObjectRefSelector objSelector = new ObjectRefSelector(relObject, win, Translate.text(\"positionRelativeTo\"), info);\n    objSelector.setEnabled(coordsChoice.getSelectedIndex() == 2);\n    modeChoice.addEventLink(ValueChangedEvent.class, new Object() {\n      void processEvent()\n      {\n        int sel = modeChoice.getSelectedIndex();\n        if (sel == 0 && coordsChoice.getItemCount() == 4)\n          coordsChoice.remove(3);\n        if (sel == 1 && coordsChoice.getItemCount() == 3)\n          coordsChoice.add(Translate.text(\"Local\"));\n        objSelector.setEnabled(coordsChoice.getSelectedIndex() == 2);\n      }\n    });\n    coordsChoice.addEventLink(ValueChangedEvent.class, new Object() {\n      void processEvent()\n      {\n        objSelector.setEnabled(coordsChoice.getSelectedIndex() == 2);\n      }\n    });\n    RowContainer row = new RowContainer();\n    BCheckBox xbox, ybox, zbox;\n    row.add(xbox = new BCheckBox(\"X\", enablex));\n    row.add(ybox = new BCheckBox(\"Y\", enabley));\n    row.add(zbox = new BCheckBox(\"Z\", enablez));\n    ComponentsDialog dlg = new ComponentsDialog(win, Translate.text(\"positionTrackTitle\"), new Widget []\n        {nameField, smoothChoice, modeChoice, jointChoice, coordsChoice, objSelector, row}, new String []\n        {Translate.text(\"trackName\"), Translate.text(\"SmoothingMethod\"), Translate.text(\"trackMode\"), Translate.text(\"applyTo\"), Translate.text(\"CoordinateSystem\"), \"\", Translate.text(\"trackAffects\")});\n    if (!dlg.clickedOk())\n      return;\n    win.setUndoRecord(new UndoRecord(win, false, UndoRecord.COPY_OBJECT_INFO, new Object [] {info, info.duplicate()}));\n    this.setName(nameField.getText());\n    smoothingMethod = smoothChoice.getSelectedIndex();\n    mode = modeChoice.getSelectedIndex();\n    relCoords = coordsChoice.getSelectedIndex();\n    relObject = objSelector.getSelection();\n    if (jointChoice.getSelectedIndex() == 0)\n      joint = -1;\n    else\n      joint = j[jointChoice.getSelectedIndex()-1].id;\n    enablex = xbox.getState();\n    enabley = ybox.getState();\n    enablez = zbox.getState();\n  }\n}", "human_rating": 2.2644247095779195, "metadata": {"project": "aoi", "class": "artofillusion.animation.PositionTrack", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/PositionTrack.java", "label_probabilities": {"readability": [2.39448e-09, 0.332296, 0.599833, 0.0678707], "understandability": [0.472313, 0.366952, 0.16065, 8.50418e-05], "complexity": [0.422985, 0.576999, 1.57321e-05, 1.55726e-08], "modularization": [0.166259, 0.833741, 8.56171e-10, 1.64175e-09], "overall": [3.16518e-06, 0.293478, 0.553163, 0.153356]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.Skeleton", "source": "/* Copyright (C) 2001-2006 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport artofillusion.*;\nimport artofillusion.animation.Joint.DOF;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport java.awt.*;\nimport java.io.*;\n\n/** This class represents the skeleton of an animated object. */\n\npublic class Skeleton\n{\n  private Joint joint[];\n  private int nextID;\n  \n  private static final int MARKER_WIDTH = 10;\n  private static final double BONE_WIDTH = 0.15;\n  private static final double WIDEST_POINT = 0.8;\n  \n  public Skeleton()\n  {\n    joint = new Joint [0];\n    nextID = 1;\n  }\n  \n  /** Create an exact duplicate of this skeleton. */\n  \n  public Skeleton duplicate()\n  {\n    Skeleton s = new Skeleton();\n    \n    s.nextID = nextID;\n    s.joint = new Joint [joint.length];\n    for (int i = 0; i < joint.length; i++)\n      s.joint[i] = joint[i].duplicate();\n    for (int i = 0; i < joint.length; i++)\n      {\n        if (joint[i].parent != null)\n          s.joint[i].parent = s.joint[s.findJointIndex(joint[i].parent.id)];\n        s.joint[i].children  = new Joint [joint[i].children.length];\n        for (int j = 0; j < joint[i].children.length; j++)\n          s.joint[i].children[j] = s.joint[s.findJointIndex(joint[i].children[j].id)];\n      }\n    return s;\n  }\n\n  /** Make this skeleton idenical to another one. */\n  \n  public void copy(Skeleton s)\n  {\n    nextID = s.nextID;\n    joint = new Joint [s.joint.length];\n    for (int i = 0; i < joint.length; i++)\n      joint[i] = s.joint[i].duplicate();\n    for (int i = 0; i < joint.length; i++)\n      {\n        if (s.joint[i].parent != null)\n          joint[i].parent = joint[findJointIndex(s.joint[i].parent.id)];\n        joint[i].children  = new Joint [s.joint[i].children.length];\n        for (int j = 0; j < joint[i].children.length; j++)\n          joint[i].children[j] = joint[findJointIndex(s.joint[i].children[j].id)];\n      }\n  }\n\n  /** Determine if this skeleton is identical to another one. */\n  \n  public boolean equals(Object o)\n  {\n    if (!(o instanceof Skeleton))\n      return false;\n    Skeleton s = (Skeleton) o;\n    if (joint.length != s.joint.length)\n      return false;\n    for (int i = 0; i < joint.length; i++)\n      if (!joint[i].equals(s.joint[i]))\n        return false;\n    return true;\n  }\n\n  /** Add a joint to the skeleton. */\n  \n  public void addJoint(Joint j, int parentID)\n  {\n    Joint newjoint[] = new Joint [joint.length+1];\n    System.arraycopy(joint, 0, newjoint, 0, joint.length);\n    newjoint[joint.length] = j;\n    joint = newjoint;\n    if (j.id == -1)\n      j.id = nextID++;\n    int parentIndex = findJointIndex(parentID);\n    if (parentIndex == -1)\n      {\n        j.parent = null;\n        return;\n      }\n    Joint parent = joint[parentIndex];\n    j.parent = parent;\n    Joint newchildren[] = new Joint [parent.children.length+1];\n    System.arraycopy(parent.children, 0, newchildren, 0, parent.children.length);\n    newchildren[parent.children.length] = j;\n    parent.children = newchildren;\n  }\n  \n  /** Delete a joint from the skeleton.  If it has children, all of them will be deleted\n      as well. */\n\n  public void deleteJoint(int id)\n  {\n    int which = findJointIndex(id);\n    Joint j = joint[which], parent = j.parent;\n    while (j.children.length > 0)\n      deleteJoint(j.children[0].id);\n    which = findJointIndex(id);\n    Joint newjoint[] = new Joint [joint.length-1];\n    for (int i = 0, k = 0; i < joint.length; i++)\n      if (i != which)\n        newjoint[k++] = joint[i];\n    joint = newjoint;\n    if (parent == null)\n      return;\n    Joint newchildren[] = new Joint [parent.children.length-1];\n    for (int i = 0, k = 0; i < parent.children.length; i++)\n      if (parent.children[i] != j)\n        newchildren[k++] = parent.children[i];\n    parent.children = newchildren;\n  }\n  \n  /** Add every joint from another skeleton to this one. */\n  \n  public void addAllJoints(Skeleton s)\n  {\n    Joint newjoint[] = new Joint [joint.length+s.joint.length];\n    System.arraycopy(joint, 0, newjoint, 0, joint.length);\n    for (int i = 0; i < s.joint.length; i++)\n      newjoint[joint.length+i] = s.joint[i].duplicate();\n    for (int i = 0; i < s.joint.length; i++)\n    {\n      Joint newj = newjoint[joint.length+i];\n      Joint oldj = s.joint[i];\n      newj.id = nextID++;\n      if (oldj.parent != null)\n        newj.parent = newjoint[joint.length+s.findJointIndex(oldj.parent.id)];\n      newj.children = new Joint [oldj.children.length];\n      for (int k = 0; k < newj.children.length; k++)\n        newj.children[k] = newjoint[joint.length+s.findJointIndex(oldj.children[k].id)];\n    }\n    joint = newjoint;\n  }\n  \n  /** Set the parent of a joint. */\n  \n  public void setJointParent(Joint j, Joint parent)\n  {\n    if (j.parent != null)\n    {\n      Joint newchildren[] = new Joint [j.parent.children.length-1];\n      for (int i = 0, k = 0; i < j.parent.children.length; i++)\n        if (j.parent.children[i] != j)\n          newchildren[k++] = j.parent.children[i];\n      j.parent.children = newchildren;\n    }\n    if (parent != null)\n    {\n      Joint newchildren[] = new Joint [parent.children.length+1];\n      System.arraycopy(parent.children, 0, newchildren, 0, parent.children.length);\n      newchildren[parent.children.length] = j;\n      parent.children = newchildren;\n    }\n    j.parent = parent;\n  }\n  \n  /** Find the array index for a given joint ID. */\n  \n  public int findJointIndex(int id)\n  {\n    int min = 0, max = joint.length-1, current = (min+max)>>1;\n    \n    if (joint.length == 0)\n      return -1;\n    while (true)\n      {\n        if (joint[current].id == id)\n          return current;\n        if (joint[current].id > id)\n          max = current-1;\n        else\n          min = current+1;\n        if (min >= max)\n          {\n            if (min < joint.length && joint[min].id == id)\n              return min;\n            return -1;\n          }\n        current = (min+max)>>1;\n      }\n  }\n  \n  /** Get the joint with the specified ID, or null if there is none. */\n  \n  public Joint getJoint(int id)\n  {\n    int which = findJointIndex(id);\n    if (which < 0 || which >= joint.length)\n      return null;\n    return joint[which];\n  }\n  \n  /** Get an array of all the joints. */\n  \n  public Joint [] getJoints()\n  {\n    Joint j[] = new Joint [joint.length];\n    for (int i = 0; i < j.length; i++)\n      j[i] = joint[i];\n    return j;\n  }\n  \n  /** Get the number of joints in the skeleton. */\n  \n  public int getNumJoints()\n  {\n    return joint.length;\n  }\n  \n  /** Get the ID for the next joint to be added. */\n  \n  public int getNextJointID()\n  {\n    return nextID;\n  }\n  \n  /** Scale the skeleton by the specified amount along each axis. */\n  \n  public void scale(double x, double y, double z)\n  {\n    for (int i = 0; i < joint.length; i++)\n      {\n        Vec3 pos = joint[i].coords.getOrigin();\n        pos.x *= x;\n        pos.y *= y;\n        pos.z *= z;\n        joint[i].coords.setOrigin(pos);\n        Vec3 zdir = joint[i].coords.getZDirection();\n        Vec3 newzdir = new Vec3(zdir.x*x, zdir.y*y, zdir.z*z);\n        double len = newzdir.length();\n        if (len > 0.0)\n          zdir = newzdir.times(1.0/len);\n        Vec3 updir = joint[i].coords.getUpDirection();\n        Vec3 newupdir = new Vec3(updir.x*x, updir.y*y, updir.z*z);\n        len = newupdir.length();\n        if (len > 0.0)\n          updir = newupdir.times(1.0/len);\n        joint[i].coords.setOrientation(zdir, updir);\n      }\n    for (int i = 0; i < joint.length; i++)\n      {\n        if (joint[i].parent == null)\n          joint[i].calcAnglesFromCoords(true);\n        else\n          joint[i].length.pos = joint[i].coords.getOrigin().distance(joint[i].parent.coords.getOrigin());\n      }\n  }\n  \n  /** Modify a Skeleton to be a weighted average of an arbitrary list of Skeletons,\n      averaged about this one.\n      @param average   the Skeleton to modify to be an average of other Skeletons\n      @param s         the list of Skeletons to average\n      @param weight    the weights for the different Skeletons\n  */\n  \n  public void blend(Skeleton average, Skeleton s[], double weight[])\n  {\n    for (int i = 0; i < joint.length; i++)\n    {\n      Joint javg = average.getJoint(joint[i].id);\n      Vec3 pos = null, newpos = null;\n      double rootangles[] = null;\n      if (joint[i].parent == null)\n      {\n        pos = joint[i].coords.getOrigin();\n        newpos = new Vec3(pos);\n        rootangles = joint[i].coords.getRotationAngles();\n        javg.coords = joint[i].coords.duplicate();\n      }\n      \n      // Find the average DOF values.\n\n      javg.angle1.pos = joint[i].angle1.pos;\n      javg.angle2.pos = joint[i].angle2.pos;\n      javg.twist.pos = joint[i].twist.pos;\n      javg.length.pos = joint[i].length.pos;\n      for (int j = 0; j < s.length; j++)\n      {\n        Joint jother = s[j].getJoint(joint[i].id);\n        if (jother == null)\n          continue;\n        javg.length.pos += weight[j]*findOffset(jother.length, joint[i].length);\n        if (joint[i].parent == null)\n        {\n          newpos.add(jother.coords.getOrigin().minus(pos).times(weight[j]));\n          double angles[] = jother.coords.getRotationAngles();\n          RotationKeyframe rot = new RotationKeyframe(angles[0]-rootangles[0], angles[1]-rootangles[1], angles[2]-rootangles[2]);\n          rot.applyToCoordinates(javg.coords, weight[j], null, null, true, true, true, true);\n        }\n        else\n        {\n          javg.angle1.pos += weight[j]*findOffset(jother.angle1, joint[i].angle1);\n          javg.angle2.pos += weight[j]*findOffset(jother.angle2, joint[i].angle2);\n          javg.twist.pos += weight[j]*findOffset(jother.twist, joint[i].twist);\n        }\n      }\n      if (joint[i].parent == null)\n      {\n        javg.coords.setOrigin(newpos);\n        double angles[] = javg.coords.getRotationAngles();\n        javg.angle1.pos = angles[0];\n        javg.angle2.pos = angles[1];\n        javg.twist.pos = angles[2];\n      }\n      \n      // Give each DOF a chance to clip the value.\n      \n      javg.angle1.set(javg.angle1.pos);\n      javg.angle2.set(javg.angle2.pos);\n      javg.twist.set(javg.twist.pos);\n      javg.length.set(javg.length.pos);\n    }\n    \n    // Update coordinate systems.\n    \n    for (int i = 0; i < average.joint.length; i++)\n      if (average.joint[i].parent == null)\n        average.joint[i].recalcCoords(true);\n  }\n  \n  /** Utility routine for finding the angle offsets. */\n\n  private double findOffset(DOF gesture, DOF defaultPose)\n  {\n    double diff = gesture.pos-defaultPose.pos;\n    if (gesture.loop)\n    {\n      double range = gesture.max-gesture.min;\n      while (diff > gesture.max)\n        diff -= range;\n      while (diff < gesture.min)\n        diff += range;\n    }\n    return diff;\n  }\n  \n  /** Draw the skeleton onto a canvas. */\n  \n  public void draw(MeshViewer view, boolean enabled)\n  {\n    Camera cam = view.getCamera();\n    int mode = view.getRenderMode();\n    boolean render = (mode != ViewerCanvas.RENDER_WIREFRAME && mode != ViewerCanvas.RENDER_TRANSPARENT && !(view.getCurrentTool() instanceof SkeletonTool));\n    Vec2 p[] = new Vec2 [joint.length], v1 = new Vec2(), v2 = new Vec2();\n    Point screenVert[] = new Point [joint.length], p1 = new Point(), p2 = new Point();\n    double screenZ[] = new double [joint.length];\n    Color color = (enabled ? ViewerCanvas.lineColor : ViewerCanvas.disabledColor), col;\n    int colInt;\n    \n    // First calculate the positions of all the joints.\n\n    for (int i = 0; i < joint.length; i++)\n      {\n        Joint j = joint[i];\n        Vec3 pos = j.coords.getOrigin();\n        p[i] = cam.getObjectToScreen().timesXY(pos);\n        screenVert[i] = new Point((int) p[i].x, (int) p[i].y);\n        screenZ[i] = cam.getObjectToView().timesZ(pos);\n      }\n    \n    // Now draw the bones.\n    \n    col = color;\n    Mat4 objToScreen = cam.getObjectToScreen();\n    for (int i = 0; i < joint.length; i++)\n      {\n        Joint j = joint[i], parent = j.parent;\n        if (parent == null)\n          continue;\n        int parentIndex = findJointIndex(parent.id);\n        Vec3 zdir = j.coords.getOrigin().minus(parent.coords.getOrigin());\n        double length = zdir.length();\n        Vec3 xdir = j.coords.getUpDirection().times(BONE_WIDTH*length);\n        Vec3 ydir = zdir.cross(xdir);\n        ydir.normalize();\n        ydir.scale(0.5*BONE_WIDTH*length);\n        zdir.scale(WIDEST_POINT);\n        Vec3 center = parent.coords.getOrigin().plus(zdir);\n        Vec3 cx1 = center.plus(xdir), cx2 = center.minus(xdir);\n        Vec3 cy1 = center.plus(ydir), cy2 = center.minus(ydir);\n        if (render)\n          {\n            Vec3 pos[] = new Vec3 [] {\n              cx1, cx2, cy1, cy2, joint[i].coords.getOrigin(), joint[parentIndex].coords.getOrigin()\n            };\n            for (int k = 1; k < pos.length; k++)\n              for (int m = 0; m < k; m++)\n                view.renderLine(pos[k], pos[m], cam, col);\n          }\n        else\n          {\n            Vec2 pos[] = new Vec2 [] {\n                objToScreen.timesXY(cx1), objToScreen.timesXY(cx2),\n                objToScreen.timesXY(cy1), objToScreen.timesXY(cy2),\n                p[i], p[parentIndex]\n            };\n            for (int k = 1; k < pos.length; k++)\n            {\n              p1.x = (int) pos[k].x;\n              p1.y = (int) pos[k].y;\n              for (int m = 0; m < k; m++)\n              {\n                p2.x = (int) pos[m].x;\n                p2.y = (int) pos[m].y;\n                view.drawLine(p1, p2, col);\n              }\n            }\n          }\n      }\n\n    // Finally draw the markers for all the joints.\n    \n    int selectedID = view.getSelectedJoint();\n    boolean locked[] = view.getLockedJoints();\n    for (int i = 0; i < joint.length; i++)\n      {\n        Joint j = joint[i];\n        if (locked[i])\n          col = ViewerCanvas.specialHighlightColor;\n        else if (j.id == selectedID)\n          col = ViewerCanvas.highlightColor;\n        else\n          col = color;\n        if (render)\n          {\n            v1.x = v2.x = p[i].x;\n            v1.y = p[i].y-MARKER_WIDTH;\n            v2.y = p[i].y+MARKER_WIDTH;\n            view.renderLine(v1, screenZ[i], v2, screenZ[i], cam, col);\n            v1.y = v2.y = p[i].y;\n            v1.x = p[i].x-MARKER_WIDTH;\n            v2.x = p[i].x+MARKER_WIDTH;\n            view.renderLine(v1, screenZ[i], v2, screenZ[i], cam, col);\n          }\n        else\n          {\n            p1.x = p2.x = screenVert[i].x;\n            p1.y = screenVert[i].y-MARKER_WIDTH;\n            p2.y = screenVert[i].y+MARKER_WIDTH;\n            view.drawLine(p1, p2, col);\n            p1.y = p2.y = screenVert[i].y;\n            p1.x = screenVert[i].x-MARKER_WIDTH;\n            p2.x = screenVert[i].x+MARKER_WIDTH;\n            view.drawLine(p1, p2, col);\n          }\n      }\n  }\n  \n  /** Update a mesh after its skeleton has moved.  oldMesh is the mesh before movement.\n      newMesh is a duplicate of it with its skeleton in a different position.  This\n      method repositions the vertices of newMesh based on the skeleton. */\n  \n  public static void adjustMesh(Mesh oldMesh, Mesh newMesh)\n  {\n    Skeleton s1 = oldMesh.getSkeleton(), s2 = newMesh.getSkeleton();\n    MeshVertex v1[] = oldMesh.getVertices(), v2[] = newMesh.getVertices();\n    Vec3 v[] = new Vec3 [v2.length];\n    Vec3 temp = new Vec3();\n    \n    for (int i = 0; i < v2.length; i++)\n      {\n        v[i] = v2[i].r;\n        if (v2[i].ikJoint == -1)\n          continue;\n        Joint j1 = s1.getJoint(v1[i].ikJoint), j2 = s2.getJoint(v2[i].ikJoint);\n        if (j1 == null || j2 == null)\n          continue;\n        double weight = (j2.parent == null ? 1.0 : v2[i].ikWeight);\n        v[i].set(v1[i].r);\n        j1.coords.toLocal().transform(v[i]);\n        j2.coords.fromLocal().transform(v[i]);\n        if (weight < 1.0)\n          {\n            v[i].scale(weight);\n            temp.set(v1[i].r);\n            j1.parent.coords.toLocal().transform(temp);\n            j2.parent.coords.fromLocal().transform(temp);\n            temp.scale(1.0-weight);\n            v[i].add(temp);\n          }\n        \n        // Adjust the vertex positions to reduce the \"squashing\" effect around\n        // bent joints.\n        \n        double olddist = v1[i].r.distance2(j1.coords.getOrigin());\n        double newdist = v[i].distance2(j2.coords.getOrigin());\n        if (olddist > 0.0 && newdist > 0.0)\n          {\n            v[i].subtract(j2.coords.getOrigin());\n            v[i].scale(Math.pow(olddist/newdist, 0.5*v1[i].ikWeight));\n            v[i].add(j2.coords.getOrigin());\n          }\n      }\n    newMesh.setVertexPositions(v);\n  }\n\n  /** Write a serialized representation of this skeleton to a stream. */\n\n  public void writeToStream(DataOutputStream out) throws IOException\n  {\n    out.writeShort(0); // Version number\n    out.writeInt(joint.length);\n    for (int i = 0; i < joint.length; i++)\n      {\n        // Write the information about this joint.\n        \n        Joint j = joint[i];\n        out.writeInt(j.id);\n        out.writeUTF(j.name);\n        j.coords.writeToFile(out);\n        j.angle1.writeToStream(out);\n        j.angle2.writeToStream(out);\n        j.twist.writeToStream(out);\n        j.length.writeToStream(out);\n        out.writeInt(j.parent == null ? -1 : j.parent.id);\n        out.writeInt(j.children.length);\n        for (int k = 0; k < j.children.length; k++)\n          out.writeInt(j.children[k].id);\n      }\n  }\n  \n  /** Reconstruct a skeleton from its serialized representation. */\n  \n  public Skeleton(DataInputStream in) throws IOException, InvalidObjectException\n  {\n    short version = in.readShort();\n    if (version != 0)\n      throw new InvalidObjectException(\"\");\n    nextID = 1;\n    joint = new Joint [in.readInt()];\n    int parentID[] = new int [joint.length];\n    int childID[][] = new int [joint.length][];\n    for (int i = 0; i < joint.length; i++)\n      {\n        // Read in the information about joints.\n        \n        int id = in.readInt();\n        String name = in.readUTF();\n        Joint j = new Joint(new CoordinateSystem(in), null, name);\n        joint[i] = j;\n        j.id = id;\n        j.angle1 = j.new DOF(in);\n        j.angle2 = j.new DOF(in);\n        j.twist = j.new DOF(in);\n        j.length = j.new DOF(in);\n        j.length.loop = false;\n        parentID[i] = in.readInt();\n        childID[i] = new int [in.readInt()];\n        for (int k = 0; k < childID[i].length; k++)\n          childID[i][k] = in.readInt();\n        if (j.id >= nextID)\n          nextID = j.id+1;\n      }\n    \n    // Assign the parents and children for each joint.\n    \n    for (int i = 0; i < joint.length; i++)\n      {\n        joint[i].parent = getJoint(parentID[i]);\n        joint[i].children = new Joint [childID[i].length];\n        for (int k = 0; k < childID[i].length; k++)\n          joint[i].children[k] = getJoint(childID[i][k]);\n      }\n  }\n}\n", "human_rating": 2.37642049696, "metadata": {"project": "aoi", "class": "artofillusion.animation.Skeleton", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/Skeleton.java", "label_probabilities": {"readability": [1.08924e-06, 0.377053, 0.622311, 0.00063514], "understandability": [9.64551e-10, 0.00864728, 0.211692, 0.779661], "complexity": [0.96707, 0.0329297, 3.99267e-07, 1.1e-19], "modularization": [0.969588, 0.0303972, 1.51168e-05, 6.427e-17], "overall": [0.0, 2.04489e-06, 0.101905, 0.898093]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.SkeletonTool", "source": "/* Copyright (C) 1999-2009 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.text.*;\n\n/** SkeletonTool is an EditingTool used for manipulating the skeletons of objects. */\n\npublic class SkeletonTool extends EditingTool\n{\n  private static final int CLICK_TOL = 6;\n  private static final int HANDLE_SIZE = 4;\n  \n  private static final int NO_HANDLES = 0;\n  private static final int UNLOCKED_HANDLES = 1;\n  private static final int ALL_HANDLES = 2;\n\n  private static int whichHandles = UNLOCKED_HANDLES;\n  private Point clickPoint;\n  private Vec3 clickPos, handlePos[];\n  private boolean hideHandle[], invertDragDir;\n  private int clickedHandle;\n  private IKSolver ik;\n  private Mesh oldMesh, mesh;\n  private UndoRecord undo;\n  private boolean allowCreating;\n  private String helpText;\n    \n  public SkeletonTool(MeshEditorWindow fr, boolean allowCreating)\n  {\n    super(fr);\n    this.allowCreating = allowCreating;\n    initButton(\"skeleton\");\n    clickedHandle = -1;\n    helpText = Translate.text(allowCreating ? \"skeletonTool.helpText\" : \"skeletonTool.helpTextNoCreate\");\n  }\n\n  public void activate()\n  {\n    super.activate();\n    theWindow.setHelpText(helpText);\n  }\n\n  public int whichClicks()\n  {\n    return ALL_CLICKS;\n  }\n\n  public String getToolTipText()\n  {\n    return Translate.text(\"skeletonTool.tipText\");\n  }\n\n  /** Find the positions of all the degree-of-freedom handles. */\n  \n  private void findHandlePositions(Mat4 objToScreen, Joint j, ViewerCanvas view)\n  {\n    if (j.parent == null || whichHandles == NO_HANDLES)\n      hideHandle = new boolean [] {true, true, true, true};\n    else if (whichHandles == UNLOCKED_HANDLES)\n      hideHandle = new boolean [] {j.angle1.fixed, j.angle2.fixed, j.length.fixed, j.twist.fixed};\n    else\n      hideHandle = new boolean [4];\n    double scale = 70.0/view.getScale();\n    handlePos = new Vec3 [] {new Vec3(0.0, scale, 0.0), new Vec3(scale, 0.0, 0.0),\n        new Vec3(0.0, 0.0, scale), new Vec3(-scale*0.6, -scale*0.6, scale*0.4)};\n    Vec3 jointPos = new Vec3(j.coords.getOrigin());\n    objToScreen.transform(jointPos);\n    int jointX = (int) jointPos.x;\n    int jointY = (int) jointPos.y;\n    for (int i = 0; i < hideHandle.length; i++)\n    {\n      if (hideHandle[i])\n        continue;\n      j.coords.fromLocal().transformDirection(handlePos[i]);\n      handlePos[i].add(j.coords.getOrigin());\n      objToScreen.transform(handlePos[i]);\n      int x = (int) handlePos[i].x;\n      int y = (int) handlePos[i].y;\n      if (x == jointX && y == jointY)\n        hideHandle[i] = true;\n    }\n  }\n  \n  public void drawOverlay(ViewerCanvas view)\n  {\n    if (ik != null)\n      return;\n    MeshViewer mv = (MeshViewer) view;\n    int selected = mv.getSelectedJoint();\n    mesh = (oldMesh == null ? (Mesh) mv.getController().getObject().getObject() : oldMesh);\n    Skeleton s = mesh.getSkeleton();\n    Joint j = s.getJoint(selected);\n    if (j == null)\n      return;\n    Camera cam = mv.getCamera();\n    CoordinateSystem objCoords = mv.getDisplayCoordinates();\n    Mat4 objToScreen = cam.getWorldToScreen().times(objCoords.fromLocal());\n    \n    if (clickedHandle == -1)\n    {\n      // Draw the handles for each degree of freedom.\n      \n      findHandlePositions(objToScreen, j, view);\n      Vec3 jointPos = new Vec3(j.coords.getOrigin());\n      objToScreen.transform(jointPos);\n      int jointX = (int) jointPos.x;\n      int jointY = (int) jointPos.y;\n      for (int i = 0; i < hideHandle.length; i++)\n      {\n        if (hideHandle[i])\n          continue;\n        int x = (int) handlePos[i].x;\n        int y = (int) handlePos[i].y;\n        view.drawLine(new Point(jointX, jointY), new Point(x, y), Color.darkGray);\n        view.drawBox(x-HANDLE_SIZE/2, y-HANDLE_SIZE/2, HANDLE_SIZE, HANDLE_SIZE, ViewerCanvas.handleColor);\n      }\n    }\n    else if (clickedHandle < 2)\n    {\n      // Draw a circle to show the DOF being moved.\n      \n      double len = j.length.pos;\n      Mat4 m1, m2;\n      if (clickedHandle == 0)\n      {\n        m1 = Mat4.zrotation(j.twist.pos*Math.PI/180.0);\n        m2 = j.parent.coords.fromLocal().times(Mat4.yrotation(j.angle2.pos*Math.PI/180.0));\n      }\n      else\n      {\n        m1 = Mat4.xrotation(j.angle1.pos*Math.PI/180.0).times(Mat4.zrotation(j.twist.pos*Math.PI/180.0));\n        m2 = j.parent.coords.fromLocal();\n      }\n      m2 = objToScreen.times(m2);\n      Point pos[] = new Point [64];\n      for (int i = 0; i < pos.length; i++)\n      {\n        double angle = i*2.0*Math.PI/pos.length;\n        Vec3 p = new Vec3(0.0, 0.0, len);\n        p = m1.timesDirection(p);\n        if (clickedHandle == 0)\n          p = m2.times(Mat4.xrotation(angle).timesDirection(p));\n        else\n          p = m2.times(Mat4.yrotation(angle).timesDirection(p));\n        pos[i] = new Point((int) p.x, (int) p.y);\n      }\n      for (int i = 1; i < pos.length; i++)\n        view.drawLine(new Point(pos[i-1].x, pos[i-1].y), new Point(pos[i].x, pos[i].y), Color.darkGray);\n      view.drawLine(new Point(pos[0].x, pos[0].y), new Point(pos[pos.length-1].x, pos[pos.length-1].y), Color.darkGray);\n    }\n  }\n\n  public void mousePressed(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    MeshViewer mv = (MeshViewer) view;\n    ViewerCanvas allViews[] = ((MeshEditorWindow) theWindow).getAllViews();\n    mesh = (Mesh) mv.getController().getObject().getObject();\n    Skeleton s = mesh.getSkeleton();\n    Joint selectedJoint = s.getJoint(mv.getSelectedJoint());\n    Camera cam = mv.getCamera();\n    CoordinateSystem objCoords = mv.getDisplayCoordinates();\n    Mat4 objToScreen = cam.getWorldToScreen().times(objCoords.fromLocal());\n    \n    clickPoint = e.getPoint();\n    if (e.isControlDown() && allowCreating)\n      {\n        // Create a new joint.\n        \n        undo = new UndoRecord(theWindow, false, UndoRecord.COPY_OBJECT, new Object [] {mesh, mesh.duplicate()});\n        Joint j, parent = s.getJoint(mv.getSelectedJoint());\n        if (parent == null)\n          {\n            double distToJoint = cam.getDistToScreen();\n            clickPos = cam.convertScreenToWorld(clickPoint, distToJoint);\n            objCoords.toLocal().transform(clickPos);\n            j = new Joint(new CoordinateSystem(clickPos, Vec3.vz(), Vec3.vy()), null, \"Root \"+s.getNextJointID());\n            j.angle1.fixed = j.angle2.fixed = true;\n            s.addJoint(j, -1);\n          }\n        else\n          {\n            double distToJoint = cam.getWorldToView().timesZ(parent.coords.getOrigin());\n            clickPos = cam.convertScreenToWorld(clickPoint, distToJoint);\n            objCoords.toLocal().transform(clickPos);\n            Vec3 zdir = clickPos.minus(parent.coords.getOrigin());\n            zdir.normalize();\n            Vec3 ydir = cam.getCameraCoordinates().getZDirection().cross(zdir);\n            ydir.normalize(); \n            j = new Joint(new CoordinateSystem(clickPos, zdir, ydir), parent, \"Bone \"+s.getNextJointID());\n            s.addJoint(j, parent.id);\n          }\n        for (int k = 0; k < allViews.length; k++)\n          ((MeshViewer) allViews[k]).setSelectedJoint(j.id);\n        boolean moving[] = new boolean [s.getNumJoints()];\n        moving[s.findJointIndex(j.id)] = true;\n        ik = new IKSolver(s, mv.getLockedJoints(), moving);\n        theWindow.updateImage();\n        theWindow.updateMenus();\n        oldMesh = (Mesh) mesh.duplicate();\n        return;\n      }\n    \n    // See whether a handle was clicked.\n    \n    if (selectedJoint != null)\n    {\n      findHandlePositions(objToScreen, selectedJoint, view);\n      for (int i = 0; i < hideHandle.length; i++)\n      {\n        if (!hideHandle[i] && Math.abs(handlePos[i].x-clickPoint.x) <= 0.5*CLICK_TOL && Math.abs(handlePos[i].y-clickPoint.y) <= 0.5*CLICK_TOL)\n        {\n          clickedHandle = i;\n          oldMesh = (Mesh) mesh.duplicate();\n          Vec2 jointPos = objToScreen.timesXY(selectedJoint.coords.getOrigin());\n          invertDragDir = (handlePos[i].x < jointPos.x);\n          theWindow.updateImage();\n          return;\n        }\n      }\n    }\n    \n    // Determine which joint was clicked on.\n    \n    Joint joint[] = s.getJoints();\n    int i;\n    for (i = 0; i < joint.length; i++)\n      {\n        Vec2 pos = objToScreen.timesXY(joint[i].coords.getOrigin());\n        if ((clickPoint.x > pos.x-CLICK_TOL) && \n            (clickPoint.x < pos.x+CLICK_TOL) &&\n            (clickPoint.y > pos.y-CLICK_TOL) && \n            (clickPoint.y < pos.y+CLICK_TOL))\n          break;\n      }\n    if (i == joint.length)\n      {\n        // No joint was clicked on, so deselect the selected joint.\n        \n        for (int j = 0; j < allViews.length; j++)\n          ((MeshViewer) allViews[j]).setSelectedJoint(-1);\n        theWindow.updateImage();\n        theWindow.updateMenus();\n        return;\n      }\n    if (e.isShiftDown())\n      {\n        // Toggle whether this joint is locked.\n        \n        for (int j = 0; j < allViews.length; j++)\n        {\n          MeshViewer v = (MeshViewer) allViews[j];\n          if (v.isJointLocked(joint[i].id))\n            v.unlockJoint(joint[i].id);\n          else\n            v.lockJoint(joint[i].id);\n        }\n        theWindow.updateImage();\n        return;\n      }\n    \n    // Make it the selected joint, and prepare to drag it.\n    \n    for (int j = 0; j < allViews.length; j++)\n      ((MeshViewer) allViews[j]).setSelectedJoint(joint[i].id);\n    clickPos = joint[i].coords.getOrigin();\n    theWindow.updateImage();\n    theWindow.updateMenus();\n    boolean moving[] = new boolean [s.getNumJoints()];\n    moving[s.findJointIndex(joint[i].id)] = true;\n    ik = new IKSolver(s, mv.getLockedJoints(), moving);\n    oldMesh = (Mesh) mesh.duplicate();\n  }\n  \n  public void mouseDragged(final WidgetMouseEvent e, ViewerCanvas view)\n  {\n    final MeshViewer mv = (MeshViewer) view;\n    final CoordinateSystem objCoords = mv.getDisplayCoordinates();\n    final Camera cam = mv.getCamera();\n    final Mesh mesh = (Mesh) mv.getController().getObject().getObject();\n    final Skeleton s = mesh.getSkeleton();\n    final Joint selectedJoint = s.getJoint(mv.getSelectedJoint());\n\n    if (clickedHandle > -1)\n    {\n      // Adjust a single degree of freedom.\n      \n      if (undo == null)\n        undo = new UndoRecord(getWindow(), false, UndoRecord.COPY_OBJECT, new Object [] {mesh, mesh.duplicate()});\n      double dist = clickPoint.x-e.getPoint().x;\n      if (invertDragDir)\n        dist = -dist;\n      Joint origJoint = oldMesh.getSkeleton().getJoint(mv.getSelectedJoint());\n      Joint.DOF dof = null;\n      Joint.DOF origDof = null;\n      String name = null;\n      switch (clickedHandle)\n      {\n        case 0:\n          dof = selectedJoint.angle1;\n          origDof = origJoint.angle1;\n          dist *= 1.8/Math.PI;\n          name = \"X Bend\";\n          break;\n        case 1:\n          dof = selectedJoint.angle2;\n          origDof = origJoint.angle2;\n          dist *= -1.8/Math.PI;\n          name = \"Y Bend\";\n          break;\n        case 2:\n          dof = selectedJoint.length;\n          origDof = origJoint.length;\n          dist /= -view.getScale();\n          name = \"Length\";\n          break;\n        case 3:\n          dof = selectedJoint.twist;\n          origDof = origJoint.twist;\n          dist *= 1.8/Math.PI;\n          name = \"Twist\";\n          break;\n      }\n      dof.set(origDof.pos+dist);\n      selectedJoint.recalcCoords(true);\n      if (!mv.getSkeletonDetached())\n        adjustMesh(mesh);\n      mv.getController().objectChanged();\n      theWindow.updateImage();\n      NumberFormat nf = NumberFormat.getNumberInstance();\n      nf.setMaximumFractionDigits(3);\n      theWindow.setHelpText(name+\": \"+nf.format(dof.pos));\n      return;\n    }\n\n    if (ik == null)\n      return;\n    boolean converged = false;\n    Vec3 target[] = new Vec3 [s.getNumJoints()];\n    int jointIndex = s.findJointIndex(selectedJoint.id);\n    ActionProcessor process = view.getActionProcessor();\n    do\n    {\n      Vec3 jointPos = objCoords.fromLocal().times(selectedJoint.coords.getOrigin());\n      double distToJoint = cam.getWorldToView().timesZ(jointPos);\n      Vec3 goal = cam.convertScreenToWorld(e.getPoint(), distToJoint);\n      objCoords.toLocal().transform(goal);\n\n      if (undo == null)\n        undo = new UndoRecord(SkeletonTool.this.getWindow(), false, UndoRecord.COPY_OBJECT, new Object [] {mesh, mesh.duplicate()});\n      target[jointIndex] = goal;\n      converged = ik.solve(target, 100);\n      if (!mv.getSkeletonDetached())\n        adjustMesh(mesh);\n      ((ObjectViewer) view).getController().objectChanged();\n      theWindow.updateImage();\n    } while (!converged && (process == null || (!process.hasEvent() && !process.hasBeenStopped())));\n  }\n\n  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    if (undo == null && e.getClickCount() == 2 && !e.isShiftDown() && !e.isControlDown())\n      ((MeshEditorWindow) theWindow).editJointCommand(); // They double-clicked without dragging.\n    ik = null;\n    mesh = oldMesh = null;\n    clickedHandle = -1;\n    if (undo != null)\n      theWindow.setUndoRecord(undo);\n    undo = null;\n    theWindow.setHelpText(helpText);\n  }\n  \n  public void iconDoubleClicked()\n  {\n    BComboBox dofChoice = new BComboBox(new String [] {\n      Translate.text(\"noDOF\"),\n      Translate.text(\"unlockedDOF\"),\n      Translate.text(\"allDOF\"),\n    });\n    dofChoice.setSelectedIndex(whichHandles);\n    ComponentsDialog dlg = new ComponentsDialog(theFrame, Translate.text(\"skeletonToolTitle\"), \n                new Widget [] {dofChoice}, new String [] {null});\n    if (!dlg.clickedOk())\n      return;\n    whichHandles = dofChoice.getSelectedIndex();\n    theWindow.updateImage();\n  }\n  \n  /** Adjust the mesh after the skeleton has changed. */\n  \n  protected void adjustMesh(Mesh newMesh)\n  {\n    Skeleton.adjustMesh(oldMesh, newMesh);\n  }\n}", "human_rating": 2.7745666987999997, "metadata": {"project": "aoi", "class": "artofillusion.animation.SkeletonTool", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/SkeletonTool.java", "label_probabilities": {"readability": [2.1087e-06, 0.7747, 0.225161, 0.000136264], "understandability": [4.72941e-10, 0.00523159, 0.617116, 0.377652], "complexity": [0.195395, 0.803749, 0.00084415, 1.21135e-05], "modularization": [0.686819, 0.31067, 0.00251102, 1.40927e-08], "overall": [2.69737e-15, 0.000637118, 0.778688, 0.220675]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.animation.VerticalAxis", "source": "/* Copyright (C) 2001,2004 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.animation;\n\nimport artofillusion.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.text.*;\nimport java.util.*;\n\n/** This draws the vertical axis on graphs of keyframe values. */\n\npublic class VerticalAxis extends CustomWidget\n{\n  private double minValue, maxValue, vscale, tickPos[];\n  private NumberFormat nf = NumberFormat.getNumberInstance();\n  private boolean lineAtBottom;\n  private Rectangle lastBounds;\n\n  public static final int TICK_SIZE = 6;\n\n  public VerticalAxis()\n  {\n    setGraphRange(0.0, 1.0);\n    setPreferredSize(new Dimension(50, 0));\n    addEventLink(RepaintEvent.class, this, \"paint\");\n  }\n\n  /** Select the range for the graph. */\n  \n  public void setGraphRange(double min, double max)\n  {\n    Rectangle dim = getBounds();\n    minValue = min;\n    maxValue = max;\n    vscale = dim.height/(max-min);\n    \n    // Select the vertical tick positions.\n    \n\n    double height = dim.height;\n    if (height <= 0)\n      return;\n    double increment = Math.pow(10.0, Math.floor(Math.log((max-min))/Math.log(10.0)));\n    double pixels = (height*increment)/(max-min);\n    if (pixels < 20.0)\n    {\n      while (pixels < 20.0)\n      {\n        pixels *= 5.0;\n        increment *= 5.0;\n      }\n    }\n    else if ((max-min)/increment < 4.0)\n      increment *= 0.5;\n    double lowest = Math.ceil(min/increment)*increment;\n    int num = (int) Math.ceil((max-lowest)/increment)+1;\n    tickPos = new double [num];\n    for (int i = 0; i < num; i++)\n      tickPos[i] = lowest+i*increment;\n  }\n\n  /** Set whether a line should be draw along the bottom edge. */\n  \n  public void showLineAtBottom(boolean show)\n  {\n    lineAtBottom = show;\n  }\n\n  private void paint(RepaintEvent ev)\n  {\n    Graphics2D g = ev.getGraphics();\n    FontMetrics fm = g.getFontMetrics(g.getFont());\n    int labelOffset = (fm.getMaxAscent()+fm.getMaxDescent())/2;\n    Rectangle dim = getBounds();\n    if (lastBounds == null || dim.width != lastBounds.width || dim.height != lastBounds.height)\n      setGraphRange(minValue, maxValue);\n\n    // Draw the ticks on the vertical axis.\n\n    if (tickPos == null)\n      return;\n    if (tickPos.length > 1)\n      nf.setMaximumFractionDigits((int) Math.max(0, 1-Math.log(tickPos[1]-tickPos[0])/Math.log(10)));\n    else\n      nf.setMaximumFractionDigits(3);\n    for (int i = 0; i < tickPos.length; i++)\n    {\n      int y = dim.height-(int) Math.round(vscale*(tickPos[i]-minValue));\n      g.drawLine(dim.width-TICK_SIZE, y, dim.width, y);\n      String s = nf.format(tickPos[i]);\n      int x = dim.width-TICK_SIZE-2-fm.stringWidth(s);\n      g.drawString(s, x, y+labelOffset);\n    }\n    if (lineAtBottom)\n      g.drawLine(0, dim.height-1, dim.width, dim.height-1);\n  }\n}\n", "human_rating": 3.000000000000613, "metadata": {"project": "aoi", "class": "artofillusion.animation.VerticalAxis", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/animation/VerticalAxis.java", "label_probabilities": {"readability": [0.0, 1.0, 3.06531e-13, 0.0], "understandability": [0.000861653, 0.155208, 0.842656, 0.00127435], "complexity": [0.0, 1.10888e-07, 1.0, 3.59017e-08], "modularization": [0.0, 7.3426e-11, 0.998341, 0.00165913], "overall": [0.0, 1.0, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.ApplicationPreferences", "source": "/* Copyright (C) 2002-2009 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport java.io.*;\nimport java.util.*;\nimport java.util.List;\n\n/** This class keeps track of program-wide user preferences. */\n\npublic class ApplicationPreferences\n{\n  private Properties properties;\n  private int defaultDisplayMode, undoLevels;\n  private double interactiveTol;\n  private boolean keepBackupFiles, useOpenGL, useCompoundMeshTool, reverseZooming;\n  private Renderer objectPreviewRenderer, texturePreviewRenderer, defaultRenderer;\n\n  /**\n   * Create a new ApplicationPreferences object, loading the preferences from a\n   * file in the default location.\n   */\n\n  public ApplicationPreferences()\n  {\n    File f = new File(getPreferencesDirectory(), \"aoiprefs\");\n    if (!f.exists())\n    {\n      // See if it exists in the old location.\n\n      File f2 = new File(System.getProperty(\"user.home\"), \".aoiprefs\");\n      if (f2.exists())\n        f2.renameTo(f);\n    }\n    initDefaultPreferences();\n    if (!f.exists())\n      {\n        properties = new Properties();\n        Translate.setLocale(Locale.getDefault());\n        return;\n      }\n    try\n      {\n        InputStream in = new BufferedInputStream(new FileInputStream(f));\n        loadPreferences(in);\n        in.close();\n      }\n    catch (IOException ex)\n      {\n        ex.printStackTrace();\n      }\n  }\n\n  /**\n   * Create a new ApplicationPreferences object, loading the preferences from an InputStream.\n   */\n\n  public ApplicationPreferences(InputStream in)\n  {\n    initDefaultPreferences();\n    try\n    {\n      loadPreferences(in);\n      in.close();\n    }\n    catch (IOException ex)\n    {\n      ex.printStackTrace();\n    }\n  }\n\n  /** Load the preferences from an InputStream. */\n\n  private void loadPreferences(InputStream in) throws IOException\n  {\n    properties = new Properties();\n    properties.load(in);\n    parsePreferences();\n  }\n\n  /** Save any changed preferences to disk. */\n\n  public void savePreferences()\n  {\n    // Copy over preferences that are stored in other classes.\n\n    properties.put(\"theme\", ThemeManager.getSelectedTheme().resource.getId());\n    ThemeManager.ColorSet colorSets[] = ThemeManager.getSelectedTheme().getColorSets();\n    for (int i = 0; i < colorSets.length; i++)\n      if (colorSets[i] == ThemeManager.getSelectedColorSet())\n        properties.put(\"themeColorSet\", Integer.toString(i));\n\n    // Write the preferences to a file.\n\n    File f = new File(getPreferencesDirectory(), \"aoiprefs\");\n    try\n      {\n        OutputStream out = new BufferedOutputStream(new FileOutputStream(f));\n        properties.store(out, \"Art of Illusion Preferences File\");\n        out.close();\n      }\n    catch (IOException ex)\n      {\n        ex.printStackTrace();\n      }\n  }\n\n  /** Get the directory in which preferences files are saved. */\n\n  public static File getPreferencesDirectory()\n  {\n    File dir = new File(System.getProperty(\"user.home\"), \".artofillusion\");\n    if (!dir.exists())\n      dir.mkdirs();\n    return dir;\n  }\n\n  /** Initialize internal variables to reasonable defaults. */\n\n  private void initDefaultPreferences()\n  {\n    List<Renderer> renderers = PluginRegistry.getPlugins(Renderer.class);\n    if (renderers.size() > 0)\n      objectPreviewRenderer = texturePreviewRenderer = defaultRenderer = getNamedRenderer(\"Raytracer\");\n    defaultDisplayMode = ViewerCanvas.RENDER_SMOOTH;\n    interactiveTol = 0.05;\n    undoLevels = 6;\n    useOpenGL = true;\n    keepBackupFiles = false;\n    useCompoundMeshTool = false;\n    reverseZooming = false;\n  }\n\n  /** Parse the properties loaded from the preferences file. */\n\n  private void parsePreferences()\n  {\n    objectPreviewRenderer = getNamedRenderer(properties.getProperty(\"objectPreviewRenderer\"));\n    texturePreviewRenderer = getNamedRenderer(properties.getProperty(\"texturePreviewRenderer\"));\n    defaultRenderer = getNamedRenderer(properties.getProperty(\"defaultRenderer\"));\n    defaultDisplayMode = parseIntProperty(\"defaultDisplayMode\", defaultDisplayMode);\n    interactiveTol = parseDoubleProperty(\"interactiveSurfaceError\", interactiveTol);\n    undoLevels = parseIntProperty(\"undoLevels\", undoLevels);\n    useOpenGL = parseBooleanProperty(\"useOpenGL\", useOpenGL);\n    keepBackupFiles = parseBooleanProperty(\"keepBackupFiles\", keepBackupFiles);\n    useCompoundMeshTool = parseBooleanProperty(\"useCompoundMeshTool\", useCompoundMeshTool);\n    reverseZooming = parseBooleanProperty(\"reverseZooming\", reverseZooming);\n    Translate.setLocale(parseLocaleProperty(\"language\"));\n    if (properties.getProperty(\"theme\") == null)\n    {\n      ThemeManager.setSelectedTheme(ThemeManager.getDefaultTheme());\n      ThemeManager.setSelectedColorSet(ThemeManager.getSelectedTheme().getColorSets()[parseIntProperty(\"colorScheme\", 0)]);\n    }\n    else\n    {\n      String themeId = properties.getProperty(\"theme\");\n      List themes = ThemeManager.getThemes();\n      for (int i = 0; i < themes.size(); i++)\n      {\n        ThemeManager.ThemeInfo theme = (ThemeManager.ThemeInfo) themes.get(i);\n        if (theme.resource.getId().equals(themeId))\n        {\n          ThemeManager.setSelectedTheme(theme);\n          int colorSetIndex = parseIntProperty(\"themeColorSet\", 0);\n          ThemeManager.ColorSet colorSets[] = theme.getColorSets();\n          if (colorSetIndex > -1 && colorSetIndex < colorSets.length)\n            ThemeManager.setSelectedColorSet(colorSets[colorSetIndex]);\n          break;\n        }\n      }\n    }\n  }\n\n  /** Parse an integer valued property. */\n\n  private int parseIntProperty(String name, int defaultVal)\n  {\n    try\n      {\n        return Integer.parseInt(properties.getProperty(name));\n      }\n    catch (Exception ex)\n      {\n        return defaultVal;\n      }\n  }\n\n  /** Parse a double valued property. */\n\n  private double parseDoubleProperty(String name, double defaultVal)\n  {\n    try\n      {\n        return Double.valueOf(properties.getProperty(name));\n      }\n    catch (Exception ex)\n      {\n        return defaultVal;\n      }\n  }\n\n  /** Parse a boolea valued property. */\n\n  private boolean parseBooleanProperty(String name, boolean defaultVal)\n  {\n    String prop = properties.getProperty(name);\n    if (prop == null)\n      return defaultVal;\n    return Boolean.valueOf(prop);\n  }\n\n  /** Parse a property specifying a locale. */\n\n  private Locale parseLocaleProperty(String name)\n  {\n    try\n      {\n        String desc = properties.getProperty(name);\n        String language = desc.substring(0, 2);\n        String country = desc.substring(3);\n        return new Locale(language, country);\n      }\n    catch (Exception ex)\n      {\n        return Locale.getDefault();\n      }\n  }\n\n  /** Look up a renderer by name. */\n\n  private Renderer getNamedRenderer(String name)\n  {\n    List<Renderer> renderers = PluginRegistry.getPlugins(Renderer.class);\n    if (renderers.size() == 0)\n      return null;\n    for (Renderer r : renderers)\n      if (r.getName().equals(name))\n        return r;\n    return renderers.get(renderers.size()-1);\n  }\n\n  /** Get the default renderer. */\n\n  public final Renderer getDefaultRenderer()\n  {\n    return defaultRenderer;\n  }\n\n  /** Set the default renderer. */\n\n  public final void setDefaultRenderer(Renderer rend)\n  {\n    defaultRenderer = rend;\n    properties.put(\"defaultRenderer\", rend.getName());\n  }\n\n  /** Get the object preview renderer. */\n\n  public final Renderer getObjectPreviewRenderer()\n  {\n    return objectPreviewRenderer;\n  }\n\n  /** Set the object preview renderer. */\n\n  public final void setObjectPreviewRenderer(Renderer rend)\n  {\n    objectPreviewRenderer = rend;\n    properties.put(\"objectPreviewRenderer\", rend.getName());\n  }\n\n  /** Get the texture preview renderer. */\n\n  public final Renderer getTexturePreviewRenderer()\n  {\n    return texturePreviewRenderer;\n  }\n\n  /** Set the texture preview renderer. */\n\n  public final void setTexturePreviewRenderer(Renderer rend)\n  {\n    texturePreviewRenderer = rend;\n    properties.put(\"texturePreviewRenderer\", rend.getName());\n  }\n\n  /** Get the default display mode. */\n\n  public final int getDefaultDisplayMode()\n  {\n    return defaultDisplayMode;\n  }\n\n  /** Set the default display mode. */\n\n  public final void setDefaultDisplayMode(int mode)\n  {\n    defaultDisplayMode = mode;\n    properties.put(\"defaultDisplayMode\", Integer.toString(mode));\n  }\n\n  /** Get the interactive surface error. */\n\n  public final double getInteractiveSurfaceError()\n  {\n    return interactiveTol;\n  }\n\n  /** Set the interactive surface error. */\n\n  public final void setInteractiveSurfaceError(double tol)\n  {\n    boolean changed = (interactiveTol != tol);\n\n    interactiveTol = tol;\n    properties.put(\"interactiveSurfaceError\", Double.toString(tol));\n    if (changed)\n      {\n        // Clear the cached meshes for objects in all windows.\n\n        EditingWindow windows[] = ArtOfIllusion.getWindows();\n        for (EditingWindow w : windows)\n          {\n            Scene sc = w.getScene();\n            if (sc == null)\n              continue;\n            for (int j = 0; j < sc.getNumObjects(); j++)\n              {\n                ObjectInfo info = sc.getObject(j);\n                Vec3 size = info.getBounds().getSize();\n                info.getObject().setSize(size.x, size.y, size.z);\n                info.clearCachedMeshes();\n              }\n            w.updateImage();\n          }\n      }\n  }\n\n  /** Get the locale for displaying text. */\n\n  public final Locale getLocale()\n  {\n    return Translate.getLocale();\n  }\n\n  /** Set the locale for displaying text. */\n\n  public final void setLocale(Locale locale)\n  {\n    Translate.setLocale(locale);\n    properties.put(\"language\", locale.getLanguage()+'_'+locale.getCountry());\n  }\n\n  /** Get the number of levels of Undo to support. */\n\n  public final int getUndoLevels()\n  {\n    return undoLevels;\n  }\n\n  /** Set the number of levels of Undo to support. */\n\n  public final void setUndoLevels(int levels)\n  {\n    undoLevels = levels;\n    properties.put(\"undoLevels\", Integer.toString(levels));\n  }\n\n  /** Get whether to use OpenGL for interactive rendering. */\n\n  public final boolean getUseOpenGL()\n  {\n    return useOpenGL;\n  }\n\n  /** Set whether to use OpenGL for interactive rendering. */\n\n  public final void setUseOpenGL(boolean use)\n  {\n    useOpenGL = use;\n    properties.put(\"useOpenGL\", Boolean.toString(use));\n  }\n\n  /** Get whether to keep backup files. */\n\n  public final boolean getKeepBackupFiles()\n  {\n    return keepBackupFiles;\n  }\n\n  /** Set whether to keep backup files. */\n\n  public final void setKeepBackupFiles(boolean keep)\n  {\n    keepBackupFiles = keep;\n    properties.put(\"keepBackupFiles\", Boolean.toString(keep));\n  }\n\n  /** Get whether to use the compound move/scale/rotate tool as the default for mesh editing. */\n\n  public final boolean getUseCompoundMeshTool()\n  {\n    return useCompoundMeshTool;\n  }\n\n  /** Set whether to use the compound move/scale/rotate tool as the default for mesh editing. */\n\n  public final void setUseCompoundMeshTool(boolean use)\n  {\n    useCompoundMeshTool = use;\n    properties.put(\"useCompoundMeshTool\", Boolean.toString(use));\n  }\n\n  /** Get whether to reverse the direction of scroll wheel zooming. */\n\n  public final boolean getReverseZooming()\n  {\n    return reverseZooming;\n  }\n\n  /** Set whether to reverse the direction of scroll wheel zooming. */\n\n  public final void setReverseZooming(boolean reverse)\n  {\n    reverseZooming = reverse;\n    properties.put(\"reverseZooming\", Boolean.toString(reverse));\n  }\n}", "human_rating": 2.4156747732224, "metadata": {"project": "aoi", "class": "artofillusion.ApplicationPreferences", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/ApplicationPreferences.java", "label_probabilities": {"readability": [5.30556e-08, 0.416488, 0.582699, 0.000812561], "understandability": [9.84635e-09, 0.0698408, 0.929939, 0.000220625], "complexity": [2.56443e-13, 0.104801, 0.895198, 9.31582e-07], "modularization": [1.42926e-11, 0.353875, 0.645926, 0.000198905], "overall": [1.05354e-15, 0.292087, 0.707912, 8.54689e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.CreateCubeTool", "source": "/* Copyright (C) 1999-2008 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.animation.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\n\nimport java.awt.*;\n\n/** CreateCubeTool is an EditingTool used for creating Cube objects. */\n\npublic class CreateCubeTool extends EditingTool\n{\n  static int counter = 1;\n  private boolean shiftDown;\n  private Point clickPoint;\n  private ObjectInfo objInfo;\n  \n  public CreateCubeTool(LayoutWindow fr)\n  {\n    super(fr);\n    initButton(\"cube\");\n  }\n\n  public void activate()\n  {\n    super.activate();\n    theWindow.setHelpText(Translate.text(\"createCubeTool.helpText\"));\n  }\n\n  public int whichClicks()\n  {\n    return ALL_CLICKS;\n  }\n\n  public String getToolTipText()\n  {\n    return Translate.text(\"createCubeTool.tipText\");\n  }\n\n  public void mousePressed(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    clickPoint = e.getPoint();\n    shiftDown = e.isShiftDown();\n  }\n  \n  public void mouseDragged(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    if (objInfo == null)\n    {\n      // Create the cube.\n      \n      Scene theScene = ((LayoutWindow) theWindow).getScene();\n      objInfo = new ObjectInfo(new Cube(1.0, 1.0, 1.0), new CoordinateSystem(), \"Cube \"+(counter++));\n      objInfo.addTrack(new PositionTrack(objInfo), 0);\n      objInfo.addTrack(new RotationTrack(objInfo), 1);\n      UndoRecord undo = new UndoRecord(theWindow, false);\n      int sel[] = ((LayoutWindow) theWindow).getSelectedIndices();\n      ((LayoutWindow) theWindow).addObject(objInfo, undo);\n      undo.addCommand(UndoRecord.SET_SCENE_SELECTION, new Object [] {sel});\n      theWindow.setUndoRecord(undo);\n      ((LayoutWindow) theWindow).setSelection(theScene.getNumObjects()-1);\n    }\n    \n    // Determine the size and position for the cube.\n    \n    Scene theScene = ((LayoutWindow) theWindow).getScene();\n    Camera cam = view.getCamera();\n    Point dragPoint = e.getPoint();\n    Vec3 v1, v2, v3, orig, xdir, ydir, zdir;\n    double xsize, ysize, zsize;\n    \n    if (shiftDown)\n    {\n      if (Math.abs(dragPoint.x-clickPoint.x) > Math.abs(dragPoint.y-clickPoint.y))\n      {\n        if (dragPoint.y < clickPoint.y)\n          dragPoint.y = clickPoint.y - Math.abs(dragPoint.x-clickPoint.x);\n        else\n          dragPoint.y = clickPoint.y + Math.abs(dragPoint.x-clickPoint.x);\n      }\n      else\n      {\n        if (dragPoint.x < clickPoint.x)\n          dragPoint.x = clickPoint.x - Math.abs(dragPoint.y-clickPoint.y);\n        else\n          dragPoint.x = clickPoint.x + Math.abs(dragPoint.y-clickPoint.y);\n      }\n    }\n    v1 = cam.convertScreenToWorld(clickPoint, Camera.DEFAULT_DISTANCE_TO_SCREEN);\n    v2 = cam.convertScreenToWorld(new Point(dragPoint.x, clickPoint.y), Camera.DEFAULT_DISTANCE_TO_SCREEN);\n    v3 = cam.convertScreenToWorld(dragPoint, Camera.DEFAULT_DISTANCE_TO_SCREEN);\n    orig = v1.plus(v3).times(0.5);\n    if (dragPoint.x < clickPoint.x)\n      xdir = v1.minus(v2);\n    else\n      xdir = v2.minus(v1);\n    if (dragPoint.y < clickPoint.y)\n      ydir = v3.minus(v2);\n    else\n      ydir = v2.minus(v3);\n    xsize = xdir.length();\n    ysize = ydir.length();\n    xdir = xdir.times(1.0/xsize);\n    ydir = ydir.times(1.0/ysize);\n    zdir = xdir.cross(ydir);\n    zsize = Math.min(xsize, ysize);\n\n    // Update the size and position, and redraw the display.\n    \n    ((Cube) objInfo.getObject()).setSize(xsize, ysize, zsize);\n    objInfo.getCoords().setOrigin(orig);\n    objInfo.getCoords().setOrientation(zdir, ydir);\n    objInfo.clearCachedMeshes();\n    theWindow.setModified();\n    theWindow.updateImage();\n  }\n  \n  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    objInfo = null;\n  }\n}", "human_rating": 3.2414765400000034, "metadata": {"project": "aoi", "class": "artofillusion.CreateCubeTool", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/CreateCubeTool.java", "label_probabilities": {"readability": [0.248359, 0.744758, 0.00688327, 2.9169e-15], "understandability": [6.23696e-07, 0.00957817, 0.990363, 5.86593e-05], "complexity": [6.48054e-07, 0.969641, 0.0303566, 1.70608e-06], "modularization": [0.172267, 0.827733, 3.12427e-10, 0.0], "overall": [6.26927e-11, 0.160984, 0.839016, 6.86164e-09]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.CreateCylinderTool", "source": "/* Copyright (C) 1999-2008 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.animation.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\n\n/** CreateCylinderTool is an EditingTool used for creating Cylinder objects. */\n\npublic class CreateCylinderTool extends EditingTool\n{\n  static int counter = 1;\n  private boolean shiftDown;\n  private Point clickPoint;\n  private double ratio = 1.0;\n  private ObjectInfo objInfo;\n  \n  public CreateCylinderTool(LayoutWindow fr)\n  {\n    super(fr);\n    initButton(\"cylinder\");\n  }\n\n  public void activate()\n  {\n    super.activate();\n    theWindow.setHelpText(Translate.text(\"createCylinderTool.helpText\"));\n  }\n\n  public int whichClicks()\n  {\n    return ALL_CLICKS;\n  }\n\n  public String getToolTipText()\n  {\n    return Translate.text(\"createCylinderTool.tipText\");\n  }\n\n  public void mousePressed(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    clickPoint = e.getPoint();\n    shiftDown = e.isShiftDown();\n  }\n  \n  public void mouseDragged(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    if (objInfo == null)\n    {\n      // Create the cylinder.\n      \n      Scene theScene = ((LayoutWindow) theWindow).getScene();\n      objInfo = new ObjectInfo(new Cylinder(1.0, 1.0, 1.0, ratio), new CoordinateSystem(), \"Cylinder \"+(counter++));\n      objInfo.addTrack(new PositionTrack(objInfo), 0);\n      objInfo.addTrack(new RotationTrack(objInfo), 1);\n      UndoRecord undo = new UndoRecord(theWindow, false);\n      int sel[] = ((LayoutWindow) theWindow).getSelectedIndices();\n      ((LayoutWindow) theWindow).addObject(objInfo, undo);\n      undo.addCommand(UndoRecord.SET_SCENE_SELECTION, new Object [] {sel});\n      theWindow.setUndoRecord(undo);\n      ((LayoutWindow) theWindow).setSelection(theScene.getNumObjects()-1);\n    }\n    \n    // Determine the size and position for the cylinder.\n    \n    Camera cam = view.getCamera();\n    Point dragPoint = e.getPoint();\n    Vec3 v1, v2, v3, orig, xdir, ydir, zdir;\n    double xsize, ysize, zsize;\n    \n    if (shiftDown)\n    {\n      if (Math.abs(dragPoint.x-clickPoint.x) > Math.abs(dragPoint.y-clickPoint.y))\n      {\n        if (dragPoint.y < clickPoint.y)\n          dragPoint.y = clickPoint.y - Math.abs(dragPoint.x-clickPoint.x);\n        else\n          dragPoint.y = clickPoint.y + Math.abs(dragPoint.x-clickPoint.x);\n      }\n      else\n      {\n        if (dragPoint.x < clickPoint.x)\n          dragPoint.x = clickPoint.x - Math.abs(dragPoint.y-clickPoint.y);\n        else\n          dragPoint.x = clickPoint.x + Math.abs(dragPoint.y-clickPoint.y);\n      }\n    }\n    v1 = cam.convertScreenToWorld(clickPoint, Camera.DEFAULT_DISTANCE_TO_SCREEN);\n    v2 = cam.convertScreenToWorld(new Point(dragPoint.x, clickPoint.y), Camera.DEFAULT_DISTANCE_TO_SCREEN);\n    v3 = cam.convertScreenToWorld(dragPoint, Camera.DEFAULT_DISTANCE_TO_SCREEN);\n    orig = v1.plus(v3).times(0.5);\n    if (dragPoint.x < clickPoint.x)\n      xdir = v1.minus(v2);\n    else\n      xdir = v2.minus(v1);\n    if (dragPoint.y < clickPoint.y)\n      ydir = v3.minus(v2);\n    else\n      ydir = v2.minus(v3);\n    xsize = xdir.length();\n    ysize = ydir.length();\n    xdir = xdir.times(1.0/xsize);\n    ydir = ydir.times(1.0/ysize);\n    zdir = xdir.cross(ydir);\n    zsize = Math.min(xsize, ysize);\n\n    // Update the size and position, and redraw the display.\n    \n    ((Cylinder) objInfo.getObject()).setSize(xsize, ysize, zsize);\n    objInfo.getCoords().setOrigin(orig);\n    objInfo.getCoords().setOrientation(zdir, ydir);\n    objInfo.clearCachedMeshes();\n    theWindow.setModified();\n    theWindow.updateImage();\n  }\n  \n  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    objInfo = null;\n  }\n  \n  public void iconDoubleClicked()\n  {\n    ValueSlider ratioSlider = new ValueSlider(0.0, 1.0, 100, ratio);\n    ComponentsDialog dlg = new ComponentsDialog(theFrame, Translate.text(\"editCylinderTitle\"), \n\t\tnew Widget [] {ratioSlider}, new String [] {Translate.text(\"radiusRatio\")});\n    if (dlg.clickedOk())\n      ratio = ratioSlider.getValue();\n  }\n}", "human_rating": 3.7942749150600004, "metadata": {"project": "aoi", "class": "artofillusion.CreateCylinderTool", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/CreateCylinderTool.java", "label_probabilities": {"readability": [0.794363, 0.205552, 8.13138e-05, 4.28746e-06], "understandability": [0.0250775, 0.967531, 0.00422515, 0.00316647], "complexity": [0.000388572, 0.18772, 0.811891, 1.25376e-08], "modularization": [0.0, 1.48226e-07, 0.999404, 0.000596285], "overall": [1.34211e-05, 0.811055, 0.188931, 2.1468e-12]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.CreateVertexTool", "source": "/* Copyright (C) 2003-2007 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport java.awt.*;\n\n/** CreateVertexTool is an EditingTool used for adding vertices to triangle meshes. */\n\npublic class CreateVertexTool extends MeshEditingTool\n{\n  private Point clickPoint;\n  private Vec3 clickPos, constrainDir;\n  private int target;\n  private int vertexToMove;\n\n  public CreateVertexTool(EditingWindow fr, MeshEditController controller)\n  {\n    super(fr, controller);\n    initButton(\"createVertex\");\n  }\n\n  public void activate()\n  {\n    super.activate();\n    setHelpText();\n  }\n  \n  /**\n   * Set the help text based on the current selection mode.\n   */\n  \n  private void setHelpText()\n  {\n    int mode = controller.getSelectionMode();\n    if (mode == MeshEditController.POINT_MODE)\n      theWindow.setHelpText(Translate.text(\"createVertexTool.helpText.point\"));\n    else if (mode == MeshEditController.EDGE_MODE)\n      theWindow.setHelpText(Translate.text(\"createVertexTool.helpText.edge\"));\n    else\n      theWindow.setHelpText(Translate.text(\"createVertexTool.helpText.face\"));\n  }\n\n  public int whichClicks()\n  {\n    return ALL_CLICKS;\n  }\n\n  public String getToolTipText()\n  {\n    return Translate.text(\"createVertexTool.tipText\");\n  }\n\n  public void mousePressed(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    TriMeshViewer tmv = (TriMeshViewer) view;\n    TriangleMesh mesh = (TriangleMesh) controller.getObject().getObject();\n    MeshVertex vert[] = mesh.getVertices();\n    int mode = controller.getSelectionMode();\n    Vec3 uvw = new Vec3();\n\n    clickPoint = e.getPoint();\n    target = tmv.findClickTarget(clickPoint, uvw);\n    if (target == -1)\n      return;\n    theWindow.setUndoRecord(new UndoRecord(theWindow, false, UndoRecord.COPY_OBJECT, new Object [] {mesh, mesh.duplicate()}));\n    if (mode == MeshEditController.POINT_MODE)\n    {\n      // Create a new vertex if this is a boundary vertex.  Otherwise, just move it.\n      \n      constrainDir = mesh.getNormals()[target];\n      if (createBoundaryVertex(mesh))\n      {\n        vertexToMove = mesh.getVertices().length-1;\n        controller.setMesh(mesh);\n        controller.objectChanged();\n        theWindow.updateImage();\n        theWindow.updateMenus();\n      }\n      else\n        vertexToMove = target;\n      clickPos = mesh.getVertices()[vertexToMove].r;\n    }\n    else\n    {\n      boolean[] split;\n      TriangleMesh newmesh = null;\n      if (mode == MeshEditController.EDGE_MODE)\n      {\n        // Subdivide an edge.\n        \n        TriangleMesh.Edge edge[] = mesh.getEdges();\n        Vec3 v1 = vert[edge[target].v1].r;\n        Vec3 v2 = vert[edge[target].v2].r;\n        clickPos = v1.times(uvw.x).plus(v2.times(uvw.y));\n        split = new boolean[edge.length];\n        split[target] = true;\n        newmesh = TriangleMesh.subdivideLinear(mesh, split);\n        constrainDir = v1.minus(v2);\n        constrainDir.normalize();\n      }\n      else if (mode == MeshEditController.FACE_MODE)\n      {\n        // Subdivide a face.\n        \n        TriangleMesh.Face face[] = mesh.getFaces();\n        Vec3 v1 = vert[face[target].v1].r;\n        Vec3 v2 = vert[face[target].v2].r;\n        Vec3 v3 = vert[face[target].v3].r;\n        clickPos = v1.times(uvw.x).plus(v2.times(uvw.y)).plus(v3.times(uvw.z));\n        split = new boolean[face.length];\n        split[target] = true;\n        newmesh = TriangleMesh.subdivideFaces(mesh, split);\n        constrainDir = v1.minus(v2).cross(v3.minus(v2));\n        constrainDir.normalize();\n      }\n      vertexToMove = newmesh.getVertices().length-1;\n      newmesh.getVertices()[vertexToMove].r.set(clickPos);\n      mesh.copyObject(newmesh);\n      controller.setMesh(mesh);\n      controller.objectChanged();\n      theWindow.updateImage();\n      theWindow.updateMenus();\n    }\n  }\n  \n  public void mouseDragged(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    if (target == -1)\n      return;\n    TriMeshViewer tmv = (TriMeshViewer) view;\n    TriangleMesh mesh = (TriangleMesh) controller.getObject().getObject();\n    Point dragPoint = e.getPoint();\n    Vec3 v[], drag;\n    int dx, dy;\n\n    dx = dragPoint.x - clickPoint.x;\n    dy = dragPoint.y - clickPoint.y;\n    drag = findDragVector(dx, dy, tmv, e.isShiftDown());\n    v = findDraggedPositions(mesh, drag);\n    mesh.setVertexPositions(v);\n    controller.objectChanged();\n    theWindow.updateImage();\n  }\n\n  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    if (target == -1)\n      return;\n    TriMeshViewer tmv = (TriMeshViewer) view;\n    Object3D meshobj = controller.getObject().getObject();\n    TriangleMesh mesh = (TriangleMesh) meshobj;\n    Point dragPoint = e.getPoint();\n    int dx, dy;\n    Vec3 v[], drag;\n\n    dx = dragPoint.x - clickPoint.x;\n    dy = dragPoint.y - clickPoint.y;\n    drag = findDragVector(dx, dy, tmv, e.isShiftDown());\n    v = findDraggedPositions(mesh, drag);\n\n    mesh.setVertexPositions(v);\n    controller.objectChanged();\n    theWindow.updateImage();\n    setHelpText();\n  }\n  \n  /**\n   * Return the new positions of every vertex.\n   */\n  \n  private Vec3 [] findDraggedPositions(TriangleMesh mesh, Vec3 drag)\n  {\n    MeshVertex vert[] = mesh.getVertices();\n    Vec3 pos[] = new Vec3 [vert.length];\n\n    for (int i = 0; i < pos.length; i++)\n      pos[i] = vert[i].r;\n    pos[vertexToMove] = clickPos.plus(drag);\n    return pos;\n  }\n  \n  /**\n   * Find the displacement vector for the vertex being dragged.\n   */\n  \n  private Vec3 findDragVector(int dx, int dy, TriMeshViewer view, boolean constrain)\n  {\n    Vec3 drag = view.getCamera().findDragVector(clickPos, dx, dy);\n    if (constrain)\n    {\n      if (controller.getSelectionMode() == MeshEditController.EDGE_MODE)\n        drag = constrainDir.times(drag.dot(constrainDir));\n      else\n        drag.subtract(constrainDir.times(drag.dot(constrainDir)));\n    }\n    return drag;\n  }\n\n  /**\n   * Try to create a new vertex when a boundary vertex is dragged.  Returns true if a new vertex was\n   * created, false otherwise.\n   */\n  \n  private boolean createBoundaryVertex(TriangleMesh mesh)\n  {\n    TriangleMesh.Vertex vert[] = (TriangleMesh.Vertex []) mesh.getVertices();\n    TriangleMesh.Vertex v = (TriangleMesh.Vertex) vert[target];\n    TriangleMesh.Edge edge[] = mesh.getEdges();\n    TriangleMesh.Face face[] = mesh.getFaces();\n    int vertEdge[] = v.getEdges();\n\n    if (edge[vertEdge[0]].f2 != -1)\n      return false;\n    theWindow.setUndoRecord(new UndoRecord(theWindow, false, UndoRecord.COPY_OBJECT, new Object [] {mesh, mesh.duplicate()}));\n\n    // Create a new vertex and two new faces.\n    \n    TriangleMesh.Vertex newvert[] = new TriangleMesh.Vertex [vert.length+1];\n    int newface[][] = new int [face.length+2][];\n    for (int i = 0; i < vert.length; i++)\n      newvert[i] = vert[i];\n    newvert[vert.length] = mesh.new Vertex(v);\n    for (int i = 0; i < face.length; i++)\n      newface[i] = new int [] {face[i].v1, face[i].v2, face[i].v3};\n    TriangleMesh.Edge e = edge[vertEdge[0]];\n    TriangleMesh.Face f = face[e.f1];\n    int oldFace1 = e.f1;\n    if ((f.v1 == e.v1 && f.v2 == e.v2) || (f.v2 == e.v1 && f.v3 == e.v2) || (f.v3 == e.v1 && f.v1 == e.v2))\n      newface[face.length] = new int [] {e.v2, e.v1, vert.length};\n    else\n      newface[face.length] = new int [] {e.v1, e.v2, vert.length};\n    e = edge[vertEdge[vertEdge.length-1]];\n    f = face[e.f1];\n    int oldFace2 = e.f1;\n    if ((f.v1 == e.v1 && f.v2 == e.v2) || (f.v2 == e.v1 && f.v3 == e.v2) || (f.v3 == e.v1 && f.v1 == e.v2))\n      newface[face.length+1] = new int [] {e.v2, e.v1, vert.length};\n    else\n      newface[face.length+1] = new int [] {e.v1, e.v2, vert.length};\n    mesh.setShape(newvert, newface);\n    \n    // Copy over the edge smoothness values.\n    \n    TriangleMesh.Edge newedge[] = mesh.getEdges();\n    for (int i = 0; i < newedge.length; i++)\n      for (int j = 0; j < edge.length; j++)\n        if ((newedge[i].v1 == edge[j].v1 && newedge[i].v2 == edge[j].v2) || (newedge[i].v1 == edge[j].v2 && newedge[i].v2 == edge[j].v1))\n          newedge[i].smoothness = edge[j].smoothness;\n    \n    // Update the parameter values.\n    \n    TextureParameter param[] = mesh.getParameters();\n    ParameterValue paramValue[] = mesh.getParameterValues();\n    for (int i = 0; i < paramValue.length; i++)\n    {\n      if (paramValue[i] instanceof VertexParameterValue)\n      {\n        double val[] = ((VertexParameterValue) paramValue[i]).getValue();\n        double newval[] = new double [newvert.length];\n        System.arraycopy(val, 0, newval, 0, val.length);\n        newval[val.length] = val[target];\n        ((VertexParameterValue) paramValue[i]).setValue(newval);\n      }\n      if (paramValue[i] instanceof FaceParameterValue)\n      {\n        double val[] = ((FaceParameterValue) paramValue[i]).getValue();\n        double newval[] = new double [newface.length];\n        System.arraycopy(val, 0, newval, 0, val.length);\n        newval[val.length] = val[oldFace1];\n        newval[val.length+1] = val[oldFace2];\n        ((FaceParameterValue) paramValue[i]).setValue(newval);\n      }\n      if (paramValue[i] instanceof FaceVertexParameterValue)\n      {\n        FaceVertexParameterValue fvpv = (FaceVertexParameterValue) paramValue[i];\n        double newval[][] = new double [newface.length][3];\n        for (int index = 0; index < newval.length; index++)\n        {\n          newval[index][0] = fvpv.getValue(index, 0);\n          newval[index][1] = fvpv.getValue(index, 1);\n          newval[index][2] = fvpv.getValue(index, 2);\n        }\n        newval[face.length][0] = newval[face.length][1] = newval[face.length][2] = param[i].defaultVal;\n        newval[face.length+1][0] = newval[face.length+1][1] = newval[face.length+1][2] = param[i].defaultVal;\n        fvpv.setValue(newval);\n      }\n    }\n    return true;\n  }\n}", "human_rating": 2.8761471948, "metadata": {"project": "aoi", "class": "artofillusion.CreateVertexTool", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/CreateVertexTool.java", "label_probabilities": {"readability": [1.7711e-05, 0.876129, 0.123836, 1.73508e-05], "understandability": [1.38549e-08, 0.0165304, 0.981572, 0.00189809], "complexity": [0.935294, 0.0647059, 2.61807e-09, 0.0], "modularization": [0.16838, 0.814475, 0.0171431, 2.33585e-06], "overall": [0.0, 0.0036873, 0.0400825, 0.95623]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.CurveViewer", "source": "/* Copyright (C) 1999-2006 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\n\n/** The CurveViewer class is a component which displays a Curve object and \n    allows the user to edit it. */\n\npublic class CurveViewer extends MeshViewer\n{\n  boolean draggingSelectionBox, dragging;\n  int deselect;\n\n  public CurveViewer(MeshEditController window, RowContainer p)\n  {\n    super(window, p);\n  }\n\n  protected void drawObject()\n  {\n    if (!showMesh)\n      return;\n    MeshVertex v[] = ((Mesh) getController().getObject().getObject()).getVertices();\n    boolean selected[] = controller.getSelection();\n    WireframeMesh wireframe = getController().getObject().getObject().getWireframeMesh();\n    for (int i = 0; i < wireframe.from.length; i++)\n      renderLine(wireframe.vert[wireframe.from[i]], wireframe.vert[wireframe.to[i]], theCamera, lineColor);\n    for (int i = 0; i < v.length; i++)\n      if (!selected[i] && theCamera.getObjectToView().timesZ(v[i].r) > theCamera.getClipDistance())\n        {\n          Vec2 p = theCamera.getObjectToScreen().timesXY(v[i].r);\n          double z = theCamera.getObjectToView().timesZ(v[i].r);\n          renderBox(((int) p.x) - HANDLE_SIZE/2, ((int) p.y) - HANDLE_SIZE/2, HANDLE_SIZE, HANDLE_SIZE, z, lineColor);\n        }\n    Color col = (currentTool.hilightSelection() ? highlightColor : lineColor);\n    for (int i = 0; i < v.length; i++)\n      if (selected[i] && theCamera.getObjectToView().timesZ(v[i].r) > theCamera.getClipDistance())\n        {\n          Vec2 p = theCamera.getObjectToScreen().timesXY(v[i].r);\n          double z = theCamera.getObjectToView().timesZ(v[i].r);\n          renderBox(((int) p.x) - HANDLE_SIZE/2, ((int) p.y) - HANDLE_SIZE/2, HANDLE_SIZE, HANDLE_SIZE, z, col);\n        }\n  }\n\n  /** When the user presses the mouse, forward events to the current tool as appropriate.\n      If this is a vertex based tool, allow them to select or deselect vertices. */\n\n  protected void mousePressed(WidgetMouseEvent e)\n  {\n    int i, j, x, y;\n    double z, nearest;\n    MeshVertex v[] = ((Curve) getController().getObject().getObject()).getVertices();\n    Vec2 pos;\n    Point p;\n\n    requestFocus();\n    sentClick = false;\n    deselect = -1;\n    dragging = false;\n    clickPoint = e.getPoint();\n    \n    // Determine which tool is active.\n    \n    if (metaTool != null && e.isMetaDown())\n      activeTool = metaTool;\n    else if (altTool != null && e.isAltDown())\n      activeTool = altTool;\n    else\n      activeTool = currentTool;\n\n    // If the current tool wants all clicks, just forward the event and return.\n\n    if ((activeTool.whichClicks() & EditingTool.ALL_CLICKS) != 0)\n      {\n        activeTool.mousePressed(e, this);\n        dragging = true;\n        sentClick = true;\n      }\n    boolean allowSelectionChange = activeTool.allowSelectionChanges();\n    boolean wantHandleClicks = ((activeTool.whichClicks() & EditingTool.HANDLE_CLICKS) != 0);\n    if (!allowSelectionChange && !wantHandleClicks)\n      return;\n\n    // See whether the click was on a currently selected vertex.\n    \n    p = e.getPoint();\n    boolean selected[] = controller.getSelection();\n    for (i = 0; i < v.length; i++)\n      if (selected[i])\n        {\n          pos = theCamera.getObjectToScreen().timesXY(v[i].r);\n          x = (int) pos.x;\n          y = (int) pos.y;\n          if (x >= p.x-HANDLE_SIZE/2 && x <= p.x+HANDLE_SIZE/2 && y >= p.y-HANDLE_SIZE/2 && y <= p.y+HANDLE_SIZE/2)\n            break;\n        }\n    if (i < v.length)\n      {\n        // The click was on a selected vertex.  If it was a shift-click, the user may want\n        // to deselect it, so set a flag.  Forward the event to the current tool.\n        \n        if (e.isShiftDown() && allowSelectionChange)\n          deselect = i;\n        if (wantHandleClicks)\n        {\n          activeTool.mousePressedOnHandle(e, this, 0, i);\n          sentClick = true;\n        }\n        return;\n      }\n\n    // The click was not on a selected vertex.  See whether it was on an unselected one.\n    // If so, select it and send an event to the current tool.\n    \n    j = -1;\n    nearest = Double.MAX_VALUE;\n    for (i = 0; i < v.length; i++)\n      {\n        pos = theCamera.getObjectToScreen().timesXY(v[i].r);\n        x = (int) pos.x;\n        y = (int) pos.y;\n        if (x >= p.x-HANDLE_SIZE/2 && x <= p.x+HANDLE_SIZE/2 && y >= p.y-HANDLE_SIZE/2 && y <= p.y+HANDLE_SIZE/2)\n          {\n            z = theCamera.getObjectToView().timesZ(v[i].r);\n            if (z > 0.0 && z < nearest)\n              {\n                nearest = z;\n                j = i;\n              }\n          }\n      }\n    if (j > -1)\n      {\n        if (allowSelectionChange)\n        {\n          boolean oldSelection[] = (boolean []) selected.clone();\n          if (!e.isShiftDown())\n            for (i = 0; i < selected.length; i++)\n              selected[i] = false;\n          selected[j] = true;\n          ((CurveEditorWindow) controller).findSelectionDistance();\n          currentTool.getWindow().setUndoRecord(new UndoRecord(currentTool.getWindow(), false, UndoRecord.SET_MESH_SELECTION, new Object [] {controller, new Integer(controller.getSelectionMode()), oldSelection}));\n          controller.setSelection(selected);\n          activeTool.getWindow().updateMenus();\n        }\n        if (e.isShiftDown())\n          repaint();\n        else if (wantHandleClicks)\n        {\n          activeTool.mousePressedOnHandle(e, this, 0, j);\n          sentClick = true;\n        }\n        return;\n      }\n    \n    // The click was not on a handle.  Start dragging a selection box.\n\n    if (allowSelectionChange)\n    {\n      draggingSelectionBox = true;\n      beginDraggingSelection(p, false);\n    }\n  }\n\n  protected void mouseDragged(WidgetMouseEvent e)\n  {\n    if (!dragging)\n      {\n        Point p = e.getPoint();\n        if (Math.abs(p.x-clickPoint.x) < 2 && Math.abs(p.y-clickPoint.y) < 2)\n          return;\n      }\n    dragging = true;\n    deselect = -1;\n    super.mouseDragged(e);\n  }\n\n  protected void mouseReleased(WidgetMouseEvent e)\n  {\n    int i, x, y;\n    MeshVertex v[] = ((Curve) getController().getObject().getObject()).getVertices();\n    Vec2 pos;\n\n    moveToGrid(e);\n    endDraggingSelection();\n    boolean selected[] = controller.getSelection();\n    boolean oldSelection[] = (boolean []) selected.clone();\n    if (draggingSelectionBox && !e.isShiftDown() && !e.isControlDown())\n      for (i = 0; i < selected.length; i++)\n        selected[i] = false;\n\n    // If the user was dragging a selection box, then select or deselect anything \n    // it intersects.\n    \n    if (selectBounds != null)\n      {\n        boolean newsel = !e.isControlDown();\n        for (i = 0; i < v.length; i++)\n          {\n            pos = theCamera.getObjectToScreen().timesXY(v[i].r);\n            x = (int) pos.x;\n            y = (int) pos.y;\n            if (selectionRegionContains(new Point(x, y)))\n              selected[i] = newsel;\n          }\n      }\n    draggingBox = draggingSelectionBox = false;\n\n    // Send the event to the current tool, if appropriate.\n\n    if (sentClick)\n      {\n        if (!dragging)\n          {\n            Point p = e.getPoint();\n            e.translatePoint(clickPoint.x-p.x, clickPoint.y-p.y);\n          }\n        activeTool.mouseReleased(e, this);\n      }\n\n    // If the user shift-clicked a selected point and released the mouse without dragging,\n    // then deselect the point.\n\n    if (deselect > -1)\n      selected[deselect] = false;\n    ((CurveEditorWindow) controller).findSelectionDistance();\n    for (int k = 0; k < selected.length; k++)\n      if (selected[k] != oldSelection[k])\n      {\n        currentTool.getWindow().setUndoRecord(new UndoRecord(currentTool.getWindow(), false, UndoRecord.SET_MESH_SELECTION, new Object [] {controller, new Integer(controller.getSelectionMode()), oldSelection}));\n        break;\n      }\n    controller.setSelection(selected);\n    activeTool.getWindow().updateMenus();\n  }\n}\n", "human_rating": 2.1999363833808, "metadata": {"project": "aoi", "class": "artofillusion.CurveViewer", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/CurveViewer.java", "label_probabilities": {"readability": [1.65952e-08, 0.200801, 0.798334, 0.000865317], "understandability": [3.32222e-09, 0.0799565, 0.906221, 0.0138226], "complexity": [0.958833, 0.0411671, 7.18828e-09, 0.0], "modularization": [6.93393e-07, 0.978544, 0.0214554, 6.87501e-12], "overall": [0.0, 0.0277433, 0.68544, 0.286817]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.image.ImageOrColor", "source": "/* Copyright (C) 2000-2004 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.image;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.io.*;\nimport java.util.Vector;\n\n/** ImageOrColor represents a color which can potentially vary with position.  It provides a \n    Widget with which the user can edit it.  They can choose either a single color, or an \n    ImageMap which is then multiplied by a user specified color. */\n\npublic class ImageOrColor\n{\n  private ImageMap map;\n  private RGBColor color;\n  \n  public ImageOrColor(RGBColor theColor)\n  {\n    color = theColor.duplicate();\n  }\n  \n  public ImageOrColor(RGBColor scaleColor, ImageMap theMap)\n  {\n    color = scaleColor.duplicate();\n    map = theMap;\n  }\n  \n  /** Get the image, or null if it is a single color. */\n  \n  public ImageMap getImage()\n  {\n    return map;\n  }\n\n  /** Get the color by which the image is multiplied. */\n  \n  public RGBColor getColor()\n  {\n    return color;\n  }  \n  \n  /** Given a texture coordinate (x and y each between 0 and 1), return the average color of\n      a region of width (xsize, ysize) centered at that location.  wrapx and wrapy specify \n      whether, for purposes of interpolation, the image should be treated as wrapping around \n      so that opposite edges touch each other. */\n  \n  public void getColor(RGBColor theColor, boolean wrapx, boolean wrapy, double x, double y, double xsize, double ysize)\n  {\n    if (map == null)\n      theColor.copy(color);\n    else\n      {\n\tmap.getColor(theColor, wrapx, wrapy, x, y, xsize, ysize);\n\ttheColor.multiply(color);\n      }\n  }\n\n  /** Return the average color over the entire image. */\n  \n  public void getAverageColor(RGBColor theColor)\n  {\n    if (map == null)\n      theColor.copy(color);\n    else\n      {\n\ttheColor.setRGB(map.getAverageComponent(0), map.getAverageComponent(1), map.getAverageComponent(2));\n\ttheColor.multiply(color);\n      }\n  }\n  \n  /** Create a duplicate of this object. */\n  \n  public ImageOrColor duplicate()\n  {\n    ImageOrColor copy = new ImageOrColor(color);\n    \n    copy.map = map;\n    return copy;\n  }\n  \n  /** Make this object identical to another one. */\n  \n  public void copy(ImageOrColor obj)\n  {\n    map = obj.map;\n    color.copy(obj.color);\n  }\n\n  /** The following two methods are used for reading and writing files.  The first is a\n      constructor which reads the necessary data from an input stream.  The other writes\n      the object's representation to an output stream. */\n  \n  public ImageOrColor(DataInputStream in, Scene theScene) throws IOException\n  {\n    int index = in.readInt();\n    \n    if (index > -1)\n      map = theScene.getImage(index);\n    color = new RGBColor(in);\n  }\n  \n  public void writeToFile(DataOutputStream out, Scene theScene) throws IOException\n  {\n    if (map == null)\n      out.writeInt(-1);\n    else\n      out.writeInt(theScene.indexOf(map));\n    color.writeToFile(out);\n  }\n\n  /** Get a Widget with which the user can edit the color.  This Widget will send out\n      ValueChangedEvents whenever the color changes.\n      @param parent    a parent BFrame which can be used for displaying dialogs\n      @param theScene  the Scene from which to get images\n  */\n  \n  public Widget getEditingPanel(final BFrame parent, final Scene theScene)\n  {\n    final RowContainer row = new RowContainer();\n    final CustomWidget preview = new CustomWidget();\n    preview.setPreferredSize(new Dimension(ImageMap.PREVIEW_WIDTH, ImageMap.PREVIEW_HEIGHT));\n    preview.addEventLink(RepaintEvent.class, new Object() {\n      void processEvent(RepaintEvent ev)\n      {\n        Graphics2D g = ev.getGraphics();\n        if (map != null)\n          g.drawImage(map.getPreview(), 0, 0, null);\n        else\n          g.drawRect(1, 1, ImageMap.PREVIEW_WIDTH-2, ImageMap.PREVIEW_HEIGHT-2);\n      }\n    });\n    preview.addEventLink(MouseClickedEvent.class, new Object() {\n      void processEvent(MouseClickedEvent ev)\n      {\n        ImagesDialog dlg = new ImagesDialog(parent, theScene, map);\n        map = dlg.getSelection();\n        preview.repaint();\n        row.dispatchEvent(new ValueChangedEvent(row));\n      }\n    });\n    final Widget colorPatch = color.getSample(ImageMap.PREVIEW_WIDTH, ImageMap.PREVIEW_HEIGHT);\n    colorPatch.addEventLink(MouseClickedEvent.class, new Object() {\n      void processEvent(MouseClickedEvent ev)\n      {\n        new ColorChooser(parent, Translate.text(\"Color\"), color);\n        colorPatch.setBackground(color.getColor());\n        colorPatch.repaint();\n        row.dispatchEvent(new ValueChangedEvent(row));\n      }\n    });\n    row.add(preview);\n    row.add(colorPatch);\n    return row;\n  }\n}", "human_rating": 3.9874091, "metadata": {"project": "aoi", "class": "artofillusion.image.ImageOrColor", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/image/ImageOrColor.java", "label_probabilities": {"readability": [0.98741, 0.0125897, 1.001e-17, 0.0], "understandability": [3.80228e-05, 0.98222, 0.0177424, 4.596e-17], "complexity": [5.54e-18, 0.00287127, 0.997122, 6.96728e-06], "modularization": [7.627e-16, 0.00180606, 0.998192, 2.09368e-06], "overall": [0.00057048, 0.992867, 0.00656229, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.image.ImageSaver", "source": "/* Copyright (C) 1999-2011 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.image;\n\nimport artofillusion.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport ch.randelshofer.media.quicktime.*;\n\nimport java.awt.*;\nimport java.awt.image.*;\nimport java.io.*;\nimport java.text.*;\nimport javax.imageio.*;\nimport javax.imageio.stream.*;\n\n/** This class is used to save rendered images to disk. */\n\npublic class ImageSaver\n{\n  private int format, index;\n  private String name, directory;\n  private boolean ok, premultiply;\n  private double quality;\n  private BFrame parent;\n  private QuickTimeWriter qt;\n\n  public static final int FORMAT_JPEG = 0;\n  public static final int FORMAT_TIFF = 1;\n  public static final int FORMAT_PNG = 2;\n  public static final int FORMAT_BMP = 3;\n  public static final int FORMAT_HDR = 4;\n  public static final int FORMAT_QUICKTIME = 5;\n  \n  private static final String FORMAT_NAME[] = new String [] {\n    \"JPEG\", \"TIFF\", \"PNG\", \"BMP\", \"HDR\", \"Quicktime\"\n  };\n  private static final String FORMAT_EXTENSION[] = new String [] {\n    \"jpg\", \"tif\", \"png\", \"bmp\", \"hdr\", \"mov\"\n  };\n  \n  private static boolean premultiplyDefault = true;\n  private static double qualityDefault = 90.0;\n  private static int lastImageFormat = FORMAT_JPEG;\n  private static int lastMovieFormat = FORMAT_QUICKTIME;\n  \n  /** Create an ImageSaver object which will be used for saving a single images.\n      The constructor displays a dialog in which the user can select the name, location,\n      and format.  The saveImage() method can then be used to save individual frames of the\n      animation.  Use clickedOk() to determine whether the user clicked the OK or Cancel\n      button. */\n\n  public ImageSaver(BFrame parent)\n  {\n    init(parent, Integer.MIN_VALUE);\n  }\n\n  /** Create an ImageSaver object which will be used for saving an animation.\n      The constructor displays a dialog in which the user can select the name, location,\n      and format.  The saveImage() method can then be used to save individual frames of the\n      animation, and lastMovieImage() should be called once all frames have been saved.\n      Use clickedOk() to determine whether the user clicked the OK or Cancel button.\n      @param parent             the parent window\n      @param width              the image width, in pixels\n      @param height             the image height, in pixels\n      @param fps                the number of frames per second\n      @param startFrameNumber   the default number for the first frame of the animation\n  */\n\n  public ImageSaver(BFrame parent, int width, int height, int fps, int startFrameNumber) throws IOException\n  {\n    init(parent, startFrameNumber);\n    if (format == FORMAT_QUICKTIME && this.clickedOk())\n    {\n      qt = new QuickTimeWriter(new File(directory, name));\n      qt.addVideoTrack(QuickTimeWriter.VideoFormat.JPG, fps, width, height);\n      qt.setCompressionQuality(0, (float) quality*0.01f);\n    }\n  }\n\n  /** Initialize the ImageSaver and display the dialog.\n      @param parent             the parent window\n      @param startFrameNumber   the default number for the first frame of an animation, or Integer.MIN_VALUE for a single image\n  */\n\n  private void init(BFrame parent, int startFrameNumber)\n  {\n    this.parent = parent;\n    boolean animate = (startFrameNumber != Integer.MIN_VALUE);\n    index = startFrameNumber;\n\n    final BComboBox formatChoice = new BComboBox();\n    for (int i = 0; i < FORMAT_NAME.length; i++)\n      formatChoice.add(FORMAT_NAME[i]);\n    formatChoice.setSelectedValue(FORMAT_NAME[animate ? lastMovieFormat : lastImageFormat]);\n    BCheckBox premultBox = new BCheckBox(\"Premultiply Transparency\", premultiplyDefault);\n    final ValueSlider qualitySlider = new ValueSlider(0.0, 100.0, 100, qualityDefault);\n    final OverlayContainer optionsPanel = new OverlayContainer();\n    final RowContainer startFramePanel = new RowContainer();\n    ValueField numberFromField = new ValueField(startFrameNumber, ValueField.INTEGER);\n    formatChoice.addEventLink(ValueChangedEvent.class, new Object() {\n      void processEvent()\n      {\n        Object value = formatChoice.getSelectedValue();\n        if (FORMAT_NAME[FORMAT_JPEG].equals(value) || FORMAT_NAME[FORMAT_QUICKTIME].equals(value))\n          optionsPanel.setVisibleChild(0);\n        else if (FORMAT_NAME[FORMAT_TIFF].equals(value))\n          optionsPanel.setVisibleChild(1);\n        else\n          optionsPanel.setVisibleChild(2);\n        startFramePanel.setVisible(!FORMAT_NAME[FORMAT_QUICKTIME].equals(value));\n      }\n    });\n    FormContainer mainPanel = new FormContainer(1, 3);\n    mainPanel.add(formatChoice, 0, 0, new LayoutInfo());\n    mainPanel.add(optionsPanel, 0, 1);\n    if (animate)\n      mainPanel.add(startFramePanel, 0, 2);\n    RowContainer jpegRow = new RowContainer();\n    jpegRow.add(Translate.label(\"Quality\"));\n    jpegRow.add(qualitySlider);\n    optionsPanel.add(jpegRow, 0);\n    optionsPanel.add(premultBox, 1);\n    optionsPanel.add(new BLabel(), 2);\n    premultBox.setEnabled(true);\n    startFramePanel.add(Translate.label(\"numberFramesFrom\"));\n    startFramePanel.add(numberFromField);\n    formatChoice.dispatchEvent(new ValueChangedEvent(formatChoice));\n    PanelDialog dlg = new PanelDialog(parent, Translate.text(\"selectFileFormat\"), mainPanel);\n    if (dlg.clickedOk())\n    {\n      premultiply = premultiplyDefault = premultBox.getState();\n      quality = qualityDefault = qualitySlider.getValue();\n      Object formatValue = formatChoice.getSelectedValue();\n      for (int i = 0; i < FORMAT_NAME.length; i++)\n        if (FORMAT_NAME[i].equals(formatValue))\n          format = i;\n      if (animate)\n        lastMovieFormat = format;\n      else\n        lastImageFormat = format;\n      index = (int) numberFromField.getValue();\n      BFileChooser fc = new BFileChooser(BFileChooser.SAVE_FILE, Translate.text(\"saveImage\"));\n      String filename = \"Untitled.\"+FORMAT_EXTENSION[format];\n      File file = (ArtOfIllusion.getCurrentDirectory() == null ? new File(filename) : new File(ArtOfIllusion.getCurrentDirectory(), filename));\n      fc.setSelectedFile(file);\n      ok = fc.showDialog(parent);\n      if (ok)\n      {\n        file = fc.getSelectedFile();\n        name = file.getName();\n        directory = file.getParentFile().getAbsolutePath();\n        if (file.isFile())\n        {\n          String options[] = new String [] {Translate.text(\"Yes\"), Translate.text(\"No\")};\n          int choice = new BStandardDialog(\"\", Translate.text(\"overwriteFile\", file.getName()), BStandardDialog.QUESTION).showOptionDialog(parent, options, options[1]);\n          if (choice == 1)\n            ok = false;\n        }\n      }\n    }\n  }\n\n  /** Determine whether the user canceled saving the image. */\n  \n  public boolean clickedOk()\n  {\n    return ok;\n  }\n  \n  /** Save the next image to disk.  Returns false if an error occurs.*/\n  \n  public boolean saveImage(Image im) throws IOException\n  {\n    return saveImage(new ComplexImage(im));\n  }\n  \n  /** Save the next image to disk.  Returns false if an error occurs.*/\n  \n  public boolean saveImage(ComplexImage img) throws IOException\n  {\n    String filename = name;\n    if (qt != null)\n    {\n      BufferedImage buffer = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_RGB);\n      Graphics2D g = buffer.createGraphics();\n      g.drawImage(img.getImage(), 0, 0, parent.getComponent());\n      g.dispose();\n      qt.writeFrame(0, buffer, 1);\n      return true;\n    }\n    if (index != Integer.MIN_VALUE)\n    {\n      // Insert the image number into the filename.\n      \n      NumberFormat nf = NumberFormat.getNumberInstance();\n      nf.setMinimumIntegerDigits(4);\n      nf.setGroupingUsed(false);\n      int i = name.lastIndexOf('.');\n      if (i == -1 || i == (name.length()-1))\n        filename += nf.format(index++);\n      else\n        filename = name.substring(0, i)+nf.format(index++)+name.substring(i);\n    }\n    try\n    {\n      if (format == FORMAT_TIFF && premultiply)\n        img = new ComplexImage(premultiplyTransparency(img.getImage()));\n      return saveImage(img, new File(directory, filename), format, (int) quality);\n    }\n    catch (Exception ex)\n    {\n      ex.printStackTrace();\n      new BStandardDialog(\"\", Translate.text(\"errorSavingFile\", ex.getMessage() == null ? \"\" : ex.getMessage()), BStandardDialog.ERROR).showMessageDialog(parent);\n    }\n    return false;\n  }\n  \n  /** Save an image to disk in the specified format.  Returns true if the image was\n      successfully saved, false if an error occurred.  For JPEG, quality should be\n      between 0 and 100.  For other formats, it is ignored. */\n  \n  public static boolean saveImage(Image im, File f, int format, int quality) throws IOException, InterruptedException\n  {\n    return saveImage(new ComplexImage(im), f, format, quality);\n  }\n  \n  /** Save an image to disk in the specified format.  Returns true if the image was\n      successfully saved, false if an error occurred.  For JPEG, quality should be\n      between 0 and 100.  For other formats, it is ignored. */\n  \n  public static boolean saveImage(ComplexImage img, File f, int format, int quality) throws IOException, InterruptedException\n  {\n    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));\n    Image im = img.getImage();\n\n    if (format == FORMAT_JPEG)\n    {\n      im = premultiplyTransparency(im);\n      writeJpegToStream(im, bos, quality);\n      bos.close();\n      return true;\n    }\n    if (format == FORMAT_TIFF)\n    {\n      DataOutputStream dos = new DataOutputStream(bos);\n      TIFFEncoder tiff = new TIFFEncoder(im);\n      tiff.writeImage(dos);\n      dos.close();\n      return true;\n    }\n    if (format == FORMAT_PNG)\n    {\n      ImageIO.write(getBufferedImage(im, true), \"png\", bos);\n      bos.close();\n      return true;\n    }\n    if (format == FORMAT_BMP)\n    {\n      im = premultiplyTransparency(im);\n      DataOutputStream dos = new DataOutputStream(bos);\n      BMPEncoder bmp = new BMPEncoder(im);\n      bmp.writeImage(dos);\n      dos.close();\n      return true;\n    }\n    if (format == FORMAT_HDR)\n    {\n      HDREncoder.writeImage(img, bos);\n      bos.close();\n      return true;\n    }\n    bos.close();\n    return false;\n  }\n\n  /**\n   * Write an image to a stream in JPEG format.\n   */\n\n  private static void writeJpegToStream(Image im, OutputStream out, int quality) throws IOException\n  {\n    ImageWriter writer = (ImageWriter) ImageIO.getImageWritersBySuffix(\"jpeg\").next();\n    ImageOutputStream ios = ImageIO.createImageOutputStream(out);\n    writer.setOutput(ios);\n    ImageWriteParam param = writer.getDefaultWriteParam();\n    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);\n    param.setCompressionQuality(quality/100.0f);\n    writer.write(null, new IIOImage(getBufferedImage(im, false), null, null), param);\n  }\n\n  /** This should be called after the last frame of an animation has been saved. */\n\n  public void lastMovieImage() throws IOException\n  {\n    if (qt != null)\n      qt.close();\n  }\n  \n  /** Determine whether this image is partially transparent, and if so, create a new image\n      in which the color components are premultiplied by the transparency. */\n  \n  private static Image premultiplyTransparency(Image im)\n  {\n    int i, data[];\n    \n    try\n    {\n      PixelGrabber pg = new PixelGrabber(im, 0, 0, -1, -1, true);\n      pg.grabPixels();\n      data = (int []) pg.getPixels();\n    }\n    catch (InterruptedException ex)\n    {\n      return im;\n    }\n    for (i = 0; i < data.length && (data[i] & 0xFF000000) == 0xFF000000; i++);\n    if (i == data.length)\n      return im;\n    \n    // The image is partially transparent.  Premultiply by the transparency.\n    \n    for (i = 0; i < data.length; i++)\n    {\n      int alpha = (data[i]>>24) & 0xFF;\n      int red = (data[i]>>16) & 0xFF;\n      int green = (data[i]>>8) & 0xFF;\n      int blue = data[i] & 0xFF;\n      red = (red*(alpha+1))>>8;\n      green = (green*(alpha+1))>>8;\n      blue = (blue*(alpha+1))>>8;\n      data[i] = (alpha<<24) + (red<<16) + (green<<8) + blue;\n    }\n    \n    // Create the new image.\n    \n    MemoryImageSource source = new MemoryImageSource(im.getWidth(null), im.getHeight(null), \n      data, 0, im.getWidth(null));\n    return Toolkit.getDefaultToolkit().createImage(source);\n  }\n  \n  /** Get a BufferedImage containing the image from a ComplexImage.  This is necessary\n      for using the ImageIO classes, which only work on BufferedImages. */\n  \n  private static BufferedImage getBufferedImage(Image im, boolean hasAlpha)\n  {\n    if (im instanceof BufferedImage)\n      return (BufferedImage) im;\n    BufferedImage bi = new BufferedImage(im.getWidth(null), im.getHeight(null), hasAlpha ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB);\n    Graphics g = bi.getGraphics();\n    g.drawImage(im, 0, 0, null);\n    g.dispose();\n    return bi;\n  }\n}\n", "human_rating": 2.2784115850236, "metadata": {"project": "aoi", "class": "artofillusion.image.ImageSaver", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/image/ImageSaver.java", "label_probabilities": {"readability": [1.40951e-07, 0.278413, 0.721586, 2.12196e-08], "understandability": [1.10758e-10, 0.112411, 0.887589, 1.0538e-07], "complexity": [0.156819, 0.837267, 0.0059133, 1.06594e-13], "modularization": [0.748017, 0.251934, 4.92877e-05, 1.02373e-15], "overall": [7.18587e-14, 0.0121499, 0.987692, 0.000158553]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.keystroke.KeystrokeEditor", "source": "/* Copyright (C) 2006-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.keystroke;\n\nimport buoy.widget.*;\nimport buoy.event.*;\nimport artofillusion.ui.*;\nimport artofillusion.script.*;\n\nimport java.awt.*;\nimport java.awt.event.*;\n\n/**\n * This class presents a user interface for editing a single KeystrokeRecord.  To use it, invoke\n * the static editKeystroke() method.\n */\n\npublic class KeystrokeEditor extends BDialog\n{\n  private BTextField keyField, nameField;\n  private BComboBox languageChoice;\n  private ScriptEditor scriptArea;\n  private BButton okButton;\n  private KeystrokeRecord record;\n\n  private static final int RESERVED_CODES[] = new int [] {\n      KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_UP, KeyEvent.VK_DOWN,\n      KeyEvent.VK_ENTER, KeyEvent.VK_ESCAPE, KeyEvent.VK_TAB, KeyEvent.VK_SHIFT,\n      KeyEvent.VK_ALT, KeyEvent.VK_CONTROL, KeyEvent.VK_META\n  };\n\n  /**\n   * Display a dialog for editing a KeystrokeRecord.\n   *\n   * @param record      the record to be edited\n   * @param parent      the parent window\n   * @return a new KeystrokeRecord representing the edited keystroke, or null if the user\n   * clicked Cancel.\n   */\n\n  public static KeystrokeRecord showEditorDialog(KeystrokeRecord record, WindowWidget parent)\n  {\n    KeystrokeEditor editor = new KeystrokeEditor(record, parent);\n    editor.setVisible(true);\n    return editor.record;\n  }\n\n  private KeystrokeEditor(KeystrokeRecord record, WindowWidget parent)\n  {\n    super(parent, true);\n    FormContainer content = new FormContainer(new double [] {0, 1}, new double [] {0, 0, 0, 0, 1, 0});\n    setContent(content);\n    this.record = record.duplicate();\n    keyField = new BTextField(KeystrokePreferencesPanel.getKeyDescription(record.getKeyCode(), record.getModifiers()));\n    keyField.setEditable(false);\n    keyField.addEventLink(KeyPressedEvent.class, this, \"setKey\");\n    nameField = new BTextField(record.getName());\n    languageChoice = new BComboBox(ScriptRunner.LANGUAGES);\n    languageChoice.setSelectedValue(record.getLanguage());\n    scriptArea = new ScriptEditor(record.getScript());\n    LayoutInfo rightLayout = new LayoutInfo(LayoutInfo.EAST, LayoutInfo.NONE);\n    LayoutInfo fillLayout = new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.HORIZONTAL, new Insets(2, 2, 2, 2), null);\n    content.add(Translate.label(\"Key\"), 0, 0, rightLayout);\n    content.add(Translate.label(\"Name\"), 0, 1, rightLayout);\n    content.add(Translate.label(\"language\"), 0, 2, rightLayout);\n    content.add(keyField, 1, 0, fillLayout);\n    content.add(nameField, 1, 1, fillLayout);\n    content.add(languageChoice, 1, 2, new LayoutInfo(LayoutInfo.WEST, LayoutInfo.NONE));\n    content.add(Translate.label(\"Script\"), 0, 3, 2, 1, new LayoutInfo(LayoutInfo.WEST, LayoutInfo.NONE, null, null));\n    content.add(scriptArea.createContainer(), 0, 4, 2, 1, new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.BOTH));\n    RowContainer buttons = new RowContainer();\n    content.add(buttons, 0, 5, 2, 1);\n    okButton = Translate.button(\"ok\", this, \"clickedOk\");\n    buttons.add(okButton);\n    buttons.add(Translate.button(\"cancel\", this, \"clickedCancel\"));\n    enableOkButton();\n    pack();\n  }\n\n  private void clickedOk()\n  {\n    record.setName(nameField.getText());\n    record.setLanguage(languageChoice.getSelectedValue().toString());\n    record.setScript(scriptArea.getText());\n    dispose();\n  }\n\n  private void clickedCancel()\n  {\n    record = null;\n    dispose();\n  }\n\n  private void enableOkButton()\n  {\n    okButton.setEnabled(record.getKeyCode() != 0);\n  }\n\n  private void setKey(KeyPressedEvent ev)\n  {\n    int code = ev.getKeyCode();\n    for (int i = 0; i < RESERVED_CODES.length; i++)\n      if (code == RESERVED_CODES[i])\n        return;\n    int modifiers = ev.getModifiers() & (KeyEvent.ALT_MASK+KeyEvent.SHIFT_MASK);\n    record.setKeyCode(code);\n    record.setModifiers(modifiers);\n    keyField.setText(KeystrokePreferencesPanel.getKeyDescription(code, modifiers));\n    enableOkButton();\n  }\n}\n", "human_rating": 2.99826589, "metadata": {"project": "aoi", "class": "artofillusion.keystroke.KeystrokeEditor", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/keystroke/KeystrokeEditor.java", "label_probabilities": {"readability": [9.08275e-05, 0.998084, 0.00182529, 5e-18], "understandability": [2.20846e-05, 0.96284, 0.0371384, 4.94761e-15], "complexity": [0.0, 7.95977e-05, 0.355123, 0.644798], "modularization": [3.20969e-06, 0.0176647, 0.955831, 0.0265009], "overall": [0.00137148, 0.935403, 0.0632256, 9.20024e-13]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.keystroke.KeystrokePreferencesPanel", "source": "/* Copyright (C) 2006-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.keystroke;\n\nimport artofillusion.script.*;\nimport buoy.widget.*;\nimport buoy.event.*;\n\nimport javax.swing.table.*;\nimport java.awt.event.*;\nimport java.awt.*;\nimport java.util.*;\nimport java.text.*;\n\nimport artofillusion.ui.*;\n\n/**\n * This class presents a user interface for editing the list of KeystrokeRecords.\n */\n\npublic class KeystrokePreferencesPanel extends FormContainer\n{\n  private ArrayList<KeystrokeRecord> records;\n  private BTable table;\n  private BButton editButton, addButton, deleteButton;\n  private boolean changed;\n  private int sortColumn = 1;\n\n  public KeystrokePreferencesPanel()\n  {\n    super(new double [] {1}, new double [] {1, 0});\n    KeystrokeRecord allRecords[] = KeystrokeManager.getAllRecords();\n    records = new ArrayList<KeystrokeRecord>(allRecords.length);\n    for (int i = 0; i < allRecords.length; i++)\n      records.add(allRecords[i]);\n    table = new BTable(new KeystrokeTableModel());\n    table.setColumnWidth(0, 100);\n    table.setColumnWidth(1, 250);\n    table.setColumnsReorderable(false);\n    table.addEventLink(SelectionChangedEvent.class, this, \"selectionChanged\");\n    table.addEventLink(MouseClickedEvent.class, this, \"tableClicked\");\n    table.getTableHeader().addEventLink(MouseClickedEvent.class, new Object() {\n      void processEvent(MouseClickedEvent ev)\n      {\n        int col = table.findColumn(ev.getPoint());\n        if (col > -1)\n        {\n          sortColumn = col;\n          sortRecords();\n        }\n      }\n    });\n    BScrollPane scroll = new BScrollPane(table, BScrollPane.SCROLLBAR_NEVER, BScrollPane.SCROLLBAR_AS_NEEDED);\n    scroll.setPreferredViewSize(new Dimension(350, table.getRowCount() == 0 ? 150 : 15*table.getRowHeight(0)));\n    add(scroll, 0, 0, new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.BOTH));\n    RowContainer buttons = new RowContainer();\n    add(buttons, 0, 1, new LayoutInfo());\n    buttons.add(editButton = Translate.button(\"edit\", \"...\", this, \"editRecord\"));\n    buttons.add(addButton = Translate.button(\"add\", \"...\", this, \"addRecord\"));\n    buttons.add(deleteButton = Translate.button(\"delete\", this, \"deleteRecords\"));\n    selectionChanged();\n  }\n\n  /**\n   * Save the changes.\n   */\n\n  public void saveChanges()\n  {\n    if (!changed)\n      return;\n    KeystrokeManager.setAllRecords((KeystrokeRecord []) records.toArray(new KeystrokeRecord [records.size()]));\n    try\n    {\n      KeystrokeManager.saveRecords();\n    }\n    catch (Exception ex)\n    {\n      new BStandardDialog(\"\", Translate.text(\"errorSavingPrefs\", ex.getMessage() == null ? \"\" : ex.getMessage()), BStandardDialog.ERROR).showMessageDialog(this);\n    }\n  }\n\n  /**\n   * This is called when the selection in the table changes.\n   */\n\n  private void selectionChanged()\n  {\n    int count = table.getSelectedRows().length;\n    editButton.setEnabled(count == 1);\n    deleteButton.setEnabled(count > 0);\n  }\n\n  /**\n   * This is called when the user clicks on the table.\n   */\n\n  private void tableClicked(MouseClickedEvent ev)\n  {\n    if (ev.getClickCount() != 2 || ev.getModifiersEx() != 0)\n      return;\n    editRecord();\n  }\n\n  /**\n   * Edit the selected record.\n   */\n\n  private void editRecord()\n  {\n    int row = table.getSelectedRows()[0];\n    KeystrokeRecord record = (KeystrokeRecord) records.get(row);\n    KeystrokeRecord edited = KeystrokeEditor.showEditorDialog(record, UIUtilities.findWindow(this));\n    if (edited == null)\n      return;\n    records.set(row, edited);\n    sortRecords();\n    changed = true;\n  }\n\n  /**\n   * Add a new record.\n   */\n\n  private void addRecord()\n  {\n    KeystrokeRecord record = new KeystrokeRecord(0, 0, \"\", \"\", ScriptRunner.LANGUAGES[0]);\n    KeystrokeRecord edited = KeystrokeEditor.showEditorDialog(record, UIUtilities.findWindow(this));\n    if (edited == null)\n      return;\n    records.add(edited);\n    sortRecords();\n    changed = true;\n  }\n\n  /**\n   * Delete the selected records.\n   */\n\n  private void deleteRecords()\n  {\n    int selected[] = table.getSelectedRows();\n    Arrays.sort(selected);\n    for (int i = 0; i < selected.length; i++)\n      records.remove(selected[i]);\n    sortRecords();\n    changed = true;\n  }\n\n  /**\n   * Resort the list of records by name.\n   */\n\n  private void sortRecords()\n  {\n    final Comparator stringComparator = Collator.getInstance(Translate.getLocale());\n    Collections.sort(records, new Comparator<KeystrokeRecord>()\n    {\n      public int compare(KeystrokeRecord r1, KeystrokeRecord r2)\n      {\n        String s1, s2;\n        if (sortColumn == 0)\n        {\n          s1 = getKeyDescription(r1.getKeyCode(), r1.getModifiers());\n          s2 = getKeyDescription(r2.getKeyCode(), r2.getModifiers());\n        }\n        else\n        {\n          s1 = r1.getName();\n          s2 = r2.getName();\n        }\n        return stringComparator.compare(s1, s2);\n      }\n    });\n    ((KeystrokeTableModel) table.getModel()).fireTableDataChanged();\n  }\n\n  /**\n   * Get a string describing a keystroke.\n   */\n\n  static String getKeyDescription(int code, int modifiers)\n  {\n    if (code == 0)\n      return \"\";\n    String keyDesc = KeyEvent.getKeyText(code);\n    if (modifiers != 0)\n      keyDesc = KeyEvent.getKeyModifiersText(modifiers)+\"+\"+keyDesc;\n    return keyDesc;\n  }\n\n  /**\n   * This is the model for the table of keystrokes.\n   */\n\n  private class KeystrokeTableModel extends AbstractTableModel\n  {\n    public int getRowCount()\n    {\n      return records.size();\n    }\n\n    public int getColumnCount()\n    {\n      return 2;\n    }\n\n    public Object getValueAt(int rowIndex, int columnIndex)\n    {\n      KeystrokeRecord record = (KeystrokeRecord) records.get(rowIndex);\n      if (columnIndex == 1)\n        return record.getName();\n      return getKeyDescription(record.getKeyCode(), record.getModifiers());\n    }\n\n    public String getColumnName(int column)\n    {\n      return (column == 1 ? Translate.text(\"Name\") : Translate.text(\"Key\"));\n    }\n  }\n}\n", "human_rating": 3.3108388186617996, "metadata": {"project": "aoi", "class": "artofillusion.keystroke.KeystrokePreferencesPanel", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/keystroke/KeystrokePreferencesPanel.java", "label_probabilities": {"readability": [0.311106, 0.688626, 0.000268399, 2.06618e-08], "understandability": [0.000216931, 0.812951, 0.186602, 0.000229695], "complexity": [6.82077e-07, 0.0278124, 0.941711, 0.0304762], "modularization": [0.000185503, 0.406105, 0.593709, 7.08585e-08], "overall": [9.40091e-05, 0.428737, 0.571168, 9.89641e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.material.Material3D", "source": "/* Copyright (C) 2000 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.material;\n\nimport artofillusion.object.*;\n\n/** Material3D represents a Material whose properties are defined in 3D. */\n\npublic abstract class Material3D extends Material\n{  \n  /** Get the properties at point (x, y, z) at time t.  More precisely, the properties \n      returned should represent an average over a region of width (xsize, ysize, zsize), \n      which is centered at (x, y, z). */\n\n  public abstract void getMaterialSpec(MaterialSpec spec, double x, double y, double z, double xsize, double ysize, double zsize, double t);\n\n  /** The default mapping is a LinearMaterialMapping. */\n  \n  public MaterialMapping getDefaultMapping(Object3D obj)\n  {\n    return new LinearMaterialMapping(obj, this);\n  }\n}", "human_rating": 3.9571827370002413, "metadata": {"project": "aoi", "class": "artofillusion.material.Material3D", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/material/Material3D.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.material.MaterialMapping", "source": "/* Copyright (C) 2000-2007 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.material;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport buoy.widget.*;\nimport java.io.*;\n\n/** A MaterialMapping describes the mapping of a Material's coordinates to the local coordinate\n    system of an object.\n   \n    This is an abstract class.  Its subclasses describe various types of\n    mappings which are appropriate for various types of objects and materials. */\n\npublic abstract class MaterialMapping\n{\n  Object3D object;\n  Material material;\n  \n  protected MaterialMapping(Object3D obj, Material mat)\n  {\n    object = obj;\n    material = mat;\n  }\n  \n  /** Every subclass of MaterialMapping must define a constructor which takes a Material\n      and an Object3D as its arguments:\n      <p>\n      public MappingSubclass(Object3D theObject, Material theMaterial)\n      <p>\n      In addition, every subclass must include a constructor with the signature\n      <p>\n      public MappingSubclass(DataInputStream in, Object3D theObject, Material theMaterial) throws IOException, InvalidObjectException\n      <p>\n      which reconstructs the mapping by reading its data from an input stream.  The following\n      method writes the object's data to an output stream. */\n  \n  public abstract void writeToFile(DataOutputStream out) throws IOException;\n     \n  /** Get the name of this type of mapping.  Subclasses should override this method to return\n      an appropriate name. */\n  \n  public static String getName()\n  {\n    return \"\";\n  }\n\n  /** Get the index of refraction for this mapping's Material. */  \n\n  public double indexOfRefraction()\n  {\n    return material.indexOfRefraction();\n  }\n  \n  /** Get the step size to use for integrating the material. */\n  \n  public abstract double getStepSize();\n  \n  /** Return true if this mapping's Material has internal scattering. */\n  \n  public boolean isScattering()\n  {\n    return material.isScattering();\n  }\n  \n  /** Return true if this mapping's Material casts shadows. */\n  \n  public boolean castsShadows()\n  {\n    return material.castsShadows();\n  }\n\n  /** Get the Material which is being mapped. */\n  \n  public Material getMaterial()\n  {\n    return material;\n  }\n\n  /** Get the object to which the material is applied. */\n\n  public Object3D getObject()\n  {\n    return object;\n  }\n\n  /** Given a point inside the object for which this mapping is being used, find the\n      corresponding material properties.  The properties should be averaged over a region of \n      width size. */\n  \n  public abstract void getMaterialSpec(Vec3 pos, MaterialSpec spec, double size, double t);\n  \n  /** Create a new MaterialMapping which is identical to this one. */\n  \n  public abstract MaterialMapping duplicate();\n  \n  /** Create a new MaterialMapping which is identical to this one, but for a\n      different object and Material. */\n  \n  public abstract MaterialMapping duplicate(Object3D obj, Material mat);\n  \n  /** Make this mapping identical to another one. */\n  \n  public abstract void copy(MaterialMapping map);\n  \n  /** This method should return a Widget in which the user can edit the mapping.  The\n      parameters are the object whose mapping is being edited, and a MaterialPreviewer\n      which should be rendered whenever one of the mapping's parameters changes. */\n\n  public abstract Widget getEditingPanel(Object3D obj, MaterialPreviewer preview);\n}", "human_rating": 3.961635758076289, "metadata": {"project": "aoi", "class": "artofillusion.material.MaterialMapping", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/material/MaterialMapping.java", "label_probabilities": {"readability": [0.961645, 0.0383463, 8.42896e-06, 1.56289e-10], "understandability": [0.949126, 0.0507472, 0.000126645, 3.24991e-13], "complexity": [6.2976e-16, 8.3078e-06, 0.0398721, 0.96012], "modularization": [2.209e-17, 6.29103e-05, 0.0339099, 0.966027], "overall": [0.984911, 0.0150895, 1.29179e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.math.Cells", "source": "/* Copyright (C) 2001-2005 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.math;\n\nimport java.util.*;\n\n/** This class provides an implementation of Steven Worley's cellular texture basis function\n    as described in\n    <p>\n    Worley, S. \"A Cellular Texture Basis Function.\" Siggraph Proceedings, pp. 291-294, 1996.\n    <p>\n    This function scatters \"feature points\" at random locations throughout 3D space.  At\n    any point (x, y, z), it defines the function f1(x, y, z) to be the distance to the\n    nearest feature point.  It similarly defines f2(x, y, z) as the distance to the second\n    nearest feature point, and similarly for f3(x, y, z), etc. */\n\npublic class Cells\n{\n  private double dx[], dy[], dz[];\n  private Vec3 feature, diff;\n  private Random random = new FastRandom(0);\n  private int metric;\n\n  private static double prob[];\n  \n  public static final int EUCLIDEAN = 0;\n  public static final int CITY_BLOCK = 1;\n  public static final int CHESS_BOARD = 2;\n\n  private static final double DENSITY = 3.0;\n  private static final int cellIndex[][] = new int [][] {{0, 1, 1}, {2, 1, 1}, {1, 0, 1},\n    {1, 2, 1}, {1, 1, 0}, {1, 1, 2}, {0, 0, 1}, {0, 2, 1}, {0, 1, 0}, {0, 1, 2}, \n    {2, 0, 1}, {2, 2, 1}, {2, 1, 0}, {2, 1, 2}, {1, 0, 0}, {1, 0, 2}, {1, 2, 0}, \n    {1, 2, 2}, {0, 0, 0}, {0, 0, 2}, {0, 2, 0}, {0, 2, 2}, {2, 0, 0}, {2, 0, 2}, \n    {2, 2, 0}, {2, 2, 2}};\n\n  static\n  {\n    // Calculate the probabilities for different numbers of points to be in a cell.\n    \n    prob = new double [10];\n    for (int i = 0; i < 10; i++)\n      {\n        prob[i] = FastMath.pow(DENSITY, i) * Math.exp(-DENSITY);\n        for (int j = 2; j <= i; j++)\n            prob[i] /= (double) j;\n      }\n    for (int i = 1; i < 10; i++)\n      prob[i] += prob[i-1];\n  }\n  \n  public Cells()\n  {\n    dx = new double [3];\n    dy = new double [3];\n    dz = new double [3];\n    feature = new Vec3();\n    diff = new Vec3();\n    metric = EUCLIDEAN;\n  }\n\n  /** Get which distance metric is being used.  Allowed values are EUCLIDEAN, CITY_BLOCK,\n      or CHESS_BOARD. */\n\n  public int getMetric()\n  {\n    return metric;\n  }\n\n  /** Set which distance metric to use.  Allowed values are EUCLIDEAN, CITY_BLOCK, \n      or CHESS_BOARD. */\n  \n  public void setMetric(int metric)\n  {\n    this.metric = metric;\n  }\n\n  /** Calculate the various functions at a specified point.  The number of functions to\n      evaluate is determined by the length of value[].  The values of the functions are\n      returned in value[], and their gradients in grad[].  A \"unique identifier\" for the\n      nearest, second nearest, etc. feature point is returned in id.  If gradients are \n      not needed, null may be passed for grad[]. */\n\n  public void calcFunctions(Vec3 p, double value[], Vec3 grad[], int id[])\n  {\n    int i, j, k, m, num;\n    int a, b, c;\n    int seed;\n    double x, y, z, r, dist2, rand;\n\n    a = floor(p.x);\n    b = floor(p.y);\n    c = floor(p.z);\n    x = p.x - (double) a;\n    y = p.y - (double) b;\n    z = p.z - (double) c;\n    for (i = 0; i < value.length; i++)\n      value[i] = Double.MAX_VALUE;\n\n    // Find the number of features in this cell.\n\n    seed = randSeed(a, b, c);\n    random.setSeed(seed);\n    random.nextInt();\n    rand = random.nextDouble();\n    for (num = 1; num < 9 && rand > prob[num]; num++);\n\n    // Find the nearest features in this cell.\n\n    for (i = 0; i < num; i++)\n      {\n        feature.x = random.nextDouble();\n        feature.y = random.nextDouble();\n        feature.z = random.nextDouble();\n        diff.x = x-feature.x;\n        diff.y = y-feature.y;\n        diff.z = z-feature.z;\n        dist2 = distance(diff);\n        sortIntoList(dist2, seed+i, value, grad, id);\n      }\n\n    // Check feature points in all the surrounding cells.\n\n    dx[0] = x*x;\n    dy[0] = y*y;\n    dz[0] = z*z;\n    dx[2] = (1.0-x)*(1.0-x);\n    dy[2] = (1.0-y)*(1.0-y);\n    dz[2] = (1.0-z)*(1.0-z);\n    r = value[value.length-1];\n    for (int cell = 0; cell < cellIndex.length; cell++)\n      {\n        i = cellIndex[cell][0];\n        j = cellIndex[cell][1];\n        k = cellIndex[cell][2];\n        if (r < dx[i]+dy[j]+dz[k])\n          continue;\n        i--;\n        j--;\n        k--;\n        seed = randSeed(a+i, b+j, c+k);\n        random.setSeed(seed);\n        random.nextInt();\n        rand = random.nextDouble();\n        for (num = 1; num < 9 && rand > prob[num]; num++);\n\n        // Find the nearest features in this cell.\n\n        for (m = 0; m < num; m++)\n          {\n            feature.x = random.nextDouble() + (double) i;\n            feature.y = random.nextDouble() + (double) j;\n            feature.z = random.nextDouble() + (double) k;\n            diff.x = x-feature.x;\n            diff.y = y-feature.y;\n            diff.z = z-feature.z;\n            dist2 = distance(diff);\n            if (dist2 < value[value.length-1])\n              sortIntoList(dist2, seed+m, value, grad, id);\n          }\n        r = value[value.length-1];\n      }\n    if (metric == EUCLIDEAN)\n      for (i = 0; i < value.length; i++)\n        {\n          value[i] = Math.sqrt(value[i]);\n          if (grad != null)\n            grad[i].scale(1.0/value[i]);\n        }\n  }\n\n  /** Calculate the random number seed to use for cell (i, j, k). */\n\n  private static final int randSeed(int i, int j, int k)\n  {\n    return i*10 + j*1000 + k*100000;\n  }\n\n  /** Given the squared distance to a feature point, sort that point into the list. */\n\n  private final void sortIntoList(double dist2, int newid, double value[], Vec3 grad[], int id[])\n  {\n    for (int i = 0; i < value.length; i++)\n      if (dist2 < value[i])\n        {\n          for (int j = value.length-1; j > i; j--)\n            {\n              value[j] = value[j-1];\n              id[j] = id[j-1];\n              if (grad != null)\n                grad[j].set(grad[j-1]);\n            }\n          value[i] = dist2;\n          id[i] = newid;\n          if (grad != null)\n            {\n              if (metric == EUCLIDEAN)\n                grad[i].set(diff);\n              else if (metric == CITY_BLOCK)\n                grad[i].set(diff.x > 0.0 ? 1.0 : -1.0, diff.y > 0.0 ? 1.0 : -1.0, diff.z > 0.0 ? 1.0 : -1.0);\n              else\n                {\n                  double ax = Math.abs(diff.x);\n                  double ay = Math.abs(diff.y);\n                  double az = Math.abs(diff.z);\n                  if (ax > ay)\n                    {\n                      if (ax > az)\n                        grad[i].set(diff.x > 0.0 ? 1.0 : -1.0, 0.0, 0.0);\n                      else\n                        grad[i].set(0.0, 0.0, diff.z > 0.0 ? 1.0 : -1.0);\n                    }\n                  else\n                    {\n                      if (ay > az)\n                        grad[i].set(0.0, diff.y > 0.0 ? 1.0 : -1.0, 0.0);\n                      else\n                        grad[i].set(0.0, 0.0, diff.z > 0.0 ? 1.0 : -1.0);\n                    }\n                }\n            }\n          return;\n        }\n  }\n  \n  /** Given the vector between two points, calculate the distance measure for the \n      desired metric. */\n  \n  private final double distance(Vec3 diff)\n  {\n    if (metric == EUCLIDEAN)\n      return diff.length2();\n    double ax = Math.abs(diff.x);\n    double ay = Math.abs(diff.y);\n    double az = Math.abs(diff.z);\n    if (metric == CITY_BLOCK)\n      return ax+ay+az;\n    if (ax > ay)\n      return (ax > az ? ax : az);\n    return (ay > az ? ay : az);\n  }\n  \n  /** A faster replacement for Math.floor(). */\n  \n  private static int floor(double d)\n  {\n    if (d < 0.0)\n    {\n      int f = (int) d;\n      if (f != d)\n        f -= 1;\n      return f;\n    }\n    return (int) d;\n  }\n}\n\n\n\n", "human_rating": 2.4177591733128563, "metadata": {"project": "aoi", "class": "artofillusion.math.Cells", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/math/Cells.java", "label_probabilities": {"readability": [4.4464e-11, 0.417761, 0.582238, 1.73135e-07], "understandability": [6.52175e-11, 4.05309e-12, 6.76266e-07, 0.999999], "complexity": [0.839412, 0.160588, 1.66336e-11, 0.0], "modularization": [0.858521, 0.141466, 1.29045e-05, 0.0], "overall": [0.0, 0.0, 7.72865e-06, 0.999992]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.math.Mat4", "source": "/* Copyright (C) 1999,2000,2003 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.math;\n\nimport java.io.*;\n\n/** This class represents a 4x4 matrix.  It is typically used for representing coordinate transformations. */\n\npublic class Mat4\n{\n  public final double m11, m12, m13, m14;\n  public final double m21, m22, m23, m24;\n  public final double m31, m32, m33, m34;\n  public final double m41, m42, m43, m44;\n  \n  /** Create a new Mat4 by explicitly setting its components. */\n  \n  public Mat4 (double e11, double e12, double e13, double e14, \n  \t\tdouble e21, double e22, double e23, double e24, \n  \t\tdouble e31, double e32, double e33, double e34, \n  \t\tdouble e41, double e42, double e43, double e44)\n  {\n    m11 = e11;  m12 = e12;  m13 = e13;  m14 = e14;\n    m21 = e21;  m22 = e22;  m23 = e23;  m24 = e24;\n    m31 = e31;  m32 = e32;  m33 = e33;  m34 = e34;\n    m41 = e41;  m42 = e42;  m43 = e43;  m44 = e44;\n  }\n\n  /** Create a new Mat4 by multiplying two matrices. */\n\n  public final Mat4 times(Mat4 a)\n  {\n    return new Mat4(m11*a.m11 + m12*a.m21 + m13*a.m31 + m14*a.m41,\n    \tm11*a.m12 + m12*a.m22 + m13*a.m32 + m14*a.m42,\n    \tm11*a.m13 + m12*a.m23 + m13*a.m33 + m14*a.m43,\n    \tm11*a.m14 + m12*a.m24 + m13*a.m34 + m14*a.m44,\n    \tm21*a.m11 + m22*a.m21 + m23*a.m31 + m24*a.m41,\n    \tm21*a.m12 + m22*a.m22 + m23*a.m32 + m24*a.m42,\n    \tm21*a.m13 + m22*a.m23 + m23*a.m33 + m24*a.m43,\n    \tm21*a.m14 + m22*a.m24 + m23*a.m34 + m24*a.m44,\n    \tm31*a.m11 + m32*a.m21 + m33*a.m31 + m34*a.m41,\n    \tm31*a.m12 + m32*a.m22 + m33*a.m32 + m34*a.m42,\n    \tm31*a.m13 + m32*a.m23 + m33*a.m33 + m34*a.m43,\n    \tm31*a.m14 + m32*a.m24 + m33*a.m34 + m34*a.m44,\n    \tm41*a.m11 + m42*a.m21 + m43*a.m31 + m44*a.m41,\n    \tm41*a.m12 + m42*a.m22 + m43*a.m32 + m44*a.m42,\n    \tm41*a.m13 + m42*a.m23 + m43*a.m33 + m44*a.m43,\n    \tm41*a.m14 + m42*a.m24 + m43*a.m34 + m44*a.m44);\n  }\n  \n  /** Multiply this matrix (M) by a vector (v) and return the product\n      Mv.  Both the input and output vectors are assumed to be in homogeneous coordinates,\n      and to have an implicit fourth element equal to 1. */\n  \n  public final Vec3 times(Vec3 v)\n  {\n    double w = m41*v.x + m42*v.y + m43*v.z + m44;\n    \n    return new Vec3((m11*v.x + m12*v.y + m13*v.z + m14)/w,\n    \t\t    (m21*v.x + m22*v.y + m23*v.z + m24)/w,\n    \t\t    (m31*v.x + m32*v.y + m33*v.z + m34)/w);\n  }\n  \n  /** This method is identical to times(), except that v is assumed to be a direction vector.\n      That is, the implicit fourth element is assumed to be 0. */\n\n  public final Vec3 timesDirection(Vec3 v)\n  {\n    return new Vec3(m11*v.x + m12*v.y + m13*v.z,\n    \t\t    m21*v.x + m22*v.y + m23*v.z,\n    \t\t    m31*v.x + m32*v.y + m33*v.z);\n  }\n\n  /** This method works exactly like the times() method, except that it only calculates\n      the x and y components of the output vector.  This can save several operations when\n      the z component is not of interest, for example, when applying a perspective\n      projection. */\n     \n  public final Vec2 timesXY(Vec3 v)\n  {\n    double w = m41*v.x + m42*v.y + m43*v.z + m44;\n    \n    return new Vec2((m11*v.x + m12*v.y + m13*v.z + m14)/w,\n    \t\t    (m21*v.x + m22*v.y + m23*v.z + m24)/w);\n  }\n\n  /** This method works exactly like the times() method, except that it only calculates\n      the x and y components of the output vector.  This can save several operations when\n      the z component is not of interest, for example, when applying a perspective\n      projection.  Also, rather than creating a new object, it allows you to pass in an\n      existing object to receive the results. */\n     \n  public final Vec2 timesXY(Vec3 v, Vec2 result)\n  {\n    double w = m41*v.x + m42*v.y + m43*v.z + m44;\n    \n    result.set((m11*v.x + m12*v.y + m13*v.z + m14)/w,\n    \t\t    (m21*v.x + m22*v.y + m23*v.z + m24)/w);\n    return result;\n  }\n  \n  /** This method works like the times() method, except that it only calculates the z\n      component of the output vector.  This is useful, for example, for determining whether\n      a point lies in front of or behind the viewer. */\n\n  public final double timesZ(Vec3 v)\n  {\n    double w = m41*v.x + m42*v.y + m43*v.z + m44;\n    \n    return (m31*v.x + m32*v.y + m33*v.z + m34)/w;\n  }\n  \n  /** This method works like times(), except that the calculation is done in place. */\n\n  public final void transform(Vec3 v)\n  {\n    double w = m41*v.x + m42*v.y + m43*v.z + m44;\n    \n    v.set((m11*v.x + m12*v.y + m13*v.z + m14)/w,\n\t(m21*v.x + m22*v.y + m23*v.z + m24)/w,\n\t(m31*v.x + m32*v.y + m33*v.z + m34)/w);\n  }\n  \n  /** This method works like timesDirection(), except that the calculation is done in place. */\n\n  public final void transformDirection(Vec3 v)\n  {\n    v.set(m11*v.x + m12*v.y + m13*v.z,\n\tm21*v.x + m22*v.y + m23*v.z,\n\tm31*v.x + m32*v.y + m33*v.z);\n  }\n\n  /** Create an identity matrix. */\n  \n  public static Mat4 identity()\n  {\n    return new Mat4(1.0, 0.0, 0.0, 0.0,\n    \t\t0.0, 1.0, 0.0, 0.0,\n    \t\t0.0, 0.0, 1.0, 0.0,\n    \t\t0.0, 0.0, 0.0, 1.0);\n  }\n\n  /** Create a matrix to scale x, y, and z by sx, sy, and sz respectively. */\n  \n  public static Mat4 scale(double sx, double sy, double sz)\n  {\n    return new Mat4(sx, 0.0, 0.0, 0.0,\n    \t\t0.0, sy, 0.0, 0.0,\n    \t\t0.0, 0.0, sz, 0.0,\n    \t\t0.0, 0.0, 0.0, 1.0);\n  }\n\n  /** Create a matrix to translate a vector by (dx, dy, dz). */\n\n  public static Mat4 translation(double dx, double dy, double dz)\n  {\n    return new Mat4(1.0, 0.0, 0.0, dx,\n    \t\t0.0, 1.0, 0.0, dy,\n    \t\t0.0, 0.0, 1.0, dz,\n    \t\t0.0, 0.0, 0.0, 1.0);\n  }\n  \n  /** Create a matrix that rotates a vector around the X axis.\n      @param angle     the rotation angle, in radians\n   */\n  \n  public static Mat4 xrotation(double angle)\n  {\n    double c = Math.cos(angle), s = Math.sin(angle);\n    \n    return new Mat4(1.0, 0.0, 0.0, 0.0,\n    \t\t0.0, c, -s, 0.0,\n    \t\t0.0, s, c, 0.0,\n    \t\t0.0, 0.0, 0.0, 1.0);\n  }\n\n  /** Create a matrix that rotates a vector around the Y axis.\n      @param angle     the rotation angle, in radians\n   */\n  \n  public static Mat4 yrotation(double angle)\n  {\n    double c = Math.cos(angle), s = Math.sin(angle);\n    \n    return new Mat4(c, 0.0, s, 0.0,\n    \t\t0.0, 1.0, 0.0, 0.0,\n    \t\t-s, 0.0, c, 0.0,\n    \t\t0.0, 0.0, 0.0, 1.0);\n  }\n\n  /** Create a matrix that rotates a vector around the Z axis.\n      @param angle     the rotation angle, in radians\n   */\n  \n  public static Mat4 zrotation(double angle)\n  {\n    double c = Math.cos(angle), s = Math.sin(angle);\n    \n    return new Mat4(c, -s, 0.0, 0.0,\n    \t\ts, c, 0.0, 0.0,\n    \t\t0.0, 0.0, 1.0, 0.0,\n    \t\t0.0, 0.0, 0.0, 1.0);\n  }\n  \n  /** This routine creates a matrix to rotate a vector around an arbitrary axis.\n      @param axis      the axis around which to rotate\n      @param angle     the rotation angle, in radians\n   */\n  \n  public static Mat4 axisRotation(Vec3 axis, double angle)\n  {\n    double c = Math.cos(angle), s = Math.sin(angle);\n    double t = 1.0 - c;\n    \n    return new Mat4(t*axis.x*axis.x + c,\n\tt*axis.x*axis.y - s*axis.z,\n\tt*axis.x*axis.z + s*axis.y,\n\t0.0,\n\tt*axis.x*axis.y + s*axis.z,\n\tt*axis.y*axis.y + c,\n\tt*axis.y*axis.z - s*axis.x,\n\t0.0,\n\tt*axis.x*axis.z - s*axis.y,\n\tt*axis.y*axis.z + s*axis.x,\n\tt*axis.z*axis.z + c,\n\t0.0,\n\t0.0, 0.0, 0.0, 1.0);\n  }\n\n  /** Create a matrix for transforming from world coordinates to viewing coordinates.  This\n      matrix transforms coordinates such that the position vector orig is translated to\n      the origin, the direction vector zdir lies along the positive z axis, and the\n      direction vection updir lies the positive y half of the yz plane. */\n\n  public static Mat4 viewTransform(Vec3 orig, Vec3 zdir, Vec3 updir)\n  {\n    Vec3 rx, ry, rz;\n\n    rz = zdir.times(1.0/zdir.length());\n    rx = updir.cross(zdir);\n    rx.normalize();\n    ry = rz.cross(rx);\n    return new Mat4(rx.x, rx.y, rx.z, -(rx.x*orig.x + rx.y*orig.y + rx.z*orig.z),\n\t\try.x, ry.y, ry.z, -(ry.x*orig.x + ry.y*orig.y + ry.z*orig.z),\n\t\trz.x, rz.y, rz.z, -(rz.x*orig.x + rz.y*orig.y + rz.z*orig.z),\n\t\t0.0, 0.0, 0.0, 1.0);\n  }\n  \n  /** Create a matrix which is the inverse of the viewTransform matrix.  That is, it first\n      rotates the rotates the z axis to lie along the direction of zdir and the y axis to\n      lie in the updir direction, then translates the origin to the point orig.  This is\n      useful for transforming from object coordinates to world coordinates. */\n     \n  public static Mat4 objectTransform(Vec3 orig, Vec3 zdir, Vec3 updir)\n  {\n    Vec3 rx, ry, rz;\n\n    rz = zdir.times(1.0/zdir.length());\n    rx = updir.cross(zdir);\n    rx.normalize();\n    ry = rz.cross(rx);\n    return new Mat4(rx.x, ry.x, rz.x, orig.x,\n\t\trx.y, ry.y, rz.y, orig.y,\n\t\trx.z, ry.z, rz.z, orig.z,\n\t\t0.0, 0.0, 0.0, 1.0);\n  }\n\n  /** Create a matrix to implement a perspective projection.  The center of projection is\n      at (0, 0, -d), and the projection plane is given by z=1. */\n\n  public static Mat4 perspective(double d)\n  {\n    double e33 = 1.0/((d+1.0)*(d+1.0));\n    \n    return new Mat4(1.0, 0.0, 0.0, 0.0,\n\t\t0.0, 1.0, 0.0, 0.0,\n\t\t0.0, 0.0, e33, 1.0-e33,\n\t\t0.0, 0.0, e33, 1.0-e33);\n  }\n  \n  public String toString()\n  {\n    return \"Mat4: {\"+m11+\", \"+m12 +\", \"+m13+\", \"+m14+\"}, {\"+m21+\", \"+m22 +\", \"+m23+\", \"+m24+\"}, {\"+m31+\", \"+m32 +\", \"+m33+\", \"+m34+\"}, {\"+m41+\", \"+m42 +\", \"+m43+\", \"+m44+\"}\";\n  }\n  \n  public boolean equals(Object o)\n  {\n    if (!(o instanceof Mat4))\n      return false;\n    Mat4 m = (Mat4) o;\n    return (m11 == m.m11 && m12 == m.m12 && m13 == m.m13 && m14 == m.m14 &&\n      m21 == m.m21 && m22 == m.m22 && m23 == m.m23 && m24 == m.m24 &&\n      m31 == m.m31 && m32 == m.m32 && m33 == m.m33 && m34 == m.m34 &&\n      m41 == m.m41 && m42 == m.m42 && m43 == m.m43 && m44 == m.m44);\n  }\n  \n  public int hashCode()\n  {\n    double d = (m11+m12+m13+m14) + 2.2*(m21+m22+m23+m24) + 3.3*(m31+m32+m33+m34) + 4.4*(m41+m42+m43+m44);\n    return Float.floatToIntBits((float) d);\n  }\n  \n  /** Create a Mat4 by reading in information that was written by writeToFile(). */\n  \n  public Mat4(DataInputStream in) throws IOException\n  {\n    m11 = in.readDouble(); m12 = in.readDouble(); m13 = in.readDouble(); m14 = in.readDouble();\n    m21 = in.readDouble(); m22 = in.readDouble(); m23 = in.readDouble(); m24 = in.readDouble();\n    m31 = in.readDouble(); m32 = in.readDouble(); m33 = in.readDouble(); m34 = in.readDouble();\n    m41 = in.readDouble(); m42 = in.readDouble(); m43 = in.readDouble(); m44 = in.readDouble();\n  }\n  \n  /** Write out a serialized representation of this object. */\n  \n  public void writeToFile(DataOutputStream out) throws IOException\n  {\n    out.writeDouble(m11); out.writeDouble(m12); out.writeDouble(m13); out.writeDouble(m14);\n    out.writeDouble(m21); out.writeDouble(m22); out.writeDouble(m23); out.writeDouble(m24);\n    out.writeDouble(m31); out.writeDouble(m32); out.writeDouble(m33); out.writeDouble(m34);\n    out.writeDouble(m41); out.writeDouble(m42); out.writeDouble(m43); out.writeDouble(m44);\n  }\n}", "human_rating": 2.99928229, "metadata": {"project": "aoi", "class": "artofillusion.math.Mat4", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/math/Mat4.java", "label_probabilities": {"readability": [0.000167046, 0.998948, 0.000885053, 3.3478e-16], "understandability": [1.66154e-10, 5.03514e-11, 1.3971e-09, 1.0], "complexity": [0.936562, 0.0634331, 4.85325e-06, 1.7e-19], "modularization": [6.97847e-11, 0.957151, 0.0428486, 3.63254e-11], "overall": [3.23e-18, 0.000177758, 0.999822, 1.78978e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.MoveScaleRotateObjectTool", "source": "/* Copyright (C) 2006-2009 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY\n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.ui.*;\nimport artofillusion.ui.Compound3DManipulator.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\n\nimport java.awt.event.*;\nimport java.awt.*;\nimport java.util.*;\n\nimport buoy.event.*;\nimport buoy.widget.*;\n\n/**\n * This editing tool presents a compound interface for moving, scaling, and rotating objects.\n */\n\npublic class MoveScaleRotateObjectTool extends EditingTool\n{\n  private boolean dragInProgress, draggingObjects;\n  private ArrayList<ObjectInfo> objects;\n  private CoordinateSystem originalCoords[];\n  private Object3D originalObjects[];\n  private ObjectInfo clickedObject;\n  private Point clickPoint;\n  private Vec3 rotationCenter[];\n  private UndoRecord undo;\n  private final Compound3DManipulator manipulator;\n  private boolean tooltipsEnabled, tooltipsAdded, applyToChildren = true;\n  private int scaleAround = POSITIONS_FIXED, rotateAround = PARENT_CENTER;\n\n  private static BToolTip ROTATE_TIP = new BToolTip(Translate.text(\"moveScaleRotateObjectTool.rotateTipText\"));\n  private static BToolTip MOVE_TIP = new BToolTip(Translate.text(\"moveScaleRotateObjectTool.moveTipText\"));\n  private static BToolTip SCALE_TIP = new BToolTip(Translate.text(\"moveScaleRotateObjectTool.scaleTipText\"));\n\n  private static final int POSITIONS_FIXED = 0;\n  private static final int POSITIONS_SCALE = 1;\n\n  private static final int OBJECT_CENTER = 0;\n  private static final int PARENT_CENTER = 1;\n  private static final int SELECTION_CENTER = 2;\n\n  public MoveScaleRotateObjectTool(LayoutWindow fr)\n  {\n    super(fr);\n    initButton(\"moveScaleRotate\");\n    manipulator = new Compound3DManipulator();\n    manipulator.addEventLink(HandlePressedEvent.class, this, \"handlePressed\");\n    manipulator.addEventLink(HandleDraggedEvent.class, this, \"handleDragged\");\n    manipulator.addEventLink(HandleReleasedEvent.class, this, \"handleReleased\");\n  }\n\n  public int whichClicks()\n  {\n    return OBJECT_CLICKS+ALL_CLICKS;\n  }\n\n  public boolean allowSelectionChanges()\n  {\n    return !dragInProgress;\n  }\n\n  public String getToolTipText()\n  {\n    return Translate.text(\"moveScaleRotateObjectTool.tipText\");\n  }\n\n  /** Get the LayoutWindow to which this tool belongs. */\n\n  public LayoutWindow getWindow()\n  {\n    return (LayoutWindow) theWindow;\n  }\n\n  public void drawOverlay(ViewerCanvas view)\n  {\n    BoundingBox selectionBounds = findSelectionBounds(view.getCamera());\n    if (!dragInProgress && manipulator.getViewMode() == Compound3DManipulator.NPQ_MODE && selectionBounds != null)\n    {\n      // Calculate the axis directions.\n\n      ObjectInfo firstObj = getWindow().getSelectedObjects().iterator().next();\n      CoordinateSystem coords = firstObj.getCoords();\n      manipulator.setNPQAxes(coords.getUpDirection().cross(coords.getZDirection()), coords.getUpDirection(), coords.getZDirection());\n    }\n    manipulator.draw(view, selectionBounds);\n    if (!dragInProgress)\n    {\n      if (selectionBounds != null)\n        theWindow.setHelpText(Translate.text(\"moveScaleRotateObjectTool.helpText\"));\n      else\n        theWindow.setHelpText(Translate.text(\"moveScaleRotateObjectTool.errorText\"));\n    }\n  }\n\n  public void mousePressed(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    BoundingBox selectionBounds = findSelectionBounds(view.getCamera());\n    dragInProgress = false;\n    draggingObjects = false;\n    if (selectionBounds != null)\n      dragInProgress = manipulator.mousePressed(e, view, selectionBounds);\n  }\n\n  public void mousePressedOnObject(WidgetMouseEvent e, ViewerCanvas view, int obj)\n  {\n    draggingObjects = true;\n    BoundingBox selectionBounds = findSelectionBounds(view.getCamera());\n    Rectangle screenBounds = manipulator.findScreenBounds(selectionBounds, view.getCamera());\n    handlePressed(manipulator.new HandlePressedEvent(view, Compound3DManipulator.MOVE, Compound3DManipulator.ALL, screenBounds, selectionBounds, e));\n    clickedObject = view.getScene().getObject(obj);\n    clickPoint = e.getPoint();\n  }\n\n  public void mouseDragged(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    if (draggingObjects)\n    {\n      BoundingBox selectionBounds = findSelectionBounds(view.getCamera());\n      Rectangle screenBounds = manipulator.findScreenBounds(selectionBounds, view.getCamera());\n      Point dragPoint = e.getPoint();\n      int dx = dragPoint.x - clickPoint.x;\n      int dy = dragPoint.y - clickPoint.y;\n      if (e.isShiftDown() && !e.isControlDown())\n        {\n          if (Math.abs(dx) > Math.abs(dy))\n            dy = 0;\n          else\n            dx = 0;\n        }\n      Vec3 v;\n      if (e.isControlDown())\n        v = view.getCamera().getCameraCoordinates().getZDirection().times(-dy*0.01);\n      else\n        v = view.getCamera().findDragVector(clickedObject.getCoords().getOrigin(), dx, dy);\n      handleDragged(manipulator.new HandleDraggedEvent(view, Compound3DManipulator.MOVE, Compound3DManipulator.ALL, screenBounds, selectionBounds, e, Mat4.translation(v.x, v.y, v.z)));\n    }\n    else\n      manipulator.mouseDragged(e, view);\n  }\n\n  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    if (draggingObjects)\n      handleReleased(null);\n    else\n      manipulator.mouseReleased(e, view);\n  }\n\n  protected void handlePressed(HandlePressedEvent ev)\n  {\n    objects = new ArrayList<ObjectInfo>();\n    int sel[];\n    if (applyToChildren)\n      sel = getWindow().getSelectionWithChildren();\n    else\n      sel = getWindow().getSelectedIndices();\n    for (int i = 0; i < sel.length; i++)\n      objects.add(theWindow.getScene().getObject(sel[i]));\n    originalCoords = new CoordinateSystem[objects.size()];\n    for (int i = 0; i < originalCoords.length; i++)\n      originalCoords[i] = objects.get(i).getCoords();\n    if (ev.getHandleType() == Compound3DManipulator.SCALE)\n    {\n      originalObjects = new Object3D[objects.size()];\n      for (int i = 0; i < originalObjects.length; i++)\n        originalObjects[i] = objects.get(i).getObject();\n    }\n    if (ev.getHandleType() == Compound3DManipulator.ROTATE)\n    {\n      manipulator.setRotateAroundSelectionCenter(rotateAround == SELECTION_CENTER);\n      rotationCenter = new Vec3[objects.size()];\n      for (int i = 0; i < rotationCenter.length; i++)\n        {\n          ObjectInfo parent = objects.get(i);\n          if (rotateAround == SELECTION_CENTER)\n              rotationCenter[i] = new Vec3();\n          else\n            rotationCenter[i] = originalCoords[i].getOrigin();\n          if (rotateAround == PARENT_CENTER)\n            while (parent.getParent() != null)\n              {\n                parent = parent.getParent();\n                if (parent.selected)\n                  rotationCenter[i] = parent.getCoords().getOrigin();\n              }\n        }\n    }\n  }\n\n  protected void handleDragged(HandleDraggedEvent ev)\n  {\n    if (undo == null)\n    {\n      undo = new UndoRecord(theWindow, false);\n      for (int i = 0; i < originalCoords.length; i++)\n      {\n        originalCoords[i] = originalCoords[i].duplicate();\n        undo.addCommand(UndoRecord.COPY_COORDS, new Object[] {objects.get(i).getCoords(), originalCoords[i]});\n        if (ev.getHandleType() == Compound3DManipulator.SCALE)\n        {\n          originalObjects[i] = originalObjects[i].duplicate();\n          undo.addCommand(UndoRecord.COPY_OBJECT, new Object[] {objects.get(i).getObject(), originalObjects[i]});\n        }\n      }\n    }\n    transformObjects(ev);\n    theWindow.setModified();\n    theWindow.updateImage();\n    if (ev.getHandleType() == Compound3DManipulator.MOVE)\n    {\n      Vec3 drag = ev.getTransform().times(new Vec3());\n      theWindow.setHelpText(Translate.text(\"reshapeMeshTool.dragText\",\n          Math.round(drag.x*1e5)/1e5+\", \"+Math.round(drag.y*1e5)/1e5+\", \"+Math.round(drag.z*1e5)/1e5));\n    }\n    else if (ev.getHandleType() == Compound3DManipulator.ROTATE)\n      theWindow.setHelpText(Translate.text(\"rotateMeshTool.dragText\", Double.toString(Math.round(ev.getRotationAngle()*1e5*180.0/Math.PI)/1e5)));\n    else if (ev.getAxis() == Compound3DManipulator.UV && !ev.getMouseEvent().isShiftDown())\n      theWindow.setHelpText(Translate.text(\"scaleMeshTool.dragText\", Math.round(ev.getPrimaryScale()*1e5)/1e5+\", \"+Math.round(ev.getSecondaryScale()*1e5)/1e5));\n    else\n      theWindow.setHelpText(Translate.text(\"scaleMeshTool.dragText\", Double.toString(Math.round(ev.getPrimaryScale()*1e5)/1e5)));\n  }\n\n  protected void handleReleased(HandleReleasedEvent ev)\n  {\n    if (undo != null)\n      theWindow.setUndoRecord(undo);\n    theWindow.updateImage();\n    undo = null;\n    rotationCenter = null;\n    dragInProgress = false;\n  }\n\n  /**\n   * Apply a transformation to the objects.\n   */\n\n  private void transformObjects(HandleDraggedEvent ev)\n  {\n    for (int i = 0; i < objects.size(); i++)\n    {\n      Mat4 transform = ev.getTransform();\n      if (ev.getHandleType() == Compound3DManipulator.SCALE)\n      {\n        if (scaleAround == POSITIONS_SCALE)\n        {\n          // Scale the positions.\n\n          CoordinateSystem coords = originalCoords[i].duplicate();\n          coords.transformOrigin(transform);\n          objects.get(i).getCoords().copyCoords(coords);\n        }\n\n        // Work out the scale factors for the size.\n\n        double xscale = 1.0, yscale = 1.0, zscale = 1.0;\n        Vec3 xdir = originalCoords[i].fromLocal().timesDirection(transform.timesDirection(new Vec3(1.0, 0.0, 0.0)));\n        Vec3 ydir = originalCoords[i].fromLocal().timesDirection(transform.timesDirection(new Vec3(0.0, 1.0, 0.0)));\n        Vec3 zdir = originalCoords[i].fromLocal().timesDirection(transform.timesDirection(new Vec3(0.0, 0.0, 1.0)));\n        xdir.normalize();\n        ydir.normalize();\n        zdir.normalize();\n        if (ev.getMouseEvent().isShiftDown())\n        {\n          xscale = yscale = zscale = ev.getPrimaryScale();\n        }\n        else if (ev.getAxis() == Compound3DManipulator.UV)\n        {\n          Vec3 uDir = manipulator.getAxisDirection(Compound3DManipulator.U, ev.getView());\n          Vec3 vDir = manipulator.getAxisDirection(Compound3DManipulator.V, ev.getView());\n          double xudot = Math.abs(xdir.dot(uDir));\n          double yudot = Math.abs(ydir.dot(uDir));\n          double zudot = Math.abs(zdir.dot(uDir));\n          double xvdot = Math.abs(xdir.dot(vDir));\n          double yvdot = Math.abs(ydir.dot(vDir));\n          double zvdot = Math.abs(zdir.dot(vDir));\n          if (xudot >= yudot && xudot >= zudot)\n          {\n            xscale = ev.getPrimaryScale();\n            if (yvdot >= zvdot)\n              yscale = ev.getSecondaryScale();\n            else\n              zscale = ev.getSecondaryScale();\n          }\n          else if (yudot >= xudot && yudot >= zudot)\n          {\n            yscale = ev.getPrimaryScale();\n            if (xvdot >= zvdot)\n              xscale = ev.getSecondaryScale();\n            else\n              zscale = ev.getSecondaryScale();\n          }\n          else\n          {\n            zscale = ev.getPrimaryScale();\n            if (xvdot >= yvdot)\n              xscale = ev.getSecondaryScale();\n            else\n              yscale = ev.getSecondaryScale();\n          }\n        }\n        else\n        {\n          Vec3 scaleDir = manipulator.getAxisDirection(ev.getAxis(), ev.getView());\n          double xdot = Math.abs(xdir.dot(scaleDir));\n          double ydot = Math.abs(ydir.dot(scaleDir));\n          double zdot = Math.abs(zdir.dot(scaleDir));\n          if (xdot >= ydot && xdot >= zdot)\n            xscale = ev.getPrimaryScale();\n          else if (ydot >= xdot && ydot >= zdot)\n            yscale = ev.getPrimaryScale();\n          else\n            zscale = ev.getPrimaryScale();\n        }\n        Vec3 size = originalObjects[i].getBounds().getSize();\n        size.x *= xscale;\n        size.y *= yscale;\n        size.z *= zscale;\n        objects.get(i).getObject().setSize(size.x, size.y, size.z);\n        getWindow().getScene().objectModified(objects.get(i).getObject());\n      }\n      else\n      {\n        if (ev.getHandleType() == Compound3DManipulator.ROTATE)\n        {\n          Vec3 center = rotationCenter[i];\n          transform = Mat4.translation(center.x, center.y, center.z).times(transform.times(Mat4.translation(-center.x, -center.y, -center.z)));\n        }\n        CoordinateSystem coords = originalCoords[i].duplicate();\n        coords.transformCoordinates(transform);\n        objects.get(i).getCoords().copyCoords(coords);\n      }\n    }\n  }\n\n  public void keyPressed(KeyPressedEvent e, ViewerCanvas view)\n  {\n    if (e.getKeyCode() == KeyEvent.VK_W && e.getModifiersEx() == 0)\n    {\n      // Change the axis mode.\n\n      ViewMode mode = manipulator.getViewMode();\n      if (mode == Compound3DManipulator.XYZ_MODE)\n        manipulator.setViewMode(Compound3DManipulator.UV_MODE);\n      else if (mode == Compound3DManipulator.UV_MODE)\n        manipulator.setViewMode(Compound3DManipulator.NPQ_MODE);\n      else\n        manipulator.setViewMode(Compound3DManipulator.XYZ_MODE);\n      theWindow.updateImage();\n      return;\n    }\n    if (e.getKeyCode() == KeyEvent.VK_F1)\n    {\n      // Enable tooltips.\n\n      tooltipsEnabled = !tooltipsEnabled;\n      if (tooltipsEnabled && !tooltipsAdded)\n      {\n        ViewerCanvas allViews[] = ((MeshEditorWindow) theWindow).getAllViews();\n        for (int i = 0; i < allViews.length; i++)\n          allViews[i].addEventLink(ToolTipEvent.class, this, \"showToolTip\");\n        tooltipsAdded = true;\n      }\n      if (!tooltipsEnabled)\n        BToolTip.hide();\n      return;\n    }\n\n    // Handle arrow keys.  This is equivalent to dragging the first selected object by one pixel.\n\n    double dx, dy;\n    int key = e.getKeyCode();\n    if (key == KeyPressedEvent.VK_UP)\n    {\n      dx = 0;\n      dy = -1;\n    }\n    else if (key == KeyPressedEvent.VK_DOWN)\n    {\n      dx = 0;\n      dy = 1;\n    }\n    else if (key == KeyPressedEvent.VK_LEFT)\n    {\n      dx = -1;\n      dy = 0;\n    }\n    else if (key == KeyPressedEvent.VK_RIGHT)\n    {\n      dx = 1;\n      dy = 0;\n    }\n    else\n      return;\n    e.consume();\n    int sel[];\n    if (applyToChildren)\n      sel = getWindow().getSelectionWithChildren();\n    else\n      sel = getWindow().getSelectedIndices();\n    if (sel.length == 0)\n      return;  // No objects are selected.\n    if (view.getSnapToGrid())\n    {\n      double scale = view.getGridSpacing()*view.getScale();\n      if (!e.isAltDown())\n        scale /= view.getSnapToSubdivisions();\n      dx *= scale;\n      dy *= scale;\n    }\n    else if (e.isAltDown())\n    {\n      dx *= 10;\n      dy *= 10;\n    }\n    Camera cam = view.getCamera();\n    CoordinateSystem cameraCoords = cam.getCameraCoordinates();\n    Scene theScene = theWindow.getScene();\n    Vec3 v;\n    if (e.isControlDown())\n      v = cameraCoords.getZDirection().times(-dy*0.01);\n    else\n    {\n      Vec3 origin = theScene.getObject(sel[0]).getCoords().getOrigin();\n      if (Math.abs(origin.minus(cameraCoords.getOrigin()).dot(cameraCoords.getZDirection())) < 1e-10)\n      {\n        // The object being moved is in the plane of the camera, so use a slightly\n        // different point to avoid dividing by zero.\n\n        origin = origin.plus(cameraCoords.getZDirection().times(cam.getClipDistance()));\n      }\n      v = cam.findDragVector(origin, dx, dy);\n    }\n    theWindow.setUndoRecord(undo = new UndoRecord(getWindow(), false));\n    ArrayList<ObjectInfo> toMove = new ArrayList<ObjectInfo>();\n    for (int i = 0; i < sel.length; i++)\n      toMove.add(theScene.getObject(sel[i]));\n    for (int i = 0; i < toMove.size(); i++)\n    {\n      CoordinateSystem c = toMove.get(i).getCoords();\n      undo.addCommand(UndoRecord.COPY_COORDS, new Object [] {c, c.duplicate()});\n      c.setOrigin(c.getOrigin().plus(v));\n    }\n    theWindow.getScene().applyTracksAfterModification(toMove);\n    theWindow.updateImage();\n    undo = null;\n  }\n\n  private void showToolTip(ToolTipEvent ev)\n  {\n    if (!tooltipsEnabled)\n      return;\n    ViewerCanvas view = (ViewerCanvas) ev.getWidget();\n    HandleType type = manipulator.getHandleTypeAtLocation(ev.getPoint(), view, findSelectionBounds(view.getCamera()));\n    if (type == Compound3DManipulator.MOVE)\n      MOVE_TIP.processEvent(ev);\n    else if (type == Compound3DManipulator.ROTATE)\n      ROTATE_TIP.processEvent(ev);\n    else if (type == Compound3DManipulator.SCALE)\n      SCALE_TIP.processEvent(ev);\n    else\n      BToolTip.hide();\n  }\n\n  /**\n   * This method returns a bounding box for the selected objects in view coordinates,\n   * or null if nothing is selected.\n   */\n\n  protected BoundingBox findSelectionBounds(Camera cam)\n  {\n    boolean anything = false;\n    BoundingBox bounds = null;\n    for (ObjectInfo info : getWindow().getSelectedObjects())\n    {\n      BoundingBox objBounds = info.getBounds().transformAndOutset(info.getCoords().fromLocal());\n      if (!anything)\n        bounds = objBounds;\n      else\n        bounds = bounds.merge(objBounds);\n      anything = true;\n    }\n    return (bounds == null ? null : bounds.transformAndOutset(cam.getWorldToView()));\n  }\n\n  public void iconDoubleClicked()\n  {\n    BCheckBox childrenBox = new BCheckBox(Translate.text(\"applyToUnselectedChildren\"), applyToChildren);\n    BComboBox centerChoice = new BComboBox(new String [] {\n      Translate.text(\"individualObjectCenters\"),\n      Translate.text(\"parentObject\"),\n      Translate.text(\"centerOfSelection\")\n    });\n    centerChoice.setSelectedIndex(rotateAround);\n    RowContainer rotateRow = new RowContainer();\n    rotateRow.add(Translate.label(\"rotateAround\"));\n    rotateRow.add(centerChoice);\n    BComboBox scaleChoice = new BComboBox(new String [] {\n      Translate.text(\"remainFixed\"),\n      Translate.text(\"scaleWithObjects\")\n    });\n    scaleChoice.setSelectedIndex(scaleAround);\n    RowContainer scaleRow = new RowContainer();\n    scaleRow.add(Translate.label(\"objectPositions\"));\n    scaleRow.add(scaleChoice);\n    ComponentsDialog dlg = new ComponentsDialog(theFrame, Translate.text(\"moveRotateResizeToolTitle\"),\n                new Widget [] {childrenBox, rotateRow, scaleRow}, new String [] {null, null, null});\n    if (!dlg.clickedOk())\n      return;\n    applyToChildren = childrenBox.getState();\n    rotateAround = centerChoice.getSelectedIndex();\n    scaleAround = scaleChoice.getSelectedIndex();\n  }\n}\n", "human_rating": 2.4550214908, "metadata": {"project": "aoi", "class": "artofillusion.MoveScaleRotateObjectTool", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/MoveScaleRotateObjectTool.java", "label_probabilities": {"readability": [3.16977e-05, 0.496665, 0.461597, 0.0417057], "understandability": [1.37164e-05, 0.00131198, 0.551269, 0.447405], "complexity": [0.295799, 0.703915, 0.000285956, 0.0], "modularization": [0.249701, 0.723729, 0.0265661, 4.05562e-06], "overall": [0.0, 0.000145129, 0.144014, 0.855841]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.object.ImplicitObject", "source": "/* Copyright (C) 2006-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.object;\n\nimport artofillusion.math.*;\nimport artofillusion.*;\n\nimport java.awt.Point;\nimport java.io.*;\nimport java.util.*;\n\n/**\n * This abstract class represents an object whose surface is defined as an isosurface of a\n * 3D field function.  Subclasses define the function and isosurface value used to generate\n * a particular surface.  More precisely, the interior of the object is defined to consist of\n * all points which satisfy the following conditions:\n * <ol>\n * <li>The value of the field at that point is greater than the cutoff value.</li>\n * <li>The point is inside the bounding box returned by getBounds().</li>\n * </ol>\n * In general, an implicit surface can be rendered in two different ways: by triangulating the\n * surface, or by directly evaluating the field function (e.g. raymarching).  Some renderers do not\n * have the ability to visualize implicit surfaces directly, and therefore must use triangulation.\n * When direct visualization is supported, the object can specify which is the preferred method to use.\n * It does this by implementing getPreferDirectRendering().\n */\n\npublic abstract class ImplicitObject extends Object3D\n{\n  private RenderingMesh cachedMesh;\n  private WireframeMesh cachedWireframe;\n  private double lastTime;\n\n  /**\n   * Get the value of the field function at a point specified in object coordinates.\n   *\n   * @param x       the x coordinate of the location at which to evaluate the function\n   * @param y       the y coordinate of the location at which to evaluate the function\n   * @param z       the z coordinate of the location at which to evaluate the function\n   * @param size    the width of the region over which to average the function for antialiasing\n   * @param time    the time at which the function is being evaluated\n   * @return the value of the field function at the specified location\n   */\n\n  public abstract double getFieldValue(double x, double y, double z, double size, double time);\n\n  /**\n   * Get the gradient of the field function at a point specified in object coordinates.\n   * <p>\n   * The default implementation of this method estimates the gradient by evaluating the\n   * field function at several closely spaced points.  In many cases, it is possible to calculate\n   * the gradient both more quickly and more accurately by analytical means.  Whenever possible,\n   * this method should be overridden to calculate the gradient directly.\n   *\n   * @param x       the x coordinate of the location at which to evaluate the function\n   * @param y       the y coordinate of the location at which to evaluate the function\n   * @param z       the z coordinate of the location at which to evaluate the function\n   * @param size    the width of the region over which to average the function for antialiasing\n   * @param time    the time at which the function is being evaluated\n   * @param grad    on exit, this should be set equal to the gradient of the field function at\n   *                the specified location\n   */\n\n  public void getFieldGradient(double x, double y, double z, double size, double time, Vec3 grad)\n  {\n    final double delta = 0.5*size;\n    final double invDelta = 1.0/delta;\n    double val = getFieldValue(x, y, z, size, time);\n    grad.x = (getFieldValue(x+delta, y, z, size, time)-val)*invDelta;\n    grad.y = (getFieldValue(x, y+delta, z, size, time)-val)*invDelta;\n    grad.z = (getFieldValue(x, y, z+delta, size, time)-val)*invDelta;\n  }\n\n  /**\n   * Get the maximum value which can ever occur for the absolute value of the field gradient.\n   * The default implementation returns Double.MAX_VALUE.  If you can guarantee that the\n   * gradient will never be larger than some fixed value, overriding this method to return it\n   * may allow faster rendering.\n   */\n\n  public double getMaxGradient()\n  {\n    return Double.MAX_VALUE;\n  }\n\n  /**\n   * Get the cutoff value which defines the surface of the object.  Points for which\n   * the field value is greater than the cutoff are inside the object.\n   * <p>\n   * The default implementation returns 1.0.  It may be overridden to return a different value.\n   */\n\n  public double getCutoff()\n  {\n    return 1.0;\n  }\n\n  /**\n   * Get the preferred rendering method to use when this object is rendered by a renderer that\n   * supports direct evaluation of the field.\n   *\n   * @return true if direct evaluation is preferred, false if it is preferable to triangulate the\n   * surface by calling getRenderingMesh()\n   */\n\n  public abstract boolean getPreferDirectRendering();\n\n  /**\n   * The default constructor does nothing.\n   */\n\n  public ImplicitObject()\n  {\n  }\n\n  /**\n   * Subclasses should invoke this method in their own constructors for loading from a file.\n   */\n\n  public ImplicitObject(DataInputStream in, Scene theScene) throws IOException, InvalidObjectException\n  {\n    super(in, theScene);\n  }\n\n  /**\n   * Subclasses should invoke this method in their own writeToFile() methods.\n   */\n\n  public void writeToFile(DataOutputStream out, Scene theScene) throws IOException\n  {\n    super.writeToFile(out, theScene);\n  }\n\n  @Override\n  public int canConvertToTriangleMesh()\n  {\n    return APPROXIMATELY;\n  }\n\n  @Override\n  public TriangleMesh convertToTriangleMesh(double tol)\n  {\n    ArrayList<Vec3> vertices = new ArrayList<Vec3>();\n    ArrayList<int[]> faces = new ArrayList<int[]>();\n    generateMesh(tol, vertices, faces);\n    Vec3 vert[] = vertices.toArray(new Vec3[vertices.size()]);\n    int face[][] = faces.toArray(new int[faces.size()][]);\n    return new TriangleMesh(vert, face);\n  }\n\n  @Override\n  public RenderingMesh getRenderingMesh(double tol, boolean interactive, ObjectInfo info)\n  {\n    if (interactive && cachedMesh != null)\n      return cachedMesh;\n    if (interactive)\n    {\n      // Limit the tolerance to avoid creating huge interactive meshes.\n\n      BoundingBox bounds = getBounds();\n      double volume = (bounds.maxx-bounds.minx)*(bounds.maxy-bounds.miny)*(bounds.maxz-bounds.minz);\n      double cells = volume/(tol*tol*tol);\n      if (cells > 1e6)\n        tol = Math.pow(volume/1e6, 1.0/3.0);\n    }\n    ArrayList<Vec3> vertices = new ArrayList<Vec3>();\n    ArrayList<int[]> faces = new ArrayList<int[]>();\n    generateMesh(tol, vertices, faces);\n    RenderingTriangle tri[] = new RenderingTriangle[faces.size()];\n    Vec3 vert[] = vertices.toArray(new Vec3[vertices.size()]);\n    for (int i = 0; i < tri.length; i++)\n    {\n      int face[] = faces.get(i);\n      tri[i] = texMapping.mapTriangle(face[0], face[1], face[2], face[0], face[1], face[2], vert);\n    }\n    Vec3 norm[] = new Vec3[vert.length];\n    for (int i = 0; i < vert.length; i++)\n    {\n      norm[i] = new Vec3();\n      getFieldGradient(vert[i].x, vert[i].y, vert[i].z, tol, lastTime, norm[i]);\n      norm[i].normalize();\n      norm[i].scale(-1);\n    }\n    RenderingMesh mesh = new RenderingMesh(vert, norm, tri, texMapping, matMapping);\n    if (interactive)\n      cachedMesh = mesh;\n    return mesh;\n  }\n\n  @Override\n  public WireframeMesh getWireframeMesh()\n  {\n    if (cachedWireframe == null)\n    {\n      RenderingMesh mesh = cachedMesh;\n      if (mesh == null)\n        mesh = getRenderingMesh(ArtOfIllusion.getPreferences().getInteractiveSurfaceError(), false, null);\n      HashSet<Point> edges = new HashSet<Point>();\n      for (RenderingTriangle tri : mesh.triangle)\n      {\n        edges.add(new Point(Math.min(tri.v1, tri.v2), Math.max(tri.v1, tri.v2)));\n        edges.add(new Point(Math.min(tri.v2, tri.v3), Math.max(tri.v2, tri.v3)));\n        edges.add(new Point(Math.min(tri.v3, tri.v1), Math.max(tri.v3, tri.v1)));\n      }\n      int from[] = new int[edges.size()];\n      int to[] = new int[edges.size()];\n      int index = 0;\n      for (Point point : edges)\n      {\n        from[index] = point.x;\n        to[index++] = point.y;\n      }\n      cachedWireframe = new WireframeMesh(mesh.vert, from, to);\n    }\n    return cachedWireframe;\n  }\n\n  protected void clearCachedMesh()\n  {\n    cachedMesh = null;\n    cachedWireframe = null;\n  }\n\n  public void sceneChanged(ObjectInfo info, Scene scene)\n  {\n    if (lastTime != scene.getTime())\n    {\n      lastTime = scene.getTime();\n      info.clearCachedMeshes();\n    }\n  }\n\n  private static final int vertexOffset[][] = new int[][]\n  {\n    {0, 0, 0},{1, 0, 0},{1, 1, 0},{0, 1, 0},\n    {0, 0, 1},{1, 0, 1},{1, 1, 1},{0, 1, 1}\n  };\n\n  private static final double edgeDirection[][] = new double[][]\n  {\n      {1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{-1.0, 0.0, 0.0},{0.0, -1.0, 0.0},\n      {1.0, 0.0, 0.0},{0.0, 1.0, 0.0},{-1.0, 0.0, 0.0},{0.0, -1.0, 0.0},\n      {0.0, 0.0, 1.0},{0.0, 0.0, 1.0},{ 0.0, 0.0, 1.0},{0.0,  0.0, 1.0}\n  };\n  private static final int edgeConnection[][] = new int[][]\n  {\n      {0,1}, {1,2}, {2,3}, {3,0},\n      {4,5}, {5,6}, {6,7}, {7,4},\n      {0,4}, {1,5}, {2,6}, {3,7}\n  };\n  private static final int cubeEdgeFlags[] = new int[]\n  {\n      0x000, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,\n      0x190, 0x099, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,\n      0x230, 0x339, 0x033, 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,\n      0x3a0, 0x2a9, 0x1a3, 0x0aa, 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,\n      0x460, 0x569, 0x663, 0x76a, 0x066, 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,\n      0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0x0ff, 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,\n      0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x055, 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,\n      0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0x0cc, 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,\n      0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0x0cc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,\n      0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x055, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,\n      0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0x0ff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,\n      0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x066, 0x76a, 0x663, 0x569, 0x460,\n      0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0x0aa, 0x1a3, 0x2a9, 0x3a0,\n      0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x033, 0x339, 0x230,\n      0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x099, 0x190,\n      0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x000\n  };\n  private static final int triangleConnectionTable[][] = new int[][]\n  {\n      {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1},\n      {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1},\n      {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1},\n      {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1},\n      {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1},\n      {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1},\n      {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1},\n      {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1},\n      {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1},\n      {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1},\n      {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1},\n      {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1},\n      {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1},\n      {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1},\n      {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1},\n      {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1},\n      {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1},\n      {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1},\n      {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1},\n      {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1},\n      {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1},\n      {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1},\n      {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1},\n      {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1},\n      {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1},\n      {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1},\n      {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1},\n      {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1},\n      {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1},\n      {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1},\n      {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1},\n      {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1},\n      {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1},\n      {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1},\n      {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1},\n      {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1},\n      {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1},\n      {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1},\n      {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1},\n      {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1},\n      {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1},\n      {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1},\n      {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1},\n      {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1},\n      {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1},\n      {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1},\n      {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1},\n      {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1},\n      {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1},\n      {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1},\n      {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1},\n      {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1},\n      {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1},\n      {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1},\n      {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1},\n      {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1},\n      {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1},\n      {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1},\n      {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1},\n      {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1},\n      {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1},\n      {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1},\n      {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1},\n      {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1},\n      {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1},\n      {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1},\n      {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1},\n      {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1},\n      {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1},\n      {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1},\n      {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1},\n      {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1},\n      {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1},\n      {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1},\n      {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1},\n      {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1},\n      {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1},\n      {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1},\n      {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1},\n      {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1},\n      {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1},\n      {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1},\n      {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1},\n      {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1},\n      {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1},\n      {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1},\n      {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1},\n      {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1},\n      {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1},\n      {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1},\n      {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1},\n      {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1},\n      {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1},\n      {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1},\n      {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1},\n      {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1},\n      {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1},\n      {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1},\n      {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1},\n      {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1},\n      {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1},\n      {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1},\n      {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1},\n      {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1},\n      {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1},\n      {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1},\n      {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1},\n      {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1},\n      {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1},\n      {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1},\n      {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1},\n      {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1},\n      {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1},\n      {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1},\n      {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1},\n      {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1},\n      {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1},\n      {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1},\n      {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1},\n      {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1},\n      {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1},\n      {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1},\n      {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1},\n      {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1},\n      {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1},\n      {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1},\n      {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1},\n      {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1},\n      {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1},\n      {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1},\n      {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1},\n      {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1},\n      {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1},\n      {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1},\n      {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1},\n      {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1},\n      {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1},\n      {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1},\n      {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1},\n      {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1},\n      {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1},\n      {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1},\n      {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1},\n      {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1},\n      {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1},\n      {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1},\n      {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1},\n      {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1},\n      {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1},\n      {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1},\n      {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1},\n      {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1},\n      {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1},\n      {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1},\n      {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1},\n      {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1},\n      {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1},\n      {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1},\n      {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1},\n      {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1},\n      {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1},\n      {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1},\n      {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1},\n      {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1},\n      {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1},\n      {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1},\n      {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1},\n      {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1},\n      {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1},\n      {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1},\n      {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1},\n      {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1},\n      {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1},\n      {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1},\n      {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1},\n      {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1},\n      {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1},\n      {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1},\n      {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1},\n      {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}\n  };\n\n  /**\n   * Construct a mesh from the implicit function.\n   *\n   * @param tol        the surface error tolerance\n   * @param vertices   the coordinates of mesh vertices will be added to this List\n   * @param faces      an int[3] will be added to this List containing the vertex indices for each mesh face\n   */\n\n  public void generateMesh(double tol, List<Vec3> vertices, List<int[]> faces)\n  {\n    BoundingBox bounds = getBounds();\n    int xsize = (int) Math.ceil((bounds.maxx-bounds.minx)/tol)+1;\n    int ysize = (int) Math.ceil((bounds.maxy-bounds.miny)/tol)+1;\n    int zsize = (int) Math.ceil((bounds.maxz-bounds.minz)/tol)+1;\n    double xscale = (bounds.maxx-bounds.minx)/xsize;\n    double yscale = (bounds.maxy-bounds.miny)/ysize;\n    double zscale = (bounds.maxz-bounds.minz)/zsize;\n    double cornerValues[] = new double[8];\n    int edgeVertIndex[] = new int[12];\n    HashMap<Integer, Integer> xEdgeVertMap = new HashMap<Integer, Integer>();\n    HashMap<Integer, Integer> yEdgeVertMap = new HashMap<Integer, Integer>();\n    HashMap<Integer, Integer> zEdgeVertMap = new HashMap<Integer, Integer>();\n    double cutoff = getCutoff();\n\n    // Look up the values for the x==minx plane.\n\n    double values[][] = new double[2][ysize*zsize];\n    for (int j = 0; j < ysize; j++)\n      for (int k = 0; k < zsize; k++)\n        values[0][j*zsize+k] = getFieldValue(bounds.minx, bounds.miny+j*yscale, bounds.minz+k*zscale, tol, lastTime)-cutoff;\n    for (int i = 0; i < xsize; i++)\n    {\n      // Look up the values for the next plane.\n\n      for (int j = 0; j < ysize-1; j++)\n        for (int k = 0; k < zsize-1; k++)\n          values[1][j*zsize+k] = getFieldValue(bounds.minx+i*xscale, bounds.miny+j*yscale, bounds.minz+k*zscale, tol, lastTime)-cutoff;\n      for (int j = 0; j < ysize-1; j++)\n      {\n        for (int k = 0; k < zsize-1; k++)\n        {\n          // Record the values at the four corners of this cell, and record which ones are outside.\n\n          int flagIndex = 0;\n          for (int corner = 0; corner < 8; corner++)\n          {\n            cornerValues[corner] = values[vertexOffset[corner][0]][(j+vertexOffset[corner][1])*zsize+k+vertexOffset[corner][2]];\n            if (cornerValues[corner] <= 0)\n              flagIndex += 1<<corner;\n          }\n          int edgeFlag = cubeEdgeFlags[flagIndex];\n          if (edgeFlag == 0)\n            continue;\n          double baseX = xscale*i+bounds.minx;\n          double baseY = yscale*j+bounds.miny;\n          double baseZ = zscale*k+bounds.minz;\n\n          // Compute a vertex for each edge of the cell that intersects the surface.\n\n          for (int edge = 0; edge < 12; edge++)\n          {\n            if ((edgeFlag&(1<<edge)) != 0)\n            {\n              int corner1 = edgeConnection[edge][0];\n              int vert1 = ysize*zsize*(i+vertexOffset[corner1][0])+zsize*(j+vertexOffset[corner1][1])+(k+vertexOffset[corner1][2]);\n              int corner2 = edgeConnection[edge][1];\n              int vert2 = ysize*zsize*(i+vertexOffset[corner2][0])+zsize*(j+vertexOffset[corner2][1])+(k+vertexOffset[corner2][2]);\n              Integer firstVert = (vert1 < vert2 ? vert1 : vert2);\n\n              // See if we already created a vertex for this edge.\n\n              if (edgeDirection[edge][0] != 0.0)\n              {\n                Integer vertIndex = xEdgeVertMap.get(firstVert);\n                if (vertIndex == null)\n                  xEdgeVertMap.put(firstVert, vertices.size());\n                else\n                {\n                  edgeVertIndex[edge] = vertIndex;\n                  continue;\n                }\n              }\n              if (edgeDirection[edge][1] != 0.0)\n              {\n                Integer vertIndex = yEdgeVertMap.get(firstVert);\n                if (vertIndex == null)\n                  yEdgeVertMap.put(firstVert, vertices.size());\n                else\n                {\n                  edgeVertIndex[edge] = vertIndex;\n                  continue;\n                }\n              }\n              if (edgeDirection[edge][2] != 0.0)\n              {\n                Integer vertIndex = zEdgeVertMap.get(firstVert);\n                if (vertIndex == null)\n                  zEdgeVertMap.put(firstVert, vertices.size());\n                else\n                {\n                  edgeVertIndex[edge] = vertIndex;\n                  continue;\n                }\n              }\n\n              // Create a new vertex.\n\n              edgeVertIndex[edge] = vertices.size();\n              double offset = findOffset(cornerValues[edgeConnection[edge][0]], cornerValues[edgeConnection[edge][1]]);\n              vertices.add(new Vec3(\n                  baseX+(vertexOffset[edgeConnection[edge][0]][0]+offset*edgeDirection[edge][0])*xscale,\n                  baseY+(vertexOffset[edgeConnection[edge][0]][1]+offset*edgeDirection[edge][1])*yscale,\n                  baseZ+(vertexOffset[edgeConnection[edge][0]][2]+offset*edgeDirection[edge][2])*zscale\n              ));\n            }\n          }\n\n          // Create new faces.\n\n          for (int face = 0; face < 5; face++)\n          {\n            if (triangleConnectionTable[flagIndex][3*face] < 0)\n              break;\n            faces.add(new int[] {\n                edgeVertIndex[triangleConnectionTable[flagIndex][3*face]],\n                edgeVertIndex[triangleConnectionTable[flagIndex][3*face+1]],\n                edgeVertIndex[triangleConnectionTable[flagIndex][3*face+2]],\n            });\n          }\n        }\n      }\n\n      // Clean up the edge vertex maps, deleting records for vertices that we don't need any more.\n\n      int firstNeeded = ysize*zsize*(i+1);\n      Iterator<Map.Entry<Integer, Integer>> xiter = xEdgeVertMap.entrySet().iterator();\n      while (xiter.hasNext())\n        if (xiter.next().getKey() < firstNeeded)\n          xiter.remove();\n      Iterator<Map.Entry<Integer, Integer>> yiter = yEdgeVertMap.entrySet().iterator();\n      while (yiter.hasNext())\n        if (yiter.next().getKey() < firstNeeded)\n          yiter.remove();\n      Iterator<Map.Entry<Integer, Integer>> ziter = zEdgeVertMap.entrySet().iterator();\n      while (ziter.hasNext())\n        if (ziter.next().getKey() < firstNeeded)\n          ziter.remove();\n\n      // Swap the value arrays so the values for x==i+1 will be in values[0].\n\n      double temp[] = values[0];\n      values[0] = values[1];\n      values[1] = temp;\n    }\n  }\n\n  private static double findOffset(double value1, double value2)\n  {\n    double delta = value2-value1;\n    if (delta == 0.0)\n      return 0.5;\n    double offset = -value1/delta;\n\n    // Don't let the offset go all the way to either end, to avoid creating degenerate triangles.\n\n    if (offset < 0.01)\n      return 0.01;\n    if (offset > 0.99)\n      return 0.99;\n    return offset;\n  }\n}\n", "human_rating": 2.8795029823875997, "metadata": {"project": "aoi", "class": "artofillusion.object.ImplicitObject", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/object/ImplicitObject.java", "label_probabilities": {"readability": [4.24518e-06, 0.879494, 0.120502, 1.6676e-09], "understandability": [1.53126e-09, 1.95545e-05, 7.60514e-06, 0.999973], "complexity": [0.967037, 0.0329634, 7.87874e-10, 0.0], "modularization": [0.896138, 0.103431, 0.000431154, 5.27637e-10], "overall": [0.0, 1.88614e-05, 0.0113335, 0.988648]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.object.MeshVertex", "source": "/* Copyright (C) 1999-2004 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.object;\n\nimport artofillusion.math.*;\n\n/** MeshVertex represents a vertex in a mesh object. */\n\npublic class MeshVertex\n{\n  public Vec3 r;\n  public int ikJoint;\n  public double ikWeight;\n  \n  public MeshVertex(Vec3 p)\n  {\n    r = p;\n    ikJoint = -1;\n    ikWeight = 1.0;\n  }\n  \n  public MeshVertex(MeshVertex v)\n  {\n    r = new Vec3(v.r);\n    ikJoint = v.ikJoint;\n    ikWeight = v.ikWeight;\n  }\n  \n  /** Create a new MeshVertex which is a weighted average of two other ones. */\n  \n  public static MeshVertex blend(MeshVertex v1, MeshVertex v2, double w1, double w2)\n  {\n    MeshVertex v = new MeshVertex (new Vec3(w1*v1.r.x + w2*v2.r.x,\n    \tw1*v1.r.y + w2*v2.r.y, w1*v1.r.z + w2*v2.r.z));\n    if (v1.ikJoint == v2.ikJoint)\n      {\n        v.ikJoint = v1.ikJoint;\n        v.ikWeight = (w1*v1.ikWeight + w2*v2.ikWeight);\n      }\n    else if (v2.ikWeight > v1.ikWeight)\n      {\n        v.ikJoint = v2.ikJoint;\n        v.ikWeight = v2.ikWeight;\n      }\n    else\n      {\n        v.ikJoint = v1.ikJoint;\n        v.ikWeight = v1.ikWeight;\n      }\n    return v;\n  }\n}", "human_rating": 3.02149060000394, "metadata": {"project": "aoi", "class": "artofillusion.object.MeshVertex", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/object/MeshVertex.java", "label_probabilities": {"readability": [0.0405447, 0.940401, 0.0190544, 3.94009e-12], "understandability": [6.32424e-09, 2.5114e-08, 2.368e-09, 1.0], "complexity": [3.53704e-07, 0.543985, 0.456014, 3.75009e-10], "modularization": [0.0, 3.25912e-09, 0.897045, 0.102955], "overall": [7.70063e-07, 0.699322, 0.300677, 1.09911e-13]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.object.ReferenceImage", "source": "/* Copyright (C) 2007 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.object;\n\nimport artofillusion.math.*;\nimport artofillusion.*;\nimport artofillusion.animation.*;\n\nimport javax.imageio.*;\nimport java.awt.*;\nimport java.awt.image.*;\nimport java.io.*;\n\n/**\n * A ReferenceImage is an object that displays an image for use during modelling.  When drawn\n * in a ViewerCanvas, it is a rectangle with the image mapped to it, but when rendered by a\n * Renderer, it is invisible.\n */\n\npublic class ReferenceImage extends Object3D\n{\n  private double width, height;\n  private Image image;\n\n  /**\n   * Create a ReferenceImage whose width and height are both 1.0, and with no image set.\n   */\n\n  public ReferenceImage()\n  {\n    width = 1.0;\n    height = 1.0;\n  }\n\n  public ReferenceImage(Image image)\n  {\n    this.image = image;\n    width = 0.01*image.getWidth(null);\n    height = 0.01*image.getHeight(null);\n  }\n\n  /**\n   * Get the Image displayed by this object.\n   */\n\n  public Image getImage()\n  {\n    return image;\n  }\n\n  /**\n   * Set the Image displayed by this object.\n   */\n\n  public void setImage(Image image)\n  {\n    this.image = image;\n  }\n\n\n  public boolean canSetTexture()\n  {\n    return false;\n  }\n\n  public Object3D duplicate()\n  {\n    ReferenceImage ri = new ReferenceImage();\n    ri.image = image;\n    ri.width = width;\n    ri.height = height;\n    return ri;\n  }\n\n  public void copyObject(Object3D obj)\n  {\n    ReferenceImage ri = (ReferenceImage) obj;\n    image = ri.image;\n    width = ri.width;\n    height = ri.height;\n  }\n\n  public BoundingBox getBounds()\n  {\n    return new BoundingBox(-0.5*width, 0.5*width, -0.5*height, 0.5*height, 0.0, 0.0);\n  }\n\n  public void setSize(double xsize, double ysize, double zsize)\n  {\n    width = xsize;\n    height = ysize;\n  }\n\n  public WireframeMesh getWireframeMesh()\n  {\n    Vec3 vert[] = new Vec3[] {new Vec3(-0.5*width, 0.5*height, 0.0), new Vec3(0.5*width, 0.5*height, 0.0),\n        new Vec3(0.5*width, -0.5*height, 0.0), new Vec3(-0.5*width, -0.5*height, 0.0)};\n    int from[] = new int[] {0, 1, 2, 3};\n    int to[] = new int[] {1, 2, 3, 0};\n    return new WireframeMesh(vert, from, to);\n  }\n\n  public Keyframe getPoseKeyframe()\n  {\n    return new NullKeyframe();\n  }\n\n  public void applyPoseKeyframe(Keyframe k)\n  {\n  }\n\n  /**\n   * This method is overridden to render the reference image into the ViewerCanvas.\n   */\n\n  public void renderObject(ObjectInfo obj, ViewerCanvas canvas, Vec3 viewDir)\n  {\n    if (image == null)\n      super.renderObject(obj, canvas, viewDir);\n    else\n      canvas.renderImage(image, new Vec3(-0.5*width, -0.5*height, 0.0), new Vec3(0.5*width, -0.5*height, 0.0),\n        new Vec3(0.5*width, 0.5*height, 0.0), new Vec3(-0.5*width, 0.5*height, 0.0));\n  }\n\n  /**\n   * Reconstruct a ReferenceImage that was saved to a file.\n   */\n\n  public ReferenceImage(DataInputStream in, Scene theScene) throws IOException\n  {\n    super(in, theScene);\n    short version = in.readShort();\n    if (version != 0)\n      throw new InvalidObjectException(\"\");\n    width = in.readDouble();\n    height = in.readDouble();\n    byte imageData[] = new byte [in.readInt()];\n    in.readFully(imageData);\n    image = ImageIO.read(new ByteArrayInputStream(imageData));\n  }\n\n  public void writeToFile(DataOutputStream out, Scene theScene) throws IOException\n  {\n    super.writeToFile(out, theScene);\n    out.writeShort(0);\n    out.writeDouble(width);\n    out.writeDouble(height);\n\n    // Save the image to the file.\n\n    ByteArrayOutputStream baos = new ByteArrayOutputStream();\n    if (image instanceof RenderedImage)\n      ImageIO.write((RenderedImage) image, \"png\", baos);\n    else\n    {\n      // We need to copy it into a BufferedImage.\n\n      BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n      Graphics2D g = bi.createGraphics();\n      g.drawImage(image, 0, 0, null);\n      g.dispose();\n      ImageIO.write(bi, \"png\", baos);\n    }\n    out.writeInt(baos.size());\n    out.write(baos.toByteArray());\n  }\n}\n", "human_rating": 2.4260475855399997, "metadata": {"project": "aoi", "class": "artofillusion.object.ReferenceImage", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/object/ReferenceImage.java", "label_probabilities": {"readability": [5.93656e-06, 0.426038, 0.573954, 1.8393e-06], "understandability": [1.58351e-05, 0.177255, 0.822728, 1.47673e-06], "complexity": [0.000869818, 0.416608, 0.582523, 4.00404e-10], "modularization": [6.40732e-11, 0.542205, 0.457795, 8.30816e-11], "overall": [3.09088e-06, 0.949007, 0.0509891, 5.86689e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.ObjectPropertiesPanel", "source": "/* Copyright (C) 2006-2009 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport buoy.widget.*;\nimport buoy.event.*;\nimport artofillusion.ui.*;\nimport artofillusion.object.*;\nimport artofillusion.math.*;\nimport artofillusion.texture.*;\nimport artofillusion.material.*;\n\nimport javax.swing.*;\nimport java.lang.reflect.*;\nimport java.util.*;\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.util.List;\n\n/**\n * This is a panel which displays information about the currently selected objects, and allows them\n * to be edited.\n */\n\npublic class ObjectPropertiesPanel extends ColumnContainer\n{\n  private LayoutWindow window;\n  private BTextField nameField;\n  private ValueField xPosField, yPosField, zPosField, xRotField, yRotField, zRotField;\n  private BComboBox textureChoice, materialChoice;\n  private PropertyEditor propEditor[];\n  private ObjectInfo objects[];\n  private Property properties[];\n  private Object3D previousObjects[];\n  private boolean ignoreNextChange;\n  private Widget lastEventSource;\n  private ActionProcessor paramChangeProcessor;\n\n  public ObjectPropertiesPanel(LayoutWindow window)\n  {\n    this.window = window;\n    nameField = new BTextField();\n    xPosField = new ValueField(0.0, ValueField.NONE, 1);\n    yPosField = new ValueField(0.0, ValueField.NONE, 1);\n    zPosField = new ValueField(0.0, ValueField.NONE, 1);\n    xRotField = new ValueField(0.0, ValueField.NONE, 1);\n    yRotField = new ValueField(0.0, ValueField.NONE, 1);\n    zRotField = new ValueField(0.0, ValueField.NONE, 1);\n    textureChoice = new BComboBox();\n    materialChoice = new BComboBox();\n    paramChangeProcessor = new ActionProcessor();\n    rebuildContents();\n    window.addEventLink(SceneChangedEvent.class, this, \"rebuildContents\");\n    nameField.addEventLink(FocusLostEvent.class, this, \"nameChanged\");\n    nameField.addEventLink(KeyPressedEvent.class, this, \"nameChanged\");\n    xPosField.addEventLink(ValueChangedEvent.class, this, \"coordinatesChanged\");\n    yPosField.addEventLink(ValueChangedEvent.class, this, \"coordinatesChanged\");\n    zPosField.addEventLink(ValueChangedEvent.class, this, \"coordinatesChanged\");\n    xRotField.addEventLink(ValueChangedEvent.class, this, \"coordinatesChanged\");\n    yRotField.addEventLink(ValueChangedEvent.class, this, \"coordinatesChanged\");\n    zRotField.addEventLink(ValueChangedEvent.class, this, \"coordinatesChanged\");\n    textureChoice.addEventLink(ValueChangedEvent.class, this, \"textureChanged\");\n    materialChoice.addEventLink(ValueChangedEvent.class, this, \"materialChanged\");\n    ListChangeListener listener = new ListChangeListener()\n    {\n      public void itemAdded(int index, Object obj)\n      {\n        rebuildContents();\n      }\n      public void itemRemoved(int index, Object obj)\n      {\n        rebuildContents();\n      }\n      public void itemChanged(int index, Object obj)\n      {\n        rebuildContents();\n      }\n    };\n    window.getScene().addTextureListener(listener);\n    window.getScene().addMaterialListener(listener);\n  }\n\n  /**\n   * Rebuild the contents of the panel.\n   */\n\n  protected void rebuildContents()\n  {\n    if (ignoreNextChange)\n    {\n      ignoreNextChange = false;\n      return;\n    }\n    if (lastEventSource == nameField)\n      nameChanged(new FocusLostEvent(nameField, false)); // Commit name changes.\n\n    // Find the selected objects.\n\n    Scene scene = window.getScene();\n    int sel[] = window.getSelectedIndices();\n    objects = new ObjectInfo [sel.length];\n    for (int i = 0; i < sel.length; i++)\n      objects[i] = scene.getObject(sel[i]);\n    boolean objectsChanged = (previousObjects == null || objects.length != previousObjects.length);\n    for (int i = 0; i < objects.length && !objectsChanged; i++)\n      objectsChanged |= (objects[i].getObject() != previousObjects[i]);\n    if (objectsChanged)\n    {\n      previousObjects = new Object3D[objects.length];\n      for (int i = 0; i < objects.length; i++)\n        previousObjects[i] = objects[i].getObject();\n    }\n\n    // If nothing is selected, just place a message in the panel.\n\n    if (objects.length == 0)\n    {\n      if (objectsChanged)\n      {\n        removeAll();\n        add(Translate.label(\"noObjectsSelected\"));\n        UIUtilities.applyDefaultBackground(this);\n        UIUtilities.applyDefaultFont(this);\n        if (getParent() != null)\n          getParent().layoutChildren();\n        repaint();\n      }\n      return;\n    }\n\n    // Set the name.\n\n    if (objects.length == 1)\n      nameField.setText(objects[0].getName());\n\n    // Set the position and orientation.\n\n    Vec3 origin = objects[0].getCoords().getOrigin();\n    xPosField.setValue(origin.x);\n    yPosField.setValue(origin.y);\n    zPosField.setValue(origin.z);\n    double angles[] = objects[0].getCoords().getRotationAngles();\n    xRotField.setValue(angles[0]);\n    yRotField.setValue(angles[1]);\n    zRotField.setValue(angles[2]);\n    for (int i = 1; i < objects.length; i++)\n    {\n      origin = objects[i].getCoords().getOrigin();\n      checkFieldValue(xPosField, origin.x);\n      checkFieldValue(yPosField, origin.y);\n      checkFieldValue(zPosField, origin.z);\n      angles = objects[i].getCoords().getRotationAngles();\n      checkFieldValue(xRotField, angles[0]);\n      checkFieldValue(yRotField, angles[1]);\n      checkFieldValue(zRotField, angles[2]);\n    }\n\n    // Set the texture.\n\n    Texture tex = objects[0].getObject().getTexture();\n    boolean canSetTexture = objects[0].getObject().canSetTexture();\n    boolean sameTexture = true;\n    for (int i = 1; i < objects.length; i++)\n    {\n      Texture thisTex = objects[i].getObject().getTexture();\n      if (thisTex != tex)\n        sameTexture = false;\n      canSetTexture &= objects[i].getObject().canSetTexture();\n    }\n    if (canSetTexture)\n    {\n      Vector<String> names = new Vector<String>();\n      int selected = -1;\n      for (int i = 0; i < scene.getNumTextures(); i++)\n      {\n        names.add(scene.getTexture(i).getName());\n        if (scene.getTexture(i) == tex)\n          selected = i;\n      }\n      if (!sameTexture)\n      {\n        selected = names.size();\n        names.add(\"\");\n      }\n      else if (tex instanceof LayeredTexture)\n      {\n        selected = names.size();\n        names.add(Translate.text(\"layeredTexture\"));\n      }\n      List<Texture> textureTypes = PluginRegistry.getPlugins(Texture.class);\n      for (Texture texture : textureTypes)\n      {\n        try\n        {\n          Method mtd = texture.getClass().getMethod(\"getTypeName\", null);\n          names.add(Translate.text(\"newTextureOfType\", mtd.invoke(null, null)));\n        }\n        catch (Exception ex)\n        {\n          ex.printStackTrace();\n        }\n      }\n      textureChoice.setModel(new DefaultComboBoxModel(names));\n      textureChoice.setSelectedIndex(selected);\n    }\n\n    // Set the material.\n\n    Material mat = objects[0].getObject().getMaterial();\n    boolean canSetMaterial = objects[0].getObject().canSetMaterial();\n    boolean sameMaterial = true;\n    for (int i = 1; i < objects.length; i++)\n    {\n      Material thisMat = objects[i].getObject().getMaterial();\n      if (thisMat != mat)\n        sameMaterial = false;\n      canSetMaterial &= objects[i].getObject().canSetMaterial();\n    }\n    if (canSetMaterial)\n    {\n      Vector<String> names = new Vector<String>();\n      int selected = -1;\n      for (int i = 0; i < scene.getNumMaterials(); i++)\n      {\n        names.add(scene.getMaterial(i).getName());\n        if (scene.getMaterial(i) == mat)\n          selected = i;\n      }\n      if (!sameMaterial)\n      {\n        selected = names.size();\n        names.add(\"\");\n      }\n      else if (mat == null)\n        selected = names.size();\n      names.add(Translate.text(\"none\"));\n      List<Material> materialTypes = PluginRegistry.getPlugins(Material.class);\n      for (Material material : materialTypes)\n      {\n        try\n        {\n          Method mtd = material.getClass().getMethod(\"getTypeName\", null);\n          names.add(Translate.text(\"newMaterialOfType\", mtd.invoke(null, null)));\n        }\n        catch (Exception ex)\n        {\n          ex.printStackTrace();\n        }\n      }\n      materialChoice.setModel(new DefaultComboBoxModel(names));\n      materialChoice.setSelectedIndex(selected);\n    }\n\n    // See whether the list of properties has changed.\n\n    Property oldProperties[] = properties;\n    findProperties();\n    boolean propertiesChanged = (oldProperties == null || properties.length != oldProperties.length);\n    for (int i = 0; i < properties.length && !propertiesChanged; i++)\n      propertiesChanged = !properties[i].equals(oldProperties[i]);\n\n    // Rebuild the panel contents.\n\n    if (!objectsChanged && !propertiesChanged)\n    {\n      showParameterValues();\n      return;\n    }\n    lastEventSource = null;\n    removeAll();\n    LayoutInfo fillLayout = new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.HORIZONTAL, new Insets(2, 2, 2, 2), null);\n    if (objects.length == 1)\n    {\n      add(Translate.label(\"Name\"));\n      add(nameField, fillLayout);\n    }\n    add(Translate.label(\"Position\"));\n    FormContainer positions = new FormContainer(new double [] {0, 1, 0, 1, 0, 1}, new double [1]);\n    positions.add(new BLabel(\"X\"), 0, 0);\n    positions.add(xPosField, 1, 0, fillLayout);\n    positions.add(new BLabel(\" Y\"), 2, 0);\n    positions.add(yPosField, 3, 0, fillLayout);\n    positions.add(new BLabel(\" Z\"), 4, 0);\n    positions.add(zPosField, 5, 0, fillLayout);\n    add(positions, fillLayout);\n    add(Translate.label(\"Orientation\"));\n    FormContainer orientation = new FormContainer(new double [] {0, 1, 0, 1, 0, 1}, new double [1]);\n    orientation.add(new BLabel(\"X\"), 0, 0);\n    orientation.add(xRotField, 1, 0, fillLayout);\n    orientation.add(new BLabel(\" Y\"), 2, 0);\n    orientation.add(yRotField, 3, 0, fillLayout);\n    orientation.add(new BLabel(\" Z\"), 4, 0);\n    orientation.add(zRotField, 5, 0, fillLayout);\n    add(orientation, fillLayout);\n    if (canSetTexture)\n    {\n      add(Translate.label(\"Texture\"));\n      add(textureChoice, fillLayout);\n    }\n    if (canSetMaterial)\n    {\n      add(Translate.label(\"Material\"));\n      add(materialChoice, fillLayout);\n    }\n\n    // Build widgets for object parameters.\n\n    LayoutInfo centerLayout = new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.NONE, new Insets(2, 2, 2, 2), null);\n    propEditor = new PropertyEditor[properties.length];\n    for (int i = 0; i < propEditor.length; i++)\n    {\n      propEditor[i] = new PropertyEditor(properties[i], null);\n      if (propEditor[i].getLabel() != null)\n        add(new BLabel(propEditor[i].getLabel()));\n      Widget widget = propEditor[i].getWidget();\n      widget.addEventLink(ValueChangedEvent.class, this, \"parameterChanged\");\n      if (widget instanceof ValueSelector || widget instanceof BCheckBox || widget instanceof ValueField)\n        add(widget, centerLayout);\n      else\n        add(widget, fillLayout);\n    }\n    showParameterValues();\n\n    // Layout and display the panel.\n\n    UIUtilities.applyDefaultBackground(this);\n    UIUtilities.applyDefaultFont(this);\n    if (getParent() != null)\n      getParent().layoutChildren();\n    repaint();\n  }\n\n  private void checkFieldValue(ValueField field, double value)\n  {\n    if (field.getValue() != value)\n      field.setValue(Double.NaN);\n  }\n\n  /**\n   * Find the list of object properties to display.\n   */\n\n  private void findProperties()\n  {\n    properties = objects[0].getObject().getProperties();\n    for (int i = 1; i < objects.length; i++)\n    {\n      Property otherProperty[] = objects[i].getObject().getProperties();\n      boolean same = (properties.length == otherProperty.length);\n      for (int j = 0; j < properties.length && same; j++)\n        if (!properties[j].equals(otherProperty[j]))\n          same = false;\n      if (!same)\n      {\n        properties = new Property[0];\n        return;\n      }\n    }\n  }\n\n  /**\n   * Update all the ValueSelectors to show the current values of object parameters.\n   */\n\n  private void showParameterValues()\n  {\n    if (propEditor == null)\n      return;\n    Object values[] = new Object [propEditor.length];\n    for (int i = 0; i < values.length; i++)\n      values[i] = objects[0].getObject().getPropertyValue(i);\n    for (int i = 1; i < objects.length; i++)\n    {\n      for (int j = 0; j < values.length; j++)\n        if (values[j] != null && !values[j].equals(objects[i].getObject().getPropertyValue(j)))\n          values[j] = null;\n    }\n    for (int i = 0; i < propEditor.length; i++)\n    {\n      propEditor[i].setValue(values[i]);\n    }\n  }\n\n  /**\n   * This is called when the value in any of the position or orientiation fields is changed.\n   */\n\n  private void coordinatesChanged(ValueChangedEvent ev)\n  {\n    UndoRecord undo = null;\n    if (ev.getWidget() != lastEventSource)\n    {\n      ignoreNextChange = true;\n      undo = new UndoRecord(window, false);\n      for (int i = 0; i < objects.length; i++)\n        undo.addCommand(UndoRecord.COPY_COORDS, new Object [] {objects[i].getCoords(), objects[i].getCoords().duplicate()});\n    }\n    for (int i = 0; i < objects.length; i++)\n    {\n      CoordinateSystem coords = objects[i].getCoords();\n      Vec3 origin = coords.getOrigin();\n      origin.x = getNewValue(origin.x, xPosField.getValue());\n      origin.y = getNewValue(origin.y, yPosField.getValue());\n      origin.z = getNewValue(origin.z, zPosField.getValue());\n      coords.setOrigin(origin);\n      double angles[] = coords.getRotationAngles();\n      angles[0] = getNewValue(angles[0], xRotField.getValue());\n      angles[1] = getNewValue(angles[1], yRotField.getValue());\n      angles[2] = getNewValue(angles[2], zRotField.getValue());\n      coords.setOrientation(angles[0], angles[1], angles[2]);\n    }\n    window.getScene().applyTracksAfterModification(Arrays.asList(objects));\n    lastEventSource = ev.getWidget();\n    if (undo != null)\n      window.setUndoRecord(undo);\n    else\n      window.setModified();\n    window.updateImage();\n  }\n\n  private double getNewValue(double oldval, double newval)\n  {\n    return (Double.isNaN(newval) ? oldval : newval);\n  }\n\n  /**\n   * This is called when an event occurs that might result in the name being changed.\n   */\n\n  private void nameChanged(WidgetEvent ev)\n  {\n    lastEventSource = ev.getWidget();\n    if (ev instanceof KeyPressedEvent && ((KeyPressedEvent) ev).getKeyCode() != KeyEvent.VK_ENTER)\n      return;\n    if (objects.length == 0 || objects[0].getName().equals(nameField.getText()))\n      return;\n    int which = window.getScene().indexOf(objects[0]);\n    window.setUndoRecord(new UndoRecord(window, false, UndoRecord.RENAME_OBJECT, new Object [] {new Integer(which), objects[0].getName()}));\n    window.setObjectName(which, nameField.getText());\n    if (ev instanceof KeyPressedEvent)\n      window.getView().requestFocus(); // This is where they'll probably expect it to go\n  }\n\n  /**\n   * This is called when the texture is changed.\n   */\n\n  private void textureChanged()\n  {\n    int index = textureChoice.getSelectedIndex();\n    Scene scene = window.getScene();\n    Texture tex = null;\n    if (index < scene.getNumTextures())\n      tex = scene.getTexture(index);\n    else\n    {\n      List<Texture> textureTypes = PluginRegistry.getPlugins(Texture.class);\n      if (index < scene.getNumTextures()+textureTypes.size())\n      {\n        try\n        {\n          tex = textureTypes.get(index-scene.getNumTextures()).getClass().newInstance();\n          int j = 0;\n          String name = \"\";\n          do\n          {\n            j++;\n            name = \"Untitled \"+j;\n          } while (scene.getTexture(name) != null);\n          tex.setName(name);\n          scene.addTexture(tex);\n          tex.edit(window, scene);\n        }\n        catch (Exception ex)\n        {\n          ex.printStackTrace();\n        }\n      }\n    }\n    if (tex != null)\n    {\n      UndoRecord undo = new UndoRecord(window, false);\n      for (int i = 0; i < objects.length; i++)\n        if (objects[i].getObject().getTexture() != tex)\n        {\n          undo.addCommand(UndoRecord.COPY_OBJECT, new Object [] {objects[i].getObject(), objects[i].getObject().duplicate()});\n          objects[i].setTexture(tex, tex.getDefaultMapping(objects[i].getObject()));\n        }\n      window.setUndoRecord(undo);\n      window.updateImage();\n      window.getScore().tracksModified(false);\n    }\n  }\n\n  /**\n   * This is called when the material is changed.\n   */\n\n  private void materialChanged()\n  {\n    int index = materialChoice.getSelectedIndex();\n    Scene scene = window.getScene();\n    Material mat = null;\n    boolean noMaterial = (index == materialChoice.getItemCount()-2);\n    if (index < scene.getNumMaterials())\n      mat = scene.getMaterial(index);\n    else\n    {\n      List<Material> materialTypes = PluginRegistry.getPlugins(Material.class);\n      if (index < scene.getNumMaterials()+materialTypes.size()+1)\n      {\n        try\n        {\n          mat = materialTypes.get(index-scene.getNumMaterials()-1).getClass().newInstance();\n          int j = 0;\n          String name = \"\";\n          do\n          {\n            j++;\n            name = \"Untitled \"+j;\n          } while (scene.getMaterial(name) != null);\n          mat.setName(name);\n          scene.addMaterial(mat);\n          mat.edit(window, scene);\n        }\n        catch (Exception ex)\n        {\n          ex.printStackTrace();\n        }\n      }\n    }\n    if (noMaterial || mat != null)\n    {\n      UndoRecord undo = new UndoRecord(window, false);\n      for (int i = 0; i < objects.length; i++)\n        if (objects[i].getObject().getMaterial() != mat)\n        {\n          undo.addCommand(UndoRecord.COPY_OBJECT, new Object [] {objects[i].getObject(), objects[i].getObject().duplicate()});\n          objects[i].setMaterial(mat, noMaterial ? null : mat.getDefaultMapping(objects[i].getObject()));\n        }\n      window.setUndoRecord(undo);\n      window.updateImage();\n      window.getScore().tracksModified(false);\n    }\n  }\n\n  /**\n   * This is called when an object parameter is changed.\n   */\n\n  private void parameterChanged(final ValueChangedEvent ev)\n  {\n    Runnable r = new Runnable() {\n      public void run()\n      {\n        processParameterChange(ev);\n      }\n    };\n    if (ev.isInProgress())\n      paramChangeProcessor.addEvent(r);\n    else\n      EventQueue.invokeLater(r); // Ensure that it won't be discarded.\n  }\n\n\n  private void processParameterChange(ValueChangedEvent ev)\n  {\n    UndoRecord undo = null;\n    if (ev.getWidget() != lastEventSource)\n    {\n      ignoreNextChange = true;\n      undo = new UndoRecord(window, false);\n      for (int i = 0; i < objects.length; i++)\n        undo.addCommand(UndoRecord.COPY_OBJECT, new Object [] {objects[i].getObject(), objects[i].getObject().duplicate()});\n    }\n    boolean changed = false;\n    for (int i = 0; i < objects.length; i++)\n    {\n      for (int j = 0; j < propEditor.length; j++)\n        if (propEditor[j].getWidget() == ev.getSource())\n        {\n          Object value = propEditor[j].getValue();\n          if (!objects[i].getObject().getPropertyValue(j).equals(value))\n          {\n            objects[i].getObject().setPropertyValue(j, value);\n            changed = true;\n          }\n        }\n      window.getScene().objectModified(objects[i].getObject());\n    }\n    lastEventSource = ev.getWidget();\n    if (undo != null && changed)\n      window.setUndoRecord(undo);\n    else if (!ev.isInProgress() && changed)\n      window.setModified();\n    window.updateImage();\n    window.getScore().tracksModified(false);\n  }\n\n  /**\n   * Always use a reasonable size, regardless of the current selection.\n   */\n\n  public Dimension getPreferredSize()\n  {\n    Dimension pref = super.getPreferredSize();\n    return new Dimension(Math.max(pref.width, 180), Math.max(pref.height, 200));\n  }\n\n  /**\n   * Allow the panel to be completely hidden.\n   */\n\n  public Dimension getMinimumSize()\n  {\n    return new Dimension();\n  }\n}\n", "human_rating": 2.4550214908, "metadata": {"project": "aoi", "class": "artofillusion.ObjectPropertiesPanel", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/ObjectPropertiesPanel.java", "label_probabilities": {"readability": [3.16977e-05, 0.496665, 0.461597, 0.0417057], "understandability": [9.07124e-08, 0.00180294, 0.732791, 0.265406], "complexity": [0.295799, 0.703915, 0.000285956, 0.0], "modularization": [0.531182, 0.460258, 0.00855951, 1.16629e-06], "overall": [0.0, 0.000229415, 0.278809, 0.720962]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.ObjectViewer", "source": "/* Copyright (C) 1999-2008 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.image.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.awt.geom.*;\nimport java.util.*;\n\n/** The ObjectViewer class is the abstract superclass of components which display \n   a single object and allow the user to edit it. */\n\npublic abstract class ObjectViewer extends ViewerCanvas\n{\n  protected MeshEditController controller;\n  protected boolean showScene, useWorldCoords, freehandSelection, draggingBox, squareBox, sentClick;\n  protected Point clickPoint, dragPoint;\n  protected Vector<Point> selectBoundsPoints;\n  protected Shape selectBounds;\n  protected ObjectInfo thisObjectInScene;\n  protected Scene theScene;\n  \n  public ObjectViewer(MeshEditController controller, RowContainer p)\n  {\n    super(ArtOfIllusion.getPreferences().getUseOpenGL() && isOpenGLAvailable());\n    this.controller = controller;\n    buildChoices(p);\n  }\n  \n  /** Get the controller which maintains the state for this viewer. */\n  \n  public MeshEditController getController()\n  {\n    return controller;\n  }\n  \n  /** Estimate the range of depth values that the camera will need to render.  This need not be exact,\n      but should err on the side of returning bounds that are slightly too large.\n      @return the two element array {minDepth, maxDepth}\n   */\n  \n  public double[] estimateDepthRange()\n  {\n    Mat4 toView = theCamera.getWorldToView();\n    \n    // Find the depth range for the object being edited.\n    \n    ObjectInfo info = getController().getObject();\n    BoundingBox bounds = info.getBounds();\n    double dx = bounds.maxx-bounds.minx;\n    double dy = bounds.maxy-bounds.miny;\n    double dz = bounds.maxz-bounds.minz;\n    double size = 0.5*Math.sqrt(dx*dx+dy*dy+dz*dz);\n    Vec3 origin = getDisplayCoordinates().fromLocal().times(bounds.getCenter());\n    double depth = toView.times(origin).z;\n    double min = depth-size, max = depth+size;\n\n    // Now check the rest of the scene.\n    \n    if (showScene)\n    {\n      for (int i = 0; i < theScene.getNumObjects(); i++)\n      {\n        info = theScene.getObject(i);\n        if (info == thisObjectInScene)\n          continue;\n        bounds = info.getBounds();\n        dx = bounds.maxx-bounds.minx;\n        dy = bounds.maxy-bounds.miny;\n        dz = bounds.maxz-bounds.minz;\n        size = 0.5*Math.sqrt(dx*dx+dy*dy+dz*dz);\n        origin = info.getCoords().fromLocal().times(bounds.getCenter());\n        if (!useWorldCoords)\n          origin = thisObjectInScene.getCoords().toLocal().times(origin);\n        depth = toView.times(origin).z;\n        if (depth-size < min)\n          min = depth-size;\n        if (depth+size > max)\n          max = depth+size;\n      }\n    }\n    return new double [] {min, max};\n  }\n\n  @Override\n  public void viewChanged(boolean selectionOnly)\n  {\n    super.viewChanged(selectionOnly);\n    if (renderMode == RENDER_RENDERED && !selectionOnly)\n    {\n      // Re-render the image.\n\n      Renderer rend = ArtOfIllusion.getPreferences().getObjectPreviewRenderer();\n      if (rend == null)\n        return;\n      adjustCamera(true);\n      Scene sc;\n      Camera cam = theCamera.duplicate();\n      if (showScene && theScene != null)\n      {\n        sc = new Scene();\n        sc.setEnvironmentColor(theScene.getEnvironmentColor());\n        sc.setEnvironmentTexture(theScene.getEnvironmentTexture());\n        sc.setEnvironmentMapping(theScene.getEnvironmentMapping());\n        sc.setEnvironmentParameterValues(theScene.getEnvironmentParameterValues());\n        sc.setEnvironmentMode(theScene.getEnvironmentMode());\n        sc.setAmbientColor(theScene.getAmbientColor());\n        Object3D thisObject = (thisObjectInScene == null ? null : thisObjectInScene.getObject());\n        for (int i = 0; i < theScene.getNumObjects(); i++)\n        {\n          ObjectInfo obj = theScene.getObject(i);\n          if (obj.getObject() == thisObject)\n            sc.addObject(obj.duplicate(controller.getObject().getObject()), null);\n          else\n            sc.addObject(obj, null);\n        }\n        if (!useWorldCoords && thisObjectInScene != null)\n        {\n          CoordinateSystem newCoords = cam.getCameraCoordinates();\n          newCoords.transformCoordinates(thisObjectInScene.getCoords().fromLocal());\n          cam.setCameraCoordinates(newCoords);\n        }\n      }\n      else\n      {\n        sc = new Scene();\n        RGBColor background = new RGBColor();\n        background.setARGB(backgroundColor.getRGB());\n        sc.setEnvironmentColor(background);\n        sc.addObject(new DirectionalLight(new RGBColor(1.0f, 1.0f, 1.0f), 0.8f), cam.getCameraCoordinates(), \"\", null);\n        ObjectInfo obj = getController().getObject();\n        obj = obj.duplicate(obj.getObject().duplicate());\n        obj.getCoords().transformCoordinates(getDisplayCoordinates().fromLocal());\n        sc.addObject(obj, null);\n      }\n      rend.configurePreview();\n      Rectangle bounds = getBounds();\n      SceneCamera sceneCamera = new SceneCamera();\n      sceneCamera.setFieldOfView(Math.atan(0.5*bounds.height/(cam.getDistToScreen()*getScale()))*360.0/Math.PI);\n      adjustCamera(isPerspective());\n      RenderListener listener = new RenderListener()\n      {\n        public void imageUpdated(Image image)\n        {\n          renderedImage = image;\n          getCanvasDrawer().imageChanged(renderedImage);\n          repaint();\n        }\n        public void statusChanged(String status)\n        {\n        }\n        public void imageComplete(ComplexImage image)\n        {\n          renderedImage = image.getImage();\n          getCanvasDrawer().imageChanged(renderedImage);\n          repaint();\n        }\n        public void renderingCanceled()\n        {\n        }\n      };\n      rend.renderScene(sc, cam, listener, sceneCamera);\n    }\n  }\n\n  public synchronized void updateImage()\n  {\n    if (renderMode == RENDER_RENDERED)\n    {\n      if (renderedImage != null && renderedImage.getWidth(null) > 0)\n        drawImage(renderedImage, 0, 0);\n      else\n        viewChanged(false);\n      drawBorder();\n      if (showAxes)\n        drawCoordinateAxes();\n      return;\n    }\n    super.updateImage();\n    if (controller.getObject() == null)\n      return;\n    \n    // Draw the rest of the objects in the scene.\n    \n    if (showScene && theScene != null)\n    {\n      Vec3 viewdir = getDisplayCoordinates().toLocal().timesDirection(theCamera.getViewToWorld().timesDirection(Vec3.vz()));\n      for (int i = 0; i < theScene.getNumObjects(); i++)\n      {\n        ObjectInfo obj = theScene.getObject(i);\n        if (!obj.isVisible() || obj == thisObjectInScene)\n          continue;\n        Mat4 objectTransform = obj.getCoords().fromLocal();\n        if (!useWorldCoords && thisObjectInScene != null)\n          objectTransform = thisObjectInScene.getCoords().toLocal().times(objectTransform);\n        theCamera.setObjectTransform(objectTransform);\n        obj.getObject().renderObject(obj, this, thisObjectInScene.getCoords().fromLocal().timesDirection(viewdir));\n      }\n    }\n\n    // Draw the object being edited.\n\n    theCamera.setObjectTransform(getDisplayCoordinates().fromLocal());\n    drawObject();\n\n    // Finish up.\n\n    drawBorder();\n    if (showAxes)\n      drawCoordinateAxes();\n  }\n  \n  protected abstract void drawObject();\n\n  /** Get the coordinate system in which the object is displayed.  This will\n      vary depending on whether the user has selected Local or Scene coordinates. */\n  \n  public CoordinateSystem getDisplayCoordinates()\n  {\n    if (useWorldCoords && thisObjectInScene != null)\n      return thisObjectInScene.getCoords();\n    else\n      return controller.getObject().getCoords();\n  }\n  \n  /** Get whether freehand selection mode is currently in use. */\n  \n  public boolean getFreehandSelection()\n  {\n    return freehandSelection;\n  }\n\n  /** Set whether to use freehand selection mode. */\n  \n  public void setFreehandSelection(boolean freehand)\n  {\n    freehandSelection = freehand;\n  }\n\n  /** Get the scene this object is part of, or null if there is none. */\n  \n  public Scene getScene()\n  {\n    return theScene;\n  }\n  \n  /** Set the scene this object is part of. */\n  \n  public void setScene(Scene sc, ObjectInfo thisObject)\n  {\n    theScene = sc;\n    thisObjectInScene = thisObject;\n  }\n\n  /** Get whether the entire scene is visible. */\n  \n  public boolean getSceneVisible()\n  {\n    return showScene;\n  }\n\n  /** Set whether the entire scene is visible. */\n  \n  public void setSceneVisible(boolean visible)\n  {\n    showScene = visible;\n    viewChanged(false);\n  }\n\n  /** Get whether to use world coordinates. */\n  \n  public boolean getUseWorldCoords()\n  {\n    return useWorldCoords;\n  }\n\n  /** Set whether to use world coordinates. */\n  \n  public void setUseWorldCoords(boolean use)\n  {\n    useWorldCoords = use;\n    viewChanged(false);\n  }\n  \n  /** Begin dragging a selection region.  The variable square determines whether\n      the region should be constrained to be square. */\n  \n  public void beginDraggingSelection(Point p, boolean square)\n  {\n    draggingBox = true;\n    clickPoint = p;\n    squareBox = square;\n    dragPoint = null;\n    if (freehandSelection)\n      selectBoundsPoints = new Vector<Point>();\n  }\n  \n  /** Finish dragging a selection region. */\n  \n  public void endDraggingSelection()\n  {\n    if (!draggingBox || dragPoint == null)\n    {\n      selectBounds = null;\n      return;\n    }\n    repaint();\n  \n    // Construct the selection region.\n    \n    if (freehandSelection)\n      selectBounds = createPolygonFromSelection();\n    else\n      selectBounds = new Rectangle(Math.min(clickPoint.x, dragPoint.x), Math.min(clickPoint.y, dragPoint.y), \n\t\tMath.abs(dragPoint.x-clickPoint.x), Math.abs(dragPoint.y-clickPoint.y));\n  }\n  \n  /** Create a Polygon from the selection bounds. */\n  \n  private Polygon createPolygonFromSelection()\n  {\n    int n = selectBoundsPoints.size(), x[] = new int [n], y[] = new int [n];\n    for (int i = 0; i < n; i++)\n    {\n      Point p = selectBoundsPoints.elementAt(i);\n      x[i] = p.x;\n      y[i] = p.y;\n    }\n    return new Polygon(x, y, n);\n  }\n\n  /** Determine whether the selection region contains the specified point. */\n  \n  public boolean selectionRegionContains(Point p)\n  {\n    if (selectBounds instanceof Rectangle)\n      return ((Rectangle) selectBounds).contains(p);\n    if (selectBounds instanceof Polygon)\n      return ((Polygon) selectBounds).contains(p);\n    return false;\n  }\n\n  /**\n   * Determine whether the selection region intersects the segment specified by the 2 points.\n   * <p> The selection intersects the line if either:<ul>\n   * <li> one of the points is inside the selection;\n   * <li> both points are outside and the line formed by them intersects\n   *      any of the boundaries of the selection.\n   * </ul>\n   */\n\n  public boolean selectionRegionIntersects(Point p1, Point p2)\n  {\n    if (selectionRegionContains(p1) || selectionRegionContains(p2))\n      return true;\n    if (selectBounds instanceof Rectangle)\n      return ((Rectangle) selectBounds).intersectsLine(p1.x, p1.y, p2.x, p2.y);\n    if (selectBounds instanceof Polygon)\n    {\n      // if any of the edges of the polygon intersect, return true\n      final Polygon polygon = ((Polygon) selectBounds);\n      final int[] xpoints = polygon.xpoints;\n      final int[] ypoints = polygon.ypoints;\n      final int npoints = polygon.npoints;\n      int lastx = xpoints[npoints - 1];\n      int lasty = ypoints[npoints - 1];\n      int curx, cury;\n\n      for (int i = 0; i < npoints; i++)\n      {\n        curx = xpoints[i];\n        cury = ypoints[i];\n        final boolean intersect =\n          Line2D.linesIntersect(\n            lastx, lasty, curx, cury, // polygon selection line\n            p1.x, p1.y, p2.x, p2.y    // tested line\n          );\n        if (intersect) return true;\n        lastx = curx;\n        lasty = cury;\n      }\n      return false;\n    }\n    return false;\n  }\n\n  protected void mouseDragged(WidgetMouseEvent e)\n  {\n    moveToGrid(e);\n    if (draggingBox && freehandSelection)\n    {\n      // Add this point to the region boundary and draw a line.\n      \n      dragPoint = e.getPoint();\n      selectBoundsPoints.addElement(dragPoint);\n      drawDraggedShape(createPolygonFromSelection());\n    }\n    else if (draggingBox)\n    {\n      // We are dragging a box, so erase and redraw it.\n\n      if (dragPoint != null)\n        drawDraggedShape(new Rectangle(Math.min(clickPoint.x, dragPoint.x), Math.min(clickPoint.y, dragPoint.y), \n              Math.abs(dragPoint.x-clickPoint.x), Math.abs(dragPoint.y-clickPoint.y)));\n      dragPoint = e.getPoint();\n      if (squareBox)\n      {\n        if (Math.abs(dragPoint.x-clickPoint.x) > Math.abs(dragPoint.y-clickPoint.y))\n        {\n          if (dragPoint.y < clickPoint.y)\n            dragPoint.y = clickPoint.y - Math.abs(dragPoint.x-clickPoint.x);\n          else\n            dragPoint.y = clickPoint.y + Math.abs(dragPoint.x-clickPoint.x);\n        }\n        else\n        {\n          if (dragPoint.x < clickPoint.x)\n            dragPoint.x = clickPoint.x - Math.abs(dragPoint.y-clickPoint.y);\n          else\n            dragPoint.x = clickPoint.x + Math.abs(dragPoint.y-clickPoint.y);\n        }\n      }\n      drawDraggedShape(new Rectangle(Math.min(clickPoint.x, dragPoint.x), Math.min(clickPoint.y, dragPoint.y), \n              Math.abs(dragPoint.x-clickPoint.x), Math.abs(dragPoint.y-clickPoint.y)));\n    }\n\n    // Send the event to the current tool, if appropriate.\n\n    if (sentClick)\n      activeTool.mouseDragged(e, this);\n  }\n  \n  public void previewObject()\n  {\n    Renderer rend = ArtOfIllusion.getPreferences().getObjectPreviewRenderer();\n    if (rend == null)\n      return;\n    adjustCamera(true);\n    Scene sc;\n    CoordinateSystem cameraCoords = theCamera.getCameraCoordinates();\n    if (showScene)\n    {\n      sc = theScene;\n      if (!useWorldCoords && thisObjectInScene != null)\n      {\n        CoordinateSystem newCoords = cameraCoords.duplicate();\n        newCoords.transformCoordinates(thisObjectInScene.getCoords().fromLocal());\n        theCamera.setCameraCoordinates(newCoords);\n      }\n    }\n    else\n    {\n      sc = new Scene();\n      sc.addObject(new DirectionalLight(new RGBColor(1.0f, 1.0f, 1.0f), 0.8f), theCamera.getCameraCoordinates(), \"\", null);\n      ObjectInfo obj = getController().getObject();\n      obj = obj.duplicate(obj.getObject().duplicate());\n      obj.getCoords().transformCoordinates(getDisplayCoordinates().fromLocal());\n      sc.addObject(obj, null);\n    }\n    rend.configurePreview();\n    SceneCamera sceneCamera = new SceneCamera();\n    sceneCamera.setFieldOfView(Math.atan(0.5*getBounds().height/(theCamera.getDistToScreen()*getScale()))*360.0/Math.PI);\n    ObjectInfo cameraInfo = new ObjectInfo(sceneCamera, theCamera.getCameraCoordinates(), \"\");\n    new RenderingDialog(UIUtilities.findFrame(this), rend, sc, theCamera, cameraInfo);\n    theCamera.setCameraCoordinates(cameraCoords);\n    adjustCamera(isPerspective());\n  }\n}", "human_rating": 2.6147206576, "metadata": {"project": "aoi", "class": "artofillusion.ObjectViewer", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/ObjectViewer.java", "label_probabilities": {"readability": [1.41465e-06, 0.615273, 0.384171, 0.000553999], "understandability": [6.68991e-07, 0.293036, 0.696728, 0.0102362], "complexity": [0.673356, 0.325896, 0.00074817, 1.02153e-09], "modularization": [0.829763, 0.170143, 9.40737e-05, 1.63721e-15], "overall": [3.57235e-08, 0.848956, 0.151044, 1.0914e-13]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.AbsModule", "source": "/* This is a Module which outputs the absolute value of a number. */\n\n/* Copyright (C) 2000 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\n\nimport java.awt.*;\n\npublic class AbsModule extends Module\n{\n  private boolean signOk, positive;\n  private double lastBlur;\n  \n  public AbsModule(Point position)\n  {\n    super(Translate.text(\"menu.absModule\"), new IOPort [] {new IOPort(IOPort.NUMBER, IOPort.INPUT, IOPort.LEFT, new String [] {\"Input\", \"(0\"})}, \n      new IOPort [] {new IOPort(IOPort.NUMBER, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Output\"})}, \n      position);\n  }\n\n  /* New point, so the value will need to be recalculated. */\n\n  public void init(PointInfo p)\n  {\n    signOk = false;\n  }\n\n  /* Calculate the output value. */\n  \n  public double getAverageValue(int which, double blur)\n  {\n    double value = (linkFrom[0] == null) ? 0.0 : linkFrom[0].getAverageValue(linkFromIndex[0], blur);\n    positive = value > 0.0;\n    signOk = true;\n    lastBlur = blur;\n    return positive ? value : -value;\n  }\n  /* The error is unchanged by this module. */\n  \n  public double getValueError(int which, double blur)\n  {\n    return (linkFrom[0] == null) ? 0.0 : linkFrom[0].getValueError(linkFromIndex[0], blur);\n  }\n\n  /* Calculate the gradient. */\n\n  public void getValueGradient(int which, Vec3 grad, double blur)\n  {\n    if (!signOk || blur != lastBlur)\n      getAverageValue(which, blur);\n    linkFrom[0].getValueGradient(linkFromIndex[0], grad, blur);\n    if (!positive)\n      grad.scale(-1.0);\n  }\n}\n", "human_rating": 3.9343045003641612, "metadata": {"project": "aoi", "class": "artofillusion.procedural.AbsModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/AbsModule.java", "label_probabilities": {"readability": [0.953062, 0.0281809, 0.0187569, 3.64161e-10], "understandability": [0.970301, 0.0292325, 0.000466585, 6.15788e-11], "complexity": [0.0, 8.457e-17, 0.195607, 0.804393], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.986357, 0.0136434, 5.26997e-13, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.ClipModule", "source": "/* Copyright (C) 2000-2011 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.io.*;\n\n/** This is a Module which clips its input to a fixed range. */\n\npublic class ClipModule extends Module\n{\n  double min, max;\n    \n  public ClipModule(Point position)\n  {\n    super(Translate.text(\"menu.clipModule\"), new IOPort [] {new IOPort(IOPort.NUMBER, IOPort.INPUT, IOPort.LEFT, new String [] {\"Input\", \"(0)\"})}, \n      new IOPort [] {new IOPort(IOPort.NUMBER, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Output\"})}, \n      position);\n    min = 0.0;\n    max = 1.0;\n  }\n  \n  /** Get the minimum clipping value. */\n  \n  public double getMinimum()\n  {\n    return min;\n  }\n  \n  /** Set the minimum clipping value. */\n  \n  public void setMinimum(double m)\n  {\n    min = m;\n  }\n  \n  /** Get the maximum clipping value. */\n  \n  public double getMaximum()\n  {\n    return max;\n  }\n  \n  /** Set the maximum clipping value. */\n  \n  public void setMaximum(double m)\n  {\n    max = m;\n  }\n\n  /* Clip the input value. */\n  \n  public double getAverageValue(int which, double blur)\n  {\n    if (linkFrom[0] == null)\n      return 0.0;\n    double v = linkFrom[0].getAverageValue(linkFromIndex[0], blur);\n    if (v < min)\n      return min;\n    if (v > max)\n      return max;\n    return v;\n  }\n\n  /* Calculate the error. */\n  \n  public double getValueError(int which, double blur)\n  {\n    if (linkFrom[0] == null)\n      return 0.0;\n    double v = linkFrom[0].getAverageValue(linkFromIndex[0], blur);\n    if (v < min || v > max)\n      return 0.0;\n    return linkFrom[0].getValueError(linkFromIndex[0], blur);\n  }\n\n  /* Calculate the gradient. */\n\n  public void getValueGradient(int which, Vec3 grad, double blur)\n  {\n    if (linkFrom[0] == null)\n      {\n        grad.set(0.0, 0.0, 0.0);\n        return;\n      }\n    double v = linkFrom[0].getAverageValue(linkFromIndex[0], blur);\n    if (v < min || v > max)\n      grad.set(0.0, 0.0, 0.0);\n    else\n      linkFrom[0].getValueGradient(linkFromIndex[0], grad, blur);\n  }\n  \n  /* Allow the user to set the parameters. */\n  \n  public boolean edit(final ProcedureEditor editor, Scene theScene)\n  {\n    final ValueField minField = new ValueField(min, ValueField.NONE);\n    final ValueField maxField = new ValueField(max, ValueField.NONE);\n    Object listener = new Object() {\n      void processEvent()\n      {\n        if (minField.getValue() <= maxField.getValue())\n        {\n          min = minField.getValue();\n          max = maxField.getValue();\n          editor.updatePreview();\n        }\n      }\n    };\n    minField.addEventLink(ValueChangedEvent.class, listener);\n    maxField.addEventLink(ValueChangedEvent.class, listener);\n    ComponentsDialog dlg = new ComponentsDialog(editor.getParentFrame(), Translate.text(\"selectClipRange\"),\n      new Widget [] {minField, maxField},\n      new String [] {Translate.text(\"Minimum\"), Translate.text(\"Maximum\")});\n    if (!dlg.clickedOk())\n      return false;\n    min = minField.getValue();\n    max = maxField.getValue();\n    if (min > max)\n    {\n      new BStandardDialog(\"\", Translate.text(\"minimumAboveMaxError\"), BStandardDialog.INFORMATION).showMessageDialog(editor.getParent());\n      return edit(editor, theScene);\n    }\n    return true;\n  }\n\n    /* Create a duplicate of this module. */\n\n  public Module duplicate()\n  {\n    ClipModule mod = new ClipModule(new Point(bounds.x, bounds.y));\n    mod.min = min;\n    mod.max = max;\n    return mod;\n  }\n\n  /* Write out the parameters. */\n\n  public void writeToStream(DataOutputStream out, Scene theScene) throws IOException\n  {\n    out.writeDouble(min);\n    out.writeDouble(max);\n  }\n  \n  /* Read in the parameters. */\n  \n  public void readFromStream(DataInputStream in, Scene theScene) throws IOException\n  {\n    min = in.readDouble();\n    max = in.readDouble();\n  }\n}\n", "human_rating": 3.11448924, "metadata": {"project": "aoi", "class": "artofillusion.procedural.ClipModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/ClipModule.java", "label_probabilities": {"readability": [0.123871, 0.866749, 0.00937912, 3.8977e-16], "understandability": [0.179457, 0.820541, 2.05518e-06, 0.0], "complexity": [0.0, 1.19065e-07, 0.379647, 0.620353], "modularization": [1e-20, 0.0332858, 0.93764, 0.0290743], "overall": [0.780944, 0.219055, 9.88665e-07, 2.11e-18]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.ColorDarkenModule", "source": "/* This is a Module which outputs the darker of two colors. */\n\n/* Copyright (C) 2001 by David M. Turner <novalis@novalis.org> and Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport java.awt.*;\n\npublic class ColorDarkenModule extends Module\n{\n  RGBColor color;\n  boolean colorOk;\n  double lastBlur;\n  \n  public ColorDarkenModule(Point position)\n  {\n    super(Translate.text(\"menu.darkerModule\"), new IOPort [] {new IOPort(IOPort.COLOR, IOPort.INPUT, IOPort.TOP, new String [] {\"Color 1\", '('+Translate.text(\"white\")+')'}),\n      new IOPort(IOPort.COLOR, IOPort.INPUT, IOPort.BOTTOM, new String [] {\"Color 2\", '('+Translate.text(\"white\")+')'})}, \n      new IOPort [] {new IOPort(IOPort.COLOR, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Darker\"})}, \n      position);\n    color = new RGBColor(0.0f, 0.0f, 0.0f);\n  }\n\n  /* New point, so the color will need to be recalculated. */\n\n  public void init(PointInfo p)\n  {\n    colorOk = false;\n  }\n\n  /* Calculate the darker color. */\n  \n  public void getColor(int which, RGBColor c, double blur)\n  {\n    if (colorOk && blur == lastBlur)\n      {\n        c.copy(color);\n        return;\n      }\n    float brightness1, brightness2;\n    colorOk = true;\n    lastBlur = blur;\n    if (linkFrom[0] == null)\n      {\n        color.setRGB(1.0f, 1.0f, 1.0f);\n        brightness1 = 1.0f;\n      }\n    else\n      {\n        linkFrom[0].getColor(linkFromIndex[0], color, blur);\n        brightness1 = color.getBrightness();\n      }\n\n    if (linkFrom[1] == null)\n      {\n        c.setRGB(1.0f, 1.0f, 1.0f);\n        brightness2 = 1.0f;\n      }\n    else\n      {\n        linkFrom[1].getColor(linkFromIndex[1], c, blur);\n        brightness2 = c.getBrightness();\n      }\n    if (brightness1 < brightness2)\n      c.copy(color);\n    else\n      color.copy(c);\n  }\n}", "human_rating": 2.009964520059, "metadata": {"project": "aoi", "class": "artofillusion.procedural.ColorDarkenModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/ColorDarkenModule.java", "label_probabilities": {"readability": [4.82e-18, 0.00996481, 0.990035, 9.0059e-08], "understandability": [0.00131953, 0.328108, 0.670536, 3.66646e-05], "complexity": [5.61592e-08, 0.000555821, 0.163575, 0.83587], "modularization": [0.0, 1.90154e-07, 0.908218, 0.0917819], "overall": [0.000184971, 0.560906, 0.438909, 8.51292e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.ColorLightenModule", "source": "/* This is a Module which outputs the lighter of two colors. */\n\n/* Copyright (C) 2001 by David M. Turner <novalis@novalis.org> and Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport java.awt.*;\n\npublic class ColorLightenModule extends Module\n{\n  RGBColor color;\n  boolean colorOk;\n  double lastBlur;\n  \n  public ColorLightenModule(Point position)\n  {\n    super(Translate.text(\"menu.lighterModule\"), new IOPort [] {new IOPort(IOPort.COLOR, IOPort.INPUT, IOPort.TOP, new String [] {\"Color 1\", '('+Translate.text(\"white\")+')'}),\n      new IOPort(IOPort.COLOR, IOPort.INPUT, IOPort.BOTTOM, new String [] {\"Color 2\", '('+Translate.text(\"white\")+')'})}, \n      new IOPort [] {new IOPort(IOPort.COLOR, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Lighter\"})}, \n      position);\n    color = new RGBColor(0.0f, 0.0f, 0.0f);\n  }\n\n  /* New point, so the color will need to be recalculated. */\n\n  public void init(PointInfo p)\n  {\n    colorOk = false;\n  }\n\n  /* Calculate the lighter color. */\n  \n  public void getColor(int which, RGBColor c, double blur)\n  {\n    if (colorOk && blur == lastBlur)\n      {\n        c.copy(color);\n        return;\n      }\n    float brightness1, brightness2;\n    colorOk = true;\n    lastBlur = blur;\n    if (linkFrom[0] == null)\n      {\n        color.setRGB(1.0f, 1.0f, 1.0f);\n        brightness1 = 1.0f;\n      }\n    else\n      {\n        linkFrom[0].getColor(linkFromIndex[0], color, blur);\n        brightness1 = color.getBrightness();\n      }\n\n    if (linkFrom[1] == null)\n      {\n        c.setRGB(1.0f, 1.0f, 1.0f);\n        brightness2 = 1.0f;\n      }\n    else\n      {\n        linkFrom[1].getColor(linkFromIndex[1], c, blur);\n        brightness2 = c.getBrightness();\n      }\n    if (brightness1 > brightness2)\n      c.copy(color);\n    else\n      color.copy(c);\n  }\n}", "human_rating": 2.802070016876174, "metadata": {"project": "aoi", "class": "artofillusion.procedural.ColorLightenModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/ColorLightenModule.java", "label_probabilities": {"readability": [0.000323504, 0.801422, 0.198255, 8.76174e-10], "understandability": [0.0143, 0.881752, 0.103948, 3.65093e-08], "complexity": [4.2263e-08, 0.00559594, 0.644136, 0.350268], "modularization": [0.0, 2.22352e-08, 0.999106, 0.000894427], "overall": [2.7784e-07, 0.998647, 0.00135234, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.ColorScaleModule", "source": "/* This is a Module which outputs the product of a color and a number. */\n\n/* Copyright (C) 2000 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport java.awt.*;\n\npublic class ColorScaleModule extends Module\n{\n  RGBColor color;\n  boolean colorOk;\n  double lastBlur;\n  \n  public ColorScaleModule(Point position)\n  {\n    super(\"\\u00D7\", new IOPort [] {new IOPort(IOPort.COLOR, IOPort.INPUT, IOPort.TOP, new String [] {\"Color\", '('+Translate.text(\"white\")+')'}),\n      new IOPort(IOPort.NUMBER, IOPort.INPUT, IOPort.BOTTOM, new String [] {\"Scale\", \"(1.0)\"})}, \n      new IOPort [] {new IOPort(IOPort.COLOR, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Product\"})}, \n      position);\n    color = new RGBColor(0.0f, 0.0f, 0.0f);\n  }\n\n  /* New point, so the color will need to be recalculated. */\n\n  public void init(PointInfo p)\n  {\n    colorOk = false;\n  }\n\n  /* Calculate the product color. */\n  \n  public void getColor(int which, RGBColor c, double blur)\n  {\n    if (colorOk && blur == lastBlur)\n      {\n        c.copy(color);\n        return;\n      }\n    colorOk = true;\n    lastBlur = blur;\n    if (linkFrom[0] == null)\n      color.setRGB(1.0f, 1.0f, 1.0f);\n    else\n      linkFrom[0].getColor(linkFromIndex[0], color, blur);\n    if (linkFrom[1] != null)\n      color.scale(linkFrom[1].getAverageValue(linkFromIndex[1], blur));\n    c.copy(color);\n  }\n}\n", "human_rating": 2.9981527116350475, "metadata": {"project": "aoi", "class": "artofillusion.procedural.ColorScaleModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/ColorScaleModule.java", "label_probabilities": {"readability": [4.29087e-08, 0.998152, 0.00184827, 2.47185e-13], "understandability": [0.000739899, 0.990513, 0.00874749, 1.7389e-16], "complexity": [4.6e-19, 0.00063426, 0.618055, 0.38131], "modularization": [0.0, 1.23e-18, 0.0139355, 0.986064], "overall": [6.57882e-10, 0.999974, 2.57115e-05, 2e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.ColorSumModule", "source": "/* This is a Module which outputs the sum of two colors. */\n\n/* Copyright (C) 2000 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport java.awt.*;\n\npublic class ColorSumModule extends Module\n{\n  RGBColor color;\n  boolean colorOk;\n  double lastBlur;\n  \n  public ColorSumModule(Point position)\n  {\n    super(\"+\", new IOPort [] {new IOPort(IOPort.COLOR, IOPort.INPUT, IOPort.TOP, new String [] {\"Color 1\", '('+Translate.text(\"black\")+')'}),\n      new IOPort(IOPort.COLOR, IOPort.INPUT, IOPort.BOTTOM, new String [] {\"Color 2\", '('+Translate.text(\"black\")+')'})}, \n      new IOPort [] {new IOPort(IOPort.COLOR, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Sum\"})}, \n      position);\n    color = new RGBColor(0.0f, 0.0f, 0.0f);\n  }\n\n  /* New point, so the color will need to be recalculated. */\n\n  public void init(PointInfo p)\n  {\n    colorOk = false;\n  }\n\n  /* Calculate the summed color. */\n  \n  public void getColor(int which, RGBColor c, double blur)\n  {\n    if (colorOk && blur == lastBlur)\n      {\n        c.copy(color);\n        return;\n      }\n    colorOk = true;\n    lastBlur = blur;\n    if (linkFrom[0] == null)\n      color.setRGB(0.0f, 0.0f, 0.0f);\n    else\n      linkFrom[0].getColor(linkFromIndex[0], color, blur);\n    if (linkFrom[1] == null)\n      c.setRGB(0.0f, 0.0f, 0.0f);\n    else\n      linkFrom[1].getColor(linkFromIndex[1], c, blur);\n    color.add(c);\n    c.copy(color);\n  }\n}\n", "human_rating": 3.7942749150600004, "metadata": {"project": "aoi", "class": "artofillusion.procedural.ColorSumModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/ColorSumModule.java", "label_probabilities": {"readability": [0.794363, 0.205552, 8.13138e-05, 4.28746e-06], "understandability": [0.267107, 0.721851, 0.0110412, 1.57919e-08], "complexity": [2.21551e-08, 0.0411545, 0.952573, 0.0062725], "modularization": [0.0, 7.16025e-09, 0.342579, 0.657421], "overall": [0.0592685, 0.940726, 5.41371e-06, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.MaxModule", "source": "/* Copyright (C) 2000-2009 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.math.*;\nimport java.awt.*;\n\n/** This is a Module which returns the maximum of two numbers. */\n\npublic class MaxModule extends Module\n{\n  double lastBlur, value, error;\n  int which;\n  boolean valueOk;\n\n  public MaxModule(Point position)\n  {\n    super(\"Max\", new IOPort [] {new IOPort(IOPort.NUMBER, IOPort.INPUT, IOPort.TOP, new String [] {\"Value 1\", \"(0)\"}),\n      new IOPort(IOPort.NUMBER, IOPort.INPUT, IOPort.BOTTOM, new String [] {\"Value 2\", \"(0)\"})}, \n      new IOPort [] {new IOPort(IOPort.NUMBER, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Maximum\"})}, \n      position);\n  }\n\n  /* New point, so the inputs will need to be compared again. */\n\n  public void init(PointInfo p)\n  {\n    valueOk = false;\n  }\n\n  /* Compare the two inputs. */\n  \n  public double getAverageValue(int which, double blur)\n  {\n    if (valueOk && blur == lastBlur)\n      return value;\n    valueOk = true;\n    double value1 = (linkFrom[0] == null) ? 0.0 : linkFrom[0].getAverageValue(linkFromIndex[0], blur);\n    double value2 = (linkFrom[1] == null) ? 0.0 : linkFrom[1].getAverageValue(linkFromIndex[1], blur);\n    double error1 = (linkFrom[0] == null) ? 0.0 : linkFrom[0].getValueError(linkFromIndex[0], blur);\n    double error2 = (linkFrom[1] == null) ? 0.0 : linkFrom[1].getValueError(linkFromIndex[1], blur);\n    double min1 = value1-error1;\n    double max1 = value1+error1;\n    double min2 = value2-error2;\n    double max2 = value2+error2;\n    if (max1 < min2)\n    {\n      value = value2;\n      error = error2;\n      which = 1;\n    }\n    else if (max2 < min1)\n    {\n      value = value1;\n      error = error1;\n      which = 0;\n    }\n    else if (value1 > value2)\n    {\n      value = value1;\n      double maxmin = (min1 < min2 ? min2 : min1);\n      error = Math.abs(value-maxmin);\n      which = 0;\n    }\n    else\n    {\n      value = value2;\n      double maxmin = (min1 < min2 ? min2 : min1);\n      error = Math.abs(value-maxmin);\n      which = 1;\n    }\n    return value;\n  }\n\n  /* Determine which input to use, and get its error. */\n\n  public double getValueError(int which, double blur)\n  {\n    if (!valueOk || blur != lastBlur)\n      getAverageValue(which, blur);\n    return error;\n  }\n\n  /* Determine which input to use, and get its gradient. */\n\n  public void getValueGradient(int which, Vec3 grad, double blur)\n  {\n    if (!valueOk || blur != lastBlur)\n      getAverageValue(which, blur);\n    if (linkFrom[which] == null)\n      grad.set(0.0, 0.0, 0.0);\n    else\n      linkFrom[which].getValueGradient(linkFromIndex[which], grad, blur);\n  }\n}\n", "human_rating": 2.9995040520000202, "metadata": {"project": "aoi", "class": "artofillusion.procedural.MaxModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/MaxModule.java", "label_probabilities": {"readability": [0.000705918, 0.998092, 0.00120219, 1.98125e-14], "understandability": [5.5884e-07, 0.00327797, 0.996106, 0.000615078], "complexity": [1.14097e-12, 0.106461, 0.892951, 0.00058768], "modularization": [0.0, 1.16295e-15, 0.99141, 0.00859009], "overall": [5.97118e-11, 0.0260966, 0.89756, 0.0763431]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.NumberModule", "source": "/* Copyright (C) 2000-2011 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.io.*;\n\n/** This is a Module which outputs a number. */\n\npublic class NumberModule extends Module\n{\n  private double value;\n  \n  public NumberModule(Point position)\n  {\n    super(\"0.0\", new IOPort [] {}, new IOPort [] {\n      new IOPort(IOPort.NUMBER, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Value\"})}, \n      position);\n  }\n  \n  public NumberModule(Point position, double v) \n  { \n    super(Double.toString(v), new IOPort [] {}, new IOPort [] { \n      new IOPort(IOPort.NUMBER, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Value\"})},  \n      position); \n    value = v; \n  }\n  \n  /** Get the value. */\n  \n  public double getValue()\n  {\n    return value;\n  }\n  \n  /** Set the value. */\n  \n  public void setValue(double v)\n  {\n    value = v;\n  }\n\n  /** Allow the user to set a new value. */\n  \n  public boolean edit(final ProcedureEditor editor, Scene theScene)\n  {\n    final ValueField field = new ValueField(value, ValueField.NONE);\n    field.addEventLink(ValueChangedEvent.class, new Object() {\n      void processEvent()\n      {\n        value = field.getValue();\n        editor.updatePreview();\n      }\n    });\n    ComponentsDialog dlg = new ComponentsDialog(editor.getParentFrame(), Translate.text(\"selectValue\"), new Widget [] {field},\n      new String [] {null});\n    if (!dlg.clickedOk())\n      return false;\n    value = field.getValue();\n    name = Double.toString(value);\n    layout();\n    return true;\n  }\n\n  /** This module simply outputs the value. */\n  \n  public double getAverageValue(int which, double blur)\n  {\n    return value;\n  }\n\n  public void getValueGradient(Vec3 grad, double blur)\n  {\n    grad.set(0.0, 0.0, 0.0);\n  }\n  \n  /* Create a duplicate of this module. */\n  \n  public Module duplicate()\n  {\n    NumberModule mod = new NumberModule(new Point(bounds.x, bounds.y));\n    \n    mod.value = value;\n    mod.name = \"\"+value;\n    return mod;\n  }\n\n  /* Write out the parameters. */\n\n  public void writeToStream(DataOutputStream out, Scene theScene) throws IOException\n  {\n    out.writeDouble(value);\n  }\n  \n  /* Read in the parameters. */\n  \n  public void readFromStream(DataInputStream in, Scene theScene) throws IOException\n  {\n    value = in.readDouble();\n    name = \"\"+value;\n    layout();\n  }\n}\n", "human_rating": 2.8235512185578, "metadata": {"project": "aoi", "class": "artofillusion.procedural.NumberModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/NumberModule.java", "label_probabilities": {"readability": [0.0170338, 0.789484, 0.193482, 1.85578e-08], "understandability": [0.200569, 0.760689, 0.0387421, 1.26125e-08], "complexity": [2.91311e-11, 0.000733943, 0.192302, 0.806964], "modularization": [3.51107e-05, 0.0558498, 0.905474, 0.0386414], "overall": [0.101952, 0.895654, 0.00239406, 4.92319e-13]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.procedural.RGBModule", "source": "/* Copyright (C) 2000 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.procedural;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport java.awt.*;\n\n/** This is a Module which takes three numbers, and uses them as the red, green, and blue\n    components of a color. */\n\npublic class RGBModule extends Module\n{\n  RGBColor color;\n  boolean colorOk;\n  double lastBlur;\n  \n  public RGBModule(Point position)\n  {\n    super(\"RGB\", new IOPort [] {new IOPort(IOPort.NUMBER, IOPort.INPUT, IOPort.LEFT, new String [] {\"Red\", \"(0)\"}),\n      new IOPort(IOPort.NUMBER, IOPort.INPUT, IOPort.LEFT, new String [] {\"Green\", \"(0)\"}),\n      new IOPort(IOPort.NUMBER, IOPort.INPUT, IOPort.LEFT, new String [] {\"Blue\", \"(0)\"})}, \n      new IOPort [] {new IOPort(IOPort.COLOR, IOPort.OUTPUT, IOPort.RIGHT, new String [] {\"Color\"})}, \n      position);\n    color = new RGBColor(0.0f, 0.0f, 0.0f);\n  }\n\n  /* New point, so the color will need to be recalculated. */\n\n  public void init(PointInfo p)\n  {\n    colorOk = false;\n  }\n\n  /* Calculate the color. */\n  \n  public void getColor(int which, RGBColor c, double blur)\n  {\n    if (colorOk && blur == lastBlur)\n      {\n        c.copy(color);\n        return;\n      }\n    colorOk = true;\n    lastBlur = blur;\n    float red = (linkFrom[0] == null) ? 0.0f : (float) linkFrom[0].getAverageValue(linkFromIndex[0], blur);\n    float green = (linkFrom[1] == null) ? 0.0f : (float) linkFrom[1].getAverageValue(linkFromIndex[1], blur);\n    float blue = (linkFrom[2] == null) ? 0.0f : (float) linkFrom[2].getAverageValue(linkFromIndex[2], blur);\n    color.setRGB(red, green, blue);\n    c.copy(color);\n  }\n}\n", "human_rating": 3.1870618837124995, "metadata": {"project": "aoi", "class": "artofillusion.procedural.RGBModule", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/procedural/RGBModule.java", "label_probabilities": {"readability": [0.187201, 0.812659, 0.000140439, 5.7125e-09], "understandability": [0.41185, 0.588126, 2.44358e-05, 3.42098e-14], "complexity": [6e-20, 1.82339e-07, 0.0998944, 0.900105], "modularization": [0.0, 2.66271e-11, 0.0177, 0.9823], "overall": [0.926245, 0.0737546, 1.217e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.raytracer.PhotonMap", "source": "/* Copyright (C) 2003-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.raytracer;\n\nimport artofillusion.math.*;\nimport artofillusion.material.*;\nimport artofillusion.texture.*;\nimport artofillusion.util.*;\n\nimport java.util.*;\n\n/** This class is a three dimensional data structure containing the photons in a scene.  The map can\n    be searched very efficiently for locating the photons near a particular point and evaluating the\n    local illumination\n    \n    Parts of this class are based on the descriptions and sample code in\n    \n    Henrick Wann Jensen, \"Realistic Image Synthesis Using Photon Mapping\", A K Peters, Natick, MA, 2001. */\n\npublic class PhotonMap\n{\n  private Raytracer rt;\n  private RaytracerRenderer renderer;\n  private ArrayList<Photon> photonList;\n  private Photon photon[], workspace[];\n  private int numWanted, filter, numEstimate;\n  private BoundingBox bounds;\n  private Vec3 direction[];\n  private boolean includeCaustics, includeDirect, includeIndirect, includeVolume;\n  private double lightScale;\n  private float cutoffDist2;\n  public Random random;\n  \n  /** Create a new PhotonMap\n   * @param totalPhotons        the number of photons which should be stored in this map\n   * @param numEstimate         the number of photons to use when estimating the illumination from this map\n   * @param includeCaustics     true if this PhotonMap should include photons that represent caustics\n   * @param includeDirect       true if this PhotonMap should include photons that represent direct illumination\n   * @param includeIndirect     true if this PhotonMap should include photons that represent indirect illumination\n   * @param includeVolume\n   * @param raytracer           the Raytracer for which this PhotonMap is being generated\n   * @param renderer            the renderer for which this PhotonMap is being generated\n   * @param bounds              a bounding box enclosing all objects at which photons should be directed\n   * @param filter              specifies which type of filter to apply to the photon intensities\n   * @param shared              another PhotonMap with which this one may share data structures to save memory (may be null)\n   */\n  \n  public PhotonMap(int totalPhotons, int numEstimate, boolean includeCaustics, boolean includeDirect, boolean includeIndirect, boolean includeVolume, Raytracer raytracer, RaytracerRenderer renderer, BoundingBox bounds, int filter, PhotonMap shared)\n  {\n    numWanted = totalPhotons;\n    this.bounds = bounds;\n    this.includeCaustics = includeCaustics;\n    this.includeDirect = includeDirect;\n    this.includeIndirect = includeIndirect;\n    this.includeVolume = includeVolume;\n    this.filter = filter;\n    this.numEstimate = numEstimate;\n    rt = raytracer;\n    this.renderer = renderer;\n    if (shared != null)\n      direction = shared.direction;\n    else\n      direction = new Vec3 [65536];\n    random = new Random(1);\n  }\n  \n  /** Get the Raytracer for which this map holds photons. */\n  \n  public Raytracer getRaytracer()\n  {\n    return rt;\n  }\n\n  /** Get the renderer for which this map holds photons. */\n\n  public RaytracerRenderer getRenderer()\n  {\n    return renderer;\n  }\n\n  /** Get the RenderWorkspace in which the map is being built. */\n\n  public RenderWorkspace getWorkspace()\n  {\n    return renderer.getWorkspace();\n  }\n\n  /** Get a bounding box enclosing all objects at which photons should be directed. */\n  \n  public BoundingBox getBounds()\n  {\n    return bounds;\n  }\n\n  /** Get the number of photons to use to estimate the local illumination. */\n\n  public int getNumToEstimate()\n  {\n    return numEstimate;\n  }\n\n  /** Generate photons from all sources until the desired number has been collected. */\n  \n  public void generatePhotons(PhotonSource source[])\n  {\n    Thread currentThread = Thread.currentThread();\n    double totalIntensity = 0.0, currentIntensity, totalRequested = 0.0;\n    double sourceIntensity[] = new double [source.length], totalSourceIntensity = 0.0;\n    \n    // Determine the total intensity of all sources.\n    \n    for (int i = 0; i < source.length; i++)\n      {\n        sourceIntensity[i] = source[i].getTotalIntensity();\n        totalSourceIntensity += sourceIntensity[i];\n      }\n    currentIntensity = 0.1*numWanted;\n    \n    // Generate photons.\n    \n    photonList = new ArrayList<Photon>((int) (1.1*numWanted));\n    int iteration = 0;\n    ThreadManager threads = new ThreadManager();\n    try\n    {\n      while (photonList.size() < numWanted)\n      {\n        for (int i = 0; i < source.length; i++)\n          {\n            if (renderer.renderThread != currentThread)\n              return;\n            source[i].generatePhotons(this, currentIntensity*sourceIntensity[i]/totalSourceIntensity, threads);\n            totalRequested += currentIntensity*sourceIntensity[i]/totalSourceIntensity;\n          }\n        if (photonList.size() >= numWanted*0.9)\n          break;\n        if (photonList.size() == 0 && currentIntensity > 5.0 && iteration > 2)\n          break; // Insignificant numbers of photons will be stored no matter how many we send out.\n        totalIntensity += currentIntensity;\n        if (photonList.size() < 10)\n          currentIntensity *= 10.0;\n        else\n          currentIntensity = (numWanted-photonList.size())*totalIntensity/photonList.size();\n        iteration++;\n      }\n    }\n    finally\n    {\n      threads.finish();\n    }\n    lightScale = totalSourceIntensity/totalRequested;\n    if (filter == 2)\n      lightScale *= 3.0f;\n    else if (filter == 1)\n      lightScale *= 1.5f;\n\n    // Create the balanced kd-tree.\n    \n    int numPhotons = photonList.size();\n    workspace = photonList.toArray(new Photon [numPhotons]);\n    photonList = null;\n    photon = new Photon [numPhotons];\n    buildTree(0, numPhotons-1, 0);\n    workspace = null;\n    \n    // Select a maximum search radius.  We use two different methods to select cutoffs, one based on photon\n    // intensity and one based on density, then keep whichever cutoff is smaller.  First, find the N brightest\n    // photons in the map.  The PhotonList can help us to do this.\n\n    PhotonList nearbyPhotons = new PhotonList(numEstimate);\n    RGBColor tempColor = new RGBColor();\n    nearbyPhotons.init(0.0f);\n    for (int i = 0; i < photon.length; i++)\n      {\n        tempColor.setERGB(photon[i].ergb);\n        float intensity = -(tempColor.getRed()+tempColor.getGreen()+tempColor.getBlue());\n        if (intensity <= nearbyPhotons.cutoff2)\n          nearbyPhotons.addPhoton(photon[i], intensity);\n      }\n    float red = 0.0f, green = 0.0f, blue = 0.0f;\n    for (int i = 0; i < nearbyPhotons.numFound; i++)\n      {\n        tempColor.setERGB(nearbyPhotons.photon[i].ergb);\n        red += tempColor.getRed();\n        green += tempColor.getGreen();\n        blue += tempColor.getBlue();\n      }\n    float max = Math.max(Math.max(red, green), blue);\n    double cutoff1;\n    if (includeVolume)\n      cutoff1 = Math.pow(max*lightScale/((4.0/3.0)*Math.PI*0.1), 1.0/3.0);\n    else\n      cutoff1 = Math.sqrt(max*lightScale/(Math.PI*0.1));\n    double volume = (bounds.maxx-bounds.minx)*(bounds.maxy-bounds.miny)*(bounds.maxz-bounds.minz);\n    double cutoff2 = Math.pow(0.5*volume*nearbyPhotons.photon.length/photon.length, 1.0/3.0);\n    cutoffDist2 = (float) (cutoff1 < cutoff2 ? cutoff1*cutoff1 : cutoff2*cutoff2);\n  }\n  \n  /** Spawn a Photon, and see whether it hits anything in the scene.  If so, add it to the map.\n      @param r         the ray along which to spawn the photon\n      @param color     the photon color\n      @param indirect  specifies whether the photon's source should be treated as indirect illumination\n  */\n  \n  public void spawnPhoton(Ray r, RGBColor color, boolean indirect)\n  {\n    if (!r.intersects(bounds))\n      return;\n    OctreeNode node = rt.getRootNode().findNode(r.getOrigin());\n    if (node == null)\n      node = rt.getRootNode().findFirstNode(r);\n    if (node == null)\n      return;\n    color = color.duplicate();\n    RTObject materialObject = renderer.getMaterialAtPoint(getWorkspace(), r.getOrigin(), node);\n    if (materialObject == null)\n      tracePhoton(r, color, 0, node, SurfaceIntersection.NO_INTERSECTION, null, null, null, null, 0.0, indirect, false);\n    else\n      tracePhoton(r, color, 0, node, SurfaceIntersection.NO_INTERSECTION, materialObject.getMaterialMapping(), null, materialObject.toLocal(), null, 0.0, indirect, false);\n  }\n  \n  /** Trace a photon through the scene, and record where it is absorbed.\n      @param r                  the ray to trace\n      @param color              the photon color\n      @param treeDepth          the depth of this ray within the ray tree\n      @param node               the first octree node which the ray intersects\n      @param first              the first object which the ray intersects, or null if this is not known\n      @param currentMaterial    the MaterialMapping at the ray's origin (may be null)\n      @param prevMaterial       the MaterialMapping the ray was passing through before entering currentMaterial\n      @param currentMatTrans    the transform to local coordinates for the current material\n      @param prevMatTrans       the transform to local coordinates for the previous material\n      @param totalDist          the distance traveled from the viewpoint\n      @param diffuse            true if this ray has been diffusely reflected since leaving the eye\n      @param caustic            true if this ray has been specularly reflected or refracted since leaving the eye\n  */\n  \n  private void tracePhoton(Ray r, RGBColor color, int treeDepth, OctreeNode node, SurfaceIntersection first, MaterialMapping currentMaterial, MaterialMapping prevMaterial, Mat4 currentMatTrans, Mat4 prevMatTrans, double totalDist, boolean diffuse, boolean caustic)\n  {\n    SurfaceIntersection second = SurfaceIntersection.NO_INTERSECTION;\n    double dist, truedot, n = 1.0, beta = 0.0, d;\n    RenderWorkspace workspace = getWorkspace();\n    Vec3 intersectionPoint = workspace.pos[treeDepth], norm = workspace.normal[treeDepth], trueNorm = workspace.trueNormal[treeDepth];\n    TextureSpec spec = workspace.surfSpec[treeDepth];\n    MaterialMapping nextMaterial, oldMaterial;\n    Mat4 nextMatTrans, oldMatTrans = null;\n    OctreeNode nextNode;\n\n    // Find whether it hits anything.\n\n    SurfaceIntersection intersect = SurfaceIntersection.NO_INTERSECTION;\n    if (first != SurfaceIntersection.NO_INTERSECTION)\n      intersect = r.findIntersection(first.getObject());\n    if (intersect != SurfaceIntersection.NO_INTERSECTION)\n    {\n      intersect.intersectionPoint(0, intersectionPoint);\n      nextNode = rt.getRootNode().findNode(intersectionPoint);\n    }\n    else\n    {\n      nextNode = rt.traceRay(r, node, workspace.context.intersect);\n      if (nextNode == null)\n        return;\n      first = workspace.context.intersect.getFirst();\n      second = workspace.context.intersect.getSecond();\n      intersect = first;\n      intersect.intersectionPoint(0, intersectionPoint);\n    }\n    \n    // Get the surface properties at the point of intersection.\n    \n    dist = intersect.intersectionDist(0);\n    totalDist += dist;\n    intersect.trueNormal(trueNorm);\n    truedot = trueNorm.dot(r.getDirection());\n    double texSmoothing = (diffuse ? renderer.smoothScale*renderer.extraGISmoothing : renderer.smoothScale);\n    if (truedot > 0.0)\n      intersect.intersectionProperties(spec, norm, r.getDirection(), totalDist*texSmoothing*3.0/(2.0+truedot), rt.getTime());\n    else\n      intersect.intersectionProperties(spec, norm, r.getDirection(), totalDist*texSmoothing*3.0/(2.0-truedot), rt.getTime());\n\n      // Reduce the photon intensity based on the current material or fog.\n\n    if (currentMaterial != null)\n    {\n      if (includeVolume && currentMaterial.isScattering())\n      {\n        // See whether a photon gets stored in the material.\n\n        propagateRay(r, nextNode, second, dist, currentMaterial, prevMaterial, currentMatTrans, prevMatTrans, color, treeDepth, totalDist, caustic, diffuse);\n      }\n      else\n      {\n        RGBColor emissive = new RGBColor(); // This will be ignored.\n        workspace.rt.propagateRay(workspace, r, nextNode, dist, currentMaterial, prevMaterial, currentMatTrans, prevMatTrans, emissive, color, treeDepth, totalDist);\n      }\n    }\n    else if (renderer.fog)\n      color.scale((float) Math.exp(-dist/renderer.fogDist));\n    if (color.getRed()+color.getGreen()+color.getBlue() < renderer.minRayIntensity)\n      return;  // The photon color is too dim to matter.\n\n    // Decide whether to store a photon here.\n\n    if (!includeVolume)\n    {\n      if ((includeDirect && treeDepth == 0) ||\n          (includeIndirect && diffuse) ||\n          (includeCaustics && caustic))\n        {\n          if (spec.diffuse.getRed()+spec.diffuse.getGreen()+spec.diffuse.getBlue()+\n              spec.hilight.getRed()+spec.hilight.getGreen()+spec.hilight.getBlue() > renderer.minRayIntensity)\n            addPhoton(intersectionPoint, r.getDirection(), color);\n        }\n    }\n\n    // Decide whether to spawn reflected and/or transmitted photons.\n    \n    if (treeDepth == renderer.maxRayDepth-1)\n      return;\n    boolean spawnSpecular = false, spawnTransmitted = false, spawnDiffuse = false;\n    if (includeCaustics || includeVolume)\n    {\n      if (spec.specular.getRed()+spec.specular.getGreen()+spec.specular.getBlue() > renderer.minRayIntensity)\n        spawnSpecular = true;\n    }\n    if (includeCaustics || includeVolume)\n    {\n      if (spec.transparent.getRed()+spec.transparent.getGreen()+spec.transparent.getBlue() > renderer.minRayIntensity)\n        spawnTransmitted = true;\n    }\n    if (includeIndirect && !includeVolume)\n      {\n        if (spec.diffuse.getRed()+spec.diffuse.getGreen()+spec.diffuse.getBlue() > renderer.minRayIntensity)\n          spawnDiffuse = true;\n      }\n    \n    // Spawn additional photons.\n    \n    double dot = norm.dot(r.getDirection());\n    RGBColor col = workspace.rayIntensity[treeDepth+1];\n    boolean totalReflect = false;\n    if (spawnTransmitted)\n      {\n        // Spawn a transmitted photon.\n\n        col.copy(color);\n        col.multiply(spec.transparent);\n        workspace.ray[treeDepth+1].getOrigin().set(intersectionPoint);\n        Vec3 temp = workspace.ray[treeDepth+1].getDirection();\n        RTObject hitObject = first.getObject();\n        if (hitObject.getMaterialMapping() == null)\n          {\n            // Not a solid object, so the bulk material does not change.\n            \n            temp.set(r.getDirection());\n            nextMaterial = currentMaterial;\n            nextMatTrans = currentMatTrans;\n            oldMaterial = prevMaterial;\n            oldMatTrans = prevMatTrans;\n          }\n        else if (dot < 0.0)\n          {\n            // Entering an object.\n\n            nextMaterial = hitObject.getMaterialMapping();\n            nextMatTrans = hitObject.toLocal();\n            oldMaterial = currentMaterial;\n            oldMatTrans = currentMatTrans;\n            if (currentMaterial == null)\n              n = nextMaterial.indexOfRefraction()/1.0;\n            else\n              n = nextMaterial.indexOfRefraction()/currentMaterial.indexOfRefraction();\n            beta = -(dot+Math.sqrt(n*n-1.0+dot*dot));\n            temp.set(norm);\n            temp.scale(beta);\n            temp.add(r.getDirection());\n            temp.scale(1.0/n);\n          }\n        else\n          {\n            // Exiting an object.\n\n            if (currentMaterial == hitObject.getMaterialMapping())\n              {\n                nextMaterial = prevMaterial;\n                nextMatTrans = prevMatTrans;\n                oldMaterial = null;\n                if (nextMaterial == null)\n                  n = 1.0/currentMaterial.indexOfRefraction();\n                else\n                  n = nextMaterial.indexOfRefraction()/currentMaterial.indexOfRefraction();\n              }\n            else\n              {\n                nextMaterial = currentMaterial;\n                nextMatTrans = currentMatTrans;\n                if (prevMaterial == hitObject.getMaterialMapping())\n                  oldMaterial = null;\n                else\n                  {\n                    oldMaterial = prevMaterial;\n                    oldMatTrans = prevMatTrans;\n                  }\n                n = 1.0;\n              }\n            beta = dot-Math.sqrt(n*n-1.0+dot*dot);\n            temp.set(norm);\n            temp.scale(-beta);\n            temp.add(r.getDirection());\n            temp.scale(1.0/n);\n          }\n        if (Double.isNaN(beta))\n          totalReflect = true;\n        else\n          {\n            d = (truedot > 0.0 ? temp.dot(trueNorm) : -temp.dot(trueNorm));\n            if (d < 0.0)\n              {\n                // Make sure it comes out the correct side.\n            \n                d += Raytracer.TOL;\n                temp.x -= d*trueNorm.x;\n                temp.y -= d*trueNorm.y;\n                temp.z -= d*trueNorm.z;\n                temp.normalize();\n              }\n            workspace.ray[treeDepth+1].newID();\n            if (renderer.gloss)\n              randomizeDirection(temp, norm, spec.cloudiness);\n            boolean newCaustic = (caustic || n != 1.0);\n            tracePhoton(workspace.ray[treeDepth+1], col, treeDepth+1, nextNode, second, nextMaterial, oldMaterial, nextMatTrans, oldMatTrans, totalDist, diffuse, newCaustic);\n          }\n      }\n    if (spawnSpecular || totalReflect)\n      {\n        // Spawn a reflection ray.\n\n        col.copy(spec.specular);\n        if (totalReflect)\n          col.add(spec.transparent.getRed(), spec.transparent.getGreen(), spec.transparent.getBlue());\n        col.multiply(color);\n        Vec3 temp = workspace.ray[treeDepth+1].getDirection();\n        temp.set(norm);\n        temp.scale(-2.0*dot);\n        temp.add(r.getDirection());\n        d = (truedot > 0.0 ? temp.dot(trueNorm) : -temp.dot(trueNorm));\n        if (d >= 0.0)\n          {\n            // Make sure it comes out the correct side.\n            \n            d += Raytracer.TOL;\n            temp.x += d*trueNorm.x;\n            temp.y += d*trueNorm.y;\n            temp.z += d*trueNorm.z;\n            temp.normalize();\n          }\n        workspace.ray[treeDepth+1].getOrigin().set(intersectionPoint);\n        workspace.ray[treeDepth+1].newID();\n        if (renderer.gloss)\n          randomizeDirection(temp, norm, spec.roughness);\n        tracePhoton(workspace.ray[treeDepth+1], col, treeDepth+1, nextNode, second, currentMaterial, prevMaterial, currentMatTrans, prevMatTrans, totalDist, diffuse, true);\n      }\n    if (spawnDiffuse)\n      {\n        // Spawn a diffusely reflected ray.\n\n        col.copy(spec.diffuse);\n        col.multiply(color);\n        Vec3 temp = workspace.ray[treeDepth+1].getDirection();\n        do\n          {\n            temp.set(0.0, 0.0, 0.0);\n            randomizePoint(temp, 1.0);\n            temp.normalize();\n            d = temp.dot(trueNorm) * (truedot > 0.0 ? 1.0 : -1.0);\n          } while (random.nextDouble() > (d < 0.0 ? -d : d));\n        if (d > 0.0)\n          {\n            // Make sure it comes out the correct side.\n            \n            temp.scale(-1.0);\n          }\n        workspace.ray[treeDepth+1].getOrigin().set(intersectionPoint);\n        workspace.ray[treeDepth+1].newID();\n        tracePhoton(workspace.ray[treeDepth+1], col, treeDepth+1, nextNode, second, currentMaterial, prevMaterial, currentMatTrans, prevMatTrans, totalDist, true, caustic);\n      }\n  }\n\n  /** Propagate a ray through a material, determine how much light is removed (due to\n      absorption and outscattering) and stored photons in the volume photon map.\n      <p>\n      On exit, rayIntensity[treeDepth] is reduced by the appropriate factor to account\n      for the absorbed light.\n\n      @param r                 the ray being propagated\n      @param node              the octree node containing the ray origin\n      @param dist              the distance between the ray origin and the endpoint\n      @param material          the MaterialMapping through which the ray is being propagated\n      @param prevMaterial      the MaterialMapping the ray was passing through before entering material\n      @param currentMatTrans   the transform to local coordinates for the current material\n      @param prevMatTrans      the transform to local coordinates for the previous material\n      @param color             on exit, this is multiplied by the attenuation factor\n      @param treeDepth         the current ray tree depth\n      @param totalDist         the distance traveled from the viewpoint\n      @param caustic            true if this ray has been specularly reflected or refracted since leaving the eye\n      @param scattered         true if this ray has already been scattered by the material\n   */\n\n  void propagateRay(Ray r, OctreeNode node, SurfaceIntersection first, double dist, MaterialMapping material, MaterialMapping prevMaterial, Mat4 currentMatTrans, Mat4 prevMatTrans, RGBColor color, int treeDepth, double totalDist, boolean caustic, boolean scattered)\n  {\n    RenderWorkspace workspace = getWorkspace();\n    MaterialSpec matSpec = workspace.matSpec;\n\n    // Integrate the material properties by stepping along the ray.\n\n    Vec3 v = workspace.ray[treeDepth+1].origin, origin = r.origin, direction = r.direction;\n    double x = 0.0, newx, dx, distToScreen = renderer.theCamera.getDistToScreen(), step;\n    double origx, origy, origz, dirx, diry, dirz;\n\n    // Find the ray origin and direction in the object's local coordinates.\n\n    v.set(origin);\n    currentMatTrans.transform(v);\n    origx = v.x;\n    origy = v.y;\n    origz = v.z;\n    v.set(direction);\n    currentMatTrans.transformDirection(v);\n    dirx = v.x;\n    diry = v.y;\n    dirz = v.z;\n\n    // Do the integration.\n\n    step = renderer.stepSize*material.getStepSize();\n    do\n    {\n      // Find the new point along the ray.\n\n      dx = step*(1.5*workspace.context.random.nextDouble());\n      if (this.rt.isAdaptive() && totalDist > distToScreen)\n        dx *= totalDist/distToScreen;\n      newx = x+dx;\n      if (newx > dist)\n      {\n        dx = dist-x;\n        x = dist;\n      }\n      else\n        x = newx;\n      totalDist += dx;\n      v.set(origx+dirx*x, origy+diry*x, origz+dirz*x);\n\n      // Find the material properties at that point.\n\n      material.getMaterialSpec(v, matSpec, dx, this.rt.getTime());\n      RGBColor trans = matSpec.transparency;\n      RGBColor scat = matSpec.scattering;\n\n      // Update the total emission and transmission.\n\n      float rt, gt, bt;\n      if (trans.getRed() == 1.0f)\n        rt = 1.0f;\n      else\n        rt = (float) Math.pow(trans.getRed(), dx);\n      if (trans.getGreen() == 1.0f)\n        gt = 1.0f;\n      else\n        gt = (float) Math.pow(trans.getGreen(), dx);\n      if (trans.getBlue() == 1.0f)\n        bt = 1.0f;\n      else\n        bt = (float) Math.pow(trans.getBlue(), dx);\n      float averageTrans = (rt+gt+bt)/3.0f;\n      if (random.nextFloat() < averageTrans)\n      {\n        // The photon does not interact with the medium here.\n\n        color.multiply(rt/averageTrans, gt/averageTrans, bt/averageTrans);\n        continue;\n      }\n      float scatProb = (scat.getRed()+scat.getGreen()+scat.getBlue())/3.0f;\n      if (scatProb > 0.98f)\n        scatProb = 0.98f; // Otherwise photons just bounce around forever and never get stored.\n      if (random.nextFloat() < scatProb && treeDepth < this.renderer.maxRayDepth-1)\n      {\n        // The photon is scattered.\n\n        if (treeDepth < this.renderer.maxRayDepth-1)\n        {\n          RGBColor rayIntensity = workspace.rayIntensity[treeDepth+1];\n          rayIntensity.copy(color);\n          rayIntensity.multiply(matSpec.scattering);\n          rayIntensity.scale(1.0f/scatProb);\n          if (rayIntensity.getMaxComponent() > this.renderer.minRayIntensity)\n          {\n            // Send out a scattered ray.\n\n            v.set(origin.x+direction.x*x, origin.y+direction.y*x, origin.z+direction.z*x);\n            while (node != null && !node.contains(v))\n            {\n              OctreeNode nextNode = node.findNextNode(r);\n              node = nextNode;\n            }\n            if (node == null)\n              break;\n            double g = matSpec.eccentricity;\n            Vec3 newdir = workspace.ray[treeDepth+1].getDirection();\n            if (g > 0.01 || g < -0.01)\n            {\n              // Importance sample the phase function.\n\n              double theta = Math.acos((1.0+g*g-Math.pow((1-g*g)/(1-g+2*g*random.nextDouble()), 2.0))/Math.abs(2*g));\n              double phi = 2*Math.PI*random.nextDouble();\n              newdir.set(Math.sin(theta)*Math.cos(phi), Math.sin(theta)*Math.sin(phi), Math.cos(theta));\n              Mat4 m = Mat4.objectTransform(new Vec3(), direction, Math.abs(direction.y) > 0.9 ? Vec3.vx() : Vec3.vy());\n              m.transformDirection(newdir);\n            }\n            else\n            {\n              // Pick a uniformly distributed random direction.\n\n              newdir.set(0.0, 0.0, 0.0);\n              randomizePoint(newdir, 1.0);\n              newdir.normalize();\n            }\n            tracePhoton(workspace.ray[treeDepth+1], rayIntensity, treeDepth+1, node, first, material, prevMaterial, currentMatTrans, prevMatTrans, totalDist, true, caustic);\n          }\n        }\n        color.setRGB(0.0, 0.0, 0.0);\n        break;\n      }\n\n      // The photon is absorbed.\n\n      color.scale(1.0/(1.0-scatProb));\n      if ((includeDirect || scattered) && color.getMaxComponent() > this.renderer.minRayIntensity)\n        addPhoton(v, direction, color);\n      color.setRGB(0.0, 0.0, 0.0);\n      break;\n    } while (x < dist);\n  }\n\n  /** Add a Photon to the map. */\n  \n  private void addPhoton(Vec3 pos, Vec3 dir, RGBColor color)\n  {\n    Photon p = new Photon(pos, dir, color);\n    synchronized (this)\n    {\n      photonList.add(p);\n    }\n    if (direction[p.direction&0xFFFF] == null)\n    {\n      int i = (p.direction>>8) & 0xFF;\n      int j = p.direction & 0xFF;\n      double phi = i*Math.PI/128, theta = j*Math.PI/256;\n      double sphi = Math.sin(phi), cphi = Math.cos(phi);\n      double stheta = Math.sin(theta), ctheta = Math.cos(theta);\n      direction[p.direction&0xFFFF] = new Vec3(cphi*stheta, ctheta, sphi*stheta);\n    }\n  }\n\n  /** Add a random displacement to a vector.  The displacements are uniformly distributed\n     over the volume of a sphere whose radius is given by size. */\n\n  void randomizePoint(Vec3 pos, double size)\n  {\n    if (size == 0.0)\n      return;\n\n    // Pick a random vector within the unit sphere.\n\n    double x, y, z;\n    do\n      {\n        x = random.nextDouble()-0.5;\n        y = random.nextDouble()-0.5;\n        z = random.nextDouble()-0.5;\n      } while (x*x + y*y + z*z > 0.25);\n    pos.x += 2.0*size*x;\n    pos.y += 2.0*size*y;\n    pos.z += 2.0*size*z;\n  }\n\n  /** Given a reflected or transmitted ray, randomly alter its direction to create gloss and\n     translucency effects.  dir is a unit vector in the \"ideal\" reflected or refracted\n     direction, which on exit is overwritten with the new direction.  norm is the local\n     surface normal, and roughness determines how much the ray direction is altered. */\n\n  void randomizeDirection(Vec3 dir, Vec3 norm, double roughness)\n  {\n    if (roughness == 0.0)\n      return;\n\n    // Pick a random vector within the unit sphere.\n\n    double x, y, z, scale, dot1, dot2;\n    do\n      {\n        x = random.nextDouble()-0.5;\n        y = random.nextDouble()-0.5;\n        z = random.nextDouble()-0.5;\n      } while (x*x + y*y + z*z > 0.25);\n    scale = Math.pow(roughness, 1.7)*0.5;\n    dot1 = dir.dot(norm);\n    dir.x += 2.0*scale*x;\n    dir.y += 2.0*scale*y;\n    dir.z += 2.0*scale*z;\n    dot2 = 2.0*dir.dot(norm);\n\n    // If the ray is on the wrong side of the surface, flip it back.\n\n    if (dot1 < 0.0 && dot2 > 0.0)\n      {\n        dir.x -= dot2*norm.x;\n        dir.y -= dot2*norm.y;\n        dir.z -= dot2*norm.z;\n      }\n    else if (dot1 > 0.0 && dot2 < 0.0)\n      {\n        dir.x += dot2*norm.x;\n        dir.y += dot2*norm.y;\n        dir.z += dot2*norm.z;\n      }\n    dir.normalize();\n  }\n  \n  /** This method is called recursively to build the packed kd-tree of photons from the workspace array.\n      @param start      the start of the segment from which to build the tree\n      @param end        the end of the segment from which to build the tree\n      @param root       the position in the packed array where the root of the tree should go\n  */\n  \n  private void buildTree(int start, int end, int root)\n  {\n    if (start == end)\n      photon[root] = workspace[start];\n    if (start >= end)\n      return;\n  \n    // Find a bounding box for the photons in this segment, and decide which axis to split.\n    \n    float minx = Float.MAX_VALUE, miny = Float.MAX_VALUE, minz = Float.MAX_VALUE;\n    float maxx = -Float.MAX_VALUE, maxy = -Float.MAX_VALUE, maxz = -Float.MAX_VALUE;\n    for (int i = start; i <= end; i++)\n      {\n        Photon p = workspace[i];\n        if (p.x < minx) minx = p.x;\n        if (p.y < miny) miny = p.y;\n        if (p.z < minz) minz = p.z;\n        if (p.x > maxx) maxx = p.x;\n        if (p.y > maxy) maxy = p.y;\n        if (p.z > maxz) maxz = p.z;\n      }\n    float xsize = maxx-minx, ysize = maxy-miny, zsize = maxz-minz;\n    int axis;\n    if (xsize > ysize && xsize > zsize)\n      axis = 0;\n    else if (ysize > zsize)\n      axis = 1;\n    else\n      axis = 2;\n    \n    // Split the photons about the median along this axis.\n    \n    int size = end-start+1;\n    int medianPos = 1;\n    while (4*medianPos <= size)\n      medianPos += medianPos;\n    if (3*medianPos <= size)\n      medianPos = 2*medianPos+start-1;\n    else\n      medianPos = end-medianPos+1;\n    medianSplit(start, end, medianPos, axis);\n\n    // Store the median photon, and build the subtrees.\n    \n    photon[root] = workspace[medianPos];\n    photon[root].axis = (short) axis;\n    buildTree(start, medianPos-1, 2*root+1);\n    buildTree(medianPos+1, end, 2*root+2);\n  }\n  \n  /** This method splits the photons about their median along a particular axis.  When this returns,\n      all the photons before medianPos will have values <= the value in medianPos, and all the ones\n      after medianPos will have values >= the value in medianPos. */\n  \n  private void medianSplit(int start, int end, int medianPos, int axis)\n  {\n    float medianEstimate;\n    \n    if (start == end)\n      return;\n    if (end-start == 1)\n      {\n        if (axisPosition(start, axis) > axisPosition(end, axis))\n          swap(start, end);\n        return;\n      }\n    while (start < end)\n      {\n        // Estimate the median value.\n      \n        float a = axisPosition(start, axis);\n        float b = axisPosition(start+1, axis);\n        float c = axisPosition(end, axis);\n        if (a > b)\n          {\n            if (a > c)\n              medianEstimate = (b > c ? b : c);\n            else\n              medianEstimate = a;\n          }\n        else\n          {\n            if (b > c)\n              medianEstimate = (a > c ? a : c);\n            else\n              medianEstimate = b;\n          }\n        \n        // Split the photons based on whether they are greater than or less than the median estimate.\n        \n        int i = start, j = end;\n        while (true)\n          {\n            for (; i < end && axisPosition(i, axis) < medianEstimate; i++);\n            for (; axisPosition(j, axis) > medianEstimate; j--);\n            if (i >= j)\n              break;\n            swap(i, j);\n            i++;\n            j--;\n          }\n        swap(i, end);\n        if (i > medianPos)\n          end = i-1;\n        if (i <= medianPos)\n          start = i;\n      }\n  }\n  \n  /** Get the position of a photon along an axis. */\n  \n  private float axisPosition(int index, int axis)\n  {\n    switch (axis)\n      {\n        case 0:\n          return workspace[index].x;\n        case 1:\n          return workspace[index].y;\n        default:\n          return workspace[index].z;\n      }\n  }\n  \n  /** Swap two photons in the workspace array. */\n  \n  private void swap(int first, int second)\n  {\n    Photon temp = workspace[first];\n    workspace[first] = workspace[second];\n    workspace[second] = temp;\n  }\n  \n  /** Determine the surface lighting at a point due to the photons in this map.\n      @param pos      the position near which to locate photons\n      @param spec     the surface properties at the point being evaluated\n      @param normal   the surface normal at the point being evaluated\n      @param viewDir  the direction from which the surface is being viewed\n      @param front    true if the surface is being viewed from the front\n      @param light    the total lighting contribution will be stored in this\n      @param pmc      the PhotonMapContext from which this is being invoked\n  */\n   \n  public void getLight(Vec3 pos, TextureSpec spec, Vec3 normal, Vec3 viewDir, boolean front, RGBColor light, PhotonMapContext pmc)\n  {\n    light.setRGB(0.0f, 0.0f, 0.0f);\n    if (photon.length == 0)\n      return;\n    PhotonList nearbyPhotons = pmc.nearbyPhotons;\n    RGBColor tempColor = pmc.tempColor;\n    RGBColor tempColor2 = pmc.tempColor2;\n    Vec3 tempVec = pmc.tempVec;\n    float startCutoff2 = (float) (Math.sqrt(pmc.lastCutoff2)+pos.distance(pmc.lastPos));\n    startCutoff2 *= startCutoff2;\n    if (startCutoff2 > cutoffDist2)\n      startCutoff2 = cutoffDist2;\n    nearbyPhotons.init(startCutoff2);\n    findPhotons(pos, 0, pmc);\n    pmc.lastPos.set(pos);\n    pmc.lastCutoff2 = nearbyPhotons.cutoff2;\n    if (nearbyPhotons.numFound == 0)\n      return;\n    float r2inv = 1.0f/nearbyPhotons.cutoff2;\n    boolean hilight = false;\n    if (spec.hilight.getMaxComponent() > renderer.minRayIntensity)\n    {\n      hilight = true;\n      tempColor2.setRGB(0.0f, 0.0f, 0.0f);\n    }\n    for (int i = 0; i < nearbyPhotons.numFound; i++)\n    {\n      Photon p = nearbyPhotons.photon[i];\n      Vec3 dir = direction[p.direction&0xFFFF];\n      double dot = normal.dot(dir);\n      if ((front && dot < -1.0e-10) || (!front && dot > 1.0e-10))\n      {\n        tempColor.setERGB(p.ergb);\n        float x = nearbyPhotons.dist2[i]*r2inv;\n        if (filter == 2)\n          tempColor.scale(x*(x-2.0f)+1.0f);\n        else if (filter == 1)\n          tempColor.scale(1.0f-x*x);\n        light.add(tempColor);\n        if (hilight)\n        {\n          tempVec.set(dir);\n          tempVec.add(viewDir);\n          tempVec.normalize();\n          double viewDot = (front ? -tempVec.dot(normal) : tempVec.dot(normal));\n          if (viewDot > 0.0)\n          {\n            float scale = (float) FastMath.pow(viewDot, (int) ((1.0-spec.roughness)*128.0)+1);\n            tempColor2.add(tempColor.getRed()*scale, tempColor.getGreen()*scale, tempColor.getBlue()*scale);\n          }\n        }\n      }\n    }\n    light.multiply(spec.diffuse);\n    if (hilight)\n    {\n      tempColor2.multiply(spec.hilight);\n      light.add(tempColor2);\n    }\n    light.scale(lightScale/(Math.PI*nearbyPhotons.cutoff2));\n  }\n\n  /** Determine the volume lighting at a point due to the photons in this map.\n      @param pos      the position near which to locate photons\n      @param spec     the material properties at the point being evaluated\n      @param viewDir  the direction from which the material is being viewed\n      @param light    the total lighting contribution will be stored in this\n      @param pmc      the PhotonMapContext from which this is being invoked\n  */\n\n  public void getVolumeLight(Vec3 pos, MaterialSpec spec, Vec3 viewDir, RGBColor light, PhotonMapContext pmc)\n  {\n    light.setRGB(0.0f, 0.0f, 0.0f);\n    if (photon.length == 0)\n      return;\n    PhotonList nearbyPhotons = pmc.nearbyPhotons;\n    RGBColor tempColor = pmc.tempColor;\n    float startCutoff2 = pmc.lastCutoff2+(float) pos.distance2(pmc.lastPos);\n    if (startCutoff2 > cutoffDist2)\n      startCutoff2 = cutoffDist2;\n    nearbyPhotons.init(startCutoff2);\n    findPhotons(pos, 0, pmc);\n    pmc.lastPos.set(pos);\n    pmc.lastCutoff2 = nearbyPhotons.cutoff2;\n    if (nearbyPhotons.numFound == 0)\n      return;\n    double eccentricity = spec.eccentricity;\n    double ec2 = eccentricity*eccentricity;\n    for (int i = 0; i < nearbyPhotons.numFound; i++)\n    {\n      Photon p = nearbyPhotons.photon[i];\n      tempColor.setERGB(p.ergb);\n      if (eccentricity != 0.0)\n      {\n        Vec3 dir = direction[p.direction&0xFFFF];\n        double dot = dir.dot(viewDir);\n        double fatt = (1.0-ec2)/Math.pow(1.0+ec2+2.0*eccentricity*dot, 1.5);\n        tempColor.scale(fatt);\n      }\n      light.add(tempColor);\n    }\n    light.scale(lightScale/((4.0/3.0)*Math.PI*Math.pow(nearbyPhotons.cutoff2, 1.5)));\n  }\n\n  /** Find the photons nearest to a given point.\n      @param pos      the position near which to locate photons\n      @param index    the point in the map from which to start searching\n      @param pmc      the PhotonMapContext from which this is being invoked\n  */\n  \n  private void findPhotons(Vec3 pos, int index, PhotonMapContext pmc)\n  {\n    Photon p = photon[index];\n    float dx = p.x-(float) pos.x, dy = p.y-(float) pos.y, dz = p.z-(float) pos.z;\n    float dist2 = dx*dx + dy*dy + dz*dz;\n    float delta;\n    switch (p.axis)\n      {\n        case 0:\n          delta = dx;\n          break;\n        case 1:\n          delta = dy;\n          break;\n        default:\n          delta = dz;\n      }\n    if (delta > 0.0f)\n      {\n        int child = (index<<1)+1;\n        if (child < photon.length)\n          {\n            findPhotons(pos, child, pmc);\n            delta *= delta;\n            child++;\n            if (child < photon.length && delta < pmc.nearbyPhotons.cutoff2)\n              findPhotons(pos, child, pmc);\n          }\n      }\n    else\n      {\n        int child = (index<<1)+2;\n        if (child < photon.length)\n          findPhotons(pos, child, pmc);\n        delta *= delta;\n        child--;\n        if (child < photon.length && delta < pmc.nearbyPhotons.cutoff2)\n          findPhotons(pos, child, pmc);\n      }\n    if (dist2 < pmc.nearbyPhotons.cutoff2)\n      pmc.nearbyPhotons.addPhoton(p, dist2);\n  }\n\n  private void validateTree(int pos)\n  {\n    int child1 = 2*pos+1, child2 = 2*pos+2;\n    if (child1 < photon.length)\n      {\n        validateLowerBranch(child1, photon[pos].axis, median(pos, photon[pos].axis));\n        validateTree(child1);\n      }\n    if (child2 < photon.length)\n      {\n        validateUpperBranch(child2, photon[pos].axis, median(pos, photon[pos].axis));\n        validateTree(child2);\n      }\n  }\n  \n  private void validateLowerBranch(int pos, int axis, float median)\n  {\n    float value = median(pos, axis);\n    if (value > median)\n      System.out.println(\"error!\");\n    int child1 = 2*pos+1, child2 = 2*pos+2;\n    if (child1 < photon.length)\n      validateLowerBranch(child1, axis, median);\n    if (child2 < photon.length)\n      validateLowerBranch(child2, axis, median);\n  }\n\n  private void validateUpperBranch(int pos, int axis, float median)\n  {\n    float value = median(pos, axis);\n    if (value < median)\n      System.out.println(\"error!\");\n    int child1 = 2*pos+1, child2 = 2*pos+2;\n    if (child1 < photon.length)\n      validateUpperBranch(child1, axis, median);\n    if (child2 < photon.length)\n      validateUpperBranch(child2, axis, median);\n  }\n\n  private float median(int index, int axis)\n  {\n    switch (axis)\n      {\n        case 0:\n          return photon[index].x;\n        case 1:\n          return photon[index].y;\n        default:\n          return photon[index].z;\n      }\n  }\n}", "human_rating": 1.848932162, "metadata": {"project": "aoi", "class": "artofillusion.raytracer.PhotonMap", "source_path": "aoi/sourcefiles/Renderers/src/artofillusion/raytracer/PhotonMap.java", "label_probabilities": {"readability": [1.30405e-05, 0.196547, 0.455799, 0.347641], "understandability": [8.02223e-08, 0.0248505, 0.750476, 0.224674], "complexity": [0.78755, 0.212447, 2.5442e-06, 0.0], "modularization": [0.974662, 0.0250395, 0.000299028, 8.64015e-09], "overall": [0.0, 0.00182194, 0.291643, 0.706535]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.raytracer.RTDirectionalLight", "source": "/* Copyright (C) 2008-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY\n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.raytracer;\n\nimport artofillusion.math.*;\nimport artofillusion.object.*;\n\n/**\n * This subclass of RTLight is used for DirectionalLights.\n */\n\npublic class RTDirectionalLight extends RTLight\n{\n  private final double radius;\n\n  public RTDirectionalLight(DirectionalLight light, CoordinateSystem coords, boolean softShadows)\n  {\n    super(light, coords);\n    radius = (softShadows ? Math.tan(light.getRadius()*Math.PI/180.0) : 0.0);\n  }\n\n  public double findRayToLight(Vec3 origin, Ray ray, RaytracerRenderer renderer, int rayNumber)\n  {\n    ray.getOrigin().set(origin);\n    Vec3 dir = ray.getDirection();\n    dir.set(getCoords().getZDirection());\n    dir.scale(-1.0);\n    if (rayNumber != -1)\n    {\n      renderer.randomizePoint(dir, ray.rt.random, radius, rayNumber);\n      dir.normalize();\n    }\n    return Double.MAX_VALUE;\n  }\n\n  @Override\n  public boolean getSoftShadows()\n  {\n    return radius != 0.0 && getLight().getType() == Light.TYPE_NORMAL;\n  }\n}\n", "human_rating": 3.9451813001203817, "metadata": {"project": "aoi", "class": "artofillusion.raytracer.RTDirectionalLight", "source_path": "aoi/sourcefiles/Renderers/src/artofillusion/raytracer/RTDirectionalLight.java", "label_probabilities": {"readability": [0.945181, 0.0548191, 6.01908e-11, 0.0], "understandability": [0.00403132, 0.960891, 0.0350778, 4.70584e-12], "complexity": [2.28479e-11, 0.00101018, 0.867418, 0.131572], "modularization": [0.0, 0.000280614, 0.228393, 0.771327], "overall": [0.93722, 0.0626685, 0.000111167, 1.55334e-12]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.raytracer.RTEllipsoid", "source": "/* Copyright (C) 1999-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.raytracer;\n\nimport artofillusion.material.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\n\n/** RTEllipsoid represents an ellipsoid to be raytraced.  It is defined by specifying a Sphere \n    object, and the transformations to and from local coordinates. */\n\npublic class RTEllipsoid extends RTObject\n{\n  Sphere theSphere;\n  double rx, ry, rz, rx2, ry2, rz2, cx, cy, cz, sy, sz, param[];\n  boolean bumpMapped, transform, uniform;\n  Mat4 toLocal, fromLocal;\n  \n  public static final double TOL = 1e-12;\n\n  public RTEllipsoid(Sphere sphere, Mat4 fromLocal, Mat4 toLocal, double param[])\n  {\n    Vec3 radii = sphere.getRadii();\n    Vec3 vx = toLocal.timesDirection(Vec3.vx()), vy = toLocal.timesDirection(Vec3.vy());\n    theSphere = sphere;\n    this.param = param;\n    uniform = sphere.getTextureMapping() instanceof UniformMapping;\n    transform = true;\n    if (vx.x == 1.0 || vx.x == -1.0)\n      {\n        if (vy.y == 1.0 || vy.y == -1.0)\n          {\n            rx = radii.x;\n            ry = radii.y;\n            rz = radii.z;\n            transform = false;\n          }\n        else if (vy.z == 1.0 || vy.z == -1.0)\n          {\n            rx = radii.x;\n            ry = radii.z;\n            rz = radii.y;\n            transform = false;\n          }\n      }\n    else if (vx.y == 1.0 || vx.y == -1.0)\n      {\n        if (vy.x == 1.0 || vy.x == -1.0)\n          {\n            rx = radii.y;\n            ry = radii.x;\n            rz = radii.z;\n            transform = false;\n          }\n        else if (vy.z == 1.0 || vy.z == -1.0)\n          {\n            rx = radii.y;\n            ry = radii.z;\n            rz = radii.x;\n            transform = false;\n          }\n      }\n    else if (vx.z == 1.0 || vx.z == -1.0)\n      {\n        if (vy.x == 1.0 || vy.x == -1.0)\n          {\n            rx = radii.z;\n            ry = radii.x;\n            rz = radii.y;\n            transform = false;\n          }\n        else if (vy.y == 1.0 || vy.y == -1.0)\n          {\n            rx = radii.z;\n            ry = radii.y;\n            rz = radii.x;\n            transform = false;\n          }\n      }\n    if (transform)\n      {\n        rx = radii.x;\n        ry = radii.y;\n        rz = radii.z;\n        this.fromLocal = fromLocal;\n      }\n    cx = fromLocal.m14/fromLocal.m44;\n    cy = fromLocal.m24/fromLocal.m44;\n    cz = fromLocal.m34/fromLocal.m44;\n    rx2 = rx*rx;\n    ry2 = ry*ry;\n    rz2 = rz*rz;\n    sy = rx2/ry2;\n    sz = rx2/rz2;\n    bumpMapped = sphere.getTexture().hasComponent(Texture.BUMP_COMPONENT);\n    this.toLocal = toLocal;\n  }\n\n  /** Get the TextureMapping for this object. */\n  \n  public final TextureMapping getTextureMapping()\n  {\n    return theSphere.getTextureMapping();\n  }\n\n  /** Get the MaterialMapping for this object. */\n  \n  public final MaterialMapping getMaterialMapping()\n  {\n    return theSphere.getMaterialMapping();\n  }  \n\n  /** Determine whether the given ray intersects this sphere. */\n\n  public SurfaceIntersection checkIntersection(Ray r)\n  {\n    Vec3 orig = r.getOrigin(), rdir = r.getDirection();\n    Vec3 v1 = r.tempVec1, v2 = r.tempVec2, dir = r.tempVec3;\n    double a, b, c, d, temp1, temp2;\n    double dist1, dist2 = 0;\n\n    v1.set(cx-orig.x, cy-orig.y, cz-orig.z);\n    if (transform)\n      {\n        toLocal.transformDirection(v1);\n        dir.set(rdir);\n        toLocal.transformDirection(dir);\n      }\n    else if (uniform)\n      dir = rdir;\n    else\n      dir.set(rdir);\n    temp1 = sy*dir.y;\n    temp2 = sz*dir.z;\n    b = dir.x*v1.x + temp1*v1.y + temp2*v1.z;\n    c = v1.x*v1.x + sy*v1.y*v1.y + sz*v1.z*v1.z - rx2;\n    int numIntersections;\n    if (c > TOL*b)\n      {\n        // Ray origin is outside ellipsoid.\n\n        if (b <= 0.0)\n          return SurfaceIntersection.NO_INTERSECTION;  // Ray points away from the ellipsoid.\n        a = dir.x*dir.x + temp1*dir.y + temp2*dir.z;\n        d = b*b - a*c;\n        if (d < 0.0)\n          return SurfaceIntersection.NO_INTERSECTION;\n        numIntersections = 2;\n        temp1 = Math.sqrt(d);\n        dist1 = (b - temp1)/a;\n        dist2 = (b + temp1)/a;\n        v2.set(orig.x+dist2*dir.x, orig.y+dist2*dir.y, orig.z+dist2*dir.z);\n        projectPoint(v2);\n      }\n    else if (c < -TOL*b)\n      {\n        // Ray origin is inside ellipsoid.\n\n        a = dir.x*dir.x + temp1*dir.y + temp2*dir.z;\n        d = b*b - a*c;\n        if (d < 0.0)\n          return SurfaceIntersection.NO_INTERSECTION;\n        numIntersections = 1;\n        dist1 = (b + Math.sqrt(d))/a;\n      }\n    else\n      {\n        // Ray origin is on the surface of the ellipsoid.\n\n        if (b <= 0.0)\n          return SurfaceIntersection.NO_INTERSECTION;  // Ray points away from the ellipsoid.\n        a = dir.x*dir.x + temp1*dir.y + temp2*dir.z;\n        d = b*b - a*c;\n        if (d < 0.0)\n          return SurfaceIntersection.NO_INTERSECTION;\n        numIntersections = 1;\n        dist1 = (b + Math.sqrt(d))/a;\n      }\n    v1.set(orig.x+dist1*rdir.x, orig.y+dist1*rdir.y, orig.z+dist1*rdir.z);\n    projectPoint(v1);\n    return new EllipsoidIntersection(this, numIntersections, v1, v2, dist1, dist2);\n  }\n  \n  /** Given a point, project it onto the surface of the ellipsoid.  This is necessary to\n      prevent roundoff error. */\n  \n  private void projectPoint(Vec3 pos)\n  {\n    if (transform)\n    {\n      toLocal.transform(pos);\n      double scale = rx/Math.sqrt(pos.x*pos.x+sy*pos.y*pos.y+sz*pos.z*pos.z);\n      pos.scale(scale);\n      fromLocal.transform(pos);\n    }\n    else\n    {\n      double dx = pos.x-cx, dy = pos.y-cy, dz = pos.z-cz;\n      double scale = rx/Math.sqrt(dx*dx+sy*dy*dy+sz*dz*dz);\n      pos.set(cx+dx*scale, cy+dy*scale, cz+dz*scale);\n    }\n  }\n\n  /** Get a bounding box for this ellipsoid. */\n  \n  public BoundingBox getBounds()\n  {\n    if (transform)\n      return (new BoundingBox(-rx, rx, -ry, ry, -rz, rz)).transformAndOutset(fromLocal);\n    else\n      return new BoundingBox(cx-rx, cx+rx, cy-ry, cy+ry, cz-rz, cz+rz);\n  }\n\n  /** Determine whether any part of the surface of the ellipsoid lies within a bounding box. */\n\n  public boolean intersectsBox(BoundingBox bb)\n  {\n    double dx, dy, dz, centerx, centery, centerz;\n\n    if (transform)\n      {\n        bb = bb.transformAndOutset(toLocal);\n        centerx = centery = centerz = 0.0;\n      }\n    else\n      {\n        centerx = cx;\n        centery = cy;\n        centerz = cz;\n      }\n    Vec3 c = new Vec3(centerx, centery, centerz);\n\n    // Find the nearest point of the box to the ellipsoid.\n\n    if (centerx < bb.minx)\n      c.x = bb.minx;\n    else if (centerx > bb.maxx)\n      c.x = bb.maxx;\n    if (centery < bb.miny)\n      c.y = bb.miny;\n    else if (centery > bb.maxy)\n      c.y = bb.maxy;\n    if (centerz < bb.minz)\n      c.z = bb.minz;\n    else if (centerz > bb.maxz)\n      c.z = bb.maxz;\n    \n    // If the ellipsoid lies entirely outside the box, return false.\n    \n    if (!transform)\n      c.set(c.x-centerx, c.y-centery, c.z-centerz);\n    if (c.x*c.x + c.y*c.y*sy + c.z*c.z*sz > rx2)\n      return false;\n\n    // If the box is completely inside the ellipsoid, return false.  Otherwise, return true.\n\n    dx = 1.0/rx;\n    dy = 1.0/ry;\n    dz = 1.0/rz;\n    c.set((bb.minx-centerx)*dx, (bb.miny-centery)*dy, (bb.minz-centerz)*dz);\n    if (c.length2() > 1.0)\n      return true;\n    c.set((bb.minx-centerx)*dx, (bb.miny-centery)*dy, (bb.maxz-centerz)*dz);\n    if (c.length2() > 1.0)\n      return true;\n    c.set((bb.minx-centerx)*dx, (bb.maxy-centery)*dy, (bb.minz-centerz)*dz);\n    if (c.length2() > 1.0)\n      return true;\n    c.set((bb.minx-centerx)*dx, (bb.maxy-centery)*dy, (bb.maxz-centerz)*dz);\n    if (c.length2() > 1.0)\n      return true;\n    c.set((bb.maxx-centerx)*dx, (bb.miny-centery)*dy, (bb.minz-centerz)*dz);\n    if (c.length2() > 1.0)\n      return true;\n    c.set((bb.maxx-centerx)*dx, (bb.miny-centery)*dy, (bb.maxz-centerz)*dz);\n    if (c.length2() > 1.0)\n      return true;\n    c.set((bb.maxx-centerx)*dx, (bb.maxy-centery)*dy, (bb.minz-centerz)*dz);\n    if (c.length2() > 1.0)\n      return true;\n    c.set((bb.maxx-centerx)*dx, (bb.maxy-centery)*dy, (bb.maxz-centerz)*dz);\n    if (c.length2() > 1.0)\n      return true;\n    return false;\n  }\n  \n  /** Get the transformation from world coordinates to the object's local coordinates. */\n  \n  public Mat4 toLocal()\n  {\n    return toLocal;\n  }\n\n\n  /**\n   * Inner class representing an intersection with an RTEllipsoid.\n   */\n\n  private static class EllipsoidIntersection implements SurfaceIntersection\n  {\n    private RTEllipsoid ellipse;\n    private int numIntersections;\n    private double dist1, dist2, r1x, r1y, r1z, r2x, r2y, r2z;\n    private boolean trueNormValid;\n    private Vec3 trueNorm, pos;\n\n    public EllipsoidIntersection(RTEllipsoid ellipse, int numIntersections, Vec3 point1, Vec3 point2, double dist1, double dist2)\n    {\n      this.ellipse = ellipse;\n      this.numIntersections = numIntersections;\n      this.dist1 = dist1;\n      this.dist2 = dist2;\n      r1x = point1.x;\n      r1y = point1.y;\n      r1z = point1.z;\n      r2x = point2.x;\n      r2y = point2.y;\n      r2z = point2.z;\n      trueNorm = new Vec3();\n      pos = new Vec3();\n    }\n\n    public RTObject getObject()\n    {\n      return ellipse;\n    }\n\n    public int numIntersections()\n    {\n      return numIntersections;\n    }\n\n    public void intersectionPoint(int n, Vec3 p)\n    {\n      if (n == 0)\n        p.set(r1x, r1y, r1z);\n      else\n        p.set(r2x, r2y, r2z);\n    }\n\n    public double intersectionDist(int n)\n    {\n      if (n == 0)\n        return dist1;\n      else\n        return dist2;\n    }\n\n    public void intersectionProperties(TextureSpec spec, Vec3 n, Vec3 viewDir, double size, double time)\n    {\n      calcTrueNorm();\n      n.set(trueNorm);\n      TextureMapping map = ellipse.theSphere.getTextureMapping();\n      pos.set(r1x, r1y, r1z);\n      if (map instanceof UniformMapping)\n        map.getTextureSpec(pos, spec, -n.dot(viewDir), size, time, ellipse.param);\n      else\n      {\n        ellipse.toLocal.transform(pos);\n        map.getTextureSpec(pos, spec, -n.dot(viewDir), size, time, ellipse.param);\n      }\n      if (ellipse.bumpMapped)\n      {\n        if (ellipse.transform)\n          ellipse.fromLocal.transformDirection(spec.bumpGrad);\n        n.scale(spec.bumpGrad.dot(n)+1.0);\n        n.subtract(spec.bumpGrad);\n        n.normalize();\n      }\n    }\n\n    public void intersectionTransparency(int n, RGBColor trans, double angle, double size, double time)\n    {\n      TextureMapping map = ellipse.theSphere.getTextureMapping();\n      if (n == 0)\n        pos.set(r1x, r1y, r1z);\n      else\n        pos.set(r2x, r2y, r2z);\n      if (map instanceof UniformMapping)\n        map.getTransparency(pos, trans, angle, size, time, ellipse.param);\n      else\n      {\n        ellipse.toLocal.transform(pos);\n        map.getTransparency(pos, trans, angle, size, time, ellipse.param);\n      }\n    }\n\n    public void trueNormal(Vec3 n)\n    {\n      calcTrueNorm();\n      n.set(trueNorm);\n    }\n\n    /** Calculate the true normal of the point of intersection. */\n\n    private final void calcTrueNorm()\n    {\n      if (trueNormValid)\n        return;\n      trueNormValid = true;\n      if (ellipse.transform)\n      {\n        trueNorm.set(r1x-ellipse.cx, r1y-ellipse.cy, r1z-ellipse.cz);\n        ellipse.toLocal.transformDirection(trueNorm);\n        trueNorm.set(trueNorm.x, trueNorm.y*ellipse.sy, trueNorm.z*ellipse.sz);\n        ellipse.fromLocal.transformDirection(trueNorm);\n      }\n      else\n        trueNorm.set(r1x-ellipse.cx, (r1y-ellipse.cy)*ellipse.sy, (r1z-ellipse.cz)*ellipse.sz);\n      trueNorm.normalize();\n    }\n  }\n}", "human_rating": 2.9907410336800098, "metadata": {"project": "aoi", "class": "artofillusion.raytracer.RTEllipsoid", "source_path": "aoi/sourcefiles/Renderers/src/artofillusion/raytracer/RTEllipsoid.java", "label_probabilities": {"readability": [3.24342e-06, 0.990734, 0.00926303, 9.43069e-15], "understandability": [1.71961e-07, 0.0423835, 0.873178, 0.0844382], "complexity": [0.804691, 0.195306, 2.06349e-06, 5.25149e-07], "modularization": [0.00344645, 0.895215, 0.101339, 6.64282e-11], "overall": [1.23496e-10, 0.0550549, 0.924878, 0.0200667]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.raytracer.RTTriangleLowMemory", "source": "/* Copyright (C) 1999-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY\n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.raytracer;\n\nimport artofillusion.*;\nimport artofillusion.material.*;\nimport artofillusion.math.*;\nimport artofillusion.texture.*;\n\n/**\n * RTTriangleLowMemory is identical to {@link RTTriangle}, except that it precalculates\n * less information.  This means that it is slightly slower, but also uses less memory.\n */\n\npublic class RTTriangleLowMemory extends RTObject\n{\n  RenderingTriangle tri;\n  short dropAxis, flags;\n  Mat4 toLocal, fromLocal;\n\n  public static final double TOL = 1e-12;\n\n  private static final short BUMP_MAPPED = 1;\n  private static final short INTERP_NORMALS = 2;\n\n  public RTTriangleLowMemory(RenderingMesh mesh, int which, Mat4 fromLocal, Mat4 toLocal)\n  {\n    tri = mesh.triangle[which];\n    Vec3 trueNorm = mesh.faceNorm[which];\n    this.fromLocal = fromLocal;\n    this.toLocal = toLocal;\n    if (tri.n1 != tri.n2 || tri.n1 != tri.n3)\n    {\n      flags |= INTERP_NORMALS;\n      Vec3 norm1 = mesh.norm[tri.n1];\n      Vec3 norm2 = mesh.norm[tri.n2];\n      Vec3 norm3 = mesh.norm[tri.n3];\n\n      // Make sure trueNorm points in the same direction as the vertex normals.\n\n      int i = 0;\n      if (trueNorm.dot(norm1) < 0.0) i++;\n      if (trueNorm.dot(norm2) < 0.0) i++;\n      if (trueNorm.dot(norm3) < 0.0) i++;\n      if (i > 1)\n        trueNorm.scale(-1.0);\n    }\n    if (Math.abs(trueNorm.y) > Math.abs(trueNorm.x))\n    {\n      if (Math.abs(trueNorm.z) > Math.abs(trueNorm.y))\n        dropAxis = 2;\n      else\n        dropAxis = 1;\n    }\n    else\n    {\n      if (Math.abs(trueNorm.z) > Math.abs(trueNorm.x))\n        dropAxis = 2;\n      else\n        dropAxis = 0;\n    }\n    if (tri.theMesh.mapping.getTexture().hasComponent(Texture.BUMP_COMPONENT))\n      flags |= BUMP_MAPPED;\n  }\n\n  /** Get the TextureMapping for this object. */\n\n  public final TextureMapping getTextureMapping()\n  {\n    return tri.getTextureMapping();\n  }\n\n  /** Get the MaterialMapping for this object. */\n\n  public final MaterialMapping getMaterialMapping()\n  {\n    return tri.theMesh.matMapping;\n  }\n\n  /** Determine whether the given ray intersects this triangle. */\n\n  public SurfaceIntersection checkIntersection(Ray r)\n  {\n    Vec3 orig = r.getOrigin(), dir = r.getDirection();\n    RenderingMesh mesh = tri.theMesh;\n    Vec3 trueNorm = mesh.faceNorm[tri.index];\n    double vd = trueNorm.dot(dir);\n    if (vd == 0.0)\n      return SurfaceIntersection.NO_INTERSECTION;  // The ray is parallel to the plane.\n    Vec3 vert1 = mesh.vert[tri.v1];\n    double v0 = trueNorm.x*(vert1.x-orig.x)+trueNorm.y*(vert1.y-orig.y)+trueNorm.z*(vert1.z-orig.z);\n    double t = v0/vd;\n    if (t < TOL)\n      return SurfaceIntersection.NO_INTERSECTION;  // Ray points away from plane of triangle.\n\n    // Determine whether the intersection point is inside the triangle.\n\n    double rix = orig.x+dir.x*t;\n    double riy = orig.y+dir.y*t;\n    double riz = orig.z+dir.z*t;\n    double edge2d1x, edge2d1y, edge2d2x, edge2d2y;\n    Vec3 vert2 = mesh.vert[tri.v2];\n    Vec3 vert3 = mesh.vert[tri.v3];\n    double vx, vy;\n    switch (dropAxis)\n    {\n      case 0:\n        vx = riy - vert1.y;\n        vy = riz - vert1.z;\n        edge2d1x = vert1.y-vert2.y;\n        edge2d1y = vert1.z-vert2.z;\n        edge2d2x = vert1.y-vert3.y;\n        edge2d2y = vert1.z-vert3.z;\n        break;\n      case 1:\n        vx = rix - vert1.x;\n        vy = riz - vert1.z;\n        edge2d1x = vert1.x-vert2.x;\n        edge2d1y = vert1.z-vert2.z;\n        edge2d2x = vert1.x-vert3.x;\n        edge2d2y = vert1.z-vert3.z;\n        break;\n      default:\n        vx = rix - vert1.x;\n        vy = riy - vert1.y;\n        edge2d1x = vert1.x-vert2.x;\n        edge2d1y = vert1.y-vert2.y;\n        edge2d2x = vert1.x-vert3.x;\n        edge2d2y = vert1.y-vert3.y;\n    }\n    double denom = 1.0/(edge2d1x*edge2d2y-edge2d1y*edge2d2x);\n    edge2d2x *= denom;\n    edge2d2y *= denom;\n    double v = edge2d2x*vy - edge2d2y*vx;\n    if (v < -TOL || v > 1.0+TOL)\n      return SurfaceIntersection.NO_INTERSECTION;\n    edge2d1x *= denom;\n    edge2d1y *= denom;\n    double w = vx*edge2d1y - vy*edge2d1x;\n    if (w < -TOL || w > 1.0+TOL)\n      return SurfaceIntersection.NO_INTERSECTION;\n    double u = 1.0-v-w;\n    if (u < -TOL || u > 1.0+TOL)\n      return SurfaceIntersection.NO_INTERSECTION;\n    TriangleIntersection intersection = (r.rt == null ? new TriangleIntersection() : (TriangleIntersection) r.rt.rtTriPool.getObject());\n    intersection.init(this, t, u, v, rix, riy, riz);\n    return intersection;\n  }\n\n  /** Get a bounding box for this triangle. */\n\n  public BoundingBox getBounds()\n  {\n    double minx, maxx, miny, maxy, minz, maxz;\n    Vec3 vert1 = tri.theMesh.vert[tri.v1];\n    Vec3 vert2 = tri.theMesh.vert[tri.v2];\n    Vec3 vert3 = tri.theMesh.vert[tri.v3];\n\n    minx = maxx = vert1.x;\n    miny = maxy = vert1.y;\n    minz = maxz = vert1.z;\n    if (vert2.x < minx)\n      minx = vert2.x;\n    if (vert2.x > maxx)\n      maxx = vert2.x;\n    if (vert2.y < miny)\n      miny = vert2.y;\n    if (vert2.y > maxy)\n      maxy = vert2.y;\n    if (vert2.z < minz)\n      minz = vert2.z;\n    if (vert2.z > maxz)\n      maxz = vert2.z;\n    if (vert3.x < minx)\n      minx = vert3.x;\n    if (vert3.x > maxx)\n      maxx = vert3.x;\n    if (vert3.y < miny)\n      miny = vert3.y;\n    if (vert3.y > maxy)\n      maxy = vert3.y;\n    if (vert3.z < minz)\n      minz = vert3.z;\n    if (vert3.z > maxz)\n      maxz = vert3.z;\n    return new BoundingBox(minx, maxx, miny, maxy, minz, maxz);\n  }\n\n  /** Determine whether any part of the triangle lies within a bounding box. */\n\n  public boolean intersectsBox(BoundingBox bb)\n  {\n    Vec3 vert1 = tri.theMesh.vert[tri.v1];\n    Vec3 vert2 = tri.theMesh.vert[tri.v2];\n    Vec3 vert3 = tri.theMesh.vert[tri.v3];\n\n    // First see if any vertex is inside the box.\n\n    if (bb.contains(vert1) || bb.contains(vert2) || bb.contains(vert3))\n      return true;\n\n    // If any edge intersects the box, return true.\n\n    if (edgeIntersectsBox(vert1, vert2, bb) || edgeIntersectsBox(vert2, vert3, bb) || edgeIntersectsBox(vert3, vert1, bb))\n      return true;\n\n    // None of the vertices is inside the box.  However, it is possible that the\n    // triangle cuts through the entire box.  Check each of the diagonals of\n    // the box to see if one intersects the triangle.\n\n    Ray r = new Ray(null);\n    Vec3 orig = r.getOrigin(), dir = r.getDirection();\n    double len;\n\n    orig.set(bb.minx, bb.miny, bb.minz);\n    dir.set(bb.maxx-bb.minx, bb.maxy-bb.miny, bb.maxz-bb.minz);\n    len = dir.length();\n    dir.scale(1.0/len);\n    SurfaceIntersection intersect = checkIntersection(r);\n    if (intersect != SurfaceIntersection.NO_INTERSECTION && intersect.intersectionDist(0) < len)\n      return true;\n    orig.set(bb.maxx, bb.miny, bb.minz);\n    dir.set(bb.minx-bb.maxx, bb.maxy-bb.miny, bb.maxz-bb.minz);\n    len = dir.length();\n    dir.scale(1.0/len);\n    intersect = checkIntersection(r);\n    if (intersect != SurfaceIntersection.NO_INTERSECTION && intersect.intersectionDist(0) < len)\n      return true;\n    orig.set(bb.minx, bb.maxy, bb.minz);\n    dir.set(bb.maxx-bb.minx, bb.miny-bb.maxy, bb.maxz-bb.minz);\n    len = dir.length();\n    dir.scale(1.0/len);\n    intersect = checkIntersection(r);\n    if (intersect != SurfaceIntersection.NO_INTERSECTION && intersect.intersectionDist(0) < len)\n      return true;\n    orig.set(bb.minx, bb.miny, bb.maxz);\n    dir.set(bb.maxx-bb.minx, bb.maxy-bb.miny, bb.minz-bb.maxz);\n    len = dir.length();\n    dir.scale(1.0/len);\n    intersect = checkIntersection(r);\n    if (intersect != SurfaceIntersection.NO_INTERSECTION && intersect.intersectionDist(0) < len)\n      return true;\n    return false;\n  }\n\n  /** Determine whether a particular edge of the triangle intersects a bounding box. */\n\n  boolean edgeIntersectsBox(Vec3 p1, Vec3 p2, BoundingBox bb)\n  {\n    double t1, t2, mint = -Double.MAX_VALUE, maxt = Double.MAX_VALUE;\n    double dirx = p2.x-p1.x, diry = p2.y-p1.y, dirz = p2.z-p1.z;\n    double len = Math.sqrt(dirx*dirx + diry*diry + dirz*dirz);\n    if (dirx == 0.0)\n      {\n        if (p1.x < bb.minx || p1.x > bb.maxx)\n          return false;\n      }\n    else\n      {\n        t1 = (bb.minx-p1.x)*len/dirx;\n        t2 = (bb.maxx-p1.x)*len/dirx;\n        if (t1 < t2)\n          {\n            if (t1 > mint)\n              mint = t1;\n            if (t2 < maxt)\n              maxt = t2;\n          }\n        else\n          {\n            if (t2 > mint)\n              mint = t2;\n            if (t1 < maxt)\n              maxt = t1;\n          }\n        if (mint > maxt || mint > len || maxt < 0.0)\n          return false;\n      }\n    if (diry == 0.0)\n      {\n        if (p1.y < bb.miny || p1.y > bb.maxy)\n          return false;\n      }\n    else\n      {\n        t1 = (bb.miny-p1.y)*len/diry;\n        t2 = (bb.maxy-p1.y)*len/diry;\n        if (t1 < t2)\n          {\n            if (t1 > mint)\n              mint = t1;\n            if (t2 < maxt)\n              maxt = t2;\n          }\n        else\n          {\n            if (t2 > mint)\n              mint = t2;\n            if (t1 < maxt)\n              maxt = t1;\n          }\n        if (mint > maxt || mint > len || maxt < 0.0)\n          return false;\n      }\n    if (dirz == 0.0)\n      {\n        if (p1.z < bb.minz || p1.z > bb.maxz)\n          return false;\n      }\n    else\n      {\n        t1 = (bb.minz-p1.z)*len/dirz;\n        t2 = (bb.maxz-p1.z)*len/dirz;\n        if (t1 < t2)\n          {\n            if (t1 > mint)\n              mint = t1;\n            if (t2 < maxt)\n              maxt = t2;\n          }\n        else\n          {\n            if (t2 > mint)\n              mint = t2;\n            if (t1 < maxt)\n              maxt = t1;\n          }\n        if (mint > maxt || mint > len || maxt < 0.0)\n          return false;\n      }\n    return true;\n  }\n\n  /** Get the transformation from world coordinates to the object's local coordinates. */\n\n  public Mat4 toLocal()\n  {\n    return toLocal;\n  }\n\n  /** Get the mesh this triangle is part of. */\n\n  public Object getObject()\n  {\n    return tri.theMesh;\n  }\n\n  /**\n   * Inner class representing an intersection with an RTTriangle.\n   */\n\n  public static class TriangleIntersection implements SurfaceIntersection\n  {\n    private RTTriangleLowMemory rtTri;\n    private double dist, u, v, rix, riy, riz;\n\n    public TriangleIntersection()\n    {\n    }\n\n    public void init(RTTriangleLowMemory rtTri, double dist, double u, double v, double rix, double riy, double riz)\n    {\n      this.rtTri = rtTri;\n      this.dist = dist;\n      this.u = u;\n      this.v = v;\n      this.rix = rix;\n      this.riy = riy;\n      this.riz = riz;\n    }\n\n    public RTObject getObject()\n    {\n      return rtTri;\n    }\n\n    public int numIntersections()\n    {\n      return 1;\n    }\n\n    public void intersectionPoint(int n, Vec3 p)\n    {\n      p.set(rix, riy, riz);\n    }\n\n    public double intersectionDist(int n)\n    {\n      return dist;\n    }\n\n    public void intersectionProperties(TextureSpec spec, Vec3 n, Vec3 viewDir, double size, double time)\n    {\n      double w = 1.0-u-v;\n      if ((rtTri.flags&INTERP_NORMALS) == 0)\n        n.set(rtTri.tri.theMesh.faceNorm[rtTri.tri.index]);\n      else\n        {\n          Vec3 normals[] = rtTri.tri.theMesh.norm;\n          Vec3 norm1 = normals[rtTri.tri.n1];\n          Vec3 norm2 = normals[rtTri.tri.n2];\n          Vec3 norm3 = normals[rtTri.tri.n3];\n          n.x = u*norm1.x + v*norm2.x + w*norm3.x;\n          n.y = u*norm1.y + v*norm2.y + w*norm3.y;\n          n.z = u*norm1.z + v*norm2.z + w*norm3.z;\n          n.normalize();\n        }\n      rtTri.tri.getTextureSpec(spec, -n.dot(viewDir), u, v, w, size, time);\n      if ((rtTri.flags&BUMP_MAPPED) != 0)\n        {\n          rtTri.fromLocal.transformDirection(spec.bumpGrad);\n          n.scale(spec.bumpGrad.dot(n)+1.0);\n          n.subtract(spec.bumpGrad);\n          n.normalize();\n        }\n    }\n\n    public void intersectionTransparency(int n, RGBColor trans, double angle, double size, double time)\n    {\n      rtTri.tri.getTransparency(trans, angle, u, v, 1.0-u-v, size, time);\n    }\n\n    public void trueNormal(Vec3 n)\n    {\n      n.set(rtTri.tri.theMesh.faceNorm[rtTri.tri.index]);\n    }\n  }\n}", "human_rating": 3.064368, "metadata": {"project": "aoi", "class": "artofillusion.raytracer.RTTriangleLowMemory", "source_path": "aoi/sourcefiles/Renderers/src/artofillusion/raytracer/RTTriangleLowMemory.java", "label_probabilities": {"readability": [0.102013, 0.860343, 0.0376435, 3e-20], "understandability": [0.0, 3.32751e-08, 0.0766872, 0.923313], "complexity": [0.17637, 0.82363, 0.0, 0.0], "modularization": [0.737359, 0.262469, 0.000171724, 1.915e-11], "overall": [0.0, 0.0, 1.23803e-12, 1.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.RotateObjectTool", "source": "/* Copyright (C) 1999-2007 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.util.Vector;\n\n/** RotateObjectTool is an EditingTool used for rotating objects in a scene. */\n\npublic class RotateObjectTool extends EditingTool\n{\n  static final int X_ONLY = 1;\n  static final int Y_ONLY = 2;\n  static final int Z_ONLY = 3;\n  static final int ALL_AXES = 4;\n\n  static final int OBJECT_CENTER = 0;\n  static final int PARENT_CENTER = 1;\n  static final int SELECTION_CENTER = 2;\n\n  static final double DRAG_SCALE = Math.PI/360.0;\n\n  Point clickPoint;\n  Vector<ObjectInfo> toMove;\n  ObjectInfo clickedObject;\n  int whichAxes, rotateAround = PARENT_CENTER;\n  boolean dragged, applyToChildren = true;\n  Vec3 rotAxis, rotationCenter[];\n  CoordinateSystem objectCoords[];\n  \n  public RotateObjectTool(EditingWindow fr)\n  {\n    super(fr);\n    initButton(\"rotate\");\n  }\n\n  public void activate()\n  {\n    super.activate();\n    theWindow.setHelpText(Translate.text(\"rotateObjectTool.helpText\"));\n  }\n\n  public int whichClicks()\n  {\n    return OBJECT_CLICKS+HANDLE_CLICKS;\n  }\n\n  public boolean allowSelectionChanges()\n  {\n    return true;\n  }\n\n  public String getToolTipText()\n  {\n    return Translate.text(\"rotateObjectTool.tipText\");\n  }\n  \n  public void mousePressedOnObject(WidgetMouseEvent e, ViewerCanvas view, int obj)\n  {\n    Scene theScene = theWindow.getScene();\n    int i, numSelected = 0, sel[];\n    Vec3 center = new Vec3();\n\n    toMove = new Vector<ObjectInfo>();\n    clickedObject = theScene.getObject(obj);\n    if (applyToChildren)\n      sel = theScene.getSelectionWithChildren();\n    else\n      sel = theScene.getSelection();\n    for (i = 0; i < sel.length; i++)\n      toMove.addElement(theScene.getObject(sel[i]));\n    objectCoords = new CoordinateSystem [toMove.size()];\n    rotationCenter = new Vec3 [toMove.size()];\n    for (i = 0; i < objectCoords.length; i++)\n      {\n        ObjectInfo info = (ObjectInfo) toMove.elementAt(i), parent = info;\n        objectCoords[i] = info.getCoords().duplicate();\n        if (rotateAround == SELECTION_CENTER)\n          {\n            rotationCenter[i] = center;\n            if (info.selected)\n              {\n                center.add(info.getCoords().getOrigin());\n                numSelected++;\n              }\n          }\n        else\n          rotationCenter[i] = info.getCoords().getOrigin();\n        if (rotateAround == PARENT_CENTER)\n          while (parent.getParent() != null)\n            {\n              parent = parent.getParent();\n              if (parent.selected)\n                rotationCenter[i] = parent.getCoords().getOrigin();\n            }\n      }\n    if (numSelected > 0)\n      center.scale(1.0/numSelected);\n    clickPoint = e.getPoint();\n    dragged = false;\n    whichAxes = ALL_AXES;\n  }\n\n  public void mousePressedOnHandle(WidgetMouseEvent e, ViewerCanvas view, int obj, int handle)\n  {\n    mousePressedOnObject(e, view, obj);\n    if (handle == 1 || handle == 6)\n      {\n        whichAxes = X_ONLY;\n        rotAxis = new Vec3(1.0, 0.0, 0.0);\n      }\n    else if (handle == 3 || handle == 4)\n      {\n        whichAxes = Y_ONLY;\n        rotAxis = new Vec3(0.0, -1.0, 0.0);\n      }\n    else\n      {\n        whichAxes = Z_ONLY;\n        if (handle < 4)\n          rotAxis = new Vec3(0.0, 0.0, 1.0);\n        else\n          rotAxis = new Vec3(0.0, 0.0, -1.0);\n      }\n    rotAxis = view.getCamera().getViewToWorld().timesDirection(rotAxis);\n  }\n  \n  public void mouseDragged(final WidgetMouseEvent e, final ViewerCanvas view)\n  {\n    Point dragPoint = e.getPoint();\n    CoordinateSystem c;\n    UndoRecord undo;\n    double angle;\n    int i;\n    Vec3 origin;\n    Mat4 rotMatrix;\n\n    if (!dragged)\n      {\n        theWindow.setUndoRecord(undo = new UndoRecord(theWindow, false));\n        for (i = 0; i < toMove.size(); i++)\n          {\n            ObjectInfo info = (ObjectInfo) toMove.elementAt(i);\n            c = info.getCoords();\n            undo.addCommand(UndoRecord.COPY_COORDS, new Object [] {c, c.duplicate()});\n          }\n        dragged = true;\n      }\n    if (whichAxes == X_ONLY)\n      angle = (clickPoint.y-dragPoint.y)*DRAG_SCALE;\n    else if (whichAxes == Y_ONLY)\n      angle = (clickPoint.x-dragPoint.x)*DRAG_SCALE;\n    else if (whichAxes == Z_ONLY)\n      angle = (dragPoint.x-clickPoint.x)*DRAG_SCALE;\n    else\n      {\n        rotAxis = new Vec3((clickPoint.y-dragPoint.y)*DRAG_SCALE, (dragPoint.x-clickPoint.x)*DRAG_SCALE, 0.0);\n        angle = rotAxis.length();\n        rotAxis = rotAxis.times(1.0/angle);\n        rotAxis = view.getCamera().getViewToWorld().timesDirection(rotAxis);\n      }\n    if (angle != 0.0)\n      {\n        for (i = 0; i < toMove.size(); i++)\n          {\n            ObjectInfo info = (ObjectInfo) toMove.elementAt(i);\n            c = info.getCoords();\n            origin = rotationCenter[i];\n            rotMatrix = Mat4.translation(origin.x, origin.y, origin.z).times(Mat4.axisRotation(rotAxis, angle)).times(Mat4.translation(-origin.x, -origin.y, -origin.z));\n            c.copyCoords(objectCoords[i]);\n            c.transformCoordinates(rotMatrix);\n          }\n      }\n    theWindow.setModified();\n    theWindow.updateImage();\n    theWindow.setHelpText(Translate.text(\"rotateMeshTool.dragText\", Double.toString(Math.round(angle*1e5*180.0/Math.PI)/1e5)));\n  }\n\n  public void mouseReleased(WidgetMouseEvent e, ViewerCanvas view)\n  {\n    theWindow.getScene().applyTracksAfterModification(toMove);\n    theWindow.setHelpText(Translate.text(\"rotateObjectTool.helpText\"));\n    toMove = null;\n    objectCoords = null;\n    rotationCenter = null;\n    theWindow.updateImage();\n  }\n\n  public void keyPressed(KeyPressedEvent e, ViewerCanvas view)\n  {\n    Scene theScene = theWindow.getScene();\n    CoordinateSystem c;\n    UndoRecord undo;\n    Vec3 origin, center = new Vec3();\n    Mat4 rotMatrix;\n    int key = e.getKeyCode(), numSelected = 0, sel[];\n\n    // Find the axis to rotate around.\n \n    if (e.isControlDown())\n      {\n        if (key == KeyPressedEvent.VK_UP || key == KeyPressedEvent.VK_RIGHT)\n          rotAxis = new Vec3(0.0, 0.0, 1.0);\n        else if (key == KeyPressedEvent.VK_DOWN || key == KeyPressedEvent.VK_LEFT)\n          rotAxis = new Vec3(0.0, 0.0, -1.0);\n        else\n          return;\n      }\n    else if (key == KeyPressedEvent.VK_UP)\n      rotAxis = new Vec3(1.0, 0.0, 0.0);\n    else if (key == KeyPressedEvent.VK_DOWN)\n      rotAxis = new Vec3(-1.0, 0.0, 0.0);\n    else if (key == KeyPressedEvent.VK_LEFT)\n      rotAxis = new Vec3(0.0, -1.0, 0.0);\n    else if (key == KeyPressedEvent.VK_RIGHT)\n      rotAxis = new Vec3(0.0, 1.0, 0.0);\n    else\n      return;\n    e.consume();\n    rotAxis = view.getCamera().getViewToWorld().timesDirection(rotAxis);\n\n    // Find the rotation center for every object.\n\n    if (applyToChildren)\n      sel = theScene.getSelectionWithChildren();\n    else\n      sel = theScene.getSelection();\n    toMove = new Vector<ObjectInfo>();\n    for (int i = 0; i < sel.length; i++)\n      toMove.addElement(theScene.getObject(sel[i]));\n    rotationCenter = new Vec3 [toMove.size()];\n    for (int i = 0; i < rotationCenter.length; i++)\n      {\n        ObjectInfo info = (ObjectInfo) toMove.elementAt(i), parent = info;\n        if (rotateAround == SELECTION_CENTER)\n          {\n            rotationCenter[i] = center;\n            if (info.selected)\n              {\n                center.add(info.getCoords().getOrigin());\n                numSelected++;\n              }\n          }\n        else\n          rotationCenter[i] = info.getCoords().getOrigin();\n        if (rotateAround == PARENT_CENTER)\n          while (parent.getParent() != null)\n            {\n              parent = parent.getParent();\n              if (parent.selected)\n                rotationCenter[i] = parent.getCoords().getOrigin();\n            }\n      }\n    if (numSelected > 0)\n      center.scale(1.0/numSelected);\n\n    // Rotate every object by 0.5 degrees.\n\n    theWindow.setUndoRecord(undo = new UndoRecord(theWindow, false));\n    double angle = DRAG_SCALE;\n    if (e.isAltDown())\n      angle *= 10.0;\n    for (int i = 0; i < toMove.size(); i++)\n      {\n        ObjectInfo info = (ObjectInfo) toMove.elementAt(i);\n        c = info.getCoords();\n        origin = rotationCenter[i];\n        rotMatrix = Mat4.translation(origin.x, origin.y, origin.z).times(Mat4.axisRotation(rotAxis, angle)).times(Mat4.translation(-origin.x, -origin.y, -origin.z));\n        undo.addCommand(UndoRecord.COPY_COORDS, new Object [] {c, c.duplicate()});\n          c.transformCoordinates(rotMatrix);\n      }\n    theWindow.getScene().applyTracksAfterModification(toMove);\n    theWindow.updateImage();\n    theWindow.setHelpText(Translate.text(\"rotateObjectTool.helpText\"));\n    toMove = null;\n    rotationCenter = null;\n  }\n\n  /* Allow the user to set options. */\n  \n  public void iconDoubleClicked()\n  {\n    BCheckBox childrenBox = new BCheckBox(Translate.text(\"applyToUnselectedChildren\"), applyToChildren);\n    BComboBox centerChoice = new BComboBox(new String [] {\n      Translate.text(\"individualObjectCenters\"),\n      Translate.text(\"parentObject\"),\n      Translate.text(\"centerOfSelection\")\n    });\n    centerChoice.setSelectedIndex(rotateAround);\n    RowContainer row = new RowContainer();\n    row.add(Translate.label(\"rotateAround\"));\n    row.add(centerChoice);\n    ComponentsDialog dlg = new ComponentsDialog(theFrame, Translate.text(\"rotateToolTitle\"), \n                new Widget [] {childrenBox, row}, new String [] {null, null});\n    if (!dlg.clickedOk())\n      return;\n    applyToChildren = childrenBox.getState();\n    rotateAround = centerChoice.getSelectedIndex();\n  }\n}", "human_rating": 2.009964520059, "metadata": {"project": "aoi", "class": "artofillusion.RotateObjectTool", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/RotateObjectTool.java", "label_probabilities": {"readability": [4.82e-18, 0.00996481, 0.990035, 9.0059e-08], "understandability": [2.68419e-05, 0.0976622, 0.902251, 6.01277e-05], "complexity": [0.0141576, 0.867501, 0.118341, 2.22681e-10], "modularization": [0.0381154, 0.819755, 0.142129, 5.36727e-12], "overall": [4.56e-18, 0.0012557, 0.557358, 0.441387]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.Scene", "source": "/* Copyright (C) 1999-2013 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.animation.*;\nimport artofillusion.image.*;\nimport artofillusion.material.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\nimport artofillusion.ui.*;\nimport artofillusion.util.*;\nimport java.awt.*;\nimport java.io.*;\nimport java.lang.reflect.*;\nimport java.util.*;\nimport java.util.List;\nimport java.util.zip.*;\nimport java.beans.*;\n\n/** The Scene class describes a collection of objects, arranged relative to each other to\n    form a scene, as well as the available textures and materials, environment options, etc. */\n\npublic class Scene\n{\n  private Vector<ObjectInfo> objects;\n  private Vector<Material> materials;\n  private Vector<Texture> textures;\n  private Vector<ImageMap> images;\n  private Vector<Integer> selection;\n  private Vector<ListChangeListener> textureListeners, materialListeners;\n  private HashMap<String, Object> metadataMap;\n  private HashMap<ObjectInfo, Integer> objectIndexMap;\n  private RGBColor ambientColor, environColor, fogColor;\n  private Texture environTexture;\n  private TextureMapping environMapping;\n  private int gridSubdivisions, environMode, framesPerSecond, nextID;\n  private double fogDist, gridSpacing, time;\n  private boolean fog, showGrid, snapToGrid, errorsLoading;\n  private String name, directory;\n  private TexturesAndMaterialsDialog texDlg;\n  private ParameterValue environParamValue[];\n  private StringBuffer loadingErrors;\n  \n  public static final int HANDLE_SIZE = 4;\n  public static final int ENVIRON_SOLID = 0;\n  public static final int ENVIRON_DIFFUSE = 1;\n  public static final int ENVIRON_EMISSIVE = 2;\n\n  private static final byte FILE_PREFIX[] = {'A', 'o', 'I', 'S', 'c', 'e', 'n', 'e'};\n\n  public Scene()\n  {\n    UniformTexture defTex = new UniformTexture();\n    \n    objects = new Vector<ObjectInfo>();\n    materials = new Vector<Material>();\n    textures = new Vector<Texture>();\n    images = new Vector<ImageMap>();\n    selection = new Vector<Integer>();\n    metadataMap = new HashMap<String, Object>();\n    textureListeners = new Vector<ListChangeListener>();\n    materialListeners = new Vector<ListChangeListener>();\n    defTex.setName(\"Default Texture\");\n    textures.addElement(defTex);\n    ambientColor = new RGBColor(0.3f, 0.3f, 0.3f);\n    environColor = new RGBColor(0.0f, 0.0f, 0.0f);\n    environTexture = defTex;\n    environMapping = defTex.getDefaultMapping(new Sphere(1.0, 1.0, 1.0));\n    environParamValue = new ParameterValue [0];\n    environMode = ENVIRON_SOLID;\n    fogColor = new RGBColor(0.3f, 0.3f, 0.3f);\n    fogDist = 20.0;\n    fog = false;\n    framesPerSecond = 30;\n    nextID = 1;\n\n    // Grids are off by default.\n    \n    showGrid = snapToGrid = false;\n    gridSpacing = 1.0;\n    gridSubdivisions = 10;\n  }\n\n  /** Get the name of this scene. */\n  \n  public String getName()\n  {\n    return name;\n  }\n\n  /** Set the name of this scene. */\n\n  public void setName(String newName)\n  {\n    name = newName;\n  }\n  \n  /** Get the directory on disk in which this scene is saved. */\n\n  public String getDirectory()\n  {\n    return directory;\n  }\n\n  /** Set the directory on disk in which this scene is saved. */\n\n  public void setDirectory(String newDir)\n  {\n    directory = newDir;\n  }\n  \n  /** Get the current time. */\n  \n  public double getTime()\n  {\n    return time;\n  }\n  \n  /** Set the current time. */\n  \n  public void setTime(double t)\n  {\n    time = t;\n    boolean processed[] = new boolean [objects.size()];\n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        applyTracksToObject(info, processed, null, i);\n      }\n    for (ObjectInfo obj : objects)\n      obj.getObject().sceneChanged(obj, this);\n  }\n  \n  /** Modify an object (and any objects that depend on it) based on its tracks at the current time. */\n  \n  public void applyTracksToObject(ObjectInfo info)\n  {\n    applyTracksToObject(info, new boolean[objects.size()], null, 0);\n    for (ObjectInfo obj : objects)\n      obj.getObject().sceneChanged(obj, this);\n  }\n\n  /** This should be called after one or more objects have been modified by the user.\n      It applies the animation tracks of all other objects which depend on the modified\n      ones.  It also applies a subset of the animation tracks on the modified objects\n      themselves to reflect their dependencies on other parts of the scene. */\n\n  public void applyTracksAfterModification(Collection<ObjectInfo> changedObjects)\n  {\n    boolean changed[] = new boolean[objects.size()];\n    boolean processed[] = new boolean[objects.size()];\n\n    // First apply a subset of the tracks of the modified objects.\n\n    for (ObjectInfo info : changedObjects)\n    {\n      int index = indexOf(info);\n      changed[index] = processed[index] = true;\n\n      // Find Constraint and IK tracks at the top of the list and apply them.\n\n      int i;\n      for (i = 0; i < info.getTracks().length && (info.getTracks()[i] instanceof ConstraintTrack ||\n          info.getTracks()[i] instanceof IKTrack || info.getTracks()[i].isNullTrack()); i++);\n      for (int j = i-1; j >= 0; j--)\n        if (info.getTracks()[j].isEnabled())\n          info.getTracks()[j].apply(time);\n      if (info.getPose() != null)\n        info.getObject().applyPoseKeyframe(info.getPose());\n    }\n\n    // Now apply tracks to all dependent objects.\n\n    for (ObjectInfo info : objects)\n      applyTracksToObject(info, processed, changed, indexOf(info));\n    for (ObjectInfo info : objects)\n      info.getObject().sceneChanged(info, this);\n  }\n\n  private void applyTracksToObject(ObjectInfo info, boolean processed[], boolean changed[], int index)\n  {\n    if (processed[index])\n    {\n      // This object has already been updated.\n\n      info.getObject().sceneChanged(info, this);\n      return;\n    }\n    processed[index] = true;\n\n    // Determine whether this object possesses a Position or Rotation track, and update any\n    // tracks it is dependent on.\n    \n    boolean hasPos = false, hasRot = false, hasPose = false;\n    for (Track track : info.getTracks())\n    {\n      if (track.isNullTrack() || !track.isEnabled())\n        continue;\n      ObjectInfo depends[] = track.getDependencies();\n      for (int i = 0; i < depends.length; i++)\n      {\n        int k = indexOf(depends[i]);\n        if (k > -1 && !processed[k])\n          applyTracksToObject(depends[i], processed, changed, k);\n        if (k > -1 && changed != null && changed[k])\n          changed[index] = true;\n      }\n      if (track instanceof PositionTrack || track instanceof ProceduralPositionTrack)\n        hasPos = true;\n      else if (track instanceof RotationTrack || track instanceof ProceduralRotationTrack)\n        hasRot = true;\n      else if (track instanceof PoseTrack || track instanceof IKTrack)\n        hasPose = true;\n    }\n    if (changed != null && !changed[index])\n      return;\n    if (hasPos)\n    {\n      Vec3 orig = info.getCoords().getOrigin();\n      orig.set(0.0, 0.0, 0.0);\n      info.getCoords().setOrigin(orig);\n    }\n    if (hasRot)\n      info.getCoords().setOrientation(0.0, 0.0, 0.0);\n    if (hasPose)\n      info.clearCachedMeshes();\n    info.setPose(null);\n    \n    // Apply the tracks.\n    \n    info.clearDistortion();\n    for (int j = info.getTracks().length-1; j >= 0; j--)\n      if (info.getTracks()[j].isEnabled())\n        info.getTracks()[j].apply(time);\n    if (info.getPose() != null)\n      info.getObject().applyPoseKeyframe(info.getPose());\n  }\n  \n  /** Get the number of frames per second. */\n  \n  public int getFramesPerSecond()\n  {\n    return framesPerSecond;\n  }\n  \n  /** Set the number of frames per second. */\n  \n  public void setFramesPerSecond(int n)\n  {\n    framesPerSecond = n;\n  }\n  \n  /** Get the scene's ambient light color. */\n  \n  public RGBColor getAmbientColor()\n  {\n    return ambientColor;\n  }\n  \n  /** Set the scene's ambient light color. */\n\n  public void setAmbientColor(RGBColor color)\n  {\n    ambientColor = color;\n  }\n\n  /** Get the Scene's environment mapping mode.  This will be either ENVIRON_SOLID, ENVIRON_DIFFUSE, or\n      ENVIRON_EMISSIVE. */\n\n  public int getEnvironmentMode()\n  {\n    return environMode;\n  }\n  \n  /** Set the Scene's environment mapping mode.  This should be either ENVIRON_SOLID, ENVIRON_DIFFUSE, or\n      ENVIRON_EMISSIVE. */\n\n  public void setEnvironmentMode(int mode)\n  {\n    environMode = mode;\n  }\n  \n  /** Get the texture being used as an environment mapping. */\n\n  public Texture getEnvironmentTexture()\n  {\n    return environTexture;\n  }\n  \n  /** Set the texture being used as an environment mapping. */\n\n  public void setEnvironmentTexture(Texture tex)\n  {\n    environTexture = tex;\n  }\n\n  /** Get the TextureMapping being used to map the environment map texture to the environment sphere. */\n\n  public TextureMapping getEnvironmentMapping()\n  {\n    return environMapping;\n  }\n  \n  /** Set the TextureMapping to use for mapping the environment map texture to the environment sphere. */\n\n  public void setEnvironmentMapping(TextureMapping map)\n  {\n    environMapping = map;\n  }\n  \n  /** Get the parameter values used for the environment map. */\n  \n  public ParameterValue [] getEnvironmentParameterValues()\n  {\n    return environParamValue;\n  }\n  \n  /** Set the parameter values used for the environment map. */\n  \n  public void setEnvironmentParameterValues(ParameterValue value[])\n  {\n    environParamValue = value;\n  }\n\n  /** Get the environment color. */\n\n  public RGBColor getEnvironmentColor()\n  {\n    return environColor;\n  }\n  \n  /** Set the environment color. */\n\n  public void setEnvironmentColor(RGBColor color)\n  {\n    environColor = color;\n  }\n  \n  /** Get the fog color. */\n\n  public RGBColor getFogColor()\n  {\n    return fogColor;\n  }\n  \n  /** Set the fog color. */\n\n  public void setFogColor(RGBColor color)\n  {\n    fogColor = color;\n  }\n\n  /** Determine whether fog is enabled. */\n  \n  public boolean getFogState()\n  {\n    return fog;\n  }\n  \n  /** Get the length constant for exponential fog. */\n\n  public double getFogDistance()\n  {\n    return fogDist;\n  }\n  \n  /** Set the state of fog in the scene.\n      @param state    sets whether fog is enabled\n      @param dist     the length constant for exponential fog.\n  */\n\n  public void setFog(boolean state, double dist)\n  {\n    fog = state;\n    fogDist = dist;\n  }\n  \n  /** Get whether the grid is displayed. */\n  \n  public boolean getShowGrid()\n  {\n    return showGrid;\n  }\n  \n  /** Set whether the grid is displayed. */\n  \n  public void setShowGrid(boolean show)\n  {\n    showGrid = show;\n  }\n  \n  /** Get whether snap-to-grid is enabled. */\n  \n  public boolean getSnapToGrid()\n  {\n    return snapToGrid;\n  }\n  \n  /** Set whether snap-to-grid is enabled. */\n  \n  public void setSnapToGrid(boolean snap)\n  {\n    snapToGrid = snap;\n  }\n  \n  /** Get the grid spacing. */\n  \n  public double getGridSpacing()\n  {\n    return gridSpacing;\n  }\n  \n  /** Set the grid spacing. */\n  \n  public void setGridSpacing(double spacing)\n  {\n    gridSpacing = spacing;\n  }\n  \n  /** Get the number of grid snap-to subdivisions. */\n  \n  public int getGridSubdivisions()\n  {\n    return gridSubdivisions;\n  }\n\n  /** Set the number of grid snap-to subdivisions. */\n  \n  public void setGridSubdivisions(int subdivisions)\n  {\n    gridSubdivisions = subdivisions;\n  }\n\n  /** Add a new object to the scene.  If undo is not null, appropriate commands will be\n      added to it to undo this operation. */\n\n  public void addObject(Object3D obj, CoordinateSystem coords, String name, UndoRecord undo)\n  {\n    addObject(new ObjectInfo(obj, coords, name), undo);\n    updateSelectionInfo();\n  }\n  \n  /** Add a new object to the scene.  If undo is not null, appropriate commands will be\n      added to it to undo this operation. */\n\n  public void addObject(ObjectInfo info, UndoRecord undo)\n  {\n    addObject(info, objects.size(), undo);\n    updateSelectionInfo();\n  }\n  \n  /** Add a new object to the scene in the specified position.  If undo is not null, \n      appropriate commands will be added to it to undo this operation. */\n\n  public void addObject(ObjectInfo info, int index, UndoRecord undo)\n  {\n    info.setId(nextID++);\n    if (info.getTracks() == null)\n      {\n        info.addTrack(new PositionTrack(info), 0);\n        info.addTrack(new RotationTrack(info), 1);\n      }\n    if (info.getObject().canSetTexture() && info.getObject().getTextureMapping() == null)\n      info.setTexture(getDefaultTexture(), getDefaultTexture().getDefaultMapping(info.getObject()));\n    info.getObject().sceneChanged(info, this);\n    objects.insertElementAt(info, index);\n    objectIndexMap = null;\n    if (undo != null)\n      undo.addCommandAtBeginning(UndoRecord.DELETE_OBJECT, new Object [] {index});\n    updateSelectionInfo();\n  }\n  \n  /** Delete an object from the scene.  If undo is not null, appropriate commands will be\n      added to it to undo this operation. */\n\n  public void removeObject(int which, UndoRecord undo)\n  {\n    ObjectInfo info = objects.elementAt(which);\n    objects.removeElementAt(which);\n    objectIndexMap = null;\n    if (undo != null)\n      undo.addCommandAtBeginning(UndoRecord.ADD_OBJECT, new Object [] {info, which});\n    if (info.getParent() != null)\n      {\n        int j;\n        for (j = 0; info.getParent().getChildren()[j] != info; j++);\n        if (undo != null)\n          undo.addCommandAtBeginning(UndoRecord.ADD_TO_GROUP, new Object [] {info.getParent(), info, j});\n        info.getParent().removeChild(j);\n      }\n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo obj = objects.elementAt(i);\n        for (int j = 0; j < obj.getTracks().length; j++)\n          {\n            Track tr = obj.getTracks()[j];\n            ObjectInfo depends[] = tr.getDependencies();\n            for (int k = 0; k < depends.length; k++)\n              if (depends[k] == info)\n                {\n                  if (undo != null)\n                    undo.addCommandAtBeginning(UndoRecord.COPY_TRACK, new Object [] {tr, tr.duplicate(tr.getParent())});\n                  obj.getTracks()[j].deleteDependencies(info);\n                }\n          }\n      }\n    clearSelection();\n  }\n  \n  /** Add a new Material to the scene. */\n  \n  public void addMaterial(Material mat)\n  {\n    addMaterial(mat, materials.size());\n  }\n\n  /**\n   * Add a new Material to the scene.\n   *\n   * @param mat    the Material to add\n   * @param index  the position in the list to add it at\n   */\n\n  public void addMaterial(Material mat, int index)\n  {\n    materials.add(index, mat);\n    for (int i = 0; i < materialListeners.size(); i++)\n      materialListeners.elementAt(i).itemAdded(materials.size()-1, mat);\n  }\n  \n  /** Remove a Material from the scene. */\n  \n  public void removeMaterial(int which)\n  {\n    Material mat = materials.elementAt(which);\n\n    materials.removeElementAt(which);\n    for (int i = 0; i < materialListeners.size(); i++)\n      materialListeners.elementAt(i).itemRemoved(which, mat);\n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo obj = objects.elementAt(i);\n        if (obj.getObject().getMaterial() == mat)\n          obj.setMaterial(null, null);\n      }\n  }\n\n  /**\n   * Reorder the list of Materials by moving a Material to a new position in the list.\n   *\n   * @param oldIndex    the index of the Material to move\n   * @param newIndex    the new position to move it to\n   */\n\n  public void reorderMaterial(int oldIndex, int newIndex)\n  {\n    if (newIndex < 0 || newIndex >= materials.size())\n      throw new IllegalArgumentException(\"Illegal value for newIndex: \"+newIndex);\n    Material mat = materials.remove(oldIndex);\n    materials.add(newIndex, mat);\n  }\n\n  /** Add a new Texture to the scene. */\n\n  public void addTexture(Texture tex)\n  {\n    addTexture(tex, textures.size());\n  }\n\n  /**\n   * Add a new Texture to the scene.\n   *\n   * @param tex    the Texture to add\n   * @param index  the position in the list to add it at\n   */\n\n  public void addTexture(Texture tex, int index)\n  {\n    textures.add(index, tex);\n    for (int i = 0; i < textureListeners.size(); i++)\n      textureListeners.elementAt(i).itemAdded(textures.size()-1, tex);\n  }\n\n  /** Remove a Texture from the scene. */\n  \n  public void removeTexture(int which)\n  {\n    Texture tex = textures.elementAt(which);\n\n    textures.removeElementAt(which);\n    for (int i = 0; i < textureListeners.size(); i++)\n      textureListeners.elementAt(i).itemRemoved(which, tex);\n    if (textures.size() == 0)\n      {\n        UniformTexture defTex = new UniformTexture();\n        defTex.setName(\"Default Texture\");\n        textures.addElement(defTex);\n        for (int i = 0; i < textureListeners.size(); i++)\n          textureListeners.elementAt(i).itemAdded(0, defTex);\n      }\n    Texture def = textures.elementAt(0);\n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo obj = objects.elementAt(i);\n        if (obj.getObject().getTexture() == tex)\n          obj.setTexture(def, def.getDefaultMapping(obj.getObject()));\n        if (obj.getObject().getTextureMapping() instanceof LayeredMapping)\n        {\n          LayeredMapping map = (LayeredMapping) obj.getObject().getTextureMapping();\n          for (int j = map.getNumLayers()-1; j >= 0; j--)\n            if (map.getLayer(j) == tex)\n              map.deleteLayer(j);\n          obj.setTexture(obj.getObject().getTexture(), map);\n        }\n      }\n    if (environTexture == tex)\n    {\n      environTexture = def;\n      environMapping = def.getDefaultMapping(new Sphere(1.0, 1.0, 1.0));\n    }\n    if (environMapping instanceof LayeredMapping)\n    {\n      Sphere tempObject = new Sphere(1, 1, 1);\n      tempObject.setTexture(environTexture, environMapping);\n      tempObject.setParameterValues(environParamValue);\n      LayeredMapping map = (LayeredMapping) environMapping;\n      for (int j = map.getNumLayers()-1; j >= 0; j--)\n        if (map.getLayer(j) == tex)\n          map.deleteLayer(j);\n      tempObject.setTexture(environTexture, environMapping);\n      environParamValue = tempObject.getParameterValues();\n    }\n  }\n\n  /**\n   * Reorder the list of Textures by moving a Texture to a new position in the list.\n   *\n   * @param oldIndex    the index of the Texture to move\n   * @param newIndex    the new position to move it to\n   */\n\n  public void reorderTexture(int oldIndex, int newIndex)\n  {\n    if (newIndex < 0 || newIndex >= textures.size())\n      throw new IllegalArgumentException(\"Illegal value for newIndex: \"+newIndex);\n    Texture tex = textures.remove(oldIndex);\n    textures.add(newIndex, tex);\n  }\n  \n  /** This method should be called after a Material has been edited.  It notifies \n      any objects using the Material that it has changed. */\n  \n  public void changeMaterial(int which)\n  {\n    Material mat = materials.elementAt(which);\n    Object3D obj;\n\n    for (int i = 0; i < objects.size(); i++)\n      {\n        obj = objects.elementAt(i).getObject();\n        if (obj.getMaterial() == mat)\n          obj.setMaterial(mat, obj.getMaterialMapping());\n      }\n    for (int i = 0; i < materialListeners.size(); i++)\n      materialListeners.elementAt(i).itemChanged(which, mat);\n  }\n  \n  /** This method should be called after a Texture has been edited.  It notifies \n      any objects using the Texture that it has changed. */\n\n  public void changeTexture(int which)\n  {\n    Texture tex = textures.elementAt(which);\n\n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo obj = objects.elementAt(i);\n        if (obj.getObject().getTexture() == tex)\n          obj.setTexture(tex, obj.getObject().getTextureMapping());\n        else if (obj.getObject().getTexture() instanceof LayeredTexture)\n          for (Texture layer : ((LayeredMapping) obj.getObject().getTextureMapping()).getLayers())\n            if (layer == tex)\n            {\n              obj.setTexture(tex, obj.getObject().getTextureMapping());\n              break;\n            }\n      }\n    for (int i = 0; i < textureListeners.size(); i++)\n      textureListeners.elementAt(i).itemChanged(which, tex);\n  }\n  \n  /** Add an object which wants to be notified when the list of Materials in the Scene changes. */\n  \n  public void addMaterialListener(ListChangeListener ls)\n  {\n    materialListeners.addElement(ls);\n  }\n  \n  /** Remove an object from the set to be notified when the list of Materials changes. */\n  \n  public void removeMaterialListener(ListChangeListener ls)\n  {\n    materialListeners.removeElement(ls);\n  }\n  \n  /** Add an object which wants to be notified when the list of Textures in the Scene changes. */\n\n  public void addTextureListener(ListChangeListener ls)\n  {\n    textureListeners.addElement(ls);\n  }\n  \n  /** Remove an object from the set to be notified when the list of Textures changes. */\n\n  public void removeTextureListener(ListChangeListener ls)\n  {\n    textureListeners.removeElement(ls);\n  }\n\n  /**\n   * Get a piece of metadata stored in this scene.\n   *\n   * @param name   the name of the piece of metadata to get\n   * @return the value associated with that name, or null if there is none\n   */\n\n  public Object getMetadata(String name)\n  {\n    return metadataMap.get(name);\n  }\n\n  /**\n   * Store a piece of metadata in this scene.  This may be an arbitrary object which\n   * you want to store as part of the scene.  When the scene is saved to disk, metadata\n   * objects are stored using the java.beans.XMLEncoder class.  This means that if the\n   * object is not a bean, you must register a PersistenceDelegate for it before calling\n   * this method.  Otherwise, it will fail to be saved.\n   *\n   * @param name   the name of the piece of metadata to set\n   * @param value  the value to store\n   */\n\n  public void setMetadata(String name, Object value)\n  {\n    metadataMap.put(name, value);\n  }\n\n  /**\n   * Get the names of all metadata objects stored in this scene.\n   */\n\n  public Set<String> getAllMetadataNames()\n  {\n    return metadataMap.keySet();\n  }\n  \n  /** Show the dialog for editing textures and materials. */\n  \n  public void showTexturesDialog(EditingWindow parent)\n\n  {\n    if (texDlg == null)\n      texDlg = new TexturesAndMaterialsDialog(parent, this);\n    else\n    {\n      Rectangle r = texDlg.getBounds();\n      texDlg.dispose();\n      texDlg = new TexturesAndMaterialsDialog(parent, this);\n      texDlg.setBounds(r);\n    }\n    texDlg.setVisible(true);\n  }\n  \n  /** Add an image map to the scene. */\n  \n  public void addImage(ImageMap im)\n  {\n    images.addElement(im);\n  }\n  \n  /** Remove an image map from the scene. */\n\n  public boolean removeImage(int which)\n  {\n    ImageMap image = images.elementAt(which);\n\n    for (int i = 0; i < textures.size(); i++)\n      if (textures.elementAt(i).usesImage(image))\n        return false;\n    for (int i = 0; i < materials.size(); i++)\n      if (materials.elementAt(i).usesImage(image))\n        return false;\n    images.removeElementAt(which);\n    return true;\n  }\n  \n  /** Replace every instance of one object in the scene with another one.  If undo is not\n      null, commands will be added to it to undo this operation. */\n  \n  public void replaceObject(Object3D original, Object3D replaceWith, UndoRecord undo)\n  {\n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        if (info.getObject() != original)\n          continue;\n        if (undo != null)\n          undo.addCommand(UndoRecord.SET_OBJECT, new Object [] {info, original});\n        info.setObject(replaceWith);\n        info.clearCachedMeshes();\n      }\n  }\n  \n  /** This should be called whenever an object changes.  It clears any cached meshes for\n      any instances of the object. */\n  \n  public void objectModified(Object3D obj)\n  {\n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        if (info.getObject() == obj)\n          {\n            info.clearCachedMeshes();\n            info.setPose(null);\n          }\n      }\n  }\n  \n  /**\n   * Set one object to be selected, deselecting all other objects.\n   * @deprecated Call setSelection() on the LayoutWindow instead.\n   */\n\n  public void setSelection(int which)\n  {\n    clearSelection();\n    addToSelection(which);\n    updateSelectionInfo();\n  }\n\n  /**\n   * Set a list of objects to be selected, deselecting all other objects.\n   * @deprecated Call setSelection() on the LayoutWindow instead.\n   */\n  \n  public void setSelection(int which[])\n  {\n    clearSelection();\n    for (int i = 0; i < which.length; i++)\n      addToSelection(which[i]);\n    updateSelectionInfo();\n  }\n  \n  /**\n   * Add an object to the list of selected objects.\n   * @deprecated Call addToSelection() on the LayoutWindow instead.\n   */\n  \n  public void addToSelection(int which)\n  {\n    ObjectInfo info = objects.elementAt(which);\n    if (!info.selected)\n      selection.addElement(which);\n    info.selected = true;\n    updateSelectionInfo();\n  }\n  \n  /**\n   * Deselect all objects.\n   * @deprecated Call clearSelection() on the LayoutWindow instead.\n   */\n  \n  public void clearSelection()\n  {\n    selection.removeAllElements();\n    for (int i = 0; i < objects.size(); i++)\n      objects.elementAt(i).selected = false;\n    updateSelectionInfo();\n  }\n  \n  /**\n   * Deselect a particular object.\n   * @deprecated Call removeFromSelection() on the LayoutWindow instead.\n   */\n  \n  public void removeFromSelection(int which)\n  {\n    ObjectInfo info = objects.elementAt(which);\n    selection.removeElement(which);\n    info.selected = false;\n    updateSelectionInfo();\n  }\n  \n  /** Calculate the list of which objects are children of selected objects. */\n  \n  private void updateSelectionInfo()\n  {\n    for (int i = objects.size()-1; i >= 0; i--)\n      objects.elementAt(i).parentSelected = false;\n    for (int i = objects.size()-1; i >= 0; i--)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        ObjectInfo parent = info.getParent();\n        while (parent != null)\n          {\n            if (parent.selected || parent.parentSelected)\n              {\n                info.parentSelected = true;\n                break;\n              }\n            parent = parent.getParent();\n          }\n      }\n  }\n  \n  /** Get the number of objects in this scene. */\n  \n  public int getNumObjects()\n  {\n    return objects.size();\n  }\n  \n  /** Get the i'th object. */\n  \n  public ObjectInfo getObject(int i)\n  {\n    return objects.elementAt(i);\n  }\n    \n  /** Get the object with the specified name, or null if there is none.  If\n      more than one object has the same name, this will return the first one. */\n  \n  public ObjectInfo getObject(String name)\n  {\n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        if (info.getName().equals(name))\n          return info;\n      }\n    return null;\n  }\n\n  /** Get the object with the specified ID, or null if there is none. */\n\n  public ObjectInfo getObjectById(int id)\n  {\n    for (int i = 0; i < objects.size(); i++)\n    {\n      ObjectInfo info = objects.elementAt(i);\n      if (info.getId() == id)\n        return info;\n    }\n    return null;\n  }\n\n  /** Get all objects in the Scene in the form of a List. */\n\n  public List<ObjectInfo> getAllObjects()\n  {\n    return Collections.unmodifiableList(objects);\n  }\n\n  /** Get the index of the specified object. */\n  \n  public int indexOf(ObjectInfo info)\n  {\n    if (objectIndexMap == null)\n    {\n      // Build an index for fast lookup.\n\n      objectIndexMap = new HashMap<ObjectInfo, Integer>();\n      for (int i = 0; i < objects.size(); i++)\n        objectIndexMap.put(objects.get(i), i);\n    }\n    Integer index = objectIndexMap.get(info);\n    return (index == null ? -1 : index);\n  }\n  \n  /** Get the number of textures in this scene. */\n  \n  public int getNumTextures()\n  {\n    return textures.size();\n  }\n  \n  /** Get the index of the specified texture. */\n  \n  public int indexOf(Texture tex)\n  {\n    return textures.indexOf(tex);\n  }\n  \n  /** Get the i'th texture. */\n  \n  public Texture getTexture(int i)\n  {\n    return textures.elementAt(i);\n  }\n  \n  /** Get the texture with the specified name, or null if there is none.  If\n      more than one texture has the same name, this will return the first one. */\n  \n  public Texture getTexture(String name)\n  {\n    for (int i = 0; i < textures.size(); i++)\n      {\n        Texture tex = textures.elementAt(i);\n        if (tex.getName().equals(name))\n          return tex;\n      }\n    return null;\n  }\n  \n  /** Get the number of materials in this scene. */\n  \n  public int getNumMaterials()\n  {\n    return materials.size();\n  }\n  \n  /** Get the i'th material. */\n  \n  public Material getMaterial(int i)\n  {\n    return materials.elementAt(i);\n  }\n  \n  /** Get the material with the specified name, or null if there is none.  If\n      more than one material has the same name, this will return the first one. */\n  \n  public Material getMaterial(String name)\n  {\n    for (int i = 0; i < materials.size(); i++)\n      {\n        Material mat = materials.elementAt(i);\n        if (mat.getName().equals(name))\n          return mat;\n      }\n    return null;\n  }\n  \n  /** Get the index of the specified material. */\n  \n  public int indexOf(Material mat)\n  {\n    return materials.indexOf(mat);\n  }\n\n  /** Get the number of image maps in this scene. */\n  \n  public int getNumImages()\n  {\n    return images.size();\n  }\n  \n  /** Get the i'th image map. */\n  \n  public ImageMap getImage(int i)\n  {\n    return images.elementAt(i);\n  }\n  \n  /** Get the index of the specified image map. */\n  \n  public int indexOf(ImageMap im)\n  {\n    return images.indexOf(im);\n  }\n  \n  /** Get the default Texture for newly created objects. */\n  \n  public Texture getDefaultTexture()\n  {\n    return textures.elementAt(0);\n  }\n    \n  /**\n   * Get a list of the indices of all selected objects.\n   * @deprecated Call getSelectedIndices() or getSelectedObjects() on the LayoutWindow instead.\n   */\n\n  public int [] getSelection()\n  {\n    int sel[] = new int [selection.size()];\n\n    for (int i = 0; i < sel.length; i++)\n      sel[i] = selection.elementAt(i);\n    return sel;\n  }\n  \n  /**\n   * Get the indices of all objects which are either selected, or are children of\n   * selected objects.\n   * @deprecated Call getSelectionWithChildren() on the LayoutWindow instead.\n   */\n  \n  public int [] getSelectionWithChildren()\n  {\n    int count = 0;\n    for (int i = objects.size()-1; i >= 0; i--)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        if (info.selected || info.parentSelected)\n          count++;\n      }\n    int sel[] = new int [count];\n    count = 0;\n    for (int i = objects.size()-1; i >= 0; i--)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        if (info.selected || info.parentSelected)\n          sel[count++] = i;\n      }\n    return sel;\n  }\n  \n  /** Return true if any errors occurred while loading the scene.  The scene is still valid\n      and usable, but some objects in it were not loaded correctly. */\n  \n  public boolean errorsOccurredInLoading()\n  {\n    return errorsLoading;\n  }\n\n  /** Get a description of any errors which occurred while loading the scene. */\n\n  public String getLoadingErrors()\n  {\n    return (loadingErrors == null ? \"\" : loadingErrors.toString());\n  }\n\n  /** The following constructor is used for reading files.  If fullScene is false, only the\n      Textures and Materials are read. */\n  \n  public Scene(File f, boolean fullScene) throws IOException, InvalidObjectException\n  {\n    setName(f.getName());\n    setDirectory(f.getParent());\n    BufferedInputStream buf = new BufferedInputStream(new FileInputStream(f));\n    buf.mark(FILE_PREFIX.length);\n\n    // See if the file begins with the expected prefix.\n\n    boolean hasPrefix = true;\n    for (int i = 0; hasPrefix && i < FILE_PREFIX.length; i++)\n      hasPrefix &= (buf.read() == FILE_PREFIX[i]);\n    if (!hasPrefix)\n      buf.reset(); // This is an old file that doesn't start with the prefix.\n\n    // We expect the data to be gzipped, but if it's somehow gotten decompressed we should accept that to.\n\n    DataInputStream in;\n    try\n    {\n      in = new DataInputStream(new GZIPInputStream(buf));\n    }\n    catch (IOException ex)\n    {\n      buf.close();\n      buf = new BufferedInputStream(new FileInputStream(f));\n      in = new DataInputStream(buf);\n    }\n    initFromStream(in, fullScene);\n    in.close();\n  }\n\n  /** The following constructor is used for reading from arbitrary input streams.  If fullScene\n      is false, only the Textures and Materials are read. */\n  \n  public Scene(DataInputStream in, boolean fullScene) throws IOException, InvalidObjectException\n  {\n    initFromStream(in, fullScene);\n  }\n  \n  /** Initialize the scene based on information read from an input stream. */\n  \n  private void initFromStream(DataInputStream in, boolean fullScene) throws IOException, InvalidObjectException\n  {\n    int count;\n    short version = in.readShort();\n    Hashtable<Integer, Object3D> table;\n    Class cls;\n    Constructor con;\n\n    if (version < 0 || version > 4)\n      throw new InvalidObjectException(\"\");\n    loadingErrors = new StringBuffer();\n    ambientColor = new RGBColor(in);\n    fogColor = new RGBColor(in);\n    fog = in.readBoolean();\n    fogDist = in.readDouble();\n    showGrid = in.readBoolean();\n    snapToGrid = in.readBoolean();\n    gridSpacing = in.readDouble();\n    gridSubdivisions = in.readInt();\n    framesPerSecond = in.readInt();\n    nextID = 1;\n    \n    // Read the image maps.\n    \n    count = in.readInt();\n    images = new Vector<ImageMap>(count);\n    for (int i = 0; i < count; i++)\n      {\n        if (version == 0)\n          {\n            images.addElement(new MIPMappedImage(in, (short) 0));\n            continue;\n          }\n        String classname = in.readUTF();\n        try\n          {\n            cls = ArtOfIllusion.getClass(classname);\n            if (cls == null)\n              throw new IOException(\"Unknown class: \"+classname);\n            con = cls.getConstructor(DataInputStream.class);\n            images.addElement((ImageMap) con.newInstance(in));\n          }\n        catch (Exception ex)\n          {\n            throw new IOException(\"Error loading image: \"+ex.getMessage());\n          }\n      }\n    \n    // Read the materials.\n    \n    count = in.readInt();\n    materials = new Vector<Material>(count);\n    for (int i = 0; i < count; i++)\n      {\n        try\n          {\n            String classname = in.readUTF();\n            int len = in.readInt();\n            byte bytes[] = new byte [len];\n            in.readFully(bytes);\n            cls = ArtOfIllusion.getClass(classname);\n            try\n              {\n                if (cls == null)\n                  throw new IOException(\"Unknown class: \"+classname);\n                con = cls.getConstructor(DataInputStream.class, Scene.class);\n                materials.addElement((Material) con.newInstance(new DataInputStream(new ByteArrayInputStream(bytes)), this));\n              }\n            catch (Exception ex)\n              {\n                ex.printStackTrace();\n                if (ex instanceof ClassNotFoundException)\n                  loadingErrors.append(Translate.text(\"errorFindingClass\", classname)).append('\\n');\n                else\n                  loadingErrors.append(Translate.text(\"errorInstantiatingClass\", classname)).append('\\n');\n                UniformMaterial m = new UniformMaterial();\n                m.setName(\"<unreadable>\");\n                materials.addElement(m);\n                errorsLoading = true;\n              }\n          }\n        catch (Exception ex)\n          {\n            ex.printStackTrace();\n            throw new IOException();\n          }\n      }\n      \n    // Read the textures.\n    \n    count = in.readInt();\n    textures = new Vector<Texture>(count);\n    for (int i = 0; i < count; i++)\n      {\n        try\n          {\n            String classname = in.readUTF();\n            int len = in.readInt();\n            byte bytes[] = new byte [len];\n            in.readFully(bytes);\n            cls = ArtOfIllusion.getClass(classname);\n            try\n              {\n                if (cls == null)\n                  throw new IOException(\"Unknown class: \"+classname);\n                con = cls.getConstructor(DataInputStream.class, Scene.class);\n                textures.addElement((Texture) con.newInstance(new DataInputStream(new ByteArrayInputStream(bytes)), this));\n              }\n            catch (Exception ex)\n              {\n                ex.printStackTrace();\n                if (ex instanceof ClassNotFoundException)\n                  loadingErrors.append(Translate.text(\"errorFindingClass\", classname)).append('\\n');\n                else\n                  loadingErrors.append(Translate.text(\"errorInstantiatingClass\", classname)).append('\\n');\n                UniformTexture t = new UniformTexture();\n                t.setName(\"<unreadable>\");\n                textures.addElement(t);\n                errorsLoading = true;\n              }\n          }\n        catch (Exception ex)\n          {\n            ex.printStackTrace();\n            throw new IOException();\n          }\n      }\n  \n    // Read the objects.\n    \n    count = in.readInt();\n    objects = new Vector<ObjectInfo>(count);\n    table = new Hashtable<Integer, Object3D>(count);\n    for (int i = 0; i < count; i++)\n      objects.addElement(readObjectFromFile(in, table, version));\n    objectIndexMap = null;\n    selection = new Vector<Integer>();\n    \n    // Read the list of children for each object.\n    \n    for (int i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        int num = in.readInt();\n        for (int j = 0; j < num; j++)\n          {\n            ObjectInfo child = objects.elementAt(in.readInt());\n            info.addChild(child, j);\n          }\n      }\n    \n    // Read in the environment mapping information.\n    \n    environMode = (int) in.readShort();\n    if (environMode == ENVIRON_SOLID)\n      {\n        environColor = new RGBColor(in);\n        environTexture = textures.elementAt(0);\n        environMapping = environTexture.getDefaultMapping(new Sphere(1.0, 1.0, 1.0));\n        environParamValue = new ParameterValue [0];\n      }\n    else\n      {\n        int texIndex = in.readInt();\n        if (texIndex == -1)\n          {\n            // This is a layered texture.\n\n            Object3D sphere = new Sphere(1.0, 1.0, 1.0);\n            environTexture = new LayeredTexture(sphere);\n            String mapClassName = in.readUTF();\n            if (!LayeredMapping.class.getName().equals(mapClassName))\n              throw new InvalidObjectException(\"\");\n            environMapping = environTexture.getDefaultMapping(sphere);\n            ((LayeredMapping) environMapping).readFromFile(in, this);\n          }\n        else\n          {\n            environTexture = textures.elementAt(texIndex);\n            try\n              {\n                Class mapClass = ArtOfIllusion.getClass(in.readUTF());\n                con = mapClass.getConstructor(DataInputStream.class, Object3D.class, Texture.class);\n                environMapping = (TextureMapping) con.newInstance(in, new Sphere(1.0, 1.0, 1.0), environTexture);\n              }\n            catch (Exception ex)\n              {\n                throw new IOException();\n              }\n          }\n        environColor = new RGBColor(0.0f, 0.0f, 0.0f);\n        environParamValue = new ParameterValue [environMapping.getParameters().length];\n        if (version > 2)\n          for (int i = 0; i < environParamValue.length; i++)\n            environParamValue[i] = Object3D.readParameterValue(in);\n      }\n\n    // Read the metadata.\n\n    metadataMap = new HashMap<String, Object>();\n    if (version > 3)\n    {\n      count = in.readInt();\n      SearchlistClassLoader loader = new SearchlistClassLoader(getClass().getClassLoader());\n      for (ClassLoader cl : PluginRegistry.getPluginClassLoaders())\n        loader.add(cl);\n      for (int i = 0; i < count; i++)\n      {\n        try\n        {\n          String name = in.readUTF();\n          byte data[] = new byte[in.readInt()];\n          in.readFully(data);\n          XMLDecoder decoder = new XMLDecoder(new ByteArrayInputStream(data), null, null, loader);\n          metadataMap.put(name, decoder.readObject());\n        }\n        catch (Exception ex)\n        {\n          ex.printStackTrace();\n          // Nothing more we can do about it.\n        }\n      }\n    }\n    textureListeners = new Vector<ListChangeListener>();\n    materialListeners = new Vector<ListChangeListener>();\n    setTime(0.0);\n  }\n  \n  private ObjectInfo readObjectFromFile(DataInputStream in, Hashtable<Integer, Object3D> table, int version) throws IOException, InvalidObjectException\n  {\n    ObjectInfo info = new ObjectInfo(null, new CoordinateSystem(in), in.readUTF());\n    Class cls;\n    Constructor con;\n    Object3D obj;\n\n    info.setId(in.readInt());\n    if (info.getId() >= nextID)\n      nextID = info.getId() +1;\n    info.setVisible(in.readBoolean());\n    Integer key = in.readInt();\n    obj = table.get(key);\n    if (obj == null)\n      {\n        try\n          {\n            String classname = in.readUTF();\n            int len = in.readInt();\n            byte bytes[] = new byte [len];\n            in.readFully(bytes);\n            try\n              {\n                cls = ArtOfIllusion.getClass(classname);\n                con = cls.getConstructor(DataInputStream.class, Scene.class);\n                obj = (Object3D) con.newInstance(new DataInputStream(new ByteArrayInputStream(bytes)), this);\n              }\n            catch (Exception ex)\n              {\n                if (ex instanceof InvocationTargetException)\n                  ((InvocationTargetException) ex).getTargetException().printStackTrace();\n                else\n                  ex.printStackTrace();\n                if (ex instanceof ClassNotFoundException)\n                  loadingErrors.append(info.getName()).append(\": \").append(Translate.text(\"errorFindingClass\", classname)).append('\\n');\n                else\n                  loadingErrors.append(info.getName()).append(\": \").append(Translate.text(\"errorInstantiatingClass\", classname)).append('\\n');\n                obj = new NullObject();\n                info.setName(\"<unreadable> \"+ info.getName());\n                errorsLoading = true;\n              }\n            table.put(key, obj);\n          }\n        catch (Exception ex)\n          {\n            ex.printStackTrace();\n            throw new IOException();\n          }\n      }\n    info.setObject(obj);\n    \n    if (version < 2 && obj.getTexture() != null)\n      {\n        // Initialize the texture parameters.\n        \n        TextureParameter texParam[] = obj.getTextureMapping().getParameters();\n        ParameterValue paramValue[] = obj.getParameterValues();\n        double val[] = new double [paramValue.length];\n        boolean perVertex[] = new boolean [paramValue.length];\n        for (int i = 0; i < val.length; i++)\n          val[i] = in.readDouble();\n        for (int i = 0; i < perVertex.length; i++)\n          perVertex[i] = in.readBoolean();\n        for (int i = 0; i < paramValue.length; i++)\n          if (paramValue[i] == null)\n          {\n            if (perVertex[i])\n              paramValue[i] = new VertexParameterValue((Mesh) obj, texParam[i]);\n            else\n              paramValue[i] = new ConstantParameterValue(val[i]);\n          }\n        obj.setParameterValues(paramValue);\n      }\n    \n    // Read the tracks for this object.\n    \n    int tracks = in.readInt();\n    try\n      {\n        for (int i = 0; i < tracks; i++)\n          {\n            cls = ArtOfIllusion.getClass(in.readUTF());\n            con = cls.getConstructor(ObjectInfo.class);\n            Track tr = (Track) con.newInstance(info);\n            tr.initFromStream(in, this);\n            info.addTrack(tr, i);\n          }\n        if (info.getTracks() == null)\n          info.tracks = new Track [0];\n      }\n    catch (Exception ex)\n      {\n        ex.printStackTrace();\n        throw new IOException();\n      }\n    return info;\n  }\n\n  /** Save the Scene to a file. */\n  \n  public void writeToFile(File f) throws IOException\n  {\n    int mode = (ArtOfIllusion.getPreferences().getKeepBackupFiles() ? SafeFileOutputStream.OVERWRITE+SafeFileOutputStream.KEEP_BACKUP : SafeFileOutputStream.OVERWRITE);\n    SafeFileOutputStream safeOut = new SafeFileOutputStream(f, mode);\n    BufferedOutputStream bout = new BufferedOutputStream(safeOut);\n    bout.write(FILE_PREFIX);\n    DataOutputStream out = new DataOutputStream(new GZIPOutputStream(bout));\n    writeToStream(out);\n    out.close();\n  }\n\n  /** Write the Scene's representation to an output stream. */\n  \n  public void writeToStream(DataOutputStream out) throws IOException\n  {\n    Material mat;\n    Texture tex;\n    int i, j, index = 0;\n    Hashtable<Object3D, Integer> table = new Hashtable<Object3D, Integer>(objects.size());\n    \n    out.writeShort(4);\n    ambientColor.writeToFile(out);\n    fogColor.writeToFile(out);\n    out.writeBoolean(fog);\n    out.writeDouble(fogDist);\n    out.writeBoolean(showGrid);\n    out.writeBoolean(snapToGrid);\n    out.writeDouble(gridSpacing);\n    out.writeInt(gridSubdivisions);\n    out.writeInt(framesPerSecond);\n\n    // Save the image maps.\n    \n    out.writeInt(images.size());\n    for (i = 0; i < images.size(); i++)\n      {\n        ImageMap img = images.elementAt(i);\n        out.writeUTF(img.getClass().getName());\n        img.writeToStream(out);\n      }\n\n    // Save the materials.\n\n    out.writeInt(materials.size());\n    for (i = 0; i < materials.size(); i++)\n      {\n        mat = materials.elementAt(i);\n        out.writeUTF(mat.getClass().getName());\n        ByteArrayOutputStream bos = new ByteArrayOutputStream();\n        mat.writeToFile(new DataOutputStream(bos), this);\n        byte bytes[] = bos.toByteArray();\n        out.writeInt(bytes.length);\n        out.write(bytes, 0, bytes.length);\n      }\n    \n    // Save the textures.\n\n    out.writeInt(textures.size());\n    for (i = 0; i < textures.size(); i++)\n      {\n        tex = textures.elementAt(i);\n        out.writeUTF(tex.getClass().getName());\n        ByteArrayOutputStream bos = new ByteArrayOutputStream();\n        tex.writeToFile(new DataOutputStream(bos), this);\n        byte bytes[] = bos.toByteArray();\n        out.writeInt(bytes.length);\n        out.write(bytes, 0, bytes.length);\n      }\n\n    // Save the objects.\n    \n    out.writeInt(objects.size());\n    for (i = 0; i < objects.size(); i++)\n      index = writeObjectToFile(out, objects.elementAt(i), table, index);\n    \n    // Record the children of each object.  The format of this will be changed in the\n    // next version.\n    \n    for (i = 0; i < objects.size(); i++)\n      {\n        ObjectInfo info = objects.elementAt(i);\n        out.writeInt(info.getChildren().length);\n        for (j = 0; j < info.getChildren().length; j++)\n          out.writeInt(indexOf(info.getChildren()[j]));\n      }\n    \n    // Save the environment mapping information.\n\n    out.writeShort((short) environMode);\n    if (environMode == ENVIRON_SOLID)\n      environColor.writeToFile(out);\n    else\n      {\n        out.writeInt(textures.lastIndexOf(environTexture));\n        out.writeUTF(environMapping.getClass().getName());\n        if (environMapping instanceof LayeredMapping)\n          ((LayeredMapping) environMapping).writeToFile(out, this);\n        else\n          environMapping.writeToFile(out);\n        for (i = 0; i < environParamValue.length; i++)\n        {\n          out.writeUTF(environParamValue[i].getClass().getName());\n          environParamValue[i].writeToStream(out);\n        }\n      }\n\n    // Save metadata.\n\n    out.writeInt(metadataMap.size());\n    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();\n    SearchlistClassLoader loader = new SearchlistClassLoader(getClass().getClassLoader());\n    for (ClassLoader cl : PluginRegistry.getPluginClassLoaders())\n      loader.add(cl);\n    Thread.currentThread().setContextClassLoader(loader); // So that plugin classes can be saved correctly.\n    ExceptionListener exceptionListener = new ExceptionListener()\n      {\n        public void exceptionThrown(Exception e)\n        {\n          e.printStackTrace();\n        }\n      };\n    for (Map.Entry<String, Object> entry : metadataMap.entrySet())\n    {\n      ByteArrayOutputStream value = new ByteArrayOutputStream();\n      XMLEncoder encoder = new XMLEncoder(value);\n      encoder.setExceptionListener(exceptionListener);\n      encoder.writeObject(entry.getValue());\n      encoder.close();\n      out.writeUTF(entry.getKey());\n      out.writeInt(value.size());\n      out.write(value.toByteArray());\n    }\n    Thread.currentThread().setContextClassLoader(contextClassLoader);\n  }\n  \n  /** Write the information about a single object to a file. */\n  \n  private int writeObjectToFile(DataOutputStream out, ObjectInfo info, Hashtable<Object3D, Integer> table, int index) throws IOException\n  {\n    Integer key;\n\n    info.getCoords().writeToFile(out);\n    out.writeUTF(info.getName());\n    out.writeInt(info.getId());\n    out.writeBoolean(info.isVisible());\n    key = table.get(info.getObject());\n    if (key == null)\n      {\n        out.writeInt(index);\n        out.writeUTF(info.getObject().getClass().getName());\n        ByteArrayOutputStream bos = new ByteArrayOutputStream();\n        info.getObject().writeToFile(new DataOutputStream(bos), this);\n        byte bytes[] = bos.toByteArray();\n        out.writeInt(bytes.length);\n        out.write(bytes, 0, bytes.length);\n        key = index++;\n        table.put(info.getObject(), key);\n      }\n    else\n      out.writeInt(key.intValue());\n    \n    // Write the tracks for this object.\n    \n    out.writeInt(info.getTracks().length);\n    for (int i = 0; i < info.getTracks().length; i++)\n      {\n        out.writeUTF(info.getTracks()[i].getClass().getName());\n        info.getTracks()[i].writeToStream(out, this);\n      }\n    return index;\n  }\n}", "human_rating": 2.5651372157199996, "metadata": {"project": "aoi", "class": "artofillusion.Scene", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/Scene.java", "label_probabilities": {"readability": [9.30393e-06, 0.675306, 0.214497, 0.110188], "understandability": [1.3329e-08, 0.000682626, 0.191176, 0.808142], "complexity": [0.170608, 0.829232, 0.000159546, 0.0], "modularization": [0.531182, 0.460258, 0.00855951, 1.16629e-06], "overall": [0.0, 7.95193e-06, 0.0626127, 0.937379]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.SceneChangedEvent", "source": "/* Copyright (C) 2006-2009 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.ui.*;\n\n/**\n * A SceneChangedEvent is dispatched by an EditingWindow to indicate that some element of the\n * scene has changed.  This includes all aspects of the scene, including the list of objects,\n * properties of individual objects, textures, the list of currently selected objects, etc.\n */\n\npublic class SceneChangedEvent\n{\n  private EditingWindow window;\n\n  public SceneChangedEvent(EditingWindow window)\n  {\n    this.window = window;\n  }\n\n  /**\n   * Get the LayoutWindow containing the scene which was changed.\n   */\n\n  public EditingWindow getWindow()\n  {\n    return window;\n  }\n}\n", "human_rating": 3.999848653, "metadata": {"project": "aoi", "class": "artofillusion.SceneChangedEvent", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/SceneChangedEvent.java", "label_probabilities": {"readability": [0.99985, 0.000149551, 4e-20, 0.0], "understandability": [0.996698, 0.00330157, 4.82091e-12, 0.0], "complexity": [0.0, 0.0, 2.64836e-09, 1.0], "modularization": [0.0, 4e-20, 0.00214848, 0.997852], "overall": [0.99961, 0.000390201, 1.4e-19, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.SceneViewer", "source": "/* Copyright (C) 1999-2011 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.image.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.ui.*;\nimport artofillusion.view.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.util.*;\n\n/** The SceneViewer class is a component which displays a view of a Scene. */\n\npublic class SceneViewer extends ViewerCanvas\n{\n  Scene theScene;\n  EditingWindow parentFrame;\n  Vector<ObjectInfo> cameras;\n  boolean draggingBox, draggingSelectionBox, squareBox, sentClick, dragging;\n  Point clickPoint, dragPoint;\n  ObjectInfo clickedObject;\n  int deselect;\n  \n  public SceneViewer(Scene s, RowContainer p, EditingWindow fr)\n  {\n    this(s, p, fr, false);\n  }\n\n  public SceneViewer(Scene s, RowContainer p, EditingWindow fr, boolean forceSoftwareRendering)\n  {\n    super(ArtOfIllusion.getPreferences().getUseOpenGL() && isOpenGLAvailable() && !forceSoftwareRendering);\n    theScene = s;\n    parentFrame = fr;\n    addEventLink(MouseClickedEvent.class, this, \"mouseClicked\");\n    draggingBox = draggingSelectionBox = false;\n    cameras = new Vector<ObjectInfo>();\n    buildChoices(p);\n    rebuildCameraList();\n    setRenderMode(ArtOfIllusion.getPreferences().getDefaultDisplayMode());\n  }\n\n  /** Get the EditingWindow in which this canvas is displayed. */\n\n  public EditingWindow getEditingWindow()\n  {\n    return parentFrame;\n  }\n\n  /**\n   * Get the Scene displayed in this canvas.\n   */\n\n  public Scene getScene()\n  {\n    return theScene;\n  }\n\n  /** Add all SceneCameras in the scene to list of available views. */\n  \n  public void rebuildCameraList()\n  {\n    cameras.removeAllElements();\n    for (int i = 0; i < theScene.getNumObjects(); i++)\n    {\n      ObjectInfo obj = theScene.getObject(i);\n      if (obj.getObject() instanceof SceneCamera)\n        cameras.addElement(obj);\n    }\n    for (int i = 0; i < theScene.getNumObjects(); i++)\n    {\n      ObjectInfo obj = theScene.getObject(i);\n      if (obj.getObject() instanceof DirectionalLight || obj.getObject() instanceof SpotLight)\n        cameras.addElement(obj);\n    }\n    for (Iterator iter = getViewerControlWidgets().values().iterator(); iter.hasNext(); )\n    {\n      Widget w = (Widget) iter.next();\n      if (w instanceof ViewerOrientationControl.OrientationChoice)\n        ((ViewerOrientationControl.OrientationChoice) w).rebuildCameraList();\n    }\n  }\n\n  /** Get the list of cameras in the scene which can be used as predefined orientations. */\n\n  public ObjectInfo[] getCameras()\n  {\n    return cameras.toArray(new ObjectInfo[cameras.size()]);\n  }\n\n  /** Deal with selecting a SceneCamera from the choice menu. */\n  \n  public void setOrientation(int which)\n  {\n    super.setOrientation(which);\n    if (which > 5 && which < 6+cameras.size())\n    {\n      boundCamera = cameras.elementAt(which-6);\n      CoordinateSystem coords = theCamera.getCameraCoordinates();\n      coords.copyCoords(boundCamera.getCoords());\n      theCamera.setCameraCoordinates(coords);\n      viewChanged(false);\n      repaint();\n    }\n    else\n    {\n      boundCamera = null;\n      viewChanged(false);\n    }\n  }\n  \n  /** Estimate the range of depth values that the camera will need to render.  This need not be exact,\n      but should err on the side of returning bounds that are slightly too large.\n      @return the two element array {minDepth, maxDepth}\n   */\n  \n  public double[] estimateDepthRange()\n  {\n    double min = Double.MAX_VALUE, max = -Double.MAX_VALUE;\n    Mat4 toView = theCamera.getWorldToView();\n    for (int i = 0; i < theScene.getNumObjects(); i++)\n    {\n      ObjectInfo info = theScene.getObject(i);\n      BoundingBox bounds = info.getBounds().transformAndOutset(toView.times(info.coords.fromLocal()));\n      if (bounds.minz < min)\n        min = bounds.minz;\n      if (bounds.maxz > max)\n        max = bounds.maxz;\n    }\n    return new double [] {min, max};\n  }\n\n  @Override\n  public Vec3 getDefaultRotationCenter()\n  {\n    int selection[] = null;\n    if (parentFrame instanceof LayoutWindow)\n      selection = ((LayoutWindow) parentFrame).getSelectedIndices();\n    if (selection == null || selection.length == 0)\n    {\n      CoordinateSystem coords = theCamera.getCameraCoordinates();\n      double distToCenter = -coords.getZDirection().dot(coords.getOrigin());\n      return coords.getOrigin().plus(coords.getZDirection().times(distToCenter));\n    }\n    BoundingBox bounds = null;\n    for (int i = 0; i < selection.length; i++)\n    {\n      ObjectInfo info = theScene.getObject(selection[i]);\n      BoundingBox objBounds = info.getBounds().transformAndOutset(info.getCoords().fromLocal());\n      bounds = (i == 0 ? objBounds : bounds.merge(objBounds));\n    }\n    return bounds.getCenter();\n  }\n\n  @Override\n  public void viewChanged(boolean selectionOnly)\n  {\n    super.viewChanged(selectionOnly);\n    if (renderMode == RENDER_RENDERED && !selectionOnly)\n    {\n      // Re-render the image.\n\n      Renderer rend = ArtOfIllusion.getPreferences().getObjectPreviewRenderer();\n      if (rend == null)\n        return;\n      adjustCamera(true);\n      Camera cam = theCamera.duplicate();\n      rend.configurePreview();\n      Rectangle bounds = getBounds();\n      SceneCamera sceneCamera = new SceneCamera();\n      sceneCamera.setFieldOfView(Math.atan(0.5*bounds.height/cam.getViewToScreen().m33)*360.0/Math.PI);\n      adjustCamera(isPerspective());\n      RenderListener listener = new RenderListener()\n      {\n        public void imageUpdated(Image image)\n        {\n          renderedImage = image;\n          getCanvasDrawer().imageChanged(renderedImage);\n          repaint();\n        }\n        public void statusChanged(String status)\n        {\n        }\n        public void imageComplete(ComplexImage image)\n        {\n          renderedImage = image.getImage();\n          getCanvasDrawer().imageChanged(renderedImage);\n          repaint();\n        }\n        public void renderingCanceled()\n        {\n        }\n      };\n      rend.renderScene(theScene, cam, listener, sceneCamera);\n    }\n  }\n\n  public synchronized void updateImage()\n  {\n    if (renderMode == RENDER_RENDERED)\n    {\n      if (renderedImage != null && renderedImage.getWidth(null) > 0)\n        drawImage(renderedImage, 0, 0);\n      else\n        viewChanged(false);\n    }\n    else\n    {\n      super.updateImage();\n\n      // Draw the objects.\n\n      Vec3 viewdir = theCamera.getViewToWorld().timesDirection(Vec3.vz());\n      for (int i = 0; i < theScene.getNumObjects(); i++)\n      {\n        ObjectInfo obj = theScene.getObject(i);\n        if (obj == boundCamera || !obj.isVisible())\n          continue;\n        theCamera.setObjectTransform(obj.getCoords().fromLocal());\n        obj.getObject().renderObject(obj, this, viewdir);\n      }\n    }\n\n    // Hilight the selection.\n\n    if (currentTool.hilightSelection())\n    {\n      ArrayList<Rectangle> selectedBoxes = new ArrayList<Rectangle>();\n      ArrayList<Rectangle> parentSelectedBoxes = new ArrayList<Rectangle>();\n      for (int i = 0; i < theScene.getNumObjects(); i++)\n      {\n        int hsize;\n        ArrayList<Rectangle> boxes;\n        ObjectInfo obj = theScene.getObject(i);\n        if (obj.isLocked())\n          continue;\n        if (obj.selected)\n        {\n          hsize = Scene.HANDLE_SIZE;\n          boxes = selectedBoxes;\n        }\n        else if (obj.parentSelected)\n        {\n          hsize = Scene.HANDLE_SIZE/2;\n          boxes = parentSelectedBoxes;\n        }\n        else\n          continue;\n        theCamera.setObjectTransform(obj.getCoords().fromLocal());\n        Rectangle bounds = theCamera.findScreenBounds(obj.getBounds());\n        if (bounds != null)\n        {\n          boxes.add(new Rectangle(bounds.x, bounds.y, hsize, hsize));\n          boxes.add(new Rectangle(bounds.x+bounds.width-hsize+1, bounds.y, hsize, hsize));\n          boxes.add(new Rectangle(bounds.x, bounds.y+bounds.height-hsize+1, hsize, hsize));\n          boxes.add(new Rectangle(bounds.x+bounds.width-hsize+1, bounds.y+bounds.height-hsize+1, hsize, hsize));\n          boxes.add(new Rectangle(bounds.x+(bounds.width-hsize)/2, bounds.y, hsize, hsize));\n          boxes.add(new Rectangle(bounds.x, bounds.y+(bounds.height-hsize)/2, hsize, hsize));\n          boxes.add(new Rectangle(bounds.x+(bounds.width-hsize)/2, bounds.y+bounds.height-hsize+1, hsize, hsize));\n          boxes.add(new Rectangle(bounds.x+bounds.width-hsize+1, bounds.y+(bounds.height-hsize)/2, hsize, hsize));\n        }\n      }\n      drawBoxes(selectedBoxes, handleColor);\n      drawBoxes(parentSelectedBoxes, highlightColor);\n    }\n    \n    // Finish up.\n    \n    drawBorder();\n    if (showAxes)\n      drawCoordinateAxes();\n  }\n\n  /** Begin dragging a box.  The variable square determines whether the box should be\n      constrained to be square. */\n  \n  public void beginDraggingBox(Point p, boolean square)\n  {\n    draggingBox = true;\n    clickPoint = p;\n    squareBox = square;\n    dragPoint = null;\n  }\n\n  /** When the user presses the mouse, forward events to the current tool as appropriate.\n      If this is an object based tool, allow them to select or deselect objects. */\n\n  protected void mousePressed(WidgetMouseEvent e)\n  {\n    int i, j, k, sel[], minarea;\n    Rectangle bounds = null;\n    ObjectInfo info;\n    Point p;\n\n    requestFocus();\n    sentClick = false;\n    deselect = -1;\n    dragging = true;\n    clickPoint = e.getPoint();\n    clickedObject = null;\n    \n    // Determine which tool is active.\n    \n    if (metaTool != null && e.isMetaDown())\n      activeTool = metaTool;\n    else if (altTool != null && e.isAltDown())\n      activeTool = altTool;\n    else\n      activeTool = currentTool;\n\n    // If the current tool wants all clicks, just forward the event.\n\n    if ((activeTool.whichClicks() & EditingTool.ALL_CLICKS) != 0)\n    {\n      moveToGrid(e);\n      activeTool.mousePressed(e, this);\n      sentClick = true;\n    }\n    boolean allowSelectionChange = activeTool.allowSelectionChanges();\n    boolean wantHandleClicks = ((activeTool.whichClicks() & EditingTool.HANDLE_CLICKS) != 0);\n    if (!allowSelectionChange && !wantHandleClicks)\n      return;\n\n    // See whether the click was on a currently selected object.\n    \n    p = e.getPoint();\n    sel = theScene.getSelection();\n    for (i = 0; i < sel.length; i++)\n    {\n      info = theScene.getObject(sel[i]);\n      theCamera.setObjectTransform(info.getCoords().fromLocal());\n      bounds = theCamera.findScreenBounds(info.getBounds());\n      if (!info.isLocked() && bounds != null && pointInRectangle(p, bounds))\n      {\n        clickedObject = info;\n        break;\n      }\n    }\n    if (i < sel.length)\n    {\n      // The click was on a selected object.  If it was a shift-click, the user may want\n      // to deselect it, so set a flag.\n      \n      if (e.isShiftDown() && allowSelectionChange)\n        deselect = sel[i];\n      \n      // If the current tool wants handle clicks, then check to see whether the click\n      // was on a handle.\n      \n      if ((activeTool.whichClicks() & EditingTool.HANDLE_CLICKS) != 0)\n      {\n        if (p.x <= bounds.x+Scene.HANDLE_SIZE)\n          j = 0;\n        else if (p.x >= bounds.x+(bounds.width-Scene.HANDLE_SIZE)/2 && \n            p.x <= bounds.x+(bounds.width-Scene.HANDLE_SIZE)/2+Scene.HANDLE_SIZE)\n          j = 1;\n        else if (p.x >= bounds.x+bounds.width-Scene.HANDLE_SIZE)\n          j = 2;\n        else j = -1;\n        if (p.y <= bounds.y+Scene.HANDLE_SIZE)\n          k = 0;\n        else if (p.y >= bounds.y+(bounds.height-Scene.HANDLE_SIZE)/2 && \n            p.y <= bounds.y+(bounds.height-Scene.HANDLE_SIZE)/2+Scene.HANDLE_SIZE)\n          k = 1;\n        else if (p.y >= bounds.y+bounds.height-Scene.HANDLE_SIZE)\n          k = 2;\n        else k = -1;\n        if (k == 0)\n        {\n          moveToGrid(e);\n          activeTool.mousePressedOnHandle(e, this, sel[i], j);\n          sentClick = true;\n          return;\n        }\n        if (j == 0 && k == 1)\n        {\n          moveToGrid(e);\n          activeTool.mousePressedOnHandle(e, this, sel[i], 3);\n          sentClick = true;\n          return;\n        }\n        if (j == 2 && k == 1)\n        {\n          moveToGrid(e);\n          activeTool.mousePressedOnHandle(e, this, sel[i], 4);\n          sentClick = true;\n          return;\n        }\n        if (k == 2)\n        {\n          moveToGrid(e);\n          activeTool.mousePressedOnHandle(e, this, sel[i], j+5);\n          sentClick = true;\n          return;\n        }\n      }\n      moveToGrid(e);\n      dragging = false;\n      if ((activeTool.whichClicks() & EditingTool.OBJECT_CLICKS) != 0)\n      {\n        activeTool.mousePressedOnObject(e, this, sel[i]);\n        sentClick = true;\n      }\n      return;\n    }\n    if (!allowSelectionChange)\n      return;\n\n    // The click was not on a selected object.  See whether it was on an unselected object.\n    // If so, select it.  If appropriate, send an event to the current tool.\n    \n    // If the click was on top of multiple objects, the conventional thing to do is to select\n    // the closest one.  I'm trying something different: select the smallest one.  This\n    // should make it easier to select small objects which are surrounded by larger objects.\n    // I may decide to change this, but it seemed like a good idea at the time...\n    \n    j = -1;\n    minarea = Integer.MAX_VALUE;\n    for (i = 0; i < theScene.getNumObjects(); i++)\n    {\n      info = theScene.getObject(i);\n      if (info.isVisible() && !info.isLocked())\n      {\n        theCamera.setObjectTransform(info.getCoords().fromLocal());\n        bounds = theCamera.findScreenBounds(info.getBounds());\n        if (bounds != null && pointInRectangle(p, bounds))\n          if (bounds.width*bounds.height < minarea)\n          {\n            j = i;\n            minarea = bounds.width*bounds.height;\n          }\n      }\n    }\n    if (j > -1)\n    {\n      info = theScene.getObject(j);\n      if (!e.isShiftDown())\n      {\n        if (parentFrame instanceof LayoutWindow)\n          ((LayoutWindow) parentFrame).clearSelection();\n        else\n          theScene.clearSelection();\n      }\n      if (parentFrame instanceof LayoutWindow)\n      {\n        parentFrame.setUndoRecord(new UndoRecord(parentFrame, false, UndoRecord.SET_SCENE_SELECTION, new Object [] {sel}));\n        ((LayoutWindow) parentFrame).addToSelection(j);\n      }\n      else\n        theScene.addToSelection(j);\n      parentFrame.updateMenus();\n      parentFrame.updateImage();\n      moveToGrid(e);\n      if ((activeTool.whichClicks() & EditingTool.OBJECT_CLICKS) != 0 && !e.isShiftDown())\n      {\n        sentClick = true;\n        activeTool.mousePressedOnObject(e, this, j);\n      }\n      clickedObject = info;\n      return;\n    }\n    \n    // The click was not on any object.  Start dragging a selection box.\n\n    if (allowSelectionChange)\n    {\n      moveToGrid(e);\n      draggingSelectionBox = true;\n      beginDraggingBox(p, false);\n    }\n    sentClick = false;\n  }\n\n  /**\n   * Determine whether a Point falls inside a Rectangle.  This method allows a 1 pixel tolerance\n   * to make it easier to click on very small objects.\n   */\n\n  private boolean pointInRectangle(Point p, Rectangle r)\n  {\n    return (r.x-1 <= p.x && r.y-1 <= p.y && r.x+r.width+1 >= p.x && r.y+r.height+1 >= p.y);\n  }\n\n  protected void mouseDragged(WidgetMouseEvent e)\n  {\n    moveToGrid(e);\n    if (!dragging)\n    {\n      Point p = e.getPoint();\n      if (Math.abs(p.x-clickPoint.x) < 2 && Math.abs(p.y-clickPoint.y) < 2)\n        return;\n    }\n    dragging = true;    \n    deselect = -1;\n    if (draggingBox)\n    {\n      // We are dragging a box, so erase and redraw it.\n\n      if (dragPoint != null)\n        drawDraggedShape(new Rectangle(Math.min(clickPoint.x, dragPoint.x), Math.min(clickPoint.y, dragPoint.y), \n            Math.abs(dragPoint.x-clickPoint.x), Math.abs(dragPoint.y-clickPoint.y)));\n      dragPoint = e.getPoint();\n      if (squareBox)\n      {\n        if (Math.abs(dragPoint.x-clickPoint.x) > Math.abs(dragPoint.y-clickPoint.y))\n        {\n          if (dragPoint.y < clickPoint.y)\n            dragPoint.y = clickPoint.y - Math.abs(dragPoint.x-clickPoint.x);\n          else\n            dragPoint.y = clickPoint.y + Math.abs(dragPoint.x-clickPoint.x);\n        }\n        else\n        {\n          if (dragPoint.x < clickPoint.x)\n            dragPoint.x = clickPoint.x - Math.abs(dragPoint.y-clickPoint.y);\n          else\n            dragPoint.x = clickPoint.x + Math.abs(dragPoint.y-clickPoint.y);\n        }\n      }\n      drawDraggedShape(new Rectangle(Math.min(clickPoint.x, dragPoint.x), Math.min(clickPoint.y, dragPoint.y), \n              Math.abs(dragPoint.x-clickPoint.x), Math.abs(dragPoint.y-clickPoint.y)));\n    }\n\n    // Send the event to the current tool, if appropriate.\n\n    if (sentClick)\n      activeTool.mouseDragged(e, this);\n  }\n\n  protected void mouseReleased(WidgetMouseEvent e)\n  {\n    Rectangle r, b;\n    int j, sel[] = theScene.getSelection();\n    ObjectInfo info;\n\n    moveToGrid(e);\n\n    // Send the event to the current tool, if appropriate.\n\n    if (sentClick)\n    {\n      if (!dragging)\n      {\n        Point p = e.getPoint();\n        e.translatePoint(clickPoint.x-p.x, clickPoint.y-p.y);\n      }\n      activeTool.mouseReleased(e, this);\n    }\n\n    // If the user was dragging a selection box, then select anything it intersects.\n    \n    int oldSelection[] = theScene.getSelection();\n    if (draggingSelectionBox)\n    {\n      dragPoint = e.getPoint();\n      r = new Rectangle(Math.min(clickPoint.x, dragPoint.x), Math.min(clickPoint.y, dragPoint.y), \n              Math.abs(dragPoint.x-clickPoint.x), Math.abs(dragPoint.y-clickPoint.y));\n      if (!e.isShiftDown())\n      {\n        if (parentFrame instanceof LayoutWindow)\n          ((LayoutWindow) parentFrame).clearSelection();\n        else\n          theScene.clearSelection();\n        parentFrame.updateMenus();\n      }\n      for (int i = 0; i < theScene.getNumObjects(); i++)\n      {\n        info = theScene.getObject(i);\n        if (info.isVisible() && !info.isLocked())\n        {\n          theCamera.setObjectTransform(info.getCoords().fromLocal());\n          b = theCamera.findScreenBounds(info.getBounds());\n          if (b != null && b.x < r.x+r.width && b.y < r.y+r.height && r.x < b.x+b.width && r.y < b.y+b.height)\n          {\n            if (!e.isShiftDown())\n            {\n              if (parentFrame instanceof LayoutWindow)\n                ((LayoutWindow) parentFrame).addToSelection(i);\n              else\n                theScene.addToSelection(i);\n              parentFrame.updateMenus();\n            }\n            else\n            {\n              for (j = 0; j < sel.length && sel[j] != i; j++);\n              if (j == sel.length)\n              {\n                if (parentFrame instanceof LayoutWindow)\n                  ((LayoutWindow) parentFrame).addToSelection(i);\n                else\n                  theScene.addToSelection(i);\n                parentFrame.updateMenus();\n              }\n            }\n          }\n        }\n      }\n      if (currentTool.hilightSelection())\n        parentFrame.updateImage();\n    }\n    draggingBox = draggingSelectionBox = false;\n\n    // If the user shift-clicked a selected object and released the mouse without dragging,\n    // then deselect the point.\n\n    if (deselect > -1)\n    {\n      if (parentFrame instanceof LayoutWindow)\n        ((LayoutWindow) parentFrame).removeFromSelection(deselect);\n      else\n        theScene.removeFromSelection(deselect);\n      parentFrame.updateMenus();\n      parentFrame.updateImage();\n    }\n    \n    // If the selection changed, set an undo record.\n    \n    int newSelection[] = theScene.getSelection();\n    boolean changed = (oldSelection.length != newSelection.length);\n    for (int i = 0; i < newSelection.length && !changed; i++)\n      changed = (oldSelection[i] != newSelection[i]);\n    if (changed)\n     parentFrame.setUndoRecord(new UndoRecord(parentFrame, false, UndoRecord.SET_SCENE_SELECTION, new Object [] {oldSelection}));\n  }\n  \n  /** Double-clicking on object should bring up its editor. */\n  \n  public void mouseClicked(MouseClickedEvent e)\n  {\n    if (e.getClickCount() == 2 && (activeTool.whichClicks() & EditingTool.OBJECT_CLICKS) != 0 && clickedObject != null && clickedObject.getObject().isEditable())\n    {\n      final Object3D obj = clickedObject.getObject();\n      parentFrame.setUndoRecord(new UndoRecord(parentFrame, false, UndoRecord.COPY_OBJECT, new Object [] {obj, obj.duplicate()}));\n      obj.edit(parentFrame, clickedObject,  new Runnable() {\n\t  public void run()\n\t  {\n\t    theScene.objectModified(obj);\n\t    parentFrame.updateImage();\n\t    parentFrame.updateMenus();\n\t  }\n\t} );\n    }\n  }\n\n  protected void processMouseScrolled(MouseScrolledEvent ev)\n  {\n    if (isPerspective() && boundCamera != null)\n    {\n      // We are moving an actual camera in the scene, so we need to set an undo record, move\n      // its children, and repaint all views in the window.\n\n      UndoRecord undo = new UndoRecord(getEditingWindow(), false);\n      super.processMouseScrolled(ev);\n      moveChildren(boundCamera, theCamera.getCameraCoordinates().fromLocal().times(boundCamera.getCoords().toLocal()), undo);\n      getEditingWindow().setUndoRecord(undo);\n      getEditingWindow().updateImage();\n    }\n    else\n      super.processMouseScrolled(ev);\n  }\n\n  /** This is called recursively to move any children of a bound camera. */\n\n  private void moveChildren(ObjectInfo obj, Mat4 transform, UndoRecord undo)\n  {\n    CoordinateSystem coords = obj.getCoords();\n    CoordinateSystem oldCoords = coords.duplicate();\n    coords.transformCoordinates(transform);\n    undo.addCommand(UndoRecord.COPY_COORDS, new Object [] {coords, oldCoords});\n    for (int i = 0; i < obj.getChildren().length; i++)\n      moveChildren(obj.getChildren()[i], transform, undo);\n  }\n}", "human_rating": 2.4550214908, "metadata": {"project": "aoi", "class": "artofillusion.SceneViewer", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/SceneViewer.java", "label_probabilities": {"readability": [3.16977e-05, 0.496665, 0.461597, 0.0417057], "understandability": [1.37164e-05, 0.00131198, 0.551269, 0.447405], "complexity": [0.0247613, 0.89237, 0.0828507, 1.78459e-05], "modularization": [0.249701, 0.723729, 0.0265661, 4.05562e-06], "overall": [0.0, 0.000145129, 0.144014, 0.855841]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.script.ScriptedObjectController", "source": "/* Copyright (C) 2002-2006 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.script;\n\nimport artofillusion.*;\nimport artofillusion.animation.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\n\n/** This class mediates interactions between an ObjectScript and the rest of\n    the program. */\n\npublic class ScriptedObjectController\n{\n  private ObjectInfo info;\n  private ScriptedObject object;\n  private ScriptedObjectEnumeration enumeration;\n  private Scene scene;\n  private boolean preview;\n  \n  /** Create a new ScriptedObjectController and execute its script. */\n  \n  ScriptedObjectController(ObjectInfo obj, ScriptedObjectEnumeration objectEnum, boolean interactive, Scene sc)\n  {\n    info = obj;\n    Object3D innerObject = obj.getObject();\n    while (innerObject instanceof ObjectWrapper)\n      innerObject = ((ObjectWrapper) innerObject).getWrappedObject();\n    object = (ScriptedObject) innerObject;\n    enumeration = objectEnum;\n    preview = interactive;\n    scene = sc;\n    object.setUsesTime(false);\n    object.setUsesCoords(false);\n    new Thread() {\n      public void run()\n      {\n        try\n          {\n            ObjectScript script = object.getObjectScript();\n            script.execute(ScriptedObjectController.this);\n            enumeration.executionComplete();\n          }\n        catch (Exception ex)\n          {\n            enumeration.executionComplete();\n            ScriptRunner.displayError(object.getLanguage(), ex);\n          }\n      }\n    }.start();\n  }\n  \n  /** Get the coordinate system which defines the scripted object's position in the scene. */\n  \n  public final CoordinateSystem getCoordinates()\n  {\n    object.setUsesCoords(true);\n    return info.getCoords();\n  }\n  \n  /** Get the current time. */\n  \n  public final double getTime()\n  {\n    object.setUsesTime(true);\n    return scene.getTime();\n  }\n  \n  /** Get the scene this object is part of. */\n  \n  public final Scene getScene()\n  {\n    object.setUsesTime(true);\n    return scene;\n  }\n  \n  /** Determine whether the script is currently being executed to create an interactive preview. */\n  \n  public final boolean isPreview()\n  {\n    return preview;\n  }\n  \n  /** Get the value of a parameter. */\n  \n  public final double getParameter(String name) throws IllegalArgumentException\n  {\n    for (int i = object.getNumParameters()-1; i >= 0; i--)\n      if (object.getParameterName(i).equals(name))\n        return object.getParameterValue(i);\n    throw new IllegalArgumentException(\"Unknown parameter '\"+name+\"'\");\n  }\n\n  /** Add an object to the scripted object. */\n  \n  public final void addObject(ObjectInfo info)\n  {\n    info.tracks = new Track [0];\n    if (info.getObject().canSetTexture() && info.getObject().getTextureMapping() == null)\n      info.setTexture(object.getTexture(), object.getTextureMapping());\n    if (info.getObject().canSetMaterial() && info.getObject().getMaterialMapping() == null)\n      info.setMaterial(object.getMaterial(), object.getMaterialMapping());\n    enumeration.addObject(info);\n  }\n  \n  /** Add an object to the scripted object. */\n  \n  public final void addObject(Object3D obj, CoordinateSystem coords)\n  {\n    addObject(new ObjectInfo(obj, coords, \"\"));\n  }\n}", "human_rating": 3.949780154780024, "metadata": {"project": "aoi", "class": "artofillusion.script.ScriptedObjectController", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/script/ScriptedObjectController.java", "label_probabilities": {"readability": [0.949787, 0.0502067, 6.02739e-06, 2.37972e-14], "understandability": [0.302956, 0.680806, 0.0162381, 1.02787e-10], "complexity": [3.63972e-08, 0.177435, 0.818645, 0.00391943], "modularization": [3.2401e-14, 0.012419, 0.353204, 0.634377], "overall": [0.029375, 0.97043, 0.000194567, 5.2e-19]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.SplineMeshEditorWindow", "source": "/* Copyright (C) 1999-2012 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.animation.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\n\nimport java.awt.*;\n\n/** The SplineMeshEditorWindow class represents the window for editing SplineMesh objects. */\n\npublic class SplineMeshEditorWindow extends MeshEditorWindow implements EditingWindow\n{\n  private ToolPalette modes;\n  private BMenu editMenu, meshMenu, skeletonMenu;\n  private BMenuItem editMenuItem[], meshMenuItem[], skeletonMenuItem[];\n  private BCheckBoxMenuItem smoothItem[], closedItem[];\n  private Runnable onClose;\n  private int selectionDistance[], maxDistance, selectMode, lastSelectedJoint;\n  private boolean topology;\n  boolean selected[];\n  private TextureParameter jointWeightParam;\n\n  public SplineMeshEditorWindow(EditingWindow parent, String title, ObjectInfo obj, Runnable onClose, boolean allowTopology)\n  {\n    super(parent, title, obj);\n    this.onClose = onClose;\n    topology = allowTopology;\n\n    FormContainer content = new FormContainer(new double [] {0, 1}, new double [] {1, 0, 0});\n    setContent(content);\n    content.setDefaultLayout(new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.BOTH, null, null));\n    content.add(helpText = new BLabel(), 0, 1, 2, 1);\n    content.add(viewsContainer, 1, 0);\n    RowContainer buttons = new RowContainer();\n    buttons.add(Translate.button(\"ok\", this, \"doOk\"));\n    buttons.add(Translate.button(\"cancel\", this, \"doCancel\"));\n    content.add(buttons, 0, 2, 2, 1, new LayoutInfo());\n    FormContainer toolsContainer = new FormContainer(new double [] {1}, new double [] {1, 0});\n    toolsContainer.setDefaultLayout(new LayoutInfo(LayoutInfo.NORTH, LayoutInfo.BOTH));\n    content.add(toolsContainer, 0, 0);\n    toolsContainer.add(tools = new ToolPalette(1, 9), 0, 0);\n    EditingTool metaTool, altTool, compoundTool;\n    tools.addTool(defaultTool = new ReshapeMeshTool(this, this));\n    tools.addTool(new ScaleMeshTool(this, this));\n    tools.addTool(new RotateMeshTool(this, this, false));\n    tools.addTool(new SkewMeshTool(this, this));\n    tools.addTool(new TaperMeshTool(this, this));\n    tools.addTool(new ThickenMeshTool(this, this));\n    tools.addTool(compoundTool = new MoveScaleRotateMeshTool(this, this));\n    if (ArtOfIllusion.getPreferences().getUseCompoundMeshTool())\n      defaultTool = compoundTool;\n    tools.addTool(new SkeletonTool(this, true));\n    tools.addTool(metaTool = new MoveViewTool(this));\n    tools.addTool(altTool = new RotateViewTool(this));\n    tools.setDefaultTool(defaultTool);\n    tools.selectTool(defaultTool);\n    for (int i = 0; i < theView.length; i++)\n    {\n      MeshViewer view = (MeshViewer) theView[i];\n      view.setMetaTool(metaTool);\n      view.setAltTool(altTool);\n      view.setScene(parent.getScene(), obj);\n      view.setFreehandSelection(lastFreehand);\n    }\n    toolsContainer.add(modes = new ToolPalette(1, 2), 0, 1);\n    modes.addTool(new GenericTool(this, \"point\", Translate.text(\"pointSelectionModeTool.tipText\")));\n    modes.addTool(new GenericTool(this, \"curve\", Translate.text(\"curveSelectionModeTool.tipText\")));\n    setSelectionMode(modes.getSelection());\n    createEditMenu();\n    createMeshMenu((SplineMesh) obj.getObject());\n    createSkeletonMenu((SplineMesh) obj.getObject());\n    createViewMenu();\n    recursivelyAddListeners(this);\n    UIUtilities.applyDefaultFont(content);\n    UIUtilities.applyDefaultBackground(content);\n    Rectangle screenBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();\n    Dimension windowDim = new Dimension((screenBounds.width*3)/4, (screenBounds.height*3)/4);\n    setBounds(new Rectangle((screenBounds.width-windowDim.width)/2, (screenBounds.height-windowDim.height)/2, windowDim.width, windowDim.height));\n    tools.requestFocus();\n    selected = new boolean [((Mesh) objInfo.getObject()).getVertices().length];\n    findSelectionDistance();\n    addExtraParameters();\n    updateMenus();\n  }\n\n  void createEditMenu()\n  {\n    editMenu = Translate.menu(\"edit\");\n    menubar.add(editMenu);\n    editMenuItem = new BMenuItem [3];\n    editMenu.add(undoItem = Translate.menuItem(\"undo\", this, \"undoCommand\"));\n    editMenu.add(redoItem = Translate.menuItem(\"redo\", this, \"redoCommand\"));\n    editMenu.add(Translate.menuItem(\"selectAll\", this, \"selectAllCommand\"));\n    editMenu.add(editMenuItem[0] = Translate.menuItem(\"extendSelection\", this, \"extendSelectionCommand\"));\n    editMenu.add(editMenuItem[1] = Translate.menuItem(\"invertSelection\", this, \"invertSelectionCommand\"));\n    editMenu.add(editMenuItem[2] = Translate.checkboxMenuItem(\"freehandSelection\", this, \"freehandModeChanged\", false));\n    editMenu.addSeparator();\n    editMenu.add(Translate.menuItem(\"meshTension\", this, \"setTensionCommand\"));\n  }\n\n  void createMeshMenu(SplineMesh obj)\n  {\n    BMenu smoothMenu, closedMenu;\n    \n    meshMenu = Translate.menu(\"mesh\");\n    menubar.add(meshMenu);\n    meshMenuItem = new BMenuItem [8];\n    meshMenuItem[0] = Translate.menuItem(\"deleteCurves\", this, \"deleteCommand\");\n    if (topology)\n      meshMenu.add(meshMenuItem[0]);\n    meshMenuItem[1] = Translate.menuItem(\"subdivide\", this, \"subdivideCommand\");\n    if (topology)\n      meshMenu.add(meshMenuItem[1]);\n    meshMenu.add(meshMenuItem[2] = Translate.menuItem(\"editPoints\", this, \"setPointsCommand\"));\n    meshMenu.add(meshMenuItem[3] = Translate.menuItem(\"transformPoints\", this, \"transformPointsCommand\"));\n    meshMenu.add(meshMenuItem[4] = Translate.menuItem(\"randomize\", this, \"randomizeCommand\"));\n    meshMenu.add(meshMenuItem[5] = Translate.menuItem(\"parameters\", this, \"setParametersCommand\"));\n    meshMenu.add(Translate.menuItem(\"centerMesh\", this, \"centerCommand\"));\n    meshMenu.add(meshMenuItem[6] = Translate.menuItem(\"extractCurve\", this, \"extractCurveCommand\"));\n    meshMenu.addSeparator();\n    meshMenu.add(meshMenuItem[7] = Translate.menuItem(\"smoothness\", this, \"setSmoothnessCommand\"));\n    meshMenu.add(smoothMenu = Translate.menu(\"smoothingMethod\"));\n    smoothItem = new BCheckBoxMenuItem [2];\n    smoothMenu.add(smoothItem[0] = Translate.checkboxMenuItem(\"interpolating\", this, \"smoothingChanged\", obj.getSmoothingMethod() == TriangleMesh.INTERPOLATING));\n    smoothMenu.add(smoothItem[1] = Translate.checkboxMenuItem(\"approximating\", this, \"smoothingChanged\", obj.getSmoothingMethod() == TriangleMesh.APPROXIMATING));\n    closedMenu = Translate.menu(\"closed\");\n    if (topology)\n      meshMenu.add(closedMenu);\n    closedItem = new BCheckBoxMenuItem [4];\n    closedMenu.add(closedItem[0] = Translate.checkboxMenuItem(\"udirection\", this, \"closedTypeChanged\", (obj.isUClosed() && !obj.isVClosed())));\n    closedMenu.add(closedItem[1] = Translate.checkboxMenuItem(\"vdirection\", this, \"closedTypeChanged\", (!obj.isUClosed() && obj.isVClosed())));\n    closedMenu.add(closedItem[2] = Translate.checkboxMenuItem(\"both\", this, \"closedTypeChanged\", (obj.isUClosed() && obj.isVClosed())));\n    closedMenu.add(closedItem[3] = Translate.checkboxMenuItem(\"neither\", this, \"closedTypeChanged\", (!obj.isUClosed() && !obj.isVClosed())));\n    if (topology)\n      meshMenu.add(Translate.menuItem(\"invertNormals\", this, \"reverseNormalsCommand\"));\n  }\n\n  void createSkeletonMenu(SplineMesh obj)\n  {\n    skeletonMenu = Translate.menu(\"skeleton\");\n    menubar.add(skeletonMenu);\n    skeletonMenuItem = new BMenuItem [7];\n    skeletonMenu.add(skeletonMenuItem[0] = Translate.menuItem(\"editBone\", this, \"editJointCommand\"));\n    skeletonMenu.add(skeletonMenuItem[1] = Translate.menuItem(\"deleteBone\", this, \"deleteJointCommand\"));\n    skeletonMenu.add(skeletonMenuItem[2] = Translate.menuItem(\"setParentBone\", this, \"setJointParentCommand\"));\n    skeletonMenu.add(skeletonMenuItem[3] = Translate.menuItem(\"importSkeleton\", this, \"importSkeletonCommand\"));\n    skeletonMenu.addSeparator();\n    skeletonMenu.add(skeletonMenuItem[4] = Translate.menuItem(\"bindSkeleton\", this, \"bindSkeletonCommand\"));\n    skeletonMenu.add(skeletonMenuItem[5] = Translate.menuItem(\"unbindSkeleton\", this, \"unbindSkeletonCommand\"));\n    skeletonMenu.add(skeletonMenuItem[6] = Translate.checkboxMenuItem(\"detachSkeleton\", this, \"skeletonDetachedChanged\", false));\n  }\n  \n  /** Get the object being edited in this window. */\n  \n  public ObjectInfo getObject()\n  {\n    return objInfo;\n  }\n  \n  /** Set the object being edited in this window. */\n  \n  public void setObject(Object3D obj)\n  {\n    objInfo.setObject(obj);\n    objInfo.clearCachedMeshes();\n  }\n  \n  /** When the selection mode changes, do our best to convert the old selection to the new mode. */\n  \n  public void setSelectionMode(int mode)\n  {\n    SplineMesh mesh = (SplineMesh) getObject().getObject();\n    MeshVertex vert[] = mesh.getVertices();\n    int i, j, usize = mesh.getUSize(), vsize = mesh.getVSize();\n    boolean newSel[];\n    \n    if (mode == selectMode)\n      return;\n    if (mode == POINT_MODE)\n    {\n      newSel = new boolean [vert.length];\n      for (i = 0; i < usize; i++)\n        if (selected[i])\n          for (j = 0; j < vsize; j++)\n            newSel[i+j*usize] = true;\n      for (i = 0; i < vsize; i++)\n        if (selected[i+usize])\n          for (j = 0; j < usize; j++)\n            newSel[j+i*usize] = true;\n    }\n    else if (mode == EDGE_MODE)\n    {\n      newSel = new boolean [usize+vsize];\n      for (i = 0; i < newSel.length; newSel[i++] = true);\n      for (i = 0; i < usize; i++)\n        for (j = 0; j < vsize; j++)\n          if (!selected[i+j*usize])\n            newSel[i] = newSel[j+usize] = false;\n    }\n    else\n      return;\n    selectMode = mode;\n    setSelection(newSel);\n    if (modes.getSelection() != mode)\n      modes.selectTool(modes.getTool(mode));\n  }\n  \n  public int getSelectionMode()\n  {\n    return selectMode;\n  }\n  \n  /** Get an array of flags telling which parts of the mesh are currently selected.  Depending\n      on the current selection mode, these flags may correspond to vertices or curves. */\n  \n  public boolean[] getSelection()\n  {\n    return selected;\n  }\n  \n  public void setSelection(boolean sel[])\n  {\n    selected = sel;\n    findSelectionDistance();\n    updateMenus();\n    for (ViewerCanvas view : theView)\n      view.repaint();\n    repaint();\n  }\n\n  public int[] getSelectionDistance()\n  {\n    if (maxDistance != getTensionDistance())\n      findSelectionDistance();\n    return selectionDistance;\n  }\n\n  /** Calculate the distance (in edges) between each vertex and the nearest selected vertex. */\n\n  void findSelectionDistance()\n  {\n    SplineMesh mesh = (SplineMesh) getObject().getObject();\n    int i, j, k, usize = mesh.getUSize(), vsize = mesh.getVSize();\n    boolean uclosed = mesh.isUClosed(), vclosed = mesh.isVClosed();\n    int dist[] = new int [mesh.getVertices().length];\n    \n    maxDistance = getTensionDistance();\n    \n    // First, set each distance to 0 or -1, depending on whether that vertex is part of the\n    // current selection.\n    \n    if (selectMode == POINT_MODE)\n      for (i = 0; i < dist.length; i++)\n        dist[i] = selected[i] ? 0 : -1;\n    else\n      {\n        for (i = 0; i < usize; i++)\n          for (j = 0; j < vsize; j++)\n            dist[i+j*usize] = (selected[i] || selected[j+usize]) ? 0 : -1;\n      }\n\n    // Now extend this outward up to maxDistance.\n\n    for (i = 0; i < maxDistance; i++)\n      for (j = 0; j < usize; j++)\n        for (k = 0; k < vsize; k++)\n          if (dist[j+k*usize] == -1)\n            {\n              if (j == 0)\n                {\n                  if (uclosed && dist[usize-1+k*usize] == i)\n                    dist[j+k*usize] = i+1;\n                }\n              else\n                if (dist[j-1+k*usize] == i)\n                  dist[j+k*usize] = i+1;\n              if (j == usize-1)\n                {\n                  if (uclosed && dist[k*usize] == i)\n                    dist[j+k*usize] = i+1;\n                }\n              else\n                if (dist[j+1+k*usize] == i)\n                  dist[j+k*usize] = i+1;\n              if (k == 0)\n                {\n                  if (vclosed && dist[j+(vsize-1)*usize] == i)\n                    dist[j+k*usize] = i+1;\n                }\n              else\n                if (dist[j+(k-1)*usize] == i)\n                  dist[j+k*usize] = i+1;\n              if (k == vsize-1)\n                {\n                  if (vclosed && dist[j] == i)\n                    dist[j+k*usize] = i+1;\n                }\n              else\n                if (dist[j+(k+1)*usize] == i)\n                  dist[j+k*usize] = i+1;\n            }\n    selectionDistance = dist;\n  }\n  \n  public void setMesh(Mesh mesh)\n  {\n    SplineMesh obj = (SplineMesh) mesh;\n\n    setObject(obj);\n    for (int i = 0; i < theView.length; i++)\n    {\n      if (selectMode == POINT_MODE && selected.length != obj.getVertices().length)\n        selected = new boolean [obj.getVertices().length];\n      if (selectMode == EDGE_MODE && selected.length != obj.getUSize()+obj.getVSize())\n        selected = new boolean [obj.getUSize()+obj.getVSize()];\n      ((SplineMeshViewer) theView[i]).visible = new boolean [obj.getVertices().length];\n    }\n    updateJointWeightParam();\n    findSelectionDistance();\n    currentTool.getWindow().updateMenus();\n  }\n\n  /* EditingWindow methods. */\n\n  public void setTool(EditingTool tool)\n  {\n    if (tool instanceof GenericTool)\n    {\n      if (selectMode == modes.getSelection())\n        return;\n      if (undoItem != null)\n        setUndoRecord(new UndoRecord(this, false, UndoRecord.SET_MESH_SELECTION, new Object [] {this, new Integer(selectMode), selected}));\n      setSelectionMode(modes.getSelection());\n      theView[currentView].getCurrentTool().activate();\n    }\n    else\n    {\n      for (int i = 0; i < theView.length; i++)\n        theView[i].setTool(tool);\n      currentTool = tool;\n    }\n  }\n\n  public void updateImage()\n  {\n    if (lastSelectedJoint != ((MeshViewer) theView[currentView]).getSelectedJoint())\n      updateJointWeightParam();\n    super.updateImage();\n  }\n\n  public void updateMenus()\n  {\n    super.updateMenus();\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    boolean curvemode = (selectMode == EDGE_MODE);\n    MeshViewer view = (MeshViewer) theView[currentView];\n    int count = 0;\n    \n    for (int i = 0; i < selected.length; i++)\n      if (selected[i])\n        count++;\n    if (count > 0)\n    {\n      editMenuItem[0].setEnabled(true);\n      meshMenuItem[0].setEnabled(curvemode);\n      meshMenuItem[1].setEnabled(curvemode);\n      meshMenuItem[2].setEnabled(true);\n      meshMenuItem[3].setEnabled(true);\n      meshMenuItem[4].setEnabled(true);\n      meshMenuItem[5].setEnabled(true);\n      meshMenuItem[6].setEnabled(curvemode && count == 1);\n      meshMenuItem[7].setEnabled(curvemode);\n    }\n    else\n    {\n      editMenuItem[0].setEnabled(false);\n      for (int i = 0; i < meshMenuItem.length; i++)\n        meshMenuItem[i].setEnabled(false);\n    }\n    Skeleton s = theMesh.getSkeleton();\n    Joint selJoint = s.getJoint(view.getSelectedJoint());\n    skeletonMenuItem[0].setEnabled(selJoint != null);\n    skeletonMenuItem[1].setEnabled(selJoint != null && selJoint.children.length == 0);\n    skeletonMenuItem[2].setEnabled(selJoint != null);\n    skeletonMenuItem[4].setEnabled(count > 0);\n    skeletonMenuItem[5].setEnabled(selJoint != null);\n  }\n\n  /** Add an extra texture parameter to the mesh which will be used for keeping track of\n      joint weights. */\n\n  private void addExtraParameters()\n  {\n    if (jointWeightParam != null)\n      return;\n    jointWeightParam = new TextureParameter(this, \"Joint Weight\", 0.0, 1.0, 0.0);\n    SplineMesh mesh = (SplineMesh) getObject().getObject();\n    TextureParameter params[] = mesh.getParameters();\n    TextureParameter newparams[] = new TextureParameter [params.length+1];\n    ParameterValue values[] = mesh.getParameterValues();\n    ParameterValue newvalues[] = new ParameterValue [values.length+1];\n    for (int i = 0; i < params.length; i++)\n    {\n      newparams[i] = params[i];\n      newvalues[i] = values[i];\n    }\n    newparams[params.length] = jointWeightParam;\n    newvalues[values.length] = new VertexParameterValue(mesh, jointWeightParam);\n    mesh.setParameters(newparams);\n    mesh.setParameterValues(newvalues);\n    getObject().clearCachedMeshes();\n    updateJointWeightParam();\n  }\n\n  /** Remove the extra texture parameter from the mesh which was used for keeping track of\n      joint weights. */\n\n  public void removeExtraParameters()\n  {\n    if (jointWeightParam == null)\n      return;\n    jointWeightParam = null;\n    SplineMesh mesh = (SplineMesh) getObject().getObject();\n    TextureParameter params[] = mesh.getParameters();\n    TextureParameter newparams[] = new TextureParameter [params.length-1];\n    ParameterValue values[] = mesh.getParameterValues();\n    ParameterValue newvalues[] = new ParameterValue [values.length-1];\n    for (int i = 0; i < newparams.length; i++)\n    {\n      newparams[i] = params[i];\n      newvalues[i] = values[i];\n    }\n    mesh.setParameters(newparams);\n    mesh.setParameterValues(newvalues);\n    getObject().clearCachedMeshes();\n  }\n\n  /** Update the parameter which records weights for the currently selected joint. */\n\n  private void updateJointWeightParam()\n  {\n    MeshVertex vert[] = ((SplineMesh) getObject().getObject()).getVertices();\n    double jointWeight[] = new double [vert.length];\n    int selJointId = ((MeshViewer) theView[currentView]).getSelectedJoint();\n    Joint selJoint = getObject().getSkeleton().getJoint(selJointId);\n    for (int i = 0; i < jointWeight.length; i++)\n    {\n      Joint vertJoint = getObject().getSkeleton().getJoint(vert[i].ikJoint);\n      if (selJoint == null)\n        jointWeight[i] = 0.0;\n      else if (vert[i].ikJoint == selJointId)\n        jointWeight[i] = (selJoint.parent == null ? 1.0 : vert[i].ikWeight);\n      else if (vertJoint != null && vertJoint.parent == selJoint)\n        jointWeight[i] = 1.0-vert[i].ikWeight;\n      else\n        jointWeight[i] = 0.0;\n    }\n    VertexParameterValue value = (VertexParameterValue) getObject().getObject().getParameterValue(jointWeightParam);\n    value.setValue(jointWeight);\n    getObject().getObject().setParameterValues(getObject().getObject().getParameterValues());\n    lastSelectedJoint = selJointId;\n    objInfo.clearCachedMeshes();\n  }\n\n  /** Get the extra texture parameter which was added to the mesh to keep track of\n      joint weighting. */\n\n  public TextureParameter getJointWeightParam()\n  {\n    return jointWeightParam;\n  }\n\n  protected void doOk()\n  {\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    if (((SplineMesh) oldMesh).getMaterial() != null)\n    {\n      if (!theMesh.isClosed())\n      {\n        String options[] = new String [] {Translate.text(\"button.ok\"), Translate.text(\"button.cancel\")};\n        BStandardDialog dlg = new BStandardDialog(\"\", UIUtilities.breakString(Translate.text(\"surfaceNoLongerClosed\")), BStandardDialog.WARNING);\n        int choice = dlg.showOptionDialog(this, options, options[0]);\n        if (choice == 1)\n          return;\n        theMesh.setMaterial(null, null);\n      }\n      else\n        theMesh.setMaterial(((SplineMesh) oldMesh).getMaterial(), ((SplineMesh) oldMesh).getMaterialMapping());\n    }\n    removeExtraParameters();\n    oldMesh.copyObject(theMesh);\n    oldMesh = null;\n    dispose();\n    if (onClose != null)\n      onClose.run();\n  }\n  \n  protected void doCancel()\n  {\n    oldMesh = null;\n    dispose();\n  }\n\n  private void freehandModeChanged()\n  {\n    setFreehand((((BCheckBoxMenuItem) editMenuItem[2]).getState()));\n  }\n  \n  private void smoothingChanged(CommandEvent ev)\n  {\n    Object source = ev.getWidget();\n    for (int i = 0; i < smoothItem.length; i++)\n      if (source == smoothItem[i])\n        setSmoothingMethod(i+2);\n  }\n  \n  private void closedTypeChanged(CommandEvent ev)\n  {\n    Object source = ev.getWidget();\n    for (int i = 0; i < closedItem.length; i++)\n      if (source == closedItem[i])\n        setClosed(i);\n  }\n  \n  private void skeletonDetachedChanged()\n  {\n    for (int i = 0; i < theView.length; i++)\n      ((SplineMeshViewer) theView[i]).setSkeletonDetached(((BCheckBoxMenuItem) skeletonMenuItem[6]).getState());\n  }\n\n  /** This is overridden to update jointWeightParam after weights are changed. */\n\n  @Override\n  public void bindSkeletonCommand()\n  {\n    super.bindSkeletonCommand();\n    updateJointWeightParam();\n    updateImage();\n  }\n\n  /** This is overridden to update jointWeightParam after weights are changed. */\n\n  @Override\n  public void unbindSkeletonCommand()\n  {\n    super.unbindSkeletonCommand();\n    updateJointWeightParam();\n    updateImage();\n  }\n\n  /** This is overridden to update jointWeightParam after weights are changed. */\n\n  @Override\n  public void setPointsCommand()\n  {\n    super.setPointsCommand();\n    updateJointWeightParam();\n    updateImage();\n  }\n\n  /** Select the entire mesh. */\n  \n  public void selectAllCommand()\n  {\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.SET_MESH_SELECTION, new Object [] {this, new Integer(selectMode), selected.clone()}));\n    for (int i = 0; i < selected.length; i++)\n      selected[i] = true;\n    setSelection(selected);\n  }\n\n  /** Extend the selection outward by one edge. */\n\n  public void extendSelectionCommand()\n  {\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.SET_MESH_SELECTION, new Object [] {this, new Integer(selectMode), selected.clone()}));\n    if (selectMode == POINT_MODE)\n    {\n      int oldDist = tensionDistance;\n      tensionDistance = 1;\n      int dist[] = getSelectionDistance();\n      boolean selected[] = new boolean [dist.length];\n      tensionDistance = oldDist;\n      for (int i = 0; i < dist.length; i++)\n        selected[i] = (dist[i] == 0 || dist[i] == 1);\n      setSelection(selected);\n    }\n    else\n    {\n      boolean oldSelection[] = selected;\n      boolean newSelection[] = new boolean [oldSelection.length];\n      int usize = theMesh.getUSize(), vsize = theMesh.getVSize();\n      for (int i = 0; i < usize-1; i++)\n        if (oldSelection[i] || oldSelection[i+1])\n          newSelection[i] = newSelection[i+1] = true;\n      if (theMesh.isUClosed() && (oldSelection[0] || oldSelection[usize-1]))\n        newSelection[0] = newSelection[usize-1] = true;\n      for (int i = 0; i < vsize-1; i++)\n        if (oldSelection[usize+i] || oldSelection[usize+i+1])\n          newSelection[usize+i] = newSelection[usize+i+1] = true;\n      if (theMesh.isVClosed() && (oldSelection[usize] || oldSelection[usize+vsize-1]))\n        newSelection[usize] = newSelection[usize+vsize-1] = true;\n      setSelection(newSelection);\n    }\n  }\n  \n  /** Invert the current selection. */\n  \n  public void invertSelectionCommand()\n  {\n    boolean newSel[] = new boolean [selected.length];\n    for (int i = 0; i < newSel.length; i++)\n      newSel[i] = !selected[i];\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.SET_MESH_SELECTION, new Object [] {this, new Integer(selectMode), selected}));\n    setSelection(newSel);\n  }\n\n  /** Delete the current selection. */\n  \n  public void deleteCommand()\n  {\n    if (!topology)\n      return;\n    int i, j, k, m, unum = 0, vnum = 0;\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    float us[] = theMesh.getUSmoothness(), vs[] = theMesh.getVSmoothness(), newus[], newvs[];\n    MeshVertex vt[] = theMesh.getVertices(), v[][];\n    int usize = theMesh.getUSize(), vsize = theMesh.getVSize();\n\n    if (selectMode != EDGE_MODE)\n      return;\n    for (i = 0; i < usize; i++)\n      if (selected[i])\n        unum++;\n    for (i = 0; i < vsize; i++)\n      if (selected[i+usize])\n        vnum++;\n    if (unum == 0 && vnum == 0)\n      return;\n    if (usize-unum < 2 || vsize-vnum < 2)\n    {\n      new BStandardDialog(\"\", Translate.text(\"curveNeeds2Points\"), BStandardDialog.INFORMATION).showMessageDialog(this);\n      return;\n    }\n    if ((theMesh.isUClosed() && usize-unum < 3) || (theMesh.isVClosed() && vsize-vnum < 3))\n    {\n      new BStandardDialog(\"\", Translate.text(\"curveNeeds3Points\"), BStandardDialog.INFORMATION).showMessageDialog(this);\n      return;\n    }\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theMesh, theMesh.duplicate()}));\n    v = new MeshVertex [usize-unum][vsize-vnum];\n    newus = new float [usize-unum];\n    newvs = new float [vsize-vnum];\n    for (i = 0, j = 0; i < usize; i++)\n    {\n      if (!selected[i])\n      {\n        for (k = 0, m = 0; k < vsize; k++)\n        {\n          if (!selected[k+usize])\n          {\n            newvs[m] = vs[k];\n            v[j][m++] = vt[i+k*usize];\n          }\n        }\n        newus[j++] = us[i];\n      }\n    }\n    theMesh.setShape(v, newus, newvs);\n    setMesh(theMesh);\n    updateImage();\n  }\n  \n  void subdivideCommand()\n  {\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    MeshVertex vt[] = theMesh.getVertices();\n    float us[] = theMesh.getUSmoothness(), vs[] = theMesh.getVSmoothness(), newus[], newvs[];\n    boolean newsel[], splitu[], splitv[];\n    MeshVertex v[][], newv[][];\n    double param[][][], newparam[][][];\n    int i, j, usplitcount = 0, vsplitcount = 0;\n    int usize = theMesh.getUSize(), vsize = theMesh.getVSize();\n    int numParam = (theMesh.getParameters() == null ? 0 : theMesh.getParameters().length);\n    \n    if (selectMode != EDGE_MODE)\n      return;\n    for (i = 0; !selected[i] && i < selected.length; i++);\n    if (i == selected.length)\n      return;\n\n    // Determine which parts need to be subdivided.\n    \n    if (theMesh.isUClosed())\n      splitu = new boolean [usize];\n    else\n      splitu = new boolean [usize-1];\n    for (i = 0; i < splitu.length; i++)\n      if (selected[i] && selected[(i+1)%usize])\n      {\n        splitu[i] = true;\n        usplitcount++;\n      }\n    if (theMesh.isVClosed())\n      splitv = new boolean [vsize];\n    else\n      splitv = new boolean [vsize-1];\n    for (i = 0; i < splitv.length; i++)\n      if (selected[i+usize] && selected[(i+1)%vsize+usize])\n      {\n        splitv[i] = true;\n        vsplitcount++;\n      }\n    newus = new float [usize+usplitcount];\n    newvs = new float [vsize+vsplitcount];\n    newsel = new boolean [selected.length+usplitcount+vsplitcount];\n    \n    // Do the subdivision along the u direction.\n\n    v = new MeshVertex [vsize][usize];\n    for (i = 0; i < usize; i++)\n      for (j = 0; j < vsize; j++)\n        v[j][i] = vt[i+j*usize];\n    newv = new MeshVertex [vsize][usize+usplitcount];\n    param = new double [vsize][usize][numParam];\n    for (int k = 0; k < numParam; k++)\n      if (theMesh.getParameterValues()[k] instanceof VertexParameterValue)\n      {\n        double val[] = ((VertexParameterValue) theMesh.getParameterValues()[k]).getValue();\n        for (i = 0; i < usize; i++)\n          for (j = 0; j < vsize; j++)\n            param[j][i][k] = val[i+usize*j];\n      }\n    newparam = new double [vsize][usize+usplitcount][numParam];\n    splitOneAxis(v, newv, us, newus, splitu, param, newparam, theMesh.isUClosed());\n\n    // Do the subdivision along the v direction.\n\n    v = new MeshVertex [usize+usplitcount][vsize];\n    for (i = 0; i < v.length; i++)\n      for (j = 0; j < v[i].length; j++)\n        v[i][j] = newv[j][i];\n    newv = new MeshVertex [usize+usplitcount][vsize+vsplitcount];\n    param = new double [usize+usplitcount][vsize][numParam];\n    for (i = 0; i < param.length; i++)\n      for (j = 0; j < param[i].length; j++)\n        for (int k = 0; k < param[i][j].length; k++)\n          param[i][j][k] = newparam[j][i][k];\n    newparam = new double [usize+usplitcount][vsize+vsplitcount][numParam];\n    splitOneAxis(v, newv, vs, newvs, splitv, param, newparam, theMesh.isVClosed());\n    \n    // Determine the new selection, and update the mesh.\n    \n    for (i = 0, j = 0; i < usize; i++)\n    {\n      if (selected[i])\n        newsel[j] = true;\n      if (i < splitu.length && splitu[i])\n        newsel[++j] = true;\n      j++;\n    }\n    for (i = 0, j = 0; i < vsize; i++)\n    {\n      if (selected[i+usize])\n        newsel[j+usize+usplitcount] = true;\n      if (i < splitv.length && splitv[i])\n        newsel[++j+usize+usplitcount] = true;\n      j++;\n    }\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theMesh, theMesh.duplicate()}));\n    theMesh.setShape(newv, newus, newvs);\n    for (int k = 0; k < numParam; k++)\n      if (theMesh.getParameterValues()[k] instanceof VertexParameterValue)\n      {\n        double val[] = new double [newus.length*newvs.length];\n        for (i = 0; i < newus.length; i++)\n          for (j = 0; j < newvs.length; j++)\n            val[i+newus.length*j] = newparam[i][j][k];\n        theMesh.setParameterValue(theMesh.getParameters()[k], new VertexParameterValue(val));\n      }\n    setMesh(theMesh);\n    setSelection(newsel);\n  }\n\n  // Perform the subdivision along one axis of the mesh.\n\n  private void splitOneAxis(MeshVertex v[][], MeshVertex newv[][], float s[], float news[], boolean split[], double param[][][], double newparam[][][], boolean closed)\n  {\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    int method = theMesh.getSmoothingMethod();\n    int numParam = param[0][0].length;\n    double paramTemp[] = new double [numParam];\n    int i, j, k, p1, p3, p4;\n        \n    for (i = 0, j = 0; i < split.length; i++)\n    {\n      p1 = i-1;\n      if (p1 < 0)\n      {\n        if (closed)\n          p1 = v[0].length-1;\n        else\n          p1 = 0;\n      }\n      if (i < v[0].length-1)\n        p3 = i+1;\n      else\n      {\n        if (closed)\n          p3 = 0;\n        else\n          p3 = v[0].length-1;\n      }\n      if ((split[i] || split[p1]) && method == Mesh.APPROXIMATING)\n        for (k = 0; k < v.length; k++)\n        {\n          newv[k][j] = SplineMesh.calcApproxPoint(v[k], s, param[k], paramTemp, p1, i, p3);\n          for (int m = 0; m < numParam; m++)\n            newparam[k][j][m] = paramTemp[m];\n        }\n      else\n        for (k = 0; k < v.length; k++)\n        {\n          newv[k][j] = v[k][i];\n          for (int m = 0; m < numParam; m++)\n            newparam[k][j][m] = param[k][i][m];\n        }\n      if (split[i] || split[p1])\n        news[j] = Math.min(s[i]*2.0f, 1.0f);\n      else\n        news[j] = s[i];\n      if (!split[i])\n      {\n        j++;\n        continue;\n      }\n      if (method == Mesh.NO_SMOOTHING)\n        for (k = 0; k < v.length; k++)\n        {\n          newv[k][j+1] = MeshVertex.blend(v[k][i], v[k][p3], 0.5, 0.5);\n          for (int m = 0; m < numParam; m++)\n            newparam[k][j+1][m] = 0.5*(param[k][i][m]+param[k][p3][m]);\n        }\n      else if (method == Mesh.INTERPOLATING)\n      {\n        if (i < v[0].length-2)\n          p4 = i+2;\n        else\n        {\n          if (closed)\n            p4 = (i+2)%v[0].length;\n          else\n            p4 = v[0].length-1;\n        }\n        for (k = 0; k < v.length; k++)\n        {\n          newv[k][j+1] = SplineMesh.calcInterpPoint(v[k], s, param[k], paramTemp, p1, i, p3, p4);\n          for (int m = 0; m < numParam; m++)\n            newparam[k][j+1][m] = paramTemp[m];\n        }\n      }\n      else\n        for (k = 0; k < v.length; k++)\n        {\n          newv[k][j+1] = MeshVertex.blend(v[k][i], v[k][p3], 0.5, 0.5);\n          for (int m = 0; m < numParam; m++)\n            newparam[k][j+1][m] = 0.5*(param[k][i][m]+param[k][p3][m]);\n        }\n      news[j+1] = 1.0f;\n      j += 2;\n    }\n    if (!closed)\n    {\n      for (k = 0; k < v.length; k++)\n      {\n        newv[k][0] = v[k][0];\n        newv[k][j] = v[k][i];\n        for (int m = 0; m < numParam; m++)\n        {\n          newparam[k][0][m] = param[k][0][m];\n          newparam[k][j][m] = param[k][i][m];\n        }\n      }\n      news[j] = s[i];\n    }\n  }\n\n  void extractCurveCommand()\n  {\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    MeshVertex vt[] = theMesh.getVertices();\n    int usize = theMesh.getUSize(), vsize = theMesh.getVSize();\n    int i, which;\n\n    if (selectMode != EDGE_MODE)\n      return;\n    for (which = 0; which < selected.length && !selected[which]; which++);\n    if (which == selected.length)\n      return;    \n    \n    // Now find the sequence of vertices.\n    \n    boolean closed;\n    Vec3 v[];\n    float smoothness[];\n    if (which < usize)\n    {\n      closed = theMesh.isVClosed();\n      v = new Vec3 [vsize];\n    }\n    else\n    {\n      closed = theMesh.isUClosed();\n      v = new Vec3 [usize];\n    }\n    smoothness = new float [v.length];\n    float usmoothness[] = theMesh.getUSmoothness();\n    float vsmoothness[] = theMesh.getVSmoothness();\n    for (i = 0; i < v.length; i++)\n    {\n      if (which < usize)\n      {\n        v[i] = vt[which+i*usize].r;\n        smoothness[i] = vsmoothness[i];\n      }\n      else\n      {\n        v[i] = vt[(which-usize)*usize+i].r;\n        smoothness[i] = usmoothness[i];\n      }\n    }\n    Curve cv = new Curve(v, smoothness, theMesh.getSmoothingMethod(), closed);\n    Widget parent = parentWindow.getFrame();\n    while (parent != null && !(parent instanceof LayoutWindow))\n      parent = parent.getParent();\n    if (parent != null)\n    {\n      String name = new BStandardDialog(\"\", Translate.text(\"extractedCurveName\"), BStandardDialog.QUESTION).showInputDialog(this, null, \"Extracted Curve\");\n      if (name != null)\n      {\n        ((LayoutWindow) parent).addObject(cv, ((MeshViewer) theView[currentView]).thisObjectInScene.getCoords().duplicate(), name, null);\n        ((LayoutWindow) parent).updateImage();\n      }\n    }\n  }\n\n  void setSmoothnessCommand()\n  {\n    final SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    SplineMesh oldMesh = (SplineMesh) theMesh.duplicate();\n    final float usmoothness[] = theMesh.getUSmoothness(), vsmoothness[] = theMesh.getVSmoothness();\n    float value;\n    int i;\n    \n    if (selectMode != EDGE_MODE)\n      return;\n    for (i = 0; i < selected.length && !selected[i]; i++);\n    if (i == selected.length)\n      return;\n    if (i < theMesh.getUSize())\n      value = usmoothness[i];\n    else\n      value = vsmoothness[i-theMesh.getUSize()];\n    value = 0.001f * (Math.round(value*1000.0f));\n    final ValueSlider smoothness = new ValueSlider(0.0, 1.0, 100, (double) value);\n    smoothness.addEventLink(ValueChangedEvent.class, new Object() {\n      void processEvent()\n      {\n        float s = (float) smoothness.getValue();\n        for (int i = 0; i < selected.length; i++)\n          if (selected[i])\n          {\n            if (i < theMesh.getUSize())\n              usmoothness[i] = s;\n            else\n              vsmoothness[i-theMesh.getUSize()] = s;\n          }\n        theMesh.setSmoothness(usmoothness, vsmoothness);\n        objectChanged();\n        updateImage();\n      }\n    } );\n    ComponentsDialog dlg = new ComponentsDialog(this, Translate.text(\"setCurveSmoothness\"), \n        new Widget [] {smoothness}, new String [] {Translate.text(\"Smoothness\")});\n    if (dlg.clickedOk())\n      setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theMesh, oldMesh}));\n    else\n    {\n      theMesh.copyObject(oldMesh);\n      objectChanged();\n      updateImage();\n    }\n  }\n\n  void reverseNormalsCommand()\n  {\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theMesh, theMesh.duplicate()}));\n    theMesh.reverseOrientation();\n    objectChanged();\n    updateImage();\n  }\n\n  void setSmoothingMethod(int method)\n  {\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theMesh, theMesh.duplicate()}));\n    for (int i = 0; i < smoothItem.length; i++)\n      smoothItem[i].setState(false);\n    smoothItem[method-2].setState(true);\n    theMesh.setSmoothingMethod(method);    \n    objectChanged();\n    updateImage();\n  }\n\n  void setClosed(int item)\n  {\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theMesh, theMesh.duplicate()}));\n    for (int i = 0; i < closedItem.length; i++)\n      closedItem[i].setState(i == item);\n    theMesh.setClosed((item == 0 || item == 2), (item == 1 || item == 2));\n    setMesh(theMesh);\n    updateImage();\n  }\n\n  /* Given a list of deltas which will be added to the selected vertices, calculate the\n     corresponding deltas for the unselected vertices according to the mesh tension. */\n  \n  public void adjustDeltas(Vec3 delta[])\n  {\n    int dist[] = getSelectionDistance(), count[] = new int [delta.length];\n    SplineMesh theMesh = (SplineMesh) objInfo.getObject();\n    int maxDistance = getTensionDistance(), usize = theMesh.getUSize(), vsize = theMesh.getVSize();\n    double tension = getMeshTension(), scale[] = new double [maxDistance+1];\n\n    \n    for (int i = 0; i < delta.length; i++)\n      if (dist[i] != 0)\n        delta[i].set(0.0, 0.0, 0.0);\n    for (int i = 0; i < maxDistance; i++)\n    {\n      for (int j = 0; j < count.length; j++)\n        count[j] = 0;\n      for (int j = 0; j < usize; j++)\n        for (int k = 0; k < vsize; k++)\n          if (dist[j+k*usize] == i)\n          {\n            if (j == 0)\n            {\n              if (theMesh.isUClosed() && dist[usize-1+k*usize] == i+1)\n              {\n                count[usize-1+k*usize]++;\n                delta[usize-1+k*usize].add(delta[j+k*usize]);\n              }\n            }\n            else\n              if (dist[j-1+k*usize] == i+1)\n              {\n                count[j-1+k*usize]++;\n                delta[j-1+k*usize].add(delta[j+k*usize]);\n              }\n            if (j == usize-1)\n            {\n              if (theMesh.isUClosed() && dist[k*usize] == i+1)\n              {\n                count[k*usize]++;\n                delta[k*usize].add(delta[j+k*usize]);\n              }\n            }\n            else\n              if (dist[j+1+k*usize] == i+1)\n              {\n                count[j+1+k*usize]++;\n                delta[j+1+k*usize].add(delta[j+k*usize]);\n              }\n            if (k == 0)\n            {\n              if (theMesh.isVClosed() && dist[j+(vsize-1)*usize] == i+1)\n              {\n                count[j+(vsize-1)*usize]++;\n                delta[j+(vsize-1)*usize].add(delta[j+k*usize]);\n              }\n            }\n            else\n              if (dist[j+(k-1)*usize] == i+1)\n              {\n                count[j+(k-1)*usize]++;\n                delta[j+(k-1)*usize].add(delta[j+k*usize]);\n              }\n            if (k == vsize-1)\n            {\n              if (theMesh.isVClosed() && dist[j] == i+1)\n              {\n                dist[j+k*usize] = i+1;\n                count[j]++;\n                delta[j].add(delta[j+k*usize]);\n              }\n            }\n            else\n              if (dist[j+(k+1)*usize] == i+1)\n              {\n                count[j+(k+1)*usize]++;\n                delta[j+(k+1)*usize].add(delta[j+k*usize]);\n              }\n          }\n      for (int j = 0; j < count.length; j++)\n        if (count[j] > 1)\n          delta[j].scale(1.0/count[j]);\n    }\n    for (int i = 0; i < scale.length; i++)\n      scale[i] = Math.pow((maxDistance-i+1.0)/(maxDistance+1.0), tension);\n    for (int i = 0; i < delta.length; i++)\n      if (dist[i] > 0)\n        delta[i].scale(scale[dist[i]]);\n  }\n}", "human_rating": 1.9956106900000057, "metadata": {"project": "aoi", "class": "artofillusion.SplineMeshEditorWindow", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/SplineMeshEditorWindow.java", "label_probabilities": {"readability": [1.35565e-15, 0.00376581, 0.988079, 0.00815526], "understandability": [6.50356e-11, 1.51925e-05, 0.0155581, 0.984427], "complexity": [0.969597, 0.0304026, 2.23029e-10, 0.0], "modularization": [1.0, 2.45908e-07, 2e-20, 0.0], "overall": [0.0, 0.0, 3.33504e-06, 0.999997]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.spmanager.HttpSPMFileSystem", "source": "/*\n *  Copyright 2004 Francois Guillet\n *  This program is free software; you can redistribute it and/or modify it under the\n *  terms of the GNU General Public License as published by the Free Software\n *  Foundation; either version 2 of the License, or (at your option) any later version.\n *  This program is distributed in the hope that it will be useful, but WITHOUT ANY\n *  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n *  PARTICULAR PURPOSE.  See the GNU General Public License for more details.\n */\npackage artofillusion.spmanager;\n\nimport artofillusion.*;\nimport artofillusion.ui.*;\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.tree.*;\nimport buoy.widget.*;\nimport buoy.event.*;\nimport java.io.*;\nimport java.util.*;\nimport java.util.zip.*;\nimport java.net.*;\nimport javax.swing.text.*;\nimport javax.swing.text.html.*;\nimport javax.swing.text.html.parser.*;\nimport java.util.regex.*;\nimport javax.xml.parsers.*;\nimport javax.xml.transform.Transformer;\nimport javax.xml.transform.TransformerFactory;\nimport javax.xml.transform.dom.DOMSource;\nimport javax.xml.transform.stream.StreamResult;\n\nimport org.xml.sax.*;\nimport org.w3c.dom.*;\nimport org.w3c.dom.Document;\n\n/**\n *  Description of the Class\n *\n *@author     Francois Guillet\n *@created    July, 01 2004\n */\npublic class HttpSPMFileSystem extends SPMFileSystem\n{\n    boolean unknownHost;\n    private URL repository;\n    private HttpStatusDialog statusDialog;\n    private boolean isDownloading;\n    private Vector callbacks;\n    private Document pluginsDoc, objectsDoc, startupDoc, toolsDoc;\n    private File file;\n    \n    private static final String[] EMPTY_STRING_ARRAY = new String[0];\n    \n\n    /**\n     *  Constructor for the HttpSPMFileSystem object\n     *\n     *@param  rep  Description of the Parameter\n     */\n    public HttpSPMFileSystem( URL rep )\n    {\n        super();\n        unknownHost = false;\n        repository = rep;\n        pluginsDoc = null;\n        objectsDoc = null;\n        startupDoc = null;\n        toolsDoc = null;\n    }\n\n\n    /**\n     *  Sets the repository attribute of the HttpSPMFileSystem object\n     *\n     *@param  rep  The new repository value\n     */\n    public void setRepository( URL rep )\n    {\n        pluginsInfo = new Vector();\n        toolInfo = new Vector();\n        objectInfo = new Vector();\n        startupInfo = new Vector();\n        initialized = false;\n        unknownHost = false;\n        repository = rep;\n        pluginsDoc = null;\n        objectsDoc = null;\n        startupDoc = null;\n        toolsDoc = null;\n        //SPManagerPlugin.getFrame().getParameters().initHttp();\n    }\n\n\n    /**\n     *  Gets the remoteInfo attribute of the HttpSPMFileSystem object\n     *\n     *@param  cb  Callback to call when done\n     */\n    public void getRemoteInfo( Runnable cb )\n    {\n        if ( !initialized )\n        {\n            super.initialize();\n            unknownHost = false;\n            if ( !isDownloading )\n            {\n                callbacks = new Vector();\n                callbacks.add( cb );\n                isDownloading = true;\n                statusDialog = new HttpStatusDialog();\n                (\n                    new Thread()\n                    {\n                        public void run()\n                        {\n                            scanPlugins();\n                            if ( !unknownHost )\n                                scanToolScripts();\n                            if ( !unknownHost )\n                                scanObjectScripts();\n                            if ( !unknownHost )\n                                scanStartupScripts();\n                            isDownloading = false;\n                            initialized = true;\n                            for ( int i = 0; i < callbacks.size(); ++i )\n                                ( (Runnable) callbacks.elementAt( i ) ).run();\n                            statusDialog.dispose();\n                            statusDialog = null;\n                        }\n                    } ).start();\n            }\n            else\n                callbacks.add( cb );\n        }\n        else\n            cb.run();\n    }\n\n\n    /**\n     *  Init stuff\n     */\n    public void initialize()\n    {\n        super.initialize();\n        statusDialog = null;\n        scanPlugins();\n        if ( !unknownHost )\n            scanToolScripts();\n        if ( !unknownHost )\n            scanObjectScripts();\n        if ( !unknownHost )\n            scanStartupScripts();\n        initialized = true;\n    }\n\n\n    /**\n     *  Scans plugins\n     */\n    private void scanPlugins()\n    {\n        if (! SPManagerFrame.getParameters().getUseCache() )\n            SPManagerFrame.getInstance().setRemoteStatusText( SPMTranslate.text( \"scanningPluginsFrom\", new String[]{repository.toString()} ), 5000 );\n        else\n        {\n            //String s = repository.toString().replaceAll(\"/AoIRepository/\", \"\");\n            String s = repository.toString();\n\t    s = s.substring(0, s.lastIndexOf('/'));\n            s = s + \"/cgi-bin/scripts.cgi?Plugins%20\" + SPManagerPlugin.AOI_VERSION;\n            SPManagerFrame.getInstance().setRemoteStatusText( SPMTranslate.text( \"scanningPluginsFrom\", new String[]{s} ), 5000 );\n        }\n        if ( statusDialog != null )\n            statusDialog.setText( SPMTranslate.text( \"scanningPlugins\" ) );\n        pluginsInfo = new Vector();\n        if ( SPManagerFrame.getParameters().getUseCache() )\n        {\n                scanFiles( \"Plugins\", pluginsInfo );\n        }\n        else\n        {\n            try\n            {\n                URL pluginsURL = new URL( repository, \"Plugins/\" );\n                scanFiles( pluginsURL, pluginsInfo, \".jar\" );\n\n            }\n            catch ( MalformedURLException e )\n            {\n                e.printStackTrace();\n            }\n        }\n    }\n\n\n    /**\n     *  Scans tools scripts\n     */\n    private void scanToolScripts()\n    {\n        if ( ! SPManagerFrame.getParameters().getUseCache() )\n            SPManagerFrame.getInstance().setRemoteStatusText( SPMTranslate.text( \"scanningToolScriptsFrom\", new String[]{repository.toString()} ), 5000 );\n        else\n        {\n            //String s = repository.toString().replaceAll(\"/AoIRepository/\", \"\");\n            String s = repository.toString();\n\t    s = s.substring(0, s.lastIndexOf('/'));\n            s = s + \"/cgi-bin/scripts.cgi?Scripts/Tools%20\" + SPManagerPlugin.AOI_VERSION;\n            SPManagerFrame.getInstance().setRemoteStatusText( SPMTranslate.text( \"scanningToolScriptsFrom\", new String[]{s} ), 5000 );\n        }\n        if ( statusDialog != null )\n            statusDialog.setText( SPMTranslate.text( \"scanningToolScripts\" ) );\n        toolInfo = new Vector();\n        if ( SPManagerFrame.getParameters().getUseCache() )\n        {\n           scanFiles( \"Scripts/Tools\", toolInfo );\n        }\n        else\n        {\n             try\n             {\n                 URL toolScriptURL = new URL( repository, \"Scripts/Tools/\" );\n                 scanFiles( toolScriptURL, toolInfo, \".bsh\" );\n\n             }\n             catch ( MalformedURLException e )\n             {\n                 e.printStackTrace();\n             }\n         }\n    }\n\n\n    /**\n     *  Scans objects scripts\n     */\n    private void scanObjectScripts()\n    {\n        if ( ! SPManagerFrame.getParameters().getUseCache() )\n                    SPManagerFrame.getInstance().setRemoteStatusText( SPMTranslate.text( \"scanningObjectScriptsFrom\", new String[]{repository.toString()} ), 5000 );\n        else\n        {\n            //String s = repository.toString().replaceAll(\"/AoIRepository/\", \"\");\n            String s = repository.toString();\n\t    s = s.substring(0, s.lastIndexOf('/'));\n            s = s + \"/cgi-bin/scripts.cgi?Scripts/Objects%20\" + SPManagerPlugin.AOI_VERSION;\n            SPManagerFrame.getInstance().setRemoteStatusText( SPMTranslate.text( \"scanningObjectScriptsFrom\", new String[]{s} ), 5000 );\n        }\n        if ( statusDialog != null )\n            statusDialog.setText( SPMTranslate.text( \"scanningObjectScripts\" ) );\n        objectInfo = new Vector();\n        if ( SPManagerFrame.getParameters().getUseCache() )\n        {\n           scanFiles( \"Scripts/Objects\", objectInfo );\n        }\n        else\n        {\n            try\n            {\n                URL objectScriptURL = new URL( repository, \"Scripts/Objects/\" );\n                scanFiles( objectScriptURL, objectInfo, \".bsh\" );\n\n            }\n            catch ( MalformedURLException e )\n            {\n                e.printStackTrace();\n            }\n        }\n    }\n\n\n    /**\n     *  Scans startup scripts\n     */\n    private void scanStartupScripts()\n    {\n        if ( ! SPManagerFrame.getParameters().getUseCache() )\n                    SPManagerFrame.getInstance().setRemoteStatusText( SPMTranslate.text( \"scanningStartupScriptsFrom\", new String[]{repository.toString()} ), 5000 );\n        else\n        {\n            //String s = repository.toString().replaceAll(\"/AoIRepository/\", \"\");\n            String s = repository.toString();\n\t    s = s.substring(0, s.lastIndexOf('/'));\n            s = s + \"/cgi-bin/scripts.cgi?Scripts/Startup%20\" + SPManagerPlugin.AOI_VERSION;\n            SPManagerFrame.getInstance().setRemoteStatusText( SPMTranslate.text( \"scanningStartupScriptsFrom\", new String[]{s} ), 5000 );\n        }\n        if ( statusDialog != null )\n            statusDialog.setText( SPMTranslate.text( \"scanningStartupScripts\" ) );\n        startupInfo = new Vector();\n        if ( SPManagerFrame.getParameters().getUseCache() )\n        {\n           scanFiles( \"Scripts/Startup\", startupInfo );\n        }\n        else\n        {\n            try\n            {\n                URL startupScriptURL = new URL( repository, \"Scripts/Startup/\" );\n                scanFiles( startupScriptURL, startupInfo, \".bsh\" );\n\n            }\n            catch ( MalformedURLException e )\n            {\n                e.printStackTrace();\n            }\n        }\n    }\n\n\n    /**\n     *  Scans file on a general basis\n     *\n     *@param  from    URL to scan files from\n     *@param  addTo   Which vector to add info to\n     *@param  suffix  Scanned files suffix\n     */\n    private void scanFiles( URL from, Vector addTo, String suffix )\n    {\n        SPMObjectInfo info;\n        boolean eligible;\n\n        Vector v = null;\n\n        try\n        {\n            Object obj = from.getContent();\n            if ( obj instanceof InputStream )\n            {\n                v = htmlFindFilesVersioning( (InputStream) ( obj ), from );\n            }\n            ( (InputStream) obj ).close();\n        }\n        catch ( IOException e )\n        {\n            if ( e instanceof UnknownHostException )\n            {\n                JOptionPane.showMessageDialog( null, from.toString() + \": \" + SPMTranslate.text( \"unknownHost\" ), SPMTranslate.text( \"error\" ), JOptionPane.ERROR_MESSAGE );\n                unknownHost = true;\n            }\n            else if ( e instanceof FileNotFoundException )\n            {\n                JOptionPane.showMessageDialog( null, from.toString() + \": \" + SPMTranslate.text( \"fileNotFound\" ), SPMTranslate.text( \"error\" ), JOptionPane.ERROR_MESSAGE );\n                unknownHost = true;\n            }\n            else\n                e.printStackTrace();\n        }\n        if ( v != null ) {\n            // sort the list\n            String[] sarray = (String[]) v.toArray(EMPTY_STRING_ARRAY);\n            Arrays.sort(sarray);\n            for ( int i = 0; i < sarray.length; i++ )\n            {\n                //String s = (String) v.elementAt( i );\n        \tString s = sarray[i];\n                System.out.println(s);\n                if ( s.endsWith( suffix ) )\n                {\n                    //check if file candidate for update or install\n                    eligible = true;\n\n                    String name = s.substring( 0, s.length() - 4 );\n                    if ( suffix.equals( \".jar\" ) )\n                    {\n                        //look for xml file\n\n\t\t\t/*\n\t\t\t *  NTJ: for AOI 2.5: The XML file name has changed to\n\t\t\t *  'extensions.xml'. For compatibility, the old name\n\t\t\t *  is checked if the new name does not exist.\n\t\t\t */\n\n                        eligible = true;\n                        String sxml;\n\t\t\tsxml = s.substring(0, s.lastIndexOf('/')) +\n\t\t\t    \"extensions.xml\";\n\n                        URL xmlURL = null;\n\t\t\ttry {\n\t\t\t    xmlURL = new URL(from, sxml);\n\t\t\t} catch (MalformedURLException e) {\n\t\t\t    e.printStackTrace();\n\t\t\t}\n\n                        try\n                        {\n                            HttpURLConnection.setFollowRedirects( false );\n                            HttpURLConnection conn =\n\t\t\t\t(HttpURLConnection) xmlURL.openConnection();\n\n\t\t\t    if (conn.getResponseCode()\n\t\t\t\t!= HttpURLConnection.HTTP_OK) {\n\t\t\t\t\n\t\t\t\teligible = false;\n\t\t\t    }\n\n\t\t\t    else {\n\t\t\t\tsxml = s.substring(0, s.lastIndexOf('.')) +\n\t\t\t\t    \".xml\";\n\t\t\t\txmlURL = new URL(from, sxml);\n\n\t\t\t\tconn =\n\t\t\t\t    (HttpURLConnection)xmlURL.openConnection();\n\n\t\t\t\tif (conn.getResponseCode()\n\t\t\t\t    != HttpURLConnection.HTTP_OK) {\n\n\t\t\t\t    eligible = false;\n\t\t\t\t}\n\t\t\t    }\n\n\t\t\t    if (eligible) {\n\t\t\t\tInputStreamReader in = new\n\t\t\t\t    InputStreamReader(conn.getInputStream());\n\n\t\t\t\tin.close();\n\t\t\t    }\n\t\t\t}\n                        catch ( IOException e )\n                        {\n                            eligible = false;\n                        }\n\t\t    }\n\n                    info = null;\n                    if ( eligible )\n                    {\n\t\t\tSystem.out.println(\"adding: \" + s);\n                        try\n                        {\n                            info = new SPMObjectInfo( new URL( from, s ) );\n                        }\n                        catch ( Exception e )\n                        {\n                            e.printStackTrace();\n                        }\n                    }\n                    if ( info != null )\n                        addTo.add( info );\n                }\n            }\n        }\n    }\n\n    /**\n     *  Scans file using server cgi\n     *\n     *@param  dir     directory to fetch scripts from\n     *@param  addTo   Which vector to add info to\n     */\n    private void scanFiles( String dir, Vector addTo )\n    {\n\n        URL cgiUrl = null;\n        try\n        {\n            //String s = repository.toString().replaceAll(\"/AoIRepository/\", \"\");\n            String s = repository.toString();\n\t    String err = \"\";\n\t    s = s.substring(0, s.lastIndexOf('/'));\n            cgiUrl = new URL( s + \"/cgi-bin/scripts.cgi?\" + dir + \"%20\" + SPManagerPlugin.AOI_VERSION );\n            //cgiUrl = new URL( s + \"/cgi-bin/scripts.cgi?-z%20\" + dir + \"%20\" + SPManagerPlugin.AOI_VERSION );\n            //cgiUrl = new URL( s + \"/cgi-bin/RepoServer\");\n            //cgiUrl = new URL( s + \"/cgi-bin/RepoServer?HTTP_X_AOI_Dir=\" + dir + \"&HTTP_X_AOI_Version=\"\n    \t    //\t+ SPManagerPlugin.AOI_VERSION);\n            \n            String content = null;\n            boolean received = false;\n            int attempts = 0;\n            System.out.println( cgiUrl );\n            while (!received && attempts++ < 5 )\n            {\n\t\tHttpURLConnection conn =\n\t\t    (HttpURLConnection) cgiUrl.openConnection();\n\n\t\tconn.setRequestProperty(\"Accept-Encoding\", \"deflate, gzip\");\n\t\tconn.setRequestProperty(\"X-AOI-Version\", SPManagerPlugin.AOI_VERSION);\n\t\tconn.setRequestProperty(\"X-AOI-Dir\", dir);\n\t\t\n\t\tif (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {\n\t\t    err = conn.getResponseMessage();\n\t\t    Thread.sleep(250);\n\t\t    continue;\n\t\t}\n\n                //InputStream is= cgiUrl.openStream();\n\t\tInputStream is= conn.getInputStream();\n                is = new BufferedInputStream( is );\n                //Document doc = SPManagerUtils.builder.parse( bis );\n\n                System.out.println(\"Content-Encoding: \" + conn.getHeaderField(\"Content-Encoding\"));\n                \n                if (conn.getHeaderField(\"Content-Encoding\").equalsIgnoreCase(\"deflate\"))\n                \tis = new InflaterInputStream(is, new Inflater(true));\n\n                else if (conn.getHeaderField(\"Content-Encoding\").equalsIgnoreCase(\"gzip\"))\n                \tis = new GZIPInputStream(is);\n\n                /*\n                byte[] prolog = new byte[40];\n                int chunk = is.read(prolog, 0, 40);\n                System.out.println(\"first \" + chunk + \" bytes >>\" + new String(prolog, \"UTF-8\") + \"<<\");\n                */\n                \n                InputSource input = null;\n                try { input = new InputSource(new InputStreamReader(is, \"UTF-8\")); }\n                catch (Exception e) { e.printStackTrace(); }\n                \n                System.out.println(\"Encoding: \" + input.getEncoding());\n                \n                Document doc = SPManagerUtils.builder.parse( input );\n                NodeList tst = doc.getElementsByTagName( \"scriptcollection\" );\n                if (tst.getLength() > 0)\n                {\n                    received = true;\n                    NodeList nl = doc.getElementsByTagName( \"scriptreference\" );\n                    Node script;\n                    String location = \"\";\n                    long length = 0;\n                    for (int i = 0; i < nl.getLength(); i++)\n                    {\n                        Node n = nl.item(i);\n                        NodeList nnl = n.getChildNodes();\n                        script = null;\n                        location = null;\n                        for (int j = 0; j < nnl.getLength(); j++)\n                        {\n                            if ( \"scriptlocation\".equals( nnl.item(j).getNodeName() ) )\n                            {\n                                location = repository.toString() + \"/\" + dir +\"/\" + nnl.item(j).getChildNodes().item(0).getNodeValue();\n                                //System.out.println( \"location found\" );\n                            }\n                            else if ( \"scriptlength\".equals( nnl.item(j).getNodeName() ) )\n                            {\n                                length = Long.parseLong( nnl.item(j).getChildNodes().item(0).getNodeValue() );\n                                //System.out.println( \"length found\" );\n                            }\n\t\t\t    else if (\"extension\".equals(nnl.item(j).getNodeName()))\n\t\t\t\tscript = nnl.item(j);\n                            else if (\"script\".equals( nnl.item(j).getNodeName() ))\n                                script = nnl.item(j);\n                        }\n                        //System.out.println( location + \" / \" + script + \" / \" + length);\n                        if ( script != null && location != null )\n                        {\n                            addTo.add( new SPMObjectInfo( script, new URL(location) , length) );\n                        }\n                    }\n\n                }\n                is.close();\n            }\n            if (!received)\n            {\n                JOptionPane.showMessageDialog( null, cgiUrl.toString() + \": \" + SPMTranslate.text( \"scriptServerFailed\" ), SPMTranslate.text( \"error\" ) + \" \" +\n\t\t\t\t\t       err,\n\t\t\t\t\t       JOptionPane.ERROR_MESSAGE );\n                return;\n            }\n\n\n        }\n        catch ( Exception e )\n        {\n            if ( e instanceof UnknownHostException )\n            {\n                JOptionPane.showMessageDialog( null, cgiUrl.toString() + \": \" + SPMTranslate.text( \"unknownHost\" ), SPMTranslate.text( \"error\" ), JOptionPane.ERROR_MESSAGE );\n                unknownHost = true;\n            }\n            else if ( e instanceof FileNotFoundException )\n            {\n                JOptionPane.showMessageDialog( null, cgiUrl.toString() + \": \" + SPMTranslate.text( \"fileNotFound\" ), SPMTranslate.text( \"error\" ), JOptionPane.ERROR_MESSAGE );\n                unknownHost = true;\n            }\n            else {\n                JOptionPane.showMessageDialog( null, cgiUrl.toString() + \": \" + SPMTranslate.text( \"httpError\" ), SPMTranslate.text( \"error\" ) + \": \" + e.getMessage(), JOptionPane.ERROR_MESSAGE );\n                e.printStackTrace();\n\t    }\n        }\n        \n        // sort the result\n        SPMObjectInfo left, right;\n        int i, j;\n        for (i = addTo.size()-1; i > 0; i--) {\n            j = i;\n            right = (SPMObjectInfo) addTo.get(i);\n\n            while (j > 0) {\n        \tleft = (SPMObjectInfo) addTo.get(j-1);\n        \tif (right.getName().compareTo(left.getName()) >= 0) break;\n        \tj--;\n            }\n\n            // relocate\n            if (j < i) {\n        \taddTo.remove(i);\n        \taddTo.add(j, right);\n            }\n        }\n    }\n\n    /**\n     *  Description of the Method\n     *\n     *@param  fileName          Description of the Parameter\n     *@param  from              Description of the Parameter\n     *@param  status            Description of the Parameter\n     *@param  downloadedLength  Description of the Parameter\n     *@param  lengthToDownload  Description of the Parameter\n     *@return                   Description of the Return Value\n     */\n    public static long downloadRemoteTextFile( URL from, String fileName, long size, StatusDialog status, long totalDownload, long downloadedLength, ArrayList errors )\n    {\n\t//if (fileName.endsWith(\".upd\")) return 0;\n\n        BufferedReader in = null;\n        BufferedWriter file = null;\n        long initialValue = downloadedLength;\n        //System.out.println( from + \": downloadedLength :\" + downloadedLength + \" \" + lengthToDownload );\n        try\n        {\n\t    HttpURLConnection conn = (HttpURLConnection) from.openConnection();\n\t    \n\t    conn.setRequestProperty(\"Cache-Control\", \"no-cache\");\n\t    conn.setRequestProperty(\"Accept-Encoding\", \"deflate, gzip\");\n\n\t    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {\n\t\tnew BStandardDialog(\"SPManager\", new String[] {\n\t\t\t\t\tSPMTranslate.text(\"httpError\"),\n\t\t\t\t\tconn.getResponseMessage() +\n\t\t\t\t\t\" (\" + conn.getResponseCode() + \")\",\n\t\t\t\t    }, BStandardDialog.ERROR)\n\t\t    .showMessageDialog(SPManagerFrame.getInstance());\n\n\t\treturn 0;\n\t    }\n\n\t    InputStream is = conn.getInputStream();\n\t    \n\t    System.out.println(\"Content-Encoding: \" + conn.getHeaderField(\"Content-Encoding\"));\n\t    \n\t    if (conn.getHeaderField(\"Content-Encoding\").equalsIgnoreCase(\"deflate\"))\n\t    \tis = new InflaterInputStream(is, new Inflater(true));\n\n\t    if (conn.getHeaderField(\"Content-Encoding\").equalsIgnoreCase(\"gzip\"))\n\t    \tis = new GZIPInputStream(is);\n\n            //in = new BufferedReader( new InputStreamReader( from.openStream() ) );\n\t    in = new BufferedReader( new InputStreamReader( is ) );\n                \n\t    file = new BufferedWriter( new FileWriter(fileName) );\n\n            double a;\n            double b = totalDownload;\n            int value;\n            int newValue;\n            value = status.getBarValue();\n\n            int i = in.read();\n            while ( i != -1 )\n            {\n                file.write( i );\n                i = in.read();\n                if ( status != null )\n                {\n                    ++downloadedLength;\n                    a = downloadedLength;\n                    newValue = (int) Math.round( ( a * 100.0 ) / b );\n                    if ( newValue > value )\n                    {\n                        status.setBarValue( newValue );\n                        status.setProgressText( newValue + \"%\" );\n                        value = newValue;\n                    }\n                }\n            }\n\n\t    file.flush();\n\t    file.close();\n\n            //System.out.println( \"downloadedLength :\" + downloadedLength + \" \" + ( downloadedLength - initialValue ) );\n\n\t    // check we got the expected data\n\t    long received = downloadedLength - initialValue;\n\t    if (received != size)\n\t\tthrow new IOException(\"SPManager: file incomplete.\" +\n\t\t\t\t      \" Only received \" + received +\n\t\t\t\t      \" bytes of \" + size);\n\n        }\n        catch ( Exception e)\n        {\n\t    /*\n            e.printStackTrace();\n            JOptionPane.showMessageDialog( null, from.toString() + \": \" + SPMTranslate.text( \"fileNotFound\" ), SPMTranslate.text( \"error\" ), JOptionPane.ERROR_MESSAGE );\n\t    */\n\t    errors.add(SPMTranslate.text(\"error\") + \"(\" + fileName + \")\" + e);\n        }\n\t/*\n        catch ( IOException e )\n        {\n            e.printStackTrace();\n            JOptionPane.showMessageDialog( null, from.toString() + \": \" + SPMTranslate.text( \"ioError\" ), SPMTranslate.text( \"error\" ), JOptionPane.ERROR_MESSAGE );\n        }\n\t*/\n        finally\n        {\n            try\n            {\n                if ( in != null )\n                    in.close();\n                if ( file != null )\n                    file.close();\n            }\n            catch ( IOException e )\n            {\n                //e.printStackTrace();\n\t\tSystem.out.println(\"SPManager: error closing \" + fileName +\n\t\t\t\t   \": \" + e);\n\t\t//errors.add(\"error closing \" + fileName);\n            }\n\n\t    //if (update.exists()) update.delete();\n        }\n        return downloadedLength - initialValue;\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  from              Description of the Parameter\n     *@param  fileName          Description of the Parameter\n     *@param  status            Description of the Parameter\n     *@param  lengthToDownload  Description of the Parameter\n     *@param  downloadedLength  Description of the Parameter\n     *@return                   Description of the Return Value\n     */\n    public static long downloadRemoteBinaryFile( URL from, String fileName, long size, StatusDialog status, long totalDownload, long downloadedLength, ArrayList errors )\n    {\n\tSystem.out.println(\"download: size=\" + size +\n\t\t\t   \"; total=\" + totalDownload +\n\t\t\t   \"; downloaded=\" + downloadedLength);\n\n\t//if (fileName.endsWith(\".upd\")) return 0;\n\n\tFile update = new File(fileName);\n\n\tThread thread = Thread.currentThread();\n\n        BufferedInputStream in = null;\n        BufferedOutputStream file = null;\n        long initialValue = downloadedLength;\n        try\n        {\n\t    HttpURLConnection conn = (HttpURLConnection) from.openConnection();\n\n\t    conn.setRequestProperty(\"Cache-Control\", \"no-cache\");\n\t    \n\t    if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {\n\t\tnew BStandardDialog(\"SPManager\", new String[] {\n\t\t\t\t\tSPMTranslate.text(\"httpError\"),\n\t\t\t\t\tconn.getResponseMessage() +\n\t\t\t\t\t\" (\" + conn.getResponseCode() + \")\",\n\t\t\t\t    }, BStandardDialog.ERROR)\n\t\t    .showMessageDialog(SPManagerFrame.getInstance());\n\n\t\treturn 0;\n\t    }\n\n            //in = new BufferedInputStream( from.openStream() );\n\t    in = new BufferedInputStream( conn.getInputStream() );\n\n            file = new BufferedOutputStream(new FileOutputStream(update));\n\n            double a;\n            double b = totalDownload;\n            int value;\n            int newValue;\n            value = status.getBarValue();\n\t    String mod=\"\", newMod;\n\n\t    if (b <= 0) status.setIdle(true);\n\n            int result = 0;\n            while ( ( result = in.read() ) != -1 )\n            {\n\t\tif (thread.interrupted()) {\n\t\t    thread.interrupt();\n\n\t\t    if (!update.delete()) {\n\t\t\tRandomAccessFile raf =\n\t\t\t    new RandomAccessFile(update, \"rw\");\n\n\t\t\traf.setLength(0);\n\t\t\traf.close();\n\t\t    }\n\n\t\t    throw new InterruptedException(\"download cancelled: \" +\n\t\t\t\t\t\t   fileName);\n\t\t}\n\n                file.write( (byte) result );\n                ++downloadedLength;\n                a = downloadedLength;\n\n\t\tif (b > a) {\n\t\t    newValue = (int) Math.round( a * 100.0 / b );\n\t\t    if ( newValue > value ) {\n\t\t\tstatus.setBarValue( newValue );\n\t\t\tstatus.setProgressText( newValue + \"%\" );\n\t\t\tvalue = newValue;\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    newMod = (a > 1000000\n\t\t\t      ? ((int) (a/100000.0)) + \" MB\"\n\t\t\t      : a > 1000\n\t\t\t      ? ((int) (a/1000.0)) + \" kB\"\n\t\t\t      : a + \" bytes\");\n\n\t\t    if (!newMod.equals(mod)) status.setProgressText(newMod);\n\t\t}\n\t    }\n\n\t    file.flush();\n\t    file.close();\n\n\t    // check we got the expected data\n\t    if (size > 0) {\n\t\tlong received = downloadedLength - initialValue;\n\t\tif (received != size)\n\t\t    throw new IOException(\"SPManager: file incomplete.\" +\n\t\t\t\t\t  \" Only received \" + received +\n\t\t\t\t\t  \" bytes of \" + size);\n\t    }\n\n\t    // test validity of zipfiles\t    \n\t    if (fileName.endsWith(\".jar\") || fileName.endsWith(\".zip\")) {\n\t\tnew ZipFile(update);\n\t\tSystem.out.println(\"SPManager: ZipFile ok\");\n\t    }\n\n        }\n        catch ( Exception e)\n        {\n\t    errors.add(SPMTranslate.text(\"error\") + \"(\" + fileName + \")\" + e);\n\n\t    /*\t    \n            e.printStackTrace();\n\n\t    JOptionPane.showMessageDialog( null, from.toString() + \": \" + SPMTranslate.text( \"errMsg\" ), SPMTranslate.text( \"error\" ), JOptionPane.ERROR_MESSAGE );\n\t    */\n        }\n\t/*\n        catch ( IOException e )\n        {\n            e.printStackTrace();\n            JOptionPane.showMessageDialog( null, from.toString() + \": \" + SPMTranslate.text( \"ioError\" ), SPMTranslate.text( \"error\" ), JOptionPane.ERROR_MESSAGE );\n        }\n\t*/\n        finally\n        {\n            try\n            {\n                if ( in != null )\n                    in.close();\n                if ( file != null )\n                    file.close();\n            }\n            catch ( IOException e )\n            {\n\t\tSystem.out.println(\"SPManager: error closing \" + fileName +\n\t\t\t\t   \": \" + e);\n\n                //e.printStackTrace();\n\t\t//errors.add(\"Error closing \" + fileName);\n            }\n\n\t    //if (update.exists()) update.delete();\n        }\n        return downloadedLength - initialValue;\n    }\n\n    /**\n     *  Description of the Method\n     *\n     *@param  is  Description of the Parameter\n     *@return     Description of the Return Value\n     */\n    private Vector htmlFindFiles( InputStream is )\n    {\n        Vector v = new Vector();\n\n        HtmlParserCallback callback = new HtmlParserCallback( v );\n//        BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( is ) );\n\t\tBufferedReader bufferedReader = null;\n        try {bufferedReader = new BufferedReader( new InputStreamReader( is, \"UTF-8\" ) ); }\n        catch (Exception e) { e.printStackTrace(); return v; }\n        try\n        {\n            new ParserDelegator().parse( bufferedReader, callback, false );\n            is.close();\n        }\n        catch ( IOException e )\n        {\n            e.printStackTrace();\n        }\n        return v;\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  is    Description of the Parameter\n     *@param  from  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n    private Vector htmlFindFilesVersioning( InputStream is, URL from )\n    {\n        Vector v = new Vector();\n\n        HtmlVersioningParserCallback callback = new HtmlVersioningParserCallback( v, from );\n        //BufferedReader bufferedReader = new BufferedReader( new InputStreamReader( is ) );\n        BufferedReader bufferedReader = null;\n        try { bufferedReader = new BufferedReader( new InputStreamReader( is, \"UTF-8\" ) ); }\n        catch (Exception e) { e.printStackTrace(); return v; }\n        try\n        {\n            new ParserDelegator().parse( bufferedReader, callback, false );\n        }\n        catch ( IOException e )\n        {\n            e.printStackTrace();\n        }\n        return v;\n    }\n\n\n    /**\n     *  Description of the Class\n     *\n     *@author     pims\n     *@created    1 juillet 2004\n     */\n    private class HtmlParserCallback extends HTMLEditorKit.ParserCallback\n    {\n        private Vector v;\n\n\n        /**\n         *  Constructor for the HtmlParserCallback object\n         *\n         *@param  v  Description of the Parameter\n         */\n        public HtmlParserCallback( Vector v )\n        {\n            this.v = v;\n        }\n\n\n        /**\n         *  Description of the Method\n         *\n         *@param  data  Description of the Parameter\n         *@param  pos   Description of the Parameter\n         */\n        public void handleText( char[] data, int pos )\n        {\n            System.out.println( \"handleText \" + new String( data ) + \" \" + pos );\n        }\n\n\n        /**\n         *  Description of the Method\n         *\n         *@param  t    Description of the Parameter\n         *@param  a    Description of the Parameter\n         *@param  pos  Description of the Parameter\n         */\n        public void handleStartTag( HTML.Tag t, MutableAttributeSet a, int pos )\n        {\n            System.out.println( \"StartTag :\" + t + \":\" + a + \":\" + pos );\n            if ( t == HTML.Tag.A )\n            {\n                String s = (String) a.getAttribute( HTML.Attribute.HREF );\n                v.add( s );\n            }\n\n        }\n\n\n        /**\n         *  Description of the Method\n         *\n         *@param  t    Description of the Parameter\n         *@param  a    Description of the Parameter\n         *@param  pos  Description of the Parameter\n         */\n        public void handleEndTag( HTML.Tag t, MutableAttributeSet a, int pos )\n        {\n            System.out.println( \"EndTag :\" + t + \":\" + a + \":\" + pos );\n        }\n    }\n\n\n\n    /**\n     *  Description of the Class\n     *\n     *@author     pims\n     *@created    1 juillet 2004\n     */\n    private class HtmlVersioningParserCallback extends HTMLEditorKit.ParserCallback\n    {\n        private Vector v;\n        private URL from;\n\n\n        /**\n         *  Constructor for the HtmlParserCallback object\n         *\n         *@param  v     Description of the Parameter\n         *@param  from  Description of the Parameter\n         */\n        public HtmlVersioningParserCallback( Vector v, URL from )\n        {\n            this.v = v;\n            this.from = from;\n        }\n\n\n        /**\n         *  Description of the Method\n         *\n         *@param  data  Description of the Parameter\n         *@param  pos   Description of the Parameter\n         */\n        public void handleText( char[] data, int pos )\n        {\n            System.out.println( \"handleText \" + new String( data ) + \" \" + pos );\n        }\n\n\n        /**\n         *  Description of the Method\n         *\n         *@param  AoIversion  Description of the Parameter\n         *@param  versions    Description of the Parameter\n         *@return             Description of the Return Value\n         */\n        private String findCorrectVersion( String AoIversion, String[] versions )\n        {\n            int maj;\n            int min;\n            //System.out.println( \"AoI \" + AoIversion );\n            //for ( int i = 0; i < versions.length; ++i )\n            //    System.out.println( versions[i] );\n            String[] tmps = AoIversion.split( \"[^0-9]\" );\n            maj = Integer.parseInt( tmps[0] );\n            min = Integer.parseInt( tmps[1] );\n            String result = null;\n            while ( result == null && ( maj >= 0 ) )\n            {\n                for ( int i = 0; i < versions.length; ++i )\n                {\n                    String[] versionsplit = versions[i].split( \" \" );\n                    tmps = versionsplit[0].split( \"[^0-9]\" );\n                    if ( ( maj == Integer.parseInt( tmps[0] ) ) && ( min == Integer.parseInt( tmps[1] ) ) )\n                        result = versionsplit[2];\n                }\n                if ( result == null )\n                {\n                    --min;\n                    if ( min < 0 )\n                    {\n                        min = 9;\n                        --maj;\n                    }\n                }\n            }\n            if ( result == null )\n            {\n                //System.out.println( \"no script for version\" );\n                return \"\";\n            }\n            if ( result.equals( \"-\" ) )\n            {\n                //System.out.println( \"-\" );\n                return \"\";\n            }\n            //System.out.println( \"result : \" + result );\n            return result;\n        }\n\n\n        /**\n         *  Description of the Method\n         *\n         *@param  t    Description of the Parameter\n         *@param  a    Description of the Parameter\n         *@param  pos  Description of the Parameter\n         */\n        public void handleStartTag( HTML.Tag t, MutableAttributeSet a, int pos )\n        {\n            System.out.println( \"StartTag :\" + t + \":\" + a + \":\" + pos );\n            if ( t == HTML.Tag.A )\n            {\n                String s = (String) a.getAttribute( HTML.Attribute.HREF );\n                if ( s.endsWith( \"/\" ) )\n                {\n                    //directory : get the location of content text file\n                    String[] ss = s.split( \"/\" );\n                    s = ss[ss.length - 1];\n                    String txt = s + \"/\" + s + \".txt\";\n                    try\n                    {\n                        URL fileURL = new URL( from, txt );\n                        System.out.println( \"fileURL \" + fileURL );\n                        HttpURLConnection.setFollowRedirects( false );\n                        HttpURLConnection connection = (HttpURLConnection) fileURL.openConnection();\n                        String header = connection.getHeaderField( 0 );\n                        InputStreamReader in = new InputStreamReader( connection.getInputStream() );\n                        //read the contents of the contents file\n                        int status = 0;\n                        String content = \"\";\n                        while ( status != -1 )\n                        {\n                            try\n                            {\n                                status = in.read();\n                                if ( status != -1 )\n                                    content += (char) status;\n                            }\n                            catch ( IOException e )\n                            {\n                                e.printStackTrace();\n                            }\n                        }\n                        in.close();\n                        //Get the file names\n                        String[] versions = content.split( \"\\n\" );\n                        //send to findCorrectVersion\n                        String name = findCorrectVersion( SPManagerPlugin.AOI_VERSION, versions );\n                        if ( !name.equals( \"\" ) )\n                            v.add( s + \"/\" + name );\n\n                    }\n                    catch ( IOException e )\n                    {\n                        return;\n                    }\n                }\n            }\n\n        }\n\n\n        /**\n         *  Description of the Method\n         *\n         *@param  t    Description of the Parameter\n         *@param  a    Description of the Parameter\n         *@param  pos  Description of the Parameter\n         */\n        public void handleEndTag( HTML.Tag t, MutableAttributeSet a, int pos )\n        {\n            System.out.println( \"EndTag :\" + t + \":\" + a + \":\" + pos );\n        }\n    }\n\n\n    /**\n     *  Description of the Class\n     *\n     *@author     pims\n     *@created    1 juillet 2004\n     */\n    private class HttpStatusDialog extends BDialog\n    {\n        private BLabel label;\n        private BProgressBar progressBar;\n\n\n        /**\n         *  Constructor for the StatusDialog object\n         */\n        public HttpStatusDialog()\n        {\n            super( SPManagerPlugin.getFrame(), SPMTranslate.text( \"remoteStatus\" ), false );\n            ColumnContainer cc = new ColumnContainer();\n            LayoutInfo layout = new LayoutInfo( LayoutInfo.CENTER, LayoutInfo.NONE, new Insets( 10, 10, 10, 10 ), new Dimension( 0, 0 ) );\n            cc.add( label = SPMTranslate.bLabel( \"status\" ), layout );\n            label.setText( SPMTranslate.text( \"scanningPlugins\" ) );\n            //cc.add( SPMTranslate.bLabel( \"connectedTo\", new String[]{repository.toString()} ) );\n            layout = new LayoutInfo( LayoutInfo.CENTER, LayoutInfo.HORIZONTAL, new Insets( 10, 10, 10, 10 ), new Dimension( 0, 0 ) );\n            cc.add( progressBar = new BProgressBar(), layout );\n            progressBar.setIndeterminate( true );\n            setContent( cc );\n            pack();\n            centerAndSizeWindow();\n            setVisible( true );\n            layoutChildren();\n            addEventLink( WindowClosingEvent.class, this, \"doClose\" );\n        }\n\n\n\n        /**\n         *  Sets the text attribute of the StatusDialog object\n         *\n         *@param  text  The new text value\n         */\n        public void setText( String text )\n        {\n            label.setText( text );\n            layoutChildren();\n        }\n\n\n        /**\n         *  Description of the Method\n         */\n        private void centerAndSizeWindow()\n        {\n\t    UIUtilities.centerDialog(this, (WindowWidget) getParent());\n\n\t    /*\n            Dimension d1 = Toolkit.getDefaultToolkit().getScreenSize();\n            Dimension d2 = getComponent().getSize();\n            int x;\n            int y;\n\n            d2.width = new Long( Math.round( d2.width * 1.3 ) ).intValue();\n            //System.out.println( d1 );\n            x = ( d1.width - d2.width ) / 2;\n            y = ( d1.height - d2.height ) / 2;\n            if ( x < 0 )\n                x = 0;\n            if ( y < 0 )\n                y = 0;\n            setBounds( new Rectangle( x, y, d2.width, d2.height + 2 ) );\n\t    */\n        }\n\n\n        /**\n         *  Description of the Method\n         */\n        private void doClose()\n        {\n            setVisible( false );\n        }\n    }\n}\n\n", "human_rating": 1.4804636, "metadata": {"project": "aoi", "class": "artofillusion.spmanager.HttpSPMFileSystem", "source_path": "aoi/sourcefiles/SPManager/src/artofillusion/spmanager/HttpSPMFileSystem.java", "label_probabilities": {"readability": [0.0, 0.206657, 0.0671503, 0.726192], "understandability": [6.56298e-08, 4.45795e-10, 0.646745, 0.353254], "complexity": [0.336889, 0.663041, 6.99278e-05, 0.0], "modularization": [0.881035, 0.118965, 0.0, 0.0], "overall": [0.0, 8.04034e-05, 0.0173088, 0.982611]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.spmanager.InstallSplitPane", "source": "/*\n *  Copyright 2004 Francois Guillet\n *  This program is free software; you can redistribute it and/or modify it under the\n *  terms of the GNU General Public License as published by the Free Software\n *  Foundation; either version 2 of the License, or (at your option) any later version.\n *  This program is distributed in the hope that it will be useful, but WITHOUT ANY\n *  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n *  PARTICULAR PURPOSE.  See the GNU General Public License for more details.\n */\npackage artofillusion.spmanager;\n\nimport artofillusion.*;\nimport artofillusion.ui.Translate;\nimport artofillusion.ui.UIUtilities;\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.event.*;\nimport javax.swing.tree.*;\nimport buoy.widget.*;\nimport buoy.event.*;\n//import artofillusion.ModellingApp;\nimport java.io.*;\nimport java.util.*;\nimport java.util.zip.*;\nimport java.net.*;\nimport java.text.*;\n\n\n/**\n *  Description of the Class\n *\n *@author     pims\n *@created    20 mars 2004\n */\npublic class InstallSplitPane extends SPMSplitPane\n{\n    private URL repository;\n\n    private BButton installAllButton, installSingleButton, selectAllButton;\n    private BCheckBox selectCB;\n    private boolean setup = false;\n    private boolean unknownHost = false;\n    private StatusDialog status;\n    private long downloadedLength = 0;\n    private long lengthToDownload;\n    private boolean isDownloading;\n    private SPMObjectInfo installNodeInfo;\n\n    protected ArrayList errors=null;\n\n    /**\n     *  Constructor for the InstallSplitPane object\n     *\n     *@param  workMode    Description of the Parameter\n     *@param  repository  Description of the Parameter\n     */\n    public InstallSplitPane( short workMode, URL repository )\n    {\n\tsuper( ( workMode == INSTALL ? \"installScriptsPlugins\" : \"updateScriptsPlugins\" ), workMode );\n\tfs = new HttpSPMFileSystem( repository );\n\tinitialize();\n    }\n\n\n    /**\n     *  Constructor for the InstallSplitPane object\n     *\n     *@param  workMode  Description of the Parameter\n     *@param  fs        Description of the Parameter\n     */\n    public InstallSplitPane( short workMode, SPMFileSystem fs )\n    {\n\tsuper( ( workMode == INSTALL ? \"installScriptsPlugins\" : \"updateScriptsPlugins\" ), workMode );\n\tthis.fs = fs;\n\tinitialize();\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    private void initialize()\n    {\n\t//initialise buttons\n\tLayoutInfo layout = new LayoutInfo( LayoutInfo.CENTER, LayoutInfo.NONE, new Insets( 0, 5, 0, 5 ), new Dimension( 0, 0 ) );\n\tif ( workMode == UPDATE )\n\t{\n\t    buttonRow.add( installAllButton = SPMTranslate.bButton( \"updateAllSelected\", this, \"doInstallAll\" ), layout );\n\t    installAllButton.setIcon( new ImageIcon( getClass().getResource( \"/artofillusion/spmanager/icons/Refresh16.gif\" ) ) );\n\t    //buttonRow.add( installSingleButton = SPMTranslate.bButton( \"updateSingle\", this, \"doInstallSingle\" ), layout );\n\t    //installSingleButton.setIcon( new ImageIcon( getClass().getResource( \"/artofillusion/spmanager/icons/Refresh16.gif\" ) ) );\n\t    buttonRow.add( selectAllButton = SPMTranslate.bButton( \"selectAll\", this, \"doSelectAll\" ), layout );\n\t    //selectAllButton.setIcon( new ImageIcon( getClass().getResource( \"/artofillusion/spmanager/icons/Refresh16.gif\" ) ) );\n\t}\n\telse\n\t{\n\t    buttonRow.add( installAllButton = SPMTranslate.bButton( \"installAllSelected\", this, \"doInstallAll\" ), layout );\n\t    installAllButton.setIcon( new ImageIcon( getClass().getResource( \"/artofillusion/spmanager/icons/Import16.gif\" ) ) );\n\t    //buttonRow.add( installSingleButton = SPMTranslate.bButton( \"installSingle\", this, \"doInstallSingle\" ), layout );\n\t    //installSingleButton.setIcon( new ImageIcon( getClass().getResource( \"/artofillusion/spmanager/icons/Import16.gif\" ) ) );\n\t    buttonRow.add( selectAllButton = SPMTranslate.bButton( \"selectAll\", this, \"doSelectAll\" ), layout );\n\t    //selectAllButton.setIcon( new ImageIcon( getClass().getResource( \"/artofillusion/spmanager/icons/Import16.gif\" ) ) );\n\t}\n\tbuttonRow.add( selectCB = SPMTranslate.bCheckBox( \"selected\", false, this, \"doSelectCB\" ) );\n\t//installSingleButton.setEnabled( false );\n\tselectCB.setEnabled( false );\n\tupdateTree();\n\tmodified = false;\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    protected void updateTree()\n    {\n\tif ( setup )\n\t{\n\t    //get the scripts\n\t    fs.getRemoteInfo(\n\t\t    new Runnable()\n\t\t    {\n\t\t\tpublic void run()\n\t\t\t{\n\t\t\t    doCallbackUpdate();\n\t\t\t}\n\t\t    } );\n\n\t}\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    public void doCallbackUpdate()\n    {\n\tgetPlugins();\n\tgetToolScripts();\n\tgetObjectScripts();\n\tgetStartupScripts();\n\tsetup = true;\n\t( (DefaultTreeModel) tree.getModel() ).reload();\n\tSPManagerFrame.getInstance().checkForUpdatedMe();\n    }\n\n\n    /**\n     *  Pane setup\n     */\n    public void doSetup()\n    {\n\tif ( !setup )\n\t{\n\t    //get the scripts\n\t    fs.getRemoteInfo(\n\t\t    new Runnable()\n\t\t    {\n\t\t\tpublic void run()\n\t\t\t{\n\t\t\t    doCallbackUpdate();\n\t\t\t}\n\t\t    } );\n\t}\n    }\n\n\n    /**\n     *  Gets the plugins attribute of the InstallSplitPane object\n     */\n    private void getPlugins()\n    {\n\tgetFiles( pluginsPath, fs.getPlugins(), getManager().fs.getPlugins() );\n    }\n\n\n    /**\n     *  Gets the toolScripts attribute of the InstallSplitPane object\n     */\n    private void getToolScripts()\n    {\n\tgetFiles( toolScriptsPath, fs.getToolScripts(), getManager().fs.getToolScripts() );\n    }\n\n\n    /**\n     *  Gets the objectScripts attribute of the InstallSplitPane object\n     */\n    private void getObjectScripts()\n    {\n\tgetFiles( objectScriptsPath, fs.getObjectScripts(), getManager().fs.getObjectScripts() );\n    }\n\n\n    /**\n     *  Gets the startupScripts attribute of the InstallSplitPane object\n     */\n    private void getStartupScripts()\n    {\n\tgetFiles( startupScriptsPath, fs.getStartupScripts(), getManager().fs.getStartupScripts() );\n    }\n\n\n    /**\n     *  Gets the files attribute of the InstallSplitPane object\n     *\n     *@param  addTo              Description of the Parameter\n     *@param  infos              Description of the Parameter\n     *@param  managerInfoVector  Description of the Parameter\n     */\n    private void getFiles( TreePath addTo, Vector infos, Vector managerInfoVector )\n    {\n\tDefaultMutableTreeNode tn;\n\tSPMObjectInfo info;\n\tSPMObjectInfo managerInfo;\n\tboolean eligible;\n\tTreeMap map = new TreeMap();\n\n\tfor ( int i = 0; i < infos.size(); i++ )\n\t{\n\t    info = (SPMObjectInfo) infos.elementAt( i );\n\n\t    if (info.restriction >= SPMParameters.HIDE) continue;\n\n\t    {\n\t\t//check if file candidate for update or install\n\t\teligible = ( workMode == INSTALL );\n\t\tmanagerInfo = null;\n\t\tString name = info.getName();\n\t\tfor ( int j = 0; j < managerInfoVector.size(); ++j )\n\t\t{\n\t\t    if ( ( (SPMObjectInfo) managerInfoVector.elementAt( j ) ).getName().equals( name ) )\n\t\t    {\n\t\t\teligible = ( workMode == UPDATE );\n\t\t\tif ( eligible )\n\t\t\t{\n\t\t\t    //check if valid update\n\n\t\t\t    managerInfo = (SPMObjectInfo) managerInfoVector.elementAt( j );\n\t\t\t    System.out.println( info.getName() );\n\t\t\t    System.out.println( \"major distant local :\" + info.getMajor() + \" \" + managerInfo.getMajor() );\n\t\t\t    System.out.println( \"minor distant local :\" + info.getMinor() + \" \" + managerInfo.getMinor() );\n\t\t\t    System.out.println( \"beta distant local :\" + info.isBeta() + \" \" + managerInfo.isBeta() );\n\t\t\t    System.out.println( \"beta distant local :\" + info.getBeta() + \" \" + managerInfo.getBeta() );\n\t\t\t    if ( info.getMajor() < managerInfo.getMajor() )\n\t\t\t    {\n\t\t\t\teligible = false;\n\t\t\t    }\n\t\t\t    else if ( info.getMajor() == managerInfo.getMajor() )\n\t\t\t    {\n\t\t\t\tif ( info.getMinor() < managerInfo.getMinor() )\n\t\t\t\t{\n\t\t\t\t    eligible = false;\n\t\t\t\t}\n\t\t\t\telse if ( info.getMinor() == managerInfo.getMinor() )\n\t\t\t\t{\n\t\t\t\t    if (managerInfo.isBeta()) {\n\t\t\t\t\tif (info.isBeta() && info.getBeta()\n\t\t\t\t\t\t<= managerInfo.getBeta())\n\t\t\t\t\t{\n\t\t\t\t\t    eligible = false;\n\t\t\t\t\t}\n\t\t\t\t    }\n\t\t\t\t    else\n\t\t\t\t    {\n\t\t\t\t\teligible = false;\n\t\t\t\t    }\n\t\t\t\t}\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t}\n\t\tif ( eligible ) {\n\t\t    map.put( info.getName(), info);\n\t\t}\n\t    }\n\t}\n\tCollection col = map.values();\n\tif ( ! col.isEmpty() )\n\t{\n\t    for( Iterator iter = col.iterator(); iter.hasNext(); )\n\t    {\n\t\tinfo = (SPMObjectInfo) iter.next();\n\t\ttn = new DefaultMutableTreeNode( info.getName() );\n\t\ttn.setAllowsChildren( false );\n\t\ttn.setUserObject( info );\n\t\ttree.addNode( addTo, tn );\n\t    }\n\t}\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    public void doInstallAll()\n    {\n\tif ( !isDownloading )\n\t{\n\t    isDownloading = true;\n\t    lengthToDownload = 0;\n\t    downloadedLength = 0;\n\t    lengthToDownload = getInstallLength( pluginsPath );\n\t    lengthToDownload += getInstallLength( toolScriptsPath );\n\t    lengthToDownload += getInstallLength( objectScriptsPath );\n\t    lengthToDownload += getInstallLength( startupScriptsPath );\n\t    if ( lengthToDownload > 0 )\n\t    {\n\t\tstatus = new StatusDialog(SPManagerPlugin.getFrame());\n\t\t(\n\t\t\tnew Thread()\n\t\t\t{\n\t\t\t    public void run()\n\t\t\t    {\n\t\t\t\tinstallAllSelected( pluginsPath );\n\t\t\t\tinstallAllSelected( toolScriptsPath );\n\t\t\t\tinstallAllSelected( objectScriptsPath );\n\t\t\t\tinstallAllSelected( startupScriptsPath );\n\n\t\t\t\ttry {\n\t\t\t\t    SwingUtilities.invokeAndWait(new Runnable() {\n\t\t\t\t\tpublic void run()\n\t\t\t\t\t{\n\t\t\t\t\t    voidSelection();\n\t\t\t\t\t    getManager().doUpdate();\n\t\t\t\t\t    isDownloading = false;\n\t\t\t\t\t    status.dispose();\n\t\t\t\t\t    status = null;\n\t\t\t\t\t    SPManagerUtils.updateAllAoIWindows();\n\t\t\t\t\t}\n\t\t\t\t    });\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t    System.out.println(\"install error: \" + e);\n\t\t\t\t}\n\t\t\t    }\n\t\t\t}).start();\n\t    }\n\t}\n    }\n\n\n    /**\n     *  Gets the installLength attribute of the InstallSplitPane object\n     *\n     *@param  path  Description of the Parameter\n     *@return       The installLength value\n     */\n    private long getInstallLength( TreePath path )\n    {\n\tlong length = 0;\n\tint count = tree.getChildNodeCount( path );\n\tif ( count > 0 )\n\t{\n\t    for ( int j = count - 1; j >= 0; --j )\n\t    {\n\t\tDefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getChildNode( path, j ).getLastPathComponent();\n\t\tSPMObjectInfo nodeInfo = (SPMObjectInfo) node.getUserObject();\n\t\tif ( nodeInfo.isSelected() )\n\t\t{\n\t\t    length += nodeInfo.getTotalLength();\n\t\t}\n\t    }\n\t}\n\treturn length;\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  path  Description of the Parameter\n     */\n    private void installAllSelected( TreePath path )\n    {\n\tint count = tree.getChildNodeCount( path );\n\tif ( count > 0 )\n\t{\n\t    if (errors == null) errors = new ArrayList(128);\n\t    else errors.clear();\n\n\t    boolean ignoreErrs = false;\n\t    int err = 0, cut1, cut2;\n\n\t    download:\n\t\tfor ( int j = count - 1; j >= 0; --j )\n\t\t{\n\t\t    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getChildNode( path, j ).getLastPathComponent();\n\t\t    SPMObjectInfo nodeInfo = (SPMObjectInfo) node.getUserObject();\n\t\t    if ( nodeInfo.isSelected() )\n\t\t    {\n\t\t\t// confirm before proceeding?\n\t\t\t\tif (nodeInfo.restriction == SPMParameters.CONFIRM) {\n\t\t\t\t    String reason = nodeInfo.getComments();\n\t\t\t\t    cut1 = reason.indexOf(\"**\");\n\t\t\t\t    cut2 = reason.indexOf(\"**\", cut1+2);\n\t\t\t\t    if (cut1 >= 0) {\n\t\t\t\t\tif (cut2 <= cut1+2) cut2 = reason.length();\n\t\t\t\t\treason = reason.substring(cut1+2, cut2) + \"\\n\";\n\t\t\t\t    }\n\t\t\t\t    else\n\t\t\t\t\treason = \"\\n\";\n\n\t\t\t\t    reason = SPMTranslate.text(\"markedConfirm\", nodeInfo.getName()) +\n\t\t\t\t    reason + SPMTranslate.text(\"Confirm\");\n\t\t\t\t    if (new BStandardDialog(\"SPManager\", UIUtilities.breakString(reason),\n\t\t\t\t\t    BStandardDialog.QUESTION)\n\t\t\t\t    .showOptionDialog(null, SPManagerFrame.YES_NO, SPManagerFrame.YES_NO[1]) == 1)\n\t\t\t\t    {\n\t\t\t\t\terrors.add(SPMTranslate.text(\"Cancelled\",\n\t\t\t\t\t\tnodeInfo.getName()));\n\n\t\t\t\t\tcontinue;\n\t\t\t\t    }\n\t\t\t\t}\n\n\t\t\t\tinstallFile( nodeInfo );\n\t\t\t\ttree.removeNode( tree.getChildNode( path, j ) );\n\n\t\t\t\tif (errors.size() > err && ignoreErrs == false) {\n\t\t\t\t    BLabel messg = SPMTranslate.bLabel(\"errMsg\");\n\n\t\t\t\t    BStandardDialog dlg = new\n\t\t\t\t    BStandardDialog(\"SPManager\", messg,\n\t\t\t\t\t    BStandardDialog.WARNING);\n\n\t\t\t\t    switch (dlg.showOptionDialog(null, SPManagerFrame.CONTINUE_IGNORE,\n\t\t\t\t\t    SPMTranslate.text(\"Continue\"))) {\n\n\t\t\t\t\t    case 1:\n\t\t\t\t\t\tbreak download;\n\n\t\t\t\t\t    case 2:\n\t\t\t\t\t\tignoreErrs = true;\n\t\t\t\t    }\n\t\t\t\t}\n\n\t\t\t\terr = errors.size();\n\t\t    }\n\t\t}\n\n\t    if (errors.size() > 0) showErrors(errors);\n\t}\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    public void doInstallSingle()\n    {\n\tif (errors == null) errors = new ArrayList(128);\n\telse errors.clear();\n\n\tinstallNodeInfo = getSelectedNodeInfo();\n\tif ( installNodeInfo == null )\n\t{\n\t    return;\n\t}\n\n\t// confirm before proceeding?\n\tif (installNodeInfo.restriction == SPMParameters.CONFIRM) {\n\t    String reason = installNodeInfo.getComments();\n\t    int cut1 = reason.indexOf(\"**\");\n\t    int cut2 = reason.indexOf(\"**\", cut1+2);\n\t    if (cut1 >= 0) {\n\t\tif (cut2 <= cut1+2) cut2 = reason.length();\n\t\treason = reason.substring(cut1+2, cut2) + \"\\n\";\n\t    }\n\t    else\n\t\treason = \"\\n\";\n\n\t    reason = SPMTranslate.text(\"markedConfirm\", installNodeInfo.getName()) +\n\t    reason + SPMTranslate.text(\"Confirm\");\n\t    if (new BStandardDialog(\"SPManager\", UIUtilities.breakString(reason),\n\t\t    BStandardDialog.QUESTION)\n\t    .showOptionDialog(null, SPManagerFrame.YES_NO, SPManagerFrame.YES_NO[1]) == 1)\n\t    {\n\t\terrors.add(SPMTranslate.text(\"Cancelled\",\n\t\t\tinstallNodeInfo.getName()));\n\n\t\tshowErrors(errors);\n\t\treturn;\n\t    }\n\n\t}\n\n\tif ( !isDownloading )\n\t{\n\t    isDownloading = true;\n\t    lengthToDownload = installNodeInfo.getTotalLength();\n\n\t    downloadedLength = 0;\n\t    if ( lengthToDownload > 0 )\n\t    {\n\t\tif (errors == null) errors = new ArrayList(128);\n\t\telse errors.clear();\n\n\t\tstatus = new StatusDialog(SPManagerPlugin.getFrame());\n\t\t(\n\t\t\tnew Thread()\n\t\t\t{\n\t\t\t    public void run()\n\t\t\t    {\n\t\t\t\tinstallFile( installNodeInfo );\n\n\t\t\t\tif (errors.size() > 0) showErrors(errors);\n\n\t\t\t\t//status.dispose();\n\t\t\t\t//SPManagerPlugin.restart();\n\t\t\t\ttry {\n\t\t\t\t    SwingUtilities.invokeAndWait(new Runnable() {\n\t\t\t\t\tpublic void run()\n\t\t\t\t\t{\n\t\t\t\t\t    /*  NTJ - replaced by restart()  */\n\t\t\t\t\t    tree.removeNode(tree.getSelectedNode());\n\t\t\t\t\t    voidSelection();\n\t\t\t\t\t    getManager().doUpdate();\n\t\t\t\t\t    isDownloading = false;\n\t\t\t\t\t    status.dispose();\n\t\t\t\t\t    status = null;\n\t\t\t\t\t    SPManagerUtils.updateAllAoIWindows();\n\t\t\t\t\t}\n\t\t\t\t    });\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t    System.out.println(\"install error: \" + e);\n\t\t\t\t}\n\t\t\t    }\n\t\t\t}).start();\n\t    }\n\t}\n\n\tif (errors.size() > 0) showErrors(errors);\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  nodeInfo  Description of the Parameter\n     */\n    public void installFile( SPMObjectInfo nodeInfo )\n    {\n\tHashMap transaction = new HashMap(32);\n\n\tif (errors == null) errors = new ArrayList(16);\n\tint errCount = errors.size();\n\n\tFile file = null;\n\tswitch ( fs.getInfoType( nodeInfo ) )\n\t{\n\tcase SPMFileSystem.PLUGIN_TYPE:\n\t    file = new File(SPManagerPlugin.PLUGIN_DIRECTORY, nodeInfo.getName() + \".jar\");\n\t    modified = true;\n\t    break;\n\tcase SPMFileSystem.TOOL_SCRIPT_TYPE:\n\t    file = new File(SPManagerPlugin.TOOL_SCRIPT_DIRECTORY, nodeInfo.getName() + \".bsh\");\n\t    break;\n\tcase SPMFileSystem.OBJECT_SCRIPT_TYPE:\n\t    file = new File(SPManagerPlugin.OBJECT_SCRIPT_DIRECTORY, nodeInfo.getName() + \".bsh\");\n\t    break;\n\tcase SPMFileSystem.STARTUP_SCRIPT_TYPE:\n\t    file = new File(SPManagerPlugin.STARTUP_SCRIPT_DIRECTORY, nodeInfo.getName() + \".bsh\");\n\t    break;\n\t}\n\n\tFile folder = new File(SPManagerPlugin.TEMP_DIR,\n\t\tfile.getParentFile().getName());\n\n\tSystem.out.println(\"folder=\" + folder.getAbsolutePath());\n\n\tif (!folder.exists() && !folder.mkdirs()) {\n\t    errors.add(SPMTranslate.text(\"error\") + \"cannot open/create \" +\n\t\t    folder.getAbsolutePath());\n\n\t    System.out.println(\"cannot open/create \" +\n\t\t    folder.getAbsolutePath());\n\t}\n\n\tFile update = new File(folder, file.getName() + \".upd\");\n\n\tSystem.out.println(\"downloading to \" + update.getAbsolutePath());\n\n\tif (status == null)\n\t    status = new StatusDialog(SPManagerPlugin.getFrame());\n\t\n\tstatus.setText( SPMTranslate.text( \"downloading\", nodeInfo.getName() ) );\n\n\tif ( fs.getInfoType( nodeInfo ) == SPMFileSystem.PLUGIN_TYPE )\n\t{\n\t    downloadedLength += HttpSPMFileSystem.downloadRemoteBinaryFile( nodeInfo.httpFile, update.getAbsolutePath(), nodeInfo.length, status, lengthToDownload, downloadedLength, errors );\n\t}\n\telse\n\t{\n\t    downloadedLength += HttpSPMFileSystem.downloadRemoteBinaryFile( nodeInfo.httpFile, update.getAbsolutePath(), nodeInfo.length, status, lengthToDownload, downloadedLength, errors );\n\t}\n\n\ttransaction.put(file, update);\n\n\tif ( nodeInfo.files != null )\n\t{\n\t    String dest;\n\t    int sep;\n\t    for ( int j = 0; j < nodeInfo.files.length; ++j )\n\t    {\n\t\tdest = (String) nodeInfo.destination.get(j);\n\t\tsep = dest.indexOf('/');\n\n\t\t// build the destination path\n\t\tif (sep == 0) {\n\t\t    file = new File(SPManagerPlugin.APP_DIRECTORY, dest.substring(1));\n\t\t}\n\t\telse if (dest.startsWith(\"$\")) {\n\t\t    try {\n\t\t\tfile = new File(SPManagerPlugin.class.getField(dest.substring(1, sep)).get(null).toString(), dest.substring(sep+1));\n\t\t    } catch (Exception e) {\n\t\t\tSystem.out.println(\"SPManager: cannot resolve: \" + dest);\n\t\t\terrors.add(\"Cannot resolve: \" + dest);\n\t\t    }\n\t\t}\n\t\telse {\n\t\t    switch ( fs.getInfoType( nodeInfo ) )\n\t\t    {\n\t\t    case SPMFileSystem.PLUGIN_TYPE:\n\t\t\tfile = new File(SPManagerPlugin.PLUGIN_DIRECTORY, dest);\n\t\t\tbreak;\n\t\t    case SPMFileSystem.TOOL_SCRIPT_TYPE:\n\t\t\tfile = new File(SPManagerPlugin.TOOL_SCRIPT_DIRECTORY, dest);\n\t\t\tbreak;\n\t\t    case SPMFileSystem.OBJECT_SCRIPT_TYPE:\n\t\t\tfile = new File(SPManagerPlugin.OBJECT_SCRIPT_DIRECTORY, dest);\n\t\t\tbreak;\n\t\t    case SPMFileSystem.STARTUP_SCRIPT_TYPE:\n\t\t\tfile = new File(SPManagerPlugin.STARTUP_SCRIPT_DIRECTORY, dest);\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\n\t\t// now add the actual file name\n\t\t//file = new File(file, nodeInfo.files[j]);  NTJ: now added in SPMObjectInfo when XML is parsed\n\n\t\tfolder = new File(SPManagerPlugin.TEMP_DIR,\n\t\t\tfile.getParentFile().getName());\n\n\t\tif (!folder.exists() && !folder.mkdirs()) {\n\t\t    errors.add(SPMTranslate.text(\"error\") +\n\t\t\t    \"cannot open/create \" +\n\t\t\t    folder.getAbsolutePath());\n\n\t\t    System.out.println(\"cannot open/create \" +\n\t\t\t    folder.getAbsolutePath());\n\t\t}\n\n\t\tupdate = new File(folder, file.getName() + \".upd\");\n\n\t\tSystem.out.println(\"downloading to \" +\n\t\t\tupdate.getAbsolutePath());\n\n\t\tif ( status != null )\n\t\t{\n\t\t    status.setText( SPMTranslate.text( \"downloading\", nodeInfo.files[j] ) );\n\t\t}\n\t\t//value = status.getBarValue();\n\t\tURL addFileURL = nodeInfo.getAddFileURL( j );\n\t\tSystem.out.println(\"downloading from \" + addFileURL.toString());\n\t\tdownloadedLength += HttpSPMFileSystem.downloadRemoteBinaryFile( addFileURL, update.getAbsolutePath(), nodeInfo.fileSizes[j], status, lengthToDownload, downloadedLength, errors );\n\n\t\ttransaction.put(file, update);\n\t    }\n\t}\n\n\tFile orig;\n\tMap.Entry entry;\n\tIterator iter = transaction.entrySet().iterator();\n\twhile (iter.hasNext()) {\n\t    try {\n\n\t\tentry = (Map.Entry) iter.next();\n\n\t\torig = (File) entry.getKey();\n\t\tupdate = (File) entry.getValue();\n\n\t\t// if there are errors, just clean up...\n\t\tif (errors.size() > errCount) {\n\n\t\t    if (!update.delete()) {\n\t\t\tSystem.out.println(\"SPManager: tx abort: \" +\n\t\t\t\t\" update file not deleted: \" +\n\t\t\t\tupdate.getAbsolutePath());\n\n\t\t\t// NTJ Happens normally on some Wincrap boxes, so don't\n\t\t\t// display an error\n\t\t\t//errors.add(\"couldn't delete \" +\n\t\t\t//   update.getAbsolutePath());\n\n\t\t\t// make file zero-length\n\t\t\tRandomAccessFile raf =\n\t\t\t    new RandomAccessFile(update, \"rw\");\n\t\t\traf.setLength(0);\n\t\t\traf.close();\n\t\t    }\n\n\t\t    continue;\n\t\t}\n\n\t\tfolder = file.getParentFile();\n\t\tif (!folder.exists() && !folder.mkdirs()) {\n\t\t    throw new RuntimeException(\"cannot open/create \" +\n\t\t\t    folder.getAbsolutePath());\n\t\t}\n\n\t\t// now delete the original, and rename the new file\n\t\tif (orig.exists()) orig.delete();\n\n\t\tSystem.out.println(\"copying file to \" +\n\t\t\torig.getAbsolutePath());\n\n\t\tif (!update.renameTo(orig)) {\n\n\t\t    System.out.println(\"SPManager: old-style copy...\");\n\t\t    if (copyFile(update, orig)) {\n\n\t\t\t// make sure update file really was deleted\n\t\t\tif (!update.delete()) {\n\t\t\t    System.out.println(\"SPManager:\" +\n\t\t\t\t    \" update file not deleted: \" +\n\t\t\t\t    update.getAbsolutePath());\n\n\t\t\t    // NTJ Happens normally on some Wincrap boxes, so don't\n\t\t\t    // display an error\n\t\t\t    //errors.add(\"couldn't delete \" +\n\t\t\t    //   update.getAbsolutePath());\n\n\t\t\t    // make file zero-length\n\t\t\t    RandomAccessFile raf =\n\t\t\t\tnew RandomAccessFile(update, \"rw\");\n\t\t\t    raf.setLength(0);\n\t\t\t    raf.close();\n\t\t\t}\n\t\t    }\n\t\t    else {\n\t\t\tSystem.out.println(\"SPManager.cleanup: \" +\n\t\t\t\t\"could not copy \" + file.getPath());\n\n\t\t\terrors.add(\"couldn't copy \" + file.getName());\n\t\t    }\n\t\t}\n\t    } catch (Exception e) {\n\t\terrors.add(SPMTranslate.text(\"error\") +\n\t\t\t\"(\" + file.getName() + \")\" + e);\n\t    }\n\t}\n\n\t//fs.deleteInfo(nodeInfo);\n    }\n\n\n    /**\n     *  copy one file to another\n     */\n    protected static boolean copyFile(File in, File out)\n    {\n\tInputStream is = null;\n\tOutputStream os = null;\n\ttry {\n\t    is = new BufferedInputStream(new FileInputStream(in));\n\t    os = new BufferedOutputStream(new FileOutputStream(out));\n\n\t    int b;\n\t    while ((b = is.read()) >= 0) os.write((byte) b);\n\t}\n\tcatch (Exception e) {\n\t    return false;\n\t}\n\tfinally {\n\t    try {\n\t\tos.flush();\n\t\tos.close();\n\t\tis.close();\n\t    } catch (Exception e) {}\n\t}\n\n\treturn true;\n    }\n\n    /**\n     *  Description of the Method\n     *\n     *@param  path  Description of the Parameter\n     */\n    private void selectAllInfos( TreePath path )\n    {\n\tSPMObjectInfo info;\n\tint count = tree.getChildNodeCount( path );\n\tfor ( int j = 0; j < count; ++j )\n\t{\n\t    DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getChildNode( path, j ).getLastPathComponent();\n\t    SPMObjectInfo nodeInfo = (SPMObjectInfo) node.getUserObject();\n\t    nodeInfo.setSelected( true );\n\n\t    if (extMap != null) extMap.clear();\n\t    selectExternals(nodeInfo);\n\t}\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    public void doSelectAll()\n    {\n\tselectAllInfos( pluginsPath );\n\tselectAllInfos( toolScriptsPath );\n\tselectAllInfos( objectScriptsPath );\n\tselectAllInfos( startupScriptsPath );\n\tSPMObjectInfo nodeInfo = getSelectedNodeInfo();\n\tif ( nodeInfo != null )\n\t{\n\t    selectCB.setState( true );\n\t}\n\trepaint();\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    public void doSelectCB()\n    {\n\tSPMObjectInfo nodeInfo = getSelectedNodeInfo();\n\tif ( nodeInfo != null )\n\t{\n\t    nodeInfo.setSelected( selectCB.getState() );\n\n\t    if (extMap != null) extMap.clear();\n\t    selectExternals(nodeInfo);\n\t}\n\trepaint();\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  info  Description of the Parameter\n     */\n    protected void notifyObjectInfoSelection( SPMObjectInfo info )\n    {\n\tselectCB.removeEventLink( ValueChangedEvent.class, this );\n\tselectCB.setState( info.isSelected() );\n\tselectCB.addEventLink( ValueChangedEvent.class, this, \"doSelectCB\" );\n\n\tsuper.notifyObjectInfoSelection(info);\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  deletable  Description of the Parameter\n     */\n    public void scriptSelection( boolean deletable )\n    {\n\t//Button.setEnabled( true );\n\tselectCB.setEnabled( true );\n\tSPMObjectInfo nodeInfo = getSelectedNodeInfo();\n\tif ( nodeInfo != null )\n\t{\n\t    selectCB.setState( nodeInfo.isSelected() );\n\n\t    // disable select and install controls if item is restricted\n\t    if (nodeInfo.restriction >= SPMParameters.DISABLE) {\n\t\tselectCB.setEnabled(false);\n\t\t//installSingleButton.setEnabled(false);\n\t    }\n\n\t    // disable select control if item has references\n\t    if (nodeInfo.refcount > 0) selectCB.setEnabled(false);\n\n\t    // disable install single if script has dependents\n\t    Collection externals = nodeInfo.getExternals();\n\t    //if (externals != null && externals.size() > 0)\n\t    //installSingleButton.setEnabled(false);\n\t}\n\tsuper.scriptSelection( deletable );\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  deletable  Description of the Parameter\n     */\n    public void pluginSelection( boolean deletable )\n    {\n\t//installSingleButton.setEnabled( true );\n\tselectCB.setEnabled( true );\n\tSPMObjectInfo nodeInfo = getSelectedNodeInfo();\n\tif ( nodeInfo != null )\n\t{\n\t    selectCB.setState( nodeInfo.isSelected() );\n\n\t    //System.out.println(\"externals =\" +\n\t    //\t       (nodeInfo.getExternals() != null\n\t    //\t\t? nodeInfo.getExternals().size()\n\t    //\t\t: 0));\n\n\t    // disable select and install controls if item is restricted\n\t    if (nodeInfo.restriction >= SPMParameters.DISABLE) {\n\t\tselectCB.setEnabled(false);\n\t\t//installSingleButton.setEnabled(false);\n\t    }\n\n\t    // disable select control if item has references\n\t    if (nodeInfo.refcount > 0) selectCB.setEnabled(false);\n\n\t    // disable install single if plugin has dependents\n\t    Collection externals = nodeInfo.getExternals();\n\t    //if (externals != null && externals.size() > 0)\n\t    //installSingleButton.setEnabled(false);\n\t}\n\tsuper.pluginSelection( deletable );\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    public void voidSelection()\n    {\n\t//installSingleButton.setEnabled( false );\n\tselectCB.setEnabled( false );\n\tsuper.voidSelection();\n    }\n\n\n    /**\n     *  Sets the repository attribute of the InstallSplitPane object\n     *\n     *@param  newRep  The new repository value\n     */\n    public void setRepository( URL newRep )\n    {\n\trepository = newRep;\n\tfs = new HttpSPMFileSystem( newRep );\n\tdoSetup();\n    }\n\n    public void showErrors()\n    { if (errors != null && errors.size() > 0) showErrors(errors); }\n    \n    /**\n     *  show errors in a panel\n     */\n    public static void showErrors(ArrayList errs)\n    {\n\tBTextArea txt = new BTextArea(5, 45);\n\ttxt.setEditable(false);\n\ttxt.setWrapStyle(BTextArea.WRAP_WORD);\n\n\tfor (int i = 0; i < errs.size(); i++)\n\t    txt.append(errs.get(i) + \"\\n\");\n\n\tBScrollPane detail =\n\t    new BScrollPane(txt, BScrollPane.SCROLLBAR_NEVER,\n\t\t    BScrollPane.SCROLLBAR_AS_NEEDED);\n\n\tBLabel messg = SPMTranslate.bLabel(\"errMsg\");\n\n\tnew BStandardDialog(\"SPManager\",\n\t\tnew Widget[] { messg, detail },\n\t\tBStandardDialog.WARNING)\n\t.showMessageDialog(null);\n    }\n\n}\n\n", "human_rating": 2.9816154000897095, "metadata": {"project": "aoi", "class": "artofillusion.spmanager.InstallSplitPane", "source_path": "aoi/sourcefiles/SPManager/src/artofillusion/spmanager/InstallSplitPane.java", "label_probabilities": {"readability": [1.10711e-13, 0.981615, 0.0183852, 8.92666e-11], "understandability": [8.96383e-12, 2.83889e-05, 2.64908e-05, 0.999945], "complexity": [0.139633, 0.860179, 0.000187046, 8.23304e-07], "modularization": [0.982942, 0.0170576, 6.42679e-13, 0.0], "overall": [8.13e-18, 2.39375e-05, 0.936614, 0.0633621]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.spmanager.SPManagerPlugin", "source": "\n/*\n *  Copyright 2004 Francois Guillet\n *  This program is free software; you can redistribute it and/or modify it under the\n *  terms of the GNU General Public License as published by the Free Software\n *  Foundation; either version 2 of the License, or (at your option) any later version.\n *  This program is distributed in the hope that it will be useful, but WITHOUT ANY\n *  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n *  PARTICULAR PURPOSE.  See the GNU General Public License for more details.\n */\npackage artofillusion.spmanager;\n\nimport artofillusion.*;\nimport artofillusion.util.SearchlistClassLoader;\nimport artofillusion.ui.*;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport buoy.event.*;\nimport buoy.widget.*;\n\nimport java.util.*;\nimport java.io.*;\nimport java.net.*;\nimport java.lang.reflect.*;\n\n/**\n *  The Plugin corresponding to the SPManager\n *\n *@author     Francois Guillet\n *@created    20 march 2004\n */\npublic class SPManagerPlugin implements Plugin\n{\n    public static String AOI_VERSION;\n    public static String UNIQUE_PATH;\n    public static String TEMP_DIR;\n    public static String APP_DIRECTORY;\n    public static String PLUGIN_DIRECTORY;\n    public static String TOOL_SCRIPT_DIRECTORY;\n    public static String OBJECT_SCRIPT_DIRECTORY;\n    public static String STARTUP_SCRIPT_DIRECTORY;\n\n    public static final int DOWNLOAD = -1;\n\n    private static SPManagerFrame spmFrame;\n\n    protected static HashMap plugins;\n    \n    /**\n     *  Description of the Method\n     *\n     *@param  message  Description of the Parameter\n     *@param  args     Description of the Parameter\n     */\n    public void processMessage( int message, Object args[] )\n    {\n\t// NTJ: get the AOI run-time (*not* compile-time) version\n\tif (AOI_VERSION == null) {\n\t    AOI_VERSION = ArtOfIllusion.getMajorVersion();\n\t    System.setProperty(\"artofillusion.version\", ArtOfIllusion.getVersion());\n\t    System.setProperty(\"artofillusion.version.major\", ArtOfIllusion.getMajorVersion());\n\t}\n\n\tswitch (message) {\n\tcase Plugin.APPLICATION_STARTING:\n\t    SPMTranslate.setLocale(ArtOfIllusion.getPreferences().getLocale());\n\n\t    APP_DIRECTORY = ArtOfIllusion.APP_DIRECTORY;\n\t    PLUGIN_DIRECTORY = ArtOfIllusion.PLUGIN_DIRECTORY;\n\t    TOOL_SCRIPT_DIRECTORY = ArtOfIllusion.TOOL_SCRIPT_DIRECTORY;\n\t    OBJECT_SCRIPT_DIRECTORY = ArtOfIllusion.OBJECT_SCRIPT_DIRECTORY;\n\t    STARTUP_SCRIPT_DIRECTORY = ArtOfIllusion.STARTUP_SCRIPT_DIRECTORY;\n\n\t    System.out.println(\"SPManager starting...\");\n\n\t    // get details of plugin classloaders\n\t    int i, j, idx;\n\t    URL urlList[];\n\t    ArrayList aoiloaders;\n\t    ClassLoader ldr = null;\n\t    URLClassLoader urlldr = null;\n\t    SearchlistClassLoader searchldr = null;\n\t    Object obj;\n\n\t    java.util.List list = PluginRegistry.getPluginClassLoaders();\n\t    HashMap loaders = new HashMap(list.size());\n\t    for (i = 0; i < list.size(); i++) {\n\t\tobj = list.get(i);\n\t\tif (obj instanceof URLClassLoader)\n\t\t    urlList = ((URLClassLoader) obj).getURLs();\n\t\telse\n\t\t    urlList = ((SearchlistClassLoader) obj).getURLs();\n\n\t\tif (urlList.length > 0)\n\t\t    loaders.put(urlList[0], obj);\n\t    }\n\n\t    /*\n\t    try {\n\t\tField ldrfield =\n\t\t    PluginRegistry.class.getDeclaredField(\"pluginLoaders\");\n\n\t\tldrfield.setAccessible(true);\n\n\t\taoiloaders = (ArrayList) ldrfield.get(null);\n\n\t    } catch (Exception e) {\n\t\tSystem.out.println(\"SPManager: cannot get pluginsLoaders: \" +\n\t\t\t\t   e);\n\t\taoiloaders = new ArrayList();\n\t    }\n\t     */\n\n\t    URL[] urlarg = new URL[1];\n\t    Class[] sig = new Class[] { URL.class };\n\t    Method addUrl = null;\n\n\t    try {\n\t\taddUrl =\n\t\t    URLClassLoader.class.getDeclaredMethod(\"addURL\", sig);\n\t\taddUrl.setAccessible(true);\n\t    } catch (Exception e) {\n\t\tSystem.out.println(\"Error getting addURL method: \" + e);\n\t    }\n\n\t    // get details of all local plugins\n\t    SPMObjectInfo info;\n\t    StringBuffer errs = null;\n\t    Class plugType;\n\t    File files[], urlfile;\n\t    URL url;\n\t    Map.Entry entry;\n\t    String key[], value;\n\t    File plugdir = new File(PLUGIN_DIRECTORY);\n\t    if (plugdir.exists()) {\n\t\tfiles = plugdir.listFiles();\n\t\tfor (i = 0; i < files.length; i++) {\n\t\t    info = new SPMObjectInfo(files[i].getAbsolutePath());\n\n\t\t    if (info.invalid) {\n\t\t\tif (errs == null) errs = new StringBuffer(1024);\n\t\t\tif (errs.length() > 0) errs.append('\\n');\n\t\t\terrs.append(SPMTranslate.text(\"pluginFailure\",\n\t\t\t\tinfo.getName()));\n\t\t    }\n\n\t\t    if (info.actions != null && info.actions.size() > 0) {\n\n\t\t\ttry {\n\t\t\t    url = files[i].toURI().toURL();\n\t\t\t} catch (Exception e) {\n\t\t\t    continue;\n\t\t\t}\n\n\t\t\t//System.out.println(\"SPM: url=\" + url);\n\n\t\t\t// get the classloader for the current plugin\n\t\t\tobj = loaders.get(url);\n\n\t\t\tif (obj == null) {\n\t\t\t    System.out.println(\"SPManager: could not find\"\n\t\t\t\t    + \" classloader: \"\n\t\t\t\t    + files[i].getPath());\n\t\t\t    continue;\n\t\t\t}\n\n\t\t\t// cast or convert it to a SearchlistClassLoader\n\t\t\tif (obj instanceof SearchlistClassLoader) {\n\t\t\t    searchldr = (SearchlistClassLoader) obj;\n\t\t\t    //System.out.println(\"loader is a srchloader\");\n\t\t\t}\n\t\t\telse {\n\t\t\t    urlldr = (URLClassLoader) obj;\n\n\t\t\t    /*\n\t\t\t    searchldr =\n\t\t\t\tnew SearchlistClassLoader((ClassLoader) obj);\n\n\t\t\t    idx = aoiloaders.indexOf(obj);\n\t\t\t    if (idx >= 0) aoiloaders.set(idx, searchldr);\n\t\t\t    else System.out.println(\"SPM: loader not in list\");\n\n\t\t\t    loaders.put(url, searchldr);\n\t\t\t     */\n\t\t\t}\n\n\t\t\t// ok, now perform the actions\n\t\t\tfor (Iterator iter = info.actions.entrySet().iterator();\n\t\t\titer.hasNext(); ) {\n\n\t\t\t    entry = (Map.Entry) iter.next();\n\t\t\t    key = entry.getKey().toString().split(\":\");\n\n\t\t\t    //System.out.println(\"SPM: action=\" +\n\t\t\t    //\t       entry.getValue().toString());\n\n\t\t\t    try {\n\t\t\t\tif (key[0].startsWith(\"/\"))\n\t\t\t\t    urlfile = new File(APP_DIRECTORY, key[0].substring(1));\n\t\t\t\telse\n\t\t\t\t    urlfile = new File(plugdir, key[0]);\n\t\t\t\t\n\t\t\t\turl = urlfile.toURI().toURL();\n\t\t\t    } catch (Exception e) {\n\t\t\t\tSystem.out.println(\"Error making url: \" + e);\n\t\t\t\tcontinue;\n\t\t\t    }\n\n\t\t\t    System.out.println(\"SPM: adding path: \" + url);\n\n\t\t\t    value = entry.getValue().toString();\n\n\t\t\t    /*\n\t\t\t    if (\"merge\".equalsIgnoreCase(value)) {\n\t\t\t\tif (searchldr != null)\n\t\t\t\t    searchldr.merge(url);\n\t\t\t\telse if (addUrl != null) {\n\t\t\t\t    try {\n\t\t\t\t\turlarg[0] = url;\n\t\t\t\t\taddUrl.invoke(urlldr, urlarg);\n\t\t\t\t    } catch (Exception e) {\n\t\t\t\t\tSystem.out.println(\"Error invoking: \"\n\t\t\t\t\t\t\t   + e);\n\t\t\t\t    }\n\t\t\t\t}\n\t\t\t\telse System.out.println(\"Could not merge path\"\n\t\t\t\t\t\t\t+ url);\t\t\t\t    \n\t\t\t    }\n\t\t\t     */\n\t\t\t    if (\"classpath\".equalsIgnoreCase(value)) {\n\t\t\t\tif (searchldr != null)\n\t\t\t\t    searchldr.add(url);\n\t\t\t\telse if (addUrl != null) {\n\t\t\t\t    try {\n\t\t\t\t\t//urlarg[0] = url;\n\t\t\t\t\t//addUrl.invoke(urlldr, urlarg);        // non-varargs call (1.4)\n\t\t\t\t\taddUrl.invoke(urlldr, url);\t\t// varargs call (1.5)\n\t\t\t\t    } catch (Exception e) {\n\t\t\t\t\tSystem.out.println(\"Error invoking: \"\n\t\t\t\t\t\t+ e);\n\t\t\t\t    }\n\t\t\t\t}\n\t\t\t\telse System.out.println(\"Could not add path\" +\n\t\t\t\t\turl);\t\t\t\t    \n\t\t\t    }\n\t\t\t    else if (\"import\".equalsIgnoreCase(value)) {\n\t\t\t\tldr = (ClassLoader) loaders.get(url);\n\t\t\t\t\n\t\t\t\tif (key.length == 1) {\n\t\t\t\t    if (obj != null) searchldr.add(ldr);\n\t\t\t\t    else System.out.println(\"SPM: could not find\"\n\t\t\t\t\t    + \" loader for: \" + url);\n\t\t\t\t}\n\t\t\t\t/*\n\t\t\t\t * NTJ - disabled. No longer needed, and requires a new method in SearchlistClassLoader\n\t\t\t\t * \n\t\t\t\telse {\n\t\t\t\t    System.out.println(\"SPM: importing: \" + key[1]);\n\t\t\t\t    if (searchldr != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t    searchldr.add(ldr.loadClass(key[1]));\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t    System.out.println(\"SPM: Error importing class: \" + key[1] + \" into \" + url);\n\t\t\t\t\t}\n\t\t\t\t    }\n\t\t\t\t    else {\n\t\t\t\t\tSystem.out.println(\"SPM: Error: Class cannot be imported without a SearchListClassLoader: \" + url\n\t\t\t\t\t\t+ \"(\" + key[1] + \")\");\n\t\t\t\t    }\n\t\t\t\t}\n\t\t\t\t*/\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\t\t}\n\n\t\tif (errs != null) {\n\t\t    BTextArea txt = new BTextArea(5, 45);\n\t\t    txt.setEditable(false);\n\n\t\t    txt.append(errs.toString());\n\n\t\t    BScrollPane detail =\n\t\t\tnew BScrollPane(txt, BScrollPane.SCROLLBAR_NEVER,\n\t\t\t\tBScrollPane.SCROLLBAR_AS_NEEDED);\n\n\t\t    BLabel messg = SPMTranslate.bLabel(\"loadError\");\n\n\t\t    new BStandardDialog(\"SPManager initialise\",\n\t\t\t    new Widget[] { messg, detail },\n\t\t\t    BStandardDialog.ERROR)\n\t\t    .showMessageDialog(null);\n\t\t}\n\t    }\n\t    else System.out.println(\"SPManager: could not find plugin dir: \" +\n\t\t    PLUGIN_DIRECTORY);\n\n\n\t    init();\n\t    break;\n\n\tcase Plugin.SCENE_WINDOW_CREATED:\n\t{\n\t    LayoutWindow layout = (LayoutWindow) args[0];\n\t    //BMenuBar menuBar = layout.getMenuBar();\n\t    //BMenu toolsMenu = menuBar.getChild( 3 );\n\t    BMenu toolsMenu = layout.getToolsMenu();\n\t    toolsMenu.addSeparator();\n\t    BMenuItem menuItem =\n\t\tSPMTranslate.bMenuItem( \"SPManager\", this, \"doMenu\" );\n\n\t    toolsMenu.add( menuItem );\n\t}\n\tbreak;\n\n\tcase APPLICATION_STOPPING:\n\t    \n\t    break;\n\t    \n\tcase DOWNLOAD:\n\t{\n\t    System.out.println(\"DOWNLOAD...\");\n\n\t    BFrame frame = (BFrame) args[0];\n\t    URL from = (URL) args[1];\n\t    URL to = (URL) (args.length > 2 ? args[2] : null);\n\n\t    download(frame, from, to);\n\t}\n\tbreak;\n\n\tdefault:\n\t    //System.out.println(\"SPManagerPlugin: ignoringmessage: \" + message);\n\t}\n    }\n\n    /**\n     *  initialise the plugin\n     */\n    public void init()\n    {\n\n\tArrayList err = new ArrayList(8);\n\n\tSystem.out.println(\"SPManager: java temp dir is \" +\n\t\tSystem.getProperty(\"java.io.tmpdir\"));\n\n\t// try system TEMP directory\n\tFile temp = new File(System.getProperty(\"java.io.tmpdir\"));\n\n\t// try 'temp' in AOI installation directory\n\tif (! ((temp.exists() && temp.isDirectory()) || temp.mkdir())) {\n\t    System.out.println(\"SPManager: could not open/create temp dir: \" +\n\t\t    temp.getAbsolutePath());\n\n\t    temp = new File(APP_DIRECTORY, \"temp\");\n\t}\n\n\t// try 'SPtemp' in user's home directory\n\tif (! ((temp.exists() && temp.isDirectory()) || temp.mkdir())) {\n\t    System.out.println(\"Cannot create temp folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\t    temp = new File(System.getProperty(\"user.dir\"), \"SPMtemp\");\n\t}\n\n\tif (! ((temp.exists() && temp.isDirectory()) || temp.mkdir())) {\n\t    err.add(\"Cannot create temp folder: \" +\n\t\t    temp.getAbsolutePath());\n\t}\n\n\tif (!temp.canWrite())\n\t    err.add(\"Write permission denied to temp folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\t// create temporary private sub-tree\n\tString path;\n\tFile t = null;\n\ttry {\n\t    t = File.createTempFile(\"spmanager-temp-\"\n\t\t    + System.getProperty(\"user.name\") + \"-\", \".lck\", temp);\n\t    t.deleteOnExit();\n\t    path= t.getName();\n\t    path = path.substring(0, path.length()- \".lck\".length());\n\t} catch (Exception e) {\n\t    // failed to create temp file, use fallback naming algorithm\n\t    System.out.println(\"SPManager: could not create temp file: \" +\n\t\t    t.getAbsolutePath() + e);\n\n\t    path = System.getProperty(\"user.name\") + \"-\"\n\t    \t+ String.valueOf(System.currentTimeMillis());\n\t}\n\t\n\ttemp = new File(temp, path);\n\n\tif (! ((temp.exists() && temp.isDirectory()) || temp.mkdir())) {\n\t    err.add(\"Cannot create temp folder: \" +\n\t\t    temp.getAbsolutePath());\n\t}\n\n\tif (!temp.canWrite())\n\t    err.add(\"Write permission denied to temp folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\tTEMP_DIR = temp.getAbsolutePath();\n\n\tSystem.out.println(\"SPManager: temp dir set to: \" +\n\t\ttemp.getAbsolutePath());\n\n\t// make sure all temp directories are created\n\tFile subfolder = new File(PLUGIN_DIRECTORY);\n\ttemp = new File(TEMP_DIR, subfolder.getName());\n\tif (!temp.exists() && !temp.mkdirs())\n\t    err.add(\"Cannot create temp plugin folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\tsubfolder = new File(TOOL_SCRIPT_DIRECTORY);\n\ttemp = new File(TEMP_DIR, subfolder.getName());\n\tif (!temp.exists() && !temp.mkdirs())\n\t    err.add(\"Cannot create temp script folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\tsubfolder = new File(OBJECT_SCRIPT_DIRECTORY);\n\ttemp = new File(TEMP_DIR, subfolder.getName());\n\tif (!temp.exists() && !temp.mkdirs())\n\t    err.add(\"Cannot create temp script folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\tsubfolder = new File(STARTUP_SCRIPT_DIRECTORY);\n\ttemp = new File(TEMP_DIR, subfolder.getName());\n\tif (!temp.exists() && !temp.mkdirs ())\n\t    err.add(\"Cannot create temp script folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\t// make sure all live directories exist\n\ttemp = new File(PLUGIN_DIRECTORY);\n\tif (!temp.exists() && !temp.mkdir())\n\t    err.add(\"Cannot create missing plugin folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\ttemp = new File(TOOL_SCRIPT_DIRECTORY);\n\tif (!temp.exists() && !temp.mkdirs())\n\t    err.add(\"Cannot create missing script folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\ttemp = new File(OBJECT_SCRIPT_DIRECTORY);\n\tif (!temp.exists() && !temp.mkdirs())\n\t    err.add(\"Cannot create missing script folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\ttemp = new File(STARTUP_SCRIPT_DIRECTORY);\n\tif (!temp.exists() && !temp.mkdirs ())\n\t    err.add(\"Cannot create missing script folder: \" +\n\t\t    temp.getAbsolutePath());\n\n\n\tif (err.size() > 0) {\n\t    BTextArea txt = new BTextArea(5, 45);\n\t    txt.setEditable(false);\n\n\t    for (int i = 0; i < err.size(); i++)\n\t\ttxt.append(err.get(i) + \"\\n\");\n\n\t    BScrollPane detail =\n\t\tnew BScrollPane(txt, BScrollPane.SCROLLBAR_NEVER,\n\t\t\tBScrollPane.SCROLLBAR_AS_NEEDED);\n\n\t    BLabel messg = SPMTranslate.bLabel(\"errMsg\");\n\n\t    new BStandardDialog(\"SPManager initialise\",\n\t\t    new Widget[] { messg, detail },\n\t\t    BStandardDialog.WARNING)\n\t    .showMessageDialog(null);\n\t}\n    }\n\n    public void registerResource(String type, String id, ClassLoader loader,\n\t    String baseName, Locale locale)\n    {\n\tString suffix = \"\";\n\n\tif (locale.getLanguage().length() > 0)\n\t    suffix += \"_\" + locale.getLanguage();\n\tif (locale.getCountry().length() > 0)\n\t    suffix += \"_\" + locale.getCountry();\n\tif (locale.getVariant().length() > 0)\n\t    suffix += \"_\" + locale.getVariant();\n\n\tURL url;\n\tint cut;\n\n\tfor (int i = 0; i < 3; i++) {\n\t    try {\n\t\turl = loader.getResource(baseName + suffix + \".properties\");\n\n\t\tif (url != null) {\n\t\t    PluginRegistry.registerResource(type, id, loader,\n\t\t\t    url.getPath(), locale);\n\t\t    break;\n\t\t}\n\t    } catch (Exception e) {}\n\n\t    // can we remove part of the suffix?\n\t    cut = suffix.lastIndexOf('_');\n\t    if (cut > 0) suffix = suffix.substring(0, cut);\n\t    else break;\n\t}\n    }\n\n    public void download(BFrame frame, URL from)\n    { download(frame, from, null); }\n\n    /**\n     *  download (and install if possible) the specified file(set).\n     */\n    public void download(BFrame frame, URL from, URL to)\n    {\n\tfinal BFrame context = frame;\n\tfinal URL url = from;\n\tfinal URL toUrl = to;\n\n\tfinal StatusDialog status = new StatusDialog(context) {\n\t    SPMObjectInfo info;\n\t    BLabel size;\n\t    BButton okbtn;\n\t    String filename, name;\n\t    ColumnContainer col;\n\t    RowContainer buttons;\n\t    BTextField savePath;\n\t    Thread worker;\n\n\t    public void setVisible(boolean vis)\n\t    {\n\t\tif (!vis) {\n\t\t    super.setVisible(vis);\n\t\t    return;\n\t\t}\n\n\t\tcol = (ColumnContainer) getContent();\n\n\t\tfilename = url.getFile();\n\t\tint cut = filename.lastIndexOf('/');\n\t\tif (cut > 0 && cut < filename.length())\n\t\t    filename = filename.substring(cut+1);\n\n\t\tcut = filename.lastIndexOf('?');\n\t\tif (cut > 0)\n\t\t    filename = filename.substring(0, cut);\n\n\t\tname = new String(filename);\n\t\tcut = name.lastIndexOf('.');\n\t\tif (cut > 0) name = name.substring(0, cut);\n\n\t\tsetText(name);\n\t\tsetProgressText(SPMTranslate.text(\"clickStart\"));\n\n\t\tokbtn = SPMTranslate.bButton(\"start\", this, \"ok\");\n\n\t\tbuttons = new RowContainer();\n\t\tbuttons.add(okbtn);\n\t\tbuttons.add(SPMTranslate.bButton(\"cancel\", this, \"close\"));\n\n\t\tokbtn.setActionCommand(\"ok\");\n\n\t\tcol.add(buttons);\n\t\tpack();\n\t\tsuper.setVisible(true);\n\t    }\n\n\t    public void close()\n\t    {\n\t\tif (worker != null) worker.interrupt();\n\t\tdoClose();\n\t    }\n\n\t    public void ok(CommandEvent ev)\n\t    {\n\t\tString cmd = ev.getActionCommand();\n\t\tokbtn.setEnabled(false);\n\n\t\tfinal BButton okbut = okbtn;\n\n\t\tfinal StatusDialog stat = this;\n\n\t\tif (cmd.equals(\"ok\")) {\n\n\t\t    setProgressText(SPMTranslate.text(\"contacting\"));\n\t\t    setIdle(true);\n\n\t\t    System.out.println(\"DOWNLOAD: creating ObjectInfo...\"+\n\t\t\t    url.toString());\n\t\t    worker = new Thread() {\n\t\t\tpublic void run()\n\t\t\t{\n\t\t\t    info = new SPMObjectInfo(url);\n\t\t\t    if (info.length == 0) {\n\t\t\t\tSystem.out.println(\"DOWNLOAD: no info\");\n\t\t\t\tinfo.length = info.getRemoteFileSize(url.toString());\n\t\t\t    }\n\n\t\t\t    /* NTJ: don't give up yet...\n\t\t\t     *\n\t\t\t\t    if (info.length < 0) {\n\t\t\t\t\tnew BStandardDialog(\"SPManager\", SPMTranslate.text(\"httpError\"), BStandardDialog.ERROR).showMessageDialog(null);\n\n\t\t\t\t\tdoClose();\n\t\t\t\t    }\n\t\t\t     */\n\n\t\t\t    // get destination if needed\n\t\t\t    if (info.name == null\n\t\t\t\t    || info.name.length() == 0) {\n\n\t\t\t\tSystem.out.println(\"need path...\");\n\n\t\t\t\tRowContainer row = new RowContainer();\n\t\t\t\trow.add(SPMTranslate.bLabel(\"savePath\"));\n\t\t\t\tsavePath = new BTextField(\"\", 25);\n\t\t\t\tsavePath.addEventLink(ValueChangedEvent.class, this, \"savePath\");\n\t\t\t\trow.add(savePath);\n\t\t\t\trow.add(SPMTranslate.bButton(\"browse\",\n\t\t\t\t\tthis,\n\t\t\t\t\"browse\"));\n\t\t\t\tcol.remove(buttons);\n\t\t\t\tcol.add(row);\n\t\t\t\tcol.add(buttons);\n\t\t\t\tpack();\n\t\t\t    }\n\n\t\t\t    long total = info.getTotalLength();\n\n\t\t\t    String sz = (total > 1000000\n\t\t\t\t    ? \" \" +\n\t\t\t\t\t    (total/1000000)\n\t\t\t\t\t    + \" MB\"\n\t\t\t\t\t    : total > 1000\n\t\t\t\t\t    ? \" \" + (total/1000)\n\t\t\t\t\t\t    + \" kB\"\n\t\t\t\t\t\t    : (total > 0)\n\t\t\t\t\t\t    ? \" \" + total\n\t\t\t\t\t\t\t    + \" bytes\"\n\t\t\t\t\t\t\t    : \"\");\n\n\t\t\t    setText(info.getName() + \" \" + sz);\n\t\t\t    setIdle(false);\n\t\t\t    setProgressText(SPMTranslate.text(\"ready\"));\n\n\t\t\t    okbut.setActionCommand(\"install\");\n\t\t\t    okbut.setText(SPMTranslate.text(\"install\"));\n\t\t\t    okbut.setEnabled(true);\n\t\t\t    pack();\n\t\t\t}\n\n\t\t\tpublic void savePath()\n\t\t\t{\n\t\t\t    String val = savePath.getText();\n\t\t\t    okbtn.setEnabled(val != null && val.length() > 0);\n\t\t\t}\n\n\t\t\tpublic void browse()\n\t\t\t{\n\t\t\t    BFileChooser fc = new\n\t\t\t    BFileChooser(BFileChooser.SAVE_FILE,\n\t\t\t\t    Translate.text(\"savePath\"));\n\n\t\t\t    File file = null;\n\t\t\t    String path = null;\n\t\t\t    String fname = savePath.getText();\n\n\t\t\t    if (fname == null || fname.length() == 0) {\n\t\t\t\tpath = System.getProperty(\"user.home\");\n\t\t\t\tfname = filename;\n\t\t\t    }\n\n\t\t\t    if (fname != null) {\n\t\t\t\tif (path != null)\n\t\t\t\t    file = new File(path, fname);\n\t\t\t\telse\n\t\t\t\t    file = new File(fname);\n\n\t\t\t\tfc.setDirectory(file.getParentFile());\n\t\t\t\tfc.setSelectedFile(file);\n\t\t\t    }\n\t\t\t    else fc.setDirectory(new File(path));\n\n\t\t\t    if (fc.showDialog(context)) {\n\t\t\t\tsavePath.setText(fc.getSelectedFile().getAbsolutePath());\n\t\t\t    }\n\t\t\t}\n\n\t\t    };\n\n\t\t    worker.start();\n\n\t\t}\n\t\telse if (cmd.equals(\"install\")) {\n\t\t    System.out.println(\"DOWNLOAD: downloading \" +\n\t\t\t    url.toString());\n\n\t\t    setText(SPMTranslate.text(\"downloading\", info.getName()));\n\t\t    pack();\n\n\t\t    final ArrayList errs = new ArrayList();\n\t\t    worker = new Thread() {\n\t\t\tpublic void run()\n\t\t\t{\n\t\t\t    long total = info.getTotalLength();\n\n\t\t\t    // full save path\n\t\t\t    String path = null;\n\t\t\t    if (savePath != null)\n\t\t\t\tpath = savePath.getText();\n\n\t\t\t    else if (info.name != null)\n\t\t\t\tpath = ArtOfIllusion.PLUGIN_DIRECTORY + File.separatorChar + info.name + \".jar\";\n\n\n\t\t\t    if (path == null || path.length() == 0) {\n\t\t\t\tSystem.out.println(\"DOWNLOAD: no save location\");\n\t\t\t\tnew BStandardDialog(\"SPManager\", SPMTranslate.text(\"noSaveLocation\"), BStandardDialog.ERROR).showMessageDialog(null);\n\n\t\t\t\tdoClose();\n\t\t\t    }\n\n\t\t\t    System.out.println(\"DOWNLOAD: downloading file...\");\n\t\t\t    if (total > 0)\n\t\t\t\tsetBarValue(total > 0 ? 0 : -1);\n\n\t\t\t    long dl = HttpSPMFileSystem\n\t\t\t    .downloadRemoteBinaryFile(url, path, info.length, stat, total, 0, errs);\n\n\t\t\t    for (int i = 0; info.files != null && i < info.files.length; i++) {\n\t\t\t\tif (worker.interrupted()) {\n\t\t\t\t    doClose();\n\t\t\t\t    return;\n\t\t\t\t}\n\n\t\t\t\tname = PLUGIN_DIRECTORY + File.separatorChar + info.destination.get(i) + info.files[i];\n\n\t\t\t\tsetText(SPMTranslate.text(\"downloading\", info.files[i]));\n\t\t\t\tpack();\n\n\t\t\t\tdl += HttpSPMFileSystem\n\t\t\t\t.downloadRemoteBinaryFile(info.getAddFileURL(i), name, info.fileSizes[i], stat, total, dl, errs);\n\t\t\t    }\n\n\t\t\t    if (errs != null && errs.size() > 0)\n\t\t\t\tInstallSplitPane.showErrors(errs);\n\t\t\t    else\n\t\t\t\tnew BStandardDialog(\"SPManager\", SPMTranslate.text(\"modified\"), BStandardDialog.ERROR).showMessageDialog(null);\n\n\t\t\t    System.out.println(\"DOWNLOAD: done\");\n\t\t\t    doClose();\n\t\t\t}\n\t\t    };\n\n\t\t    worker.start();\n\t\t}\n\t\telse System.out.println(\"?? cmd=\" + cmd);\n\t    }\n\t};\n    }\n\n    /**\n     *  Description of the Method\n     */\n    public void doMenu()\n    {\n\t// NTJ: don't implement yet... (Nov 2006)\n\t//if (!Translate.getLocale().equals(Locale.getDefault())) {\n\t//}\n\n\tif ( spmFrame == null )\n\t    spmFrame = new SPManagerFrame();\n\t( (Window) spmFrame.getComponent() ).toFront();\n\t//spmFrame.layoutChildren();\n\t( (Window) spmFrame.getComponent() ).show();\n\t//spmFrame.printBounds( spmFrame );\n    }\n\n\n    /**\n     *  restart the plugin\n     */\n    public static void restart()\n    {\n\tSPManagerFrame old = spmFrame;\n\n\tspmFrame = new SPManagerFrame();\n\t((Window) spmFrame.getComponent()).toFront();\n\t((Window) spmFrame.getComponent()).show();\n\n\told.dispose();\n    }\n\n    /**\n     *  close the frame\n     */\n    public void close()\n    {\n\tif (spmFrame != null) {\n\t    spmFrame.setVisible(false);\n\t    spmFrame.dispose();\n\t}\n    }\n\n\n    /**\n     *  Gets the name attribute of the SPManagerPlugin object\n     *\n     *@return    The name value\n     */\n    public String getName()\n    {\n\treturn \"Script and Plugin Manager\";\n    }\n\n\n    /**\n     *  Gets the frame attribute of the SPManagerPlugin class\n     *\n     *@return    The frame value\n     */\n    public static SPManagerFrame getFrame()\n    {\n\treturn spmFrame;\n    }\n\n    /**\n     *  update an already-loaded plugin\n     */\n    public static void updatePlugin(String name, String action, String target)\n    {\n\n    }\n\n    /**\n     *  main routine so SPManager can be run standalone\n     */\n    public static void main(String[] argv)\n    {\n\tchar slash = File.separatorChar;\n\n\tAPP_DIRECTORY = System.getProperty(\"user.dir\");\n\ttry {\n\t    URL url = SPManagerPlugin.class\n\t    .getResource(\"/artofillusion/spmanager/SPManagerPlugin.class\");\n\n\t    System.out.println(\"SPManager.main: url=\" + url);\n\n\t    System.out.println(\"SPManager.main: path=\" + url.getPath());\n\n\t    String furl = url.getPath();\n\t    if (furl.indexOf('!') < 0) furl = url.toString();\n\n\t    int cut = furl.indexOf('!');\n\n\t    if (cut > 0) {\n\n\t\tfurl = furl.substring(0, cut);\n\n\t\tcut = furl.indexOf(\"jar:\");\n\t\tif (cut >= 0)\n\t\t    furl = furl.substring(cut+\"jar:\".length());\n\n\t\tif (!furl.startsWith(\"file:\")) furl = \"file:\" + furl;\n\n\t\tSystem.out.println(\"SPManager.main: furl=\" + furl);\n\n\t\tFile dir = new File(new URL(furl).getPath()).getParentFile()\n\t\t.getParentFile();\n\n\t\tSystem.out.println(\"SPManager.main: dir=\" +\n\t\t\tdir.getAbsolutePath());\n\n\t\tif (dir.exists())\n\t\t    APP_DIRECTORY = dir.getAbsolutePath();\n\t\telse\n\t\t    APP_DIRECTORY = System.getProperty(\"user.dir\");\n\n\t\tSystem.out.println(\"SPManager.main: app_dir=\" + APP_DIRECTORY);\n\t    }\n\t}\n\tcatch (Exception ex) {\n\t    System.out.println(\"Error looking up app_dir: \" + ex);\n\t}\n\n\tSPMTranslate.setLocale(Locale.getDefault());\n\n\tPLUGIN_DIRECTORY = APP_DIRECTORY + slash + \"Plugins\";\n\tTOOL_SCRIPT_DIRECTORY = APP_DIRECTORY + slash + \"Scripts\" + slash + \"Tools\";\n\tOBJECT_SCRIPT_DIRECTORY = APP_DIRECTORY + slash + \"Scripts\" + slash + \"Objects\";\n\tSTARTUP_SCRIPT_DIRECTORY = APP_DIRECTORY + slash + \"Scripts\" + slash + \"Startup\";\n\n\tSPManagerPlugin spm = new SPManagerPlugin();\n\tspm.init();\n\n\t// create Frame with overridden 'close' method\n\tspmFrame = new SPManagerFrame() {\n\t    protected void hideSPManager()\n\t    {\n\t\tsetVisible(false);\n\t\tdispose();\n\t    }\n\t};\n\n\tspm.doMenu();\n    }\n}\n\n", "human_rating": 2.01416464, "metadata": {"project": "aoi", "class": "artofillusion.spmanager.SPManagerPlugin", "source_path": "aoi/sourcefiles/SPManager/src/artofillusion/spmanager/SPManagerPlugin.java", "label_probabilities": {"readability": [0.0, 0.0163848, 0.981395, 0.00222024], "understandability": [3.09275e-10, 0.00021811, 0.999159, 0.000623198], "complexity": [0.839472, 0.160528, 1e-20, 0.0], "modularization": [0.609967, 0.390033, 4.63151e-11, 0.0], "overall": [0.0, 2.14389e-05, 0.863959, 0.13602]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.spmanager.SPManagerUtils", "source": "/*\n *  This class implements utilities\n */\n/*\n *  Copyright (C) 2003 by Francois Guillet\n *  This program is free software; you can redistribute it and/or modify it under the\n *  terms of the GNU General Public License as published by the Free Software\n *  Foundation; either version 2 of the License, or (at your option) any later version.\n *  This program is distributed in the hope that it will be useful, but WITHOUT ANY\n *  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n *  PARTICULAR PURPOSE.  See the GNU General Public License for more details.\n */\npackage artofillusion.spmanager;\n\nimport java.awt.*;\nimport javax.swing.*;\nimport javax.xml.parsers.DocumentBuilderFactory;\nimport javax.xml.parsers.DocumentBuilder;\nimport javax.xml.parsers.ParserConfigurationException;\nimport org.w3c.dom.*;\nimport java.io.*;\nimport java.util.zip.*;\nimport artofillusion.*;\nimport artofillusion.ui.*;\n\n/**\n *  Description of the Class\n *\n *@author     pims\n *@created    6 juillet 2004\n */\npublic class SPManagerUtils\n{\n    public static DocumentBuilderFactory factory;\n    public static DocumentBuilder builder;\n\n    static {\n        factory = DocumentBuilderFactory.newInstance();\n        try\n        {\n            builder = factory.newDocumentBuilder();\n        }\n        catch (ParserConfigurationException ex)\n        {\n            ex.printStackTrace();\n        }\n    }\n\n    /**\n     *  Description of the Method\n     *\n     *@param  intArray  Description of the Parameter\n     *@return           Description of the Return Value\n     */\n    public static int[] increaseIntArray( int[] intArray )\n    {\n        if ( intArray == null )\n        {\n            int[] tmpArray = new int[1];\n            return tmpArray;\n        }\n        else\n        {\n            int[] tmpArray = new int[intArray.length + 1];\n            System.arraycopy( intArray, 0, tmpArray, 0, intArray.length );\n            return tmpArray;\n        }\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  intArray  Description of the Parameter\n     *@param  element   Description of the Parameter\n     *@return           Description of the Return Value\n     */\n    public static int[] deleteIntArrayElement( int[] intArray, int element )\n    {\n        if ( intArray == null )\n            return null;\n        else if ( intArray.length == 1 )\n            return null;\n        else\n        {\n            int[] tmpArray = new int[intArray.length - 1];\n            if ( element > 0 )\n                System.arraycopy( intArray, 0, tmpArray, 0, element );\n            if ( element < intArray.length - 1 )\n                System.arraycopy( intArray, element + 1, tmpArray, element, tmpArray.length - element );\n            int i;\n            return tmpArray;\n        }\n    }\n\n\n    /**\n     *  Sets the dialogLocation attribute of the SPManagerUtils class\n     *\n     *@param  frame        The new dialogLocation value\n     *@param  parentFrame  The new dialogLocation value\n     */\n    public static void setDialogLocation( JFrame frame, JFrame parentFrame )\n    {\n        Point location = new Point();\n        location.x = parentFrame.getLocation().x + parentFrame.getWidth() / 2 - frame.getWidth() / 2;\n        location.y = parentFrame.getLocation().y + parentFrame.getHeight() / 2 - frame.getHeight() / 2;\n        if ( location.x < 0 )\n            location.x = 0;\n        if ( location.y < 0 )\n            location.y = 0;\n        frame.setLocation( location );\n    }\n\n\n    /**\n     *  Description of the Method\n     */\n    public static void updateAllAoIWindows()\n    {\n\ttry {\n\t    EditingWindow allWindows[] = ArtOfIllusion.getWindows();\n\t    for ( int i = 0; i < allWindows.length; i++ )\n\t\tif ( allWindows[i] instanceof LayoutWindow )\n\t\t    ( (LayoutWindow) allWindows[i] ).rebuildScriptsMenu();\n\t} catch (Throwable t) {}\n    }\n\n\n    /**\n     *  Gets the jarFileContent attribute of the SPManagerUtils class\n     *\n     *@param  filename  Description of the Parameter\n     *@return           The jarFileContent value\n     */\n    public static byte[] getJarFileContent( String filename )\n    {\n        File dir = new File( SPManagerPlugin.PLUGIN_DIRECTORY );\n        if ( dir.exists() )\n        {\n            String[] files = dir.list();\n            for ( int i = 0; i < files.length; i++ )\n                if ( files[i].startsWith( \"SPManager\" ) )\n                {\n                    ZipFile zf = null;\n                    try\n                    {\n                        zf = new ZipFile( new File( dir, files[i] ) );\n                    }\n                    catch ( IOException ex )\n                    {\n                        continue;\n                        // Not a zip file.\n                    }\n                    if ( zf != null )\n                    {\n                        ZipEntry ze = zf.getEntry( filename );\n                        if ( ze != null )\n                        {\n                            int size = (int) ze.getSize();\n                            byte data[] = new byte[size];\n                            try\n                            {\n                                BufferedInputStream in = new BufferedInputStream( zf.getInputStream( ze ) );\n                                for ( int j = 0; j < size; j++ )\n                                    data[j] = (byte) in.read();\n                                in.close();\n                            }\n                            catch ( IOException ex )\n                            {\n                                System.out.println( \"IOException in getJarFileContent\" );\n                            }\n                            return data;\n                        }\n                        else\n                            System.out.println( \"File \" + filename + \" not found within zip file\" );\n                    }\n                }\n        }\n        else\n        {\n            System.out.println( \"Dir does not exist\" );\n        }\n        return null;\n    }\n\n\n    /**\n     *  Gets the jarFileContent attribute of the SPManagerUtils class\n     *\n     *@param  jarPath   Description of the Parameter\n     *@param  filename  Description of the Parameter\n     *@return           The jarFileContent value\n     */\n    public static byte[] getJarFileContent( String jarPath, String filename )\n    {\n        ZipFile zf = null;\n        try\n        {\n            zf = new ZipFile( new File( jarPath ) );\n        }\n        catch ( IOException ex )\n        {\n            return null;\n            // Not a zip file.\n        }\n        if ( zf != null )\n        {\n            ZipEntry ze = zf.getEntry( filename );\n            if ( ze != null )\n            {\n                int size = (int) ze.getSize();\n                byte data[] = new byte[size];\n                try\n                {\n                    BufferedInputStream in = new BufferedInputStream( zf.getInputStream( ze ) );\n                    for ( int j = 0; j < size; j++ )\n                        data[j] = (byte) in.read();\n                    in.close();\n                }\n                catch ( IOException ex )\n                {\n                    System.out.println( \"IOException in getJarFileContent\" );\n                }\n                return data;\n            }\n            else\n                System.out.println( \"File \" + filename + \" not found within zip file\" );\n        }\n        return null;\n    }\n\n    /**\n     *  Gets a named node from a node list. Returns null if the node does not\n     *  exist.\n     *\n     *@param  nl        The node list\n     *@param  nodeName  The node name\n     *@return           The node named nodeName\n     */\n    public static Node getNodeFromNodeList( NodeList nl, String nodeName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t  int index )\n    {\n        for ( int i = 0; i < nl.getLength(); ++i )\n        {\n            Node n = nl.item( i );\n            if ( n.getNodeName().equals( nodeName ) )\n            {\n                if (index-- == 0) return n;\n            }\n        }\n        return null;\n    }\n\n    /**\n     *  Gets a named attribute value from a node\n     *\n     *@param  name  The attribute name\n     *@param  node  Description of the Parameter\n     *@return       The attribute value\n     */\n    public static String getAttribute( Node node, String name )\n    {\n        NamedNodeMap nm = node.getAttributes();\n        if ( nm == null )\n            return null;\n        Node nn = nm.getNamedItem( name );\n        if ( nn == null )\n            return null;\n        return nn.getNodeValue();\n    }\n\n\n    /**\n     *  Gets a value from a named child node\n     *\n     *@param  name  The child node name\n     *@param  node  The node\n     *@return       The attribute value\n     */\n    public static String getNodeValue( Node node, String name,\n\t\t\t\t\t\t\t\t\t\t\t\t\tString defaultVal, int index)\n    {\n        NodeList nl = node.getChildNodes();\n        if ( nl.getLength() == 0 ) return defaultVal;\n\n        Node n = getNodeFromNodeList( nl, name, index );\n        if ( n == null ) return defaultVal;\n\n\tn = n.getChildNodes().item(0);\n\tif (n == null) return defaultVal;\n\n        String value = n.getNodeValue();\n        if (value == null) value = defaultVal;\n\n        return value;\n    }\n\n    /**\n     *  method to parse digits into an int\n     */\n    public static int parseInt(String val, int start, int max)\n\tthrows NumberFormatException\n    {\n\tif (val == null || val.length() <= start) return 0;\n\n\tif (max < 0 || max > val.length()) max = val.length();\n\n\tchar c;\n\n\t// throw exception if the value cannot be a number\n\tc = val.charAt(start);\n\tif (! (Character.isDigit(c) || \"+-\".indexOf(c) >= 0))\n\t    throw new NumberFormatException(val);\n\n\tint result = 0;\n\tfor (int i = start; i < max; i++) {\n\t    c = val.charAt(i);\n\t    if (Character.isDigit(c))\n\t\tresult = (result*10) + Character.digit(c, 10);\n\t    else break;\n\t}\n\n\treturn result;\n    }\n\n    /**\n     *  parse a double value from a String.\n     *\n     *  The string is parsed from the first (zeroeth) char up to the first\n     *  char which is not valid in a double representation\n     *  (ie digit, '.', 'e', 'E', '+', or '-').\n     */\n    public static double parseDouble(String val)\n\tthrows NumberFormatException\n    {\n\tif (val == null || val.length() == 0) return 0;\n\n\tchar c;\n\n\t// throw exception if the value cannot be a number\n\tc = val.charAt(0);\n\tif (! (Character.isDigit(c) || \"+-.\".indexOf(c) >= 0))\n\t    throw new NumberFormatException(val);\n\n\tlong result = 0;\n\tlong frac = 0;\n\tint exp = 0;\n\tboolean mantissa = true;\n\tint sign = 1, esign = 1;\n\n\tint max = val.length();\n\tfor (int i = 0; i < max; i++) {\n\t    c = val.charAt(i);\n\n\t    if (result == 0 && (c == '-' || c == '+'))\n\t\tsign = (c == '-' ? -1 : 1);\n\t    else if (frac == 0 && c == '.')\n\t\tfrac = 1;\n\t    else if (mantissa == true && (c == 'e' || c == 'E'))\n\t\tmantissa = false;\n\t    else if (Character.isDigit(c)) {\n\t\tif (mantissa) {\n\t\t    result = (result*10) + Character.digit(c, 10);\n\n\t\t    if (frac > 0) frac *= 10;\n\t\t    System.out.println(\"test: c=\" + c + \"; frac=\" + frac);\n\t\t}\n\t\telse {\n\t\t    if (exp == 0 && (c == '-' || c == '+'))\n\t\t\tesign = (c == '-' ? -1 : 1);\n\t\t    else\n\t\t\texp = (exp*10) + Character.digit(c, 10);\n\t\t}\n\t    }\n\t    else\n\t\tbreak;\n\t}\n\n\tif (frac == 0) frac = 1;\n\n\tSystem.out.println(\"parseDouble: esign:\" + esign + \"; exp:\" + exp\n\t\t\t   + \"; sign:\" + sign + \"; result:\" + result\n\t\t\t   + \"; frac:\" + frac);\n\n\treturn (Math.pow(10.0, esign * exp) * sign * result)/frac;\n    }\n\n    /**\n     *  parse a version string into a numeric value.\n     *\n     *  Each component is parsed as an int and scaled into a 3-digit\n     *  column.\n     *<br>Eg 1.2 is parsed into 1002; 1.20 is parsed into 1020; and 1.20.3\n     *  is parsed into 1020003\n     *\n     */\n    public static long parseVersion(String val)\n\tthrows NumberFormatException\n    {\n\tlong result = parseInt(val, 0, -1);\n\n\tint pos = 0;\n\twhile ((pos = val.indexOf('.', pos)) >= 0) {\n\t    result = (result*1000) + parseInt(val, pos+1, -1);\n\t    pos++;\n\t}\n\n\treturn result;\n    }\n}\n\n", "human_rating": 2.006932037, "metadata": {"project": "aoi", "class": "artofillusion.spmanager.SPManagerUtils", "source_path": "aoi/sourcefiles/SPManager/src/artofillusion/spmanager/SPManagerUtils.java", "label_probabilities": {"readability": [0.0, 0.00788651, 0.991159, 0.000954507], "understandability": [2.0344e-12, 0.998858, 0.00114228, 0.0], "complexity": [0.0, 0.842427, 0.155819, 0.00175383], "modularization": [0.0, 1.0, 0.0, 0.0], "overall": [0.0, 0.0, 1.0, 5.36855e-09]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.spmanager.SPMFileSystem", "source": "/* Copyright 2004 Francois Guillet\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. \n*/\n\npackage artofillusion.spmanager;\n\nimport java.util.Vector;\nimport artofillusion.*;\n\npublic class SPMFileSystem\n{   \n    protected Vector pluginsInfo, toolInfo, objectInfo, startupInfo;\n    protected boolean initialized;\n    \n    public final static short PLUGIN_TYPE = 0;\n    public final static short TOOL_SCRIPT_TYPE = 1;\n    public final static short OBJECT_SCRIPT_TYPE = 2;\n    public final static short STARTUP_SCRIPT_TYPE = 3;\n    \n    public SPMFileSystem()\n    {\n        pluginsInfo = new Vector();\n        toolInfo = new Vector();\n        objectInfo = new Vector();\n        startupInfo = new Vector();\n        initialized = false;\n    }\n    \n    public short getInfoType(SPMObjectInfo info)\n    {\n        for (int i = 0; i < pluginsInfo.size(); ++i)\n            if (info == pluginsInfo.elementAt(i)) return PLUGIN_TYPE;\n        for (int i = 0; i < toolInfo.size(); ++i)\n            if (info == toolInfo.elementAt(i)) return TOOL_SCRIPT_TYPE;\n        for (int i = 0; i < objectInfo.size(); ++i)\n            if (info == objectInfo.elementAt(i)) return OBJECT_SCRIPT_TYPE;\n        for (int i = 0; i < startupInfo.size(); ++i)\n            if (info == startupInfo.elementAt(i)) return STARTUP_SCRIPT_TYPE;\n        return PLUGIN_TYPE;\n    }\n    \n    public void deleteInfo(SPMObjectInfo info)\n    {\n        pluginsInfo.remove(info);\n        toolInfo.remove(info);\n        objectInfo.remove(info);\n        startupInfo.remove(info);\n    }\n    \n    public void downloadRemoteFile(SPMObjectInfo nodeInfo, String fileName)\n    {\n        System.out.println(\"Download request for a non able SPMFileSystem\");\n    }\n    \n    public void initialize()\n    {\n        pluginsInfo.clear();\n        toolInfo.clear();\n        objectInfo.clear();\n        startupInfo.clear();\n    }\n    \n    public Vector getPlugins()\n    {\n        if (!initialized) initialize();\n        return pluginsInfo;\n    }\n    \n    public Vector getToolScripts()\n    {\n        if (!initialized) initialize();\n        return toolInfo;\n    }\n    \n    public Vector getObjectScripts()\n    {\n        if (!initialized) initialize();\n        return objectInfo;\n    }\n    \n    public Vector getStartupScripts()\n    {\n        if (!initialized) initialize();\n        return startupInfo;\n    }\n    \n    public void getRemoteInfo(Runnable cb)\n    {\n        if (!initialized) initialize();\n    }\n}\n", "human_rating": 3.84406442663479, "metadata": {"project": "aoi", "class": "artofillusion.spmanager.SPMFileSystem", "source_path": "aoi/sourcefiles/SPManager/src/artofillusion/spmanager/SPMFileSystem.java", "label_probabilities": {"readability": [0.844074, 0.155915, 1.17127e-05, 1.23479e-09], "understandability": [0.480279, 0.516873, 0.0028481, 1.79189e-08], "complexity": [4.59832e-15, 2.97e-05, 0.300961, 0.699009], "modularization": [2.209e-17, 6.29103e-05, 0.0339099, 0.966027], "overall": [0.000148382, 0.971835, 0.028017, 2.03086e-13]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.spmanager.SPMTranslate", "source": "/*\n *  Copyright (C) 2003 by Francois Guillet\n *  Copyright (C) 2003 by Peter Eastman for original Translate.java code\n *  This program is free software; you can redistribute it and/or modify it under the\n *  terms of the GNU General Public License as published by the Free Software\n *  Foundation; either version 2 of the License, or (at your option) any later version.\n *  This program is distributed in the hope that it will be useful, but WITHOUT ANY\n *  WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n *  PARTICULAR PURPOSE.  See the GNU General Public License for more details.\n */\npackage artofillusion.spmanager;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\nimport javax.swing.event.*;\nimport java.text.*;\nimport java.util.*;\nimport java.util.zip.*;\nimport buoy.event.*;\nimport buoy.widget.*;\n//import artofillusion.ui.*;\nimport artofillusion.*;\nimport java.io.*;\n\n/**\n *  This class extends AoI Translate Class so that i) the spmanager properties\n *  file is used instead of AoI properties file ii) buoy objects are returned\n *\n *@author     pims\n *@created    27 mai 2004\n */\n\npublic class SPMTranslate\n{\n    private static Locale locale = Locale.getDefault();\n    private static ResourceBundle resources;\n\n\n    /**\n     *  Set the locale to be used for generating text.\n     *\n     *@param  l  The new locale value\n     */\n\n    public static void setLocale( Locale l )\n    {\n        locale = l;\n/*\n        File dir = new File( ModellingApp.PLUGIN_DIRECTORY );\n        if ( dir.exists() )\n        {\n            String[] files = dir.list();\n            for ( int i = 0; i < files.length; i++ )\n                if ( files[i].startsWith( \"SPManager\" ) )\n                {\n                    ZipFile zf = null;\n                    try\n                    {\n                        zf = new ZipFile( new File( ModellingApp.PLUGIN_DIRECTORY, files[i] ) );\n                    }\n                    catch ( IOException ex )\n                    {\n                        continue;\n                        // Not a zip file.\n                    }\n                    if ( zf != null )\n                    {\n                        JarClassLoader jcl = new JarClassLoader( zf );\n                        resources = ResourceBundle.getBundle( \"spmanager\", locale, jcl );\n                    }\n                }\n        }\n        else\n        {\n            System.out.println( \"Dir does not exist\" );\n        }*/\n        resources = ResourceBundle.getBundle(\"spmanager\", locale);\n    }\n\n\n    /**\n     *  Get the locale currently used for generating text.\n     *\n     *@return    The locale value\n     */\n\n    public static Locale getLocale()\n    {\n        return locale;\n    }\n\n\n    /**\n     *  Get a Menu whose text is given by the property \"menu.(name)\".\n     *\n     *@param  name  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n\n    public static BMenu bMenu( String name )\n    {\n        try\n        {\n            return new BMenu( resources.getString( \"menu.\" + name ) );\n        }\n        catch ( MissingResourceException ex )\n        {\n            return new BMenu( name );\n        }\n    }\n\n\n    /**\n     *  Get a BMenuItem whose text is given by the property \"menu.(name)\". This\n     *  checks for a property called \"menu.shortcut.(name)\", and if it is found,\n     *  sets the menu shortcut accordingly. No event link is added.\n     *\n     *@param  name  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n\n    public static BMenuItem bMenuItem( String name )\n    {\n        return bMenuItem( name, null, null, null );\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  name    Description of the Parameter\n     *@param  target  Description of the Parameter\n     *@param  method  Description of the Parameter\n     *@return         Description of the Return Value\n     */\n    public static BMenuItem bMenuItem( String name, java.lang.Object target, String method )\n    {\n        return bMenuItem( name, CommandEvent.class, target, method );\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  name       Description of the Parameter\n     *@param  eventType  Description of the Parameter\n     *@param  target     Description of the Parameter\n     *@param  method     Description of the Parameter\n     *@return            Description of the Return Value\n     */\n    public static BMenuItem bMenuItem( String name, java.lang.Class eventType, java.lang.Object target, String method )\n    {\n        String command = name;\n        BMenuItem item = null;\n        try\n        {\n            command = resources.getString( \"menu.\" + name );\n            String shortcut = resources.getString( \"menu.\" + name + \".shortcut\" );\n            if ( shortcut.length() > 1 && shortcut.charAt( 0 ) == '^' )\n                item = new BMenuItem( command, new Shortcut( shortcut.charAt( 1 ), Shortcut.SHIFT_MASK | Shortcut.DEFAULT_MASK ) );\n            else if ( shortcut.length() > 0 )\n                item = new BMenuItem( command, new Shortcut( shortcut.charAt( 0 ) ) );\n        }\n        catch ( MissingResourceException ex )\n        {\n            item = new BMenuItem( command );\n        }\n        if ( eventType != null )\n            item.addEventLink( eventType, target, method );\n        return item;\n    }\n\n\n    /**\n     *  Get a BCheckboxMenuItem whose text is given by the property\n     *  \"checkbox.(name)\". State specifies the initial state of the item.\n     *\n     *@param  name   Description of the Parameter\n     *@param  state  Description of the Parameter\n     *@return        Description of the Return Value\n     */\n\n    public static BCheckBoxMenuItem bCheckBoxMenuItem( String name, boolean state )\n    {\n        String command = name;\n        try\n        {\n            command = resources.getString( \"menu.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        BCheckBoxMenuItem item = new BCheckBoxMenuItem( command, state );\n        return item;\n    }\n\n\n    /**\n     *  Get a BButton whose text is given by the property \"button.(name)\".\n     *\n     *@param  name  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n\n    public static BButton bButton( String name )\n    {\n        return bButton( name, null, null, null );\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  name    Description of the Parameter\n     *@param  target  Description of the Parameter\n     *@param  method  Description of the Parameter\n     *@return         Description of the Return Value\n     */\n    public static BButton bButton( String name, java.lang.Object target, String method )\n    {\n        return bButton( name, CommandEvent.class, target, method );\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  name       Description of the Parameter\n     *@param  eventType  Description of the Parameter\n     *@param  target     Description of the Parameter\n     *@param  method     Description of the Parameter\n     *@return            Description of the Return Value\n     */\n    public static BButton bButton( String name, java.lang.Class eventType, Object target, String method )\n    {\n        String command = name;\n        try\n        {\n            command = resources.getString( \"button.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        BButton button = new BButton( command );\n        if ( eventType != null )\n            button.addEventLink( eventType, target, method );\n        return button;\n    }\n\n\n    /**\n     *  Get a BRadioButton whose text is given by the property \"radio.(name)\".\n     *  group is the RadioButtonGroup the radio button created button will\n     *  belong to.\n     *\n     *@param  name   Description of the Parameter\n     *@param  state  Description of the Parameter\n     *@param  group  Description of the Parameter\n     *@return        Description of the Return Value\n     */\n\n    public static BRadioButton bRadioButton( String name, boolean state, RadioButtonGroup group )\n    {\n        return bRadioButton( name, state, group, null, null );\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  name    Description of the Parameter\n     *@param  state   Description of the Parameter\n     *@param  group   Description of the Parameter\n     *@param  target  Description of the Parameter\n     *@param  method  Description of the Parameter\n     *@return         Description of the Return Value\n     */\n    public static BRadioButton bRadioButton( String name, boolean state, RadioButtonGroup group, Object target, String method )\n    {\n        String command = name;\n        try\n        {\n            command = resources.getString( \"radio.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        BRadioButton radio = new BRadioButton( command, state, group );\n        //radio.setText(command);\n        //radio.setState(state);\n        if ( target != null )\n            group.addEventLink( SelectionChangedEvent.class, target, method );\n        return radio;\n    }\n\n\n    /**\n     *  These functions are for compatibility with the AWT preview window\n     *\n     *@param  name      Description of the Parameter\n     *@param  listener  Description of the Parameter\n     *@return           Description of the Return Value\n     */\n\n    public static Button button( String name, ActionListener listener )\n    {\n        return button( name, null, listener );\n    }\n\n\n    /**\n     *  These functions are for compatibility with the AWT preview window\n     *\n     *@param  name      Description of the Parameter\n     *@param  suffix    Description of the Parameter\n     *@param  listener  Description of the Parameter\n     *@return           Description of the Return Value\n     */\n    public static Button button( String name, String suffix, ActionListener listener )\n    {\n        String command = name;\n        try\n        {\n            command = resources.getString( \"button.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        if ( suffix != null )\n            command += suffix;\n        Button b = new Button( command );\n        if ( listener != null )\n        {\n            b.setActionCommand( name );\n            b.addActionListener( listener );\n        }\n        return b;\n    }\n\n\n    /**\n     *  returns a BCheckBox whose label is given by the property\n     *  \"checkbox.name\". state is the initial state of the checkbox\n     *\n     *@param  name   Description of the Parameter\n     *@param  state  Description of the Parameter\n     *@return        Description of the Return Value\n     */\n    public static BCheckBox bCheckBox( String name, boolean state )\n    {\n        return bCheckBox( name, state, null, null );\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  name    Description of the Parameter\n     *@param  state   Description of the Parameter\n     *@param  target  Description of the Parameter\n     *@param  method  Description of the Parameter\n     *@return         Description of the Return Value\n     */\n    public static BCheckBox bCheckBox( String name, boolean state, Object target, String method )\n    {\n        String command = name;\n        try\n        {\n            command = resources.getString( \"checkbox.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        BCheckBox b = new BCheckBox( command, state );\n        if ( target != null )\n            b.addEventLink( ValueChangedEvent.class, target, method );\n        return b;\n    }\n\n\n    /**\n     *  Get a Label whose text is given by the property \"label.name\". If the\n     *  property is not found, this simply uses name.\n     *\n     *@param  name  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n    public static BLabel bLabel( String name )\n    {\n        return bLabel( name, null );\n    }\n\n\n    /**\n     *  Description of the Method\n     *\n     *@param  name  Description of the Parameter\n     *@param  args  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n    public static BLabel bLabel( String name, Object[] args )\n    {\n        try\n        {\n            name = resources.getString( \"label.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        if ( args != null )\n        {\n            return new BLabel( MessageFormat.format( name, args ) );\n        }\n        return new BLabel( name );\n    }\n\n\n    /**\n     *  Get the text given by the property \"name\". If the property is not found,\n     *  this simply returns name.\n     *\n     *@param  name  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n\n    public static String text( String name )\n    {\n        try\n        {\n            return resources.getString( \"text.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n            return name;\n        }\n    }\n\n\n    /**\n     *  Get the text given by the property \"name\". If the property is not found,\n     *  this simply uses name. Any occurrance of the pattern \"{0}\" in the text\n     *  string will be replaced with the string representation of arg1.\n     *\n     *@param  name  Description of the Parameter\n     *@param  arg1  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n\n    public static String text( String name, Object arg1 )\n    {\n        String pattern = name;\n        try\n        {\n            pattern = resources.getString( \"text.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        return MessageFormat.format( pattern, new Object[]{arg1} );\n    }\n\n\n    /**\n     *  Get the text given by the property \"name\". If the property is not found,\n     *  this simply uses name. Any occurrances of the patterns \"{0}\" and \"{1}\"\n     *  in the text string will be replaced with the strings representations of\n     *  arg1 and arg2, respectively.\n     *\n     *@param  name  Description of the Parameter\n     *@param  arg1  Description of the Parameter\n     *@param  arg2  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n\n    public static String text( String name, Object arg1, Object arg2 )\n    {\n        String pattern = name;\n        try\n        {\n            pattern = resources.getString( \"text.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        return MessageFormat.format( pattern, new Object[]{arg1, arg2} );\n    }\n\n\n    /**\n     *  Get the text given by the property \"name\". If the property is not found,\n     *  this simply uses name. That string and the args array are then passed to\n     *  MessageFormat.format() so that any variable fields can be replaced with\n     *  the correct values.\n     *\n     *@param  name  Description of the Parameter\n     *@param  args  Description of the Parameter\n     *@return       Description of the Return Value\n     */\n\n    public static String text( String name, Object args[] )\n    {\n        String pattern = name;\n        try\n        {\n            pattern = resources.getString( \"text.\" + name );\n        }\n        catch ( MissingResourceException ex )\n        {\n        }\n        return MessageFormat.format( pattern, args );\n    }\n}\n\n", "human_rating": 2.895028908000009, "metadata": {"project": "aoi", "class": "artofillusion.spmanager.SPMTranslate", "source_path": "aoi/sourcefiles/SPManager/src/artofillusion/spmanager/SPMTranslate.java", "label_probabilities": {"readability": [0.000436977, 0.894155, 0.105408, 8.9367e-15], "understandability": [0.000531847, 0.995393, 0.00407533, 1.854e-13], "complexity": [3.8435e-16, 0.00118411, 0.997558, 0.00125808], "modularization": [4.6596e-16, 0.0044314, 0.578026, 0.417542], "overall": [0.000700186, 0.998944, 0.000355825, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.texture.FaceVertexParameterValue", "source": "/* Copyright (C) 2003-2006 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.texture;\n\nimport artofillusion.*;\nimport artofillusion.object.*;\nimport java.io.*;\n\n/** This class defines a scalar parameter whose value is defined at each vertex of each face of a mesh. */\n\npublic class FaceVertexParameterValue implements ParameterValue\n{\n  private double values[];\n  private int faceStartIndex[];\n\n  /** This constructor is private.  It is used internally by duplicate(). */\n\n  private FaceVertexParameterValue()\n  {\n  }\n  \n  /**\n   * Create a new FaceVertexParameterValue object.  val is an array containing the parameter\n   * value at every vertex of every face.  Specifically, val[i][j] is the value at the j'th\n   * vertex of the i'th face.\n   */\n  \n  public FaceVertexParameterValue(double val[][])\n  {\n    setValue(val);\n  }\n  \n  /** Create a new FaceVertexParameterValue for a mesh, and initialize it to appropriate default values. */\n  \n  public FaceVertexParameterValue(FacetedMesh mesh, TextureParameter param)\n  {\n    faceStartIndex = new int[mesh.getFaceCount()+1];\n    int totalValues = 0;\n    for (int i = 0; i < mesh.getFaceCount(); i++)\n    {\n      totalValues += mesh.getFaceVertexCount(i);\n      faceStartIndex[i+1] = totalValues;\n    }\n\n    MeshVertex vertex[] = mesh.getVertices();\n    values = new double[totalValues];\n    int index = 0;\n    if (param.type == TextureParameter.NORMAL_PARAMETER)\n      for (int face = 0; face < mesh.getFaceCount(); face++)\n        for (int vert = 0; vert < mesh.getFaceVertexCount(face); vert++)\n          values[index++] = param.defaultVal;\n    if (param.type == TextureParameter.X_COORDINATE)\n      for (int face = 0; face < mesh.getFaceCount(); face++)\n        for (int vert = 0; vert < mesh.getFaceVertexCount(face); vert++)\n          values[index++] = vertex[mesh.getFaceVertexIndex(face, vert)].r.x;\n    if (param.type == TextureParameter.Y_COORDINATE)\n      for (int face = 0; face < mesh.getFaceCount(); face++)\n        for (int vert = 0; vert < mesh.getFaceVertexCount(face); vert++)\n          values[index++] = vertex[mesh.getFaceVertexIndex(face, vert)].r.y;\n    if (param.type == TextureParameter.Z_COORDINATE)\n      for (int face = 0; face < mesh.getFaceCount(); face++)\n        for (int vert = 0; vert < mesh.getFaceVertexCount(face); vert++)\n          values[index++] = vertex[mesh.getFaceVertexIndex(face, vert)].r.z;\n  }\n\n  /**\n   * Set the list of parameter values.  val is an array containing the parameter\n   * value at every vertex of every face.  Specifically, val[i][j] is the value at the j'th\n   * vertex of the i'th face.\n   */\n\n  public void setValue(double val[][])\n  {\n    faceStartIndex = new int[val.length+1];\n    int totalValues = 0;\n    for (int i = 0; i < val.length; i++)\n    {\n      totalValues += val[i].length;\n      faceStartIndex[i+1] = totalValues;\n    }\n    values = new double[totalValues];\n    int index = 0;\n    for (int i = 0; i < val.length; i++)\n      for (int j = 0; j < val[i].length; j++)\n        values[index++] = val[i][j];\n  }\n\n  /**\n   * Get the value of the parameter at a particular vertex in a particular face.\n   *\n   * @param faceIndex     the index of the face within the mesh\n   * @param vertIndex     the index of the vertex within the face\n   * @return the value at the specified face/vertex\n   */\n\n  public double getValue(int faceIndex, int vertIndex)\n  {\n    return values[faceStartIndex[faceIndex]+vertIndex];\n  }\n\n  /**\n   * Set the value of the parameter at a particular vertex in a particular face.\n   *\n   * @param faceIndex     the index of the face within the mesh\n   * @param vertIndex     the index of the vertex within the face\n   * @param newValue      the value to set for the specified face/vertex\n   */\n\n  public void setValue(int faceIndex, int vertIndex, double newValue)\n  {\n    values[faceStartIndex[faceIndex]+vertIndex] = newValue;\n  }\n\n  /**\n   * Get the value of the parameter at a particular point within the interior of a face.\n   * This method assumes the face is triangular (which is always the case for a parameter\n   * of a RenderingMesh).\n   */\n  \n  public double getValue(int faceIndex, int v1, int v2, int v3, double u, double v, double w)\n  {\n    return u*getValue(faceIndex, 0)+v*getValue(faceIndex, 1)+w*getValue(faceIndex, 2);\n  }\n\n  /**\n   * Get the number of faces for which the parameter has values.\n   */\n\n  public int getFaceCount()\n  {\n    return faceStartIndex.length-1;\n  }\n\n  /**\n   * Get the number of vertices in a particular face.\n   *\n   * @param faceIndex     the index of the face within the mesh\n   */\n\n  public int getFaceVertexCount(int faceIndex)\n  {\n    return faceStartIndex[faceIndex+1]-faceStartIndex[faceIndex];\n  }\n  \n  /** Get the average value of the parameter over the entire surface. */\n  \n  public double getAverageValue()\n  {\n    double avg = 0.0;\n\n    for (int i = 0; i < values.length; i++)\n      avg += values[i];\n    return (avg/values.length);\n  }\n  \n  /** Create a duplicate of this object. */\n  \n  public ParameterValue duplicate()\n  {\n    FaceVertexParameterValue copy = new FaceVertexParameterValue();\n    copy.values = (double[]) values.clone();\n    copy.faceStartIndex = (int[]) faceStartIndex.clone();\n    return copy;\n  }\n  \n  /** Determine whether this object represents the same set of values as another one. */\n  \n  public boolean equals(Object o)\n  {\n    if (!(o instanceof FaceVertexParameterValue))\n      return false;\n    FaceVertexParameterValue v = (FaceVertexParameterValue) o;\n    if (v.values.length != values.length || v.faceStartIndex.length != faceStartIndex.length)\n      return false;\n    for (int i = 0; i < values.length; i++)\n      if (v.values[i] != values[i])\n        return false;\n    for (int i = 0; i < faceStartIndex.length; i++)\n      if (v.faceStartIndex[i] != faceStartIndex[i])\n        return false;\n    return true;\n  }\n  \n  /** Write out a serialized representation of this object to a stream. */\n  \n  public void writeToStream(DataOutputStream out) throws IOException\n  {\n    out.writeInt(-1);\n    out.writeInt(values.length);\n    for (int i = 0; i < values.length; i++)\n      out.writeDouble(values[i]);\n    out.writeInt(faceStartIndex.length);\n    for (int i = 1; i < faceStartIndex.length; i++)\n      out.writeInt(faceStartIndex[i]);\n  }\n  \n  /** Reconstruct a serialized object. */\n  \n  public FaceVertexParameterValue(DataInputStream in) throws IOException\n  {\n    int version = in.readInt();\n    if (version >= 0)\n    {\n      // Old format from before a version number was being stored.\n\n      int faces = version;\n      values = new double[faces*3];\n      faceStartIndex = new int[values.length+1];\n      for (int i = 0; i < 3; i++)\n        for (int j = 0; j < faces; j++)\n          values[j*3+i] = in.readDouble();\n      for (int i = 1; i <= faces; i++)\n        faceStartIndex[i] = i*3;\n    }\n    else if (version != -1)\n      throw new InvalidObjectException(\"\");\n    else\n    {\n      values = new double[in.readInt()];\n      for (int i = 0; i < values.length; i++)\n        values[i] = in.readDouble();\n      faceStartIndex = new int[in.readInt()];\n      for (int i = 1; i < faceStartIndex.length; i++)\n        faceStartIndex[i] = in.readInt();\n    }\n  }\n}\n", "human_rating": 3.3125024094679993, "metadata": {"project": "aoi", "class": "artofillusion.texture.FaceVertexParameterValue", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/texture/FaceVertexParameterValue.java", "label_probabilities": {"readability": [0.344153, 0.624197, 0.0316496, 2.09468e-07], "understandability": [2.2314e-05, 0.602984, 0.39633, 0.000664096], "complexity": [0.0298168, 0.703421, 0.266762, 1.69984e-08], "modularization": [7.16628e-14, 0.0313527, 0.968473, 0.000174472], "overall": [0.000478604, 0.986218, 0.0133035, 3.7e-19]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.texture.UniformTexture", "source": "/* Copyright (C) 1999-2004 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.texture;\n\nimport artofillusion.*;\nimport artofillusion.object.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.io.*;\n\n/** UniformMaterial represents a material whose properties do not vary with position. */\n\npublic class UniformTexture extends Texture\n{\n  public RGBColor diffuseColor, specularColor, transparentColor, emissiveColor;\n  public double roughness, cloudiness;\n  public float transparency, specularity, shininess;\n  \n  public UniformTexture()\n  {\n    // Generate the default color.\n\n    diffuseColor = new RGBColor(1.0f, 1.0f, 1.0f);\n    specularColor = new RGBColor(1.0f, 1.0f, 1.0f);\n    transparentColor = new RGBColor(1.0f, 1.0f, 1.0f);\n    emissiveColor = new RGBColor(0.0f, 0.0f, 0.0f);\n    transparency = 0.0f;\n    specularity = 0.0f;\n    shininess = 0.0f;\n    roughness = 0.2;\n    cloudiness = 0.0;\n    name = \"\";\n  }\n  \n  /** Create a texture which is completely invisible. */\n\n  public static UniformTexture invisibleTexture()\n  {\n    UniformTexture tex = new UniformTexture();\n\n    tex.diffuseColor.setRGB(0.0f, 0.0f, 0.0f);\n    tex.specularColor.setRGB(0.0f, 0.0f, 0.0f);\n    tex.transparency = 1.0f;\n    return tex;\n  }\n\n  public static String getTypeName()\n  {\n    return \"Uniform\";\n  }\n\n  public void getTextureSpec(TextureSpec spec)\n  {\n    float frac = (1.0f-transparency)*(1.0f-specularity);\n    \n    spec.diffuse.setRGB(diffuseColor.red*frac, diffuseColor.green*frac, diffuseColor.blue*frac);\n    frac = (1.0f-transparency)*specularity;\n    spec.specular.setRGB(specularColor.red*frac, specularColor.green*frac, specularColor.blue*frac);\n    frac = (1.0f-transparency)*shininess;\n    spec.hilight.setRGB(specularColor.red*frac, specularColor.green*frac, specularColor.blue*frac);\n    spec.transparent.setRGB(transparentColor.red*transparency, transparentColor.green*transparency, transparentColor.blue*transparency);\n    spec.emissive.copy(emissiveColor);\n    spec.roughness = roughness;\n    spec.cloudiness = cloudiness;\n    spec.bumpGrad.set(0.0, 0.0, 0.0);\n  }\n  \n  public void getTransparency(RGBColor trans)\n  {\n    trans.setRGB(transparentColor.red*transparency, transparentColor.green*transparency, transparentColor.blue*transparency);\n  }\n  \n  public void getAverageSpec(TextureSpec spec, double time, double param[])\n  {\n    getTextureSpec(spec);\n  }\n  \n  /** The only TextureMapping which can be used for a UniformTexture is a UniformMapping. */\n  \n  public TextureMapping getDefaultMapping(Object3D object)\n  {\n    return new UniformMapping(object, this);\n  }\n\n  /** Create a duplicate of the texture. */\n  \n  public Texture duplicate()\n  {\n    UniformTexture m = new UniformTexture();\n    \n    m.name = name;\n    m.diffuseColor.copy(diffuseColor);\n    m.specularColor.copy(specularColor);\n    m.transparentColor.copy(transparentColor);\n    m.emissiveColor.copy(emissiveColor);\n    m.transparency = transparency;\n    m.specularity = specularity;\n    m.roughness = roughness;\n    m.cloudiness = cloudiness;\n    m.shininess = shininess;\n    return m;\n  }\n\n  /** Determine whether this texture has a non-zero value anywhere for a particular component.\n      @param component    the texture component to check for (one of the *_COMPONENT constants)\n  */\n  \n  public boolean hasComponent(int component)\n  {\n    switch (component)\n      {\n        case DIFFUSE_COLOR_COMPONENT:\n          return (transparency < 1.0f && specularity < 1.0f && diffuseColor.getMaxComponent() > 0.0);\n        case SPECULAR_COLOR_COMPONENT:\n          return (transparency < 1.0f && specularity > 0.0f && specularColor.getMaxComponent() > 0.0);\n        case TRANSPARENT_COLOR_COMPONENT:\n          return (transparency > 0.0f && transparentColor.getMaxComponent() > 0.0);\n        case HILIGHT_COLOR_COMPONENT:\n          return (transparency < 1.0f && shininess > 0.0f && specularColor.getMaxComponent() > 0.0);\n        case EMISSIVE_COLOR_COMPONENT:\n          return (emissiveColor.getMaxComponent() > 0.0);\n        default:\n          return false;\n      }\n  }\n  \n  /** Allow the user to interactively edit the material. */\n  \n  public void edit(final BFrame fr, Scene sc)\n  {\n    BTextField nameField = new BTextField(name, 15);\n    final ValueSlider transSlider = new ValueSlider(0.0, 1.0, 100, (double) transparency);\n    final ValueSlider specSlider = new ValueSlider(0.0, 1.0, 100, (double) specularity);\n    final ValueSlider shinSlider = new ValueSlider(0.0, 1.0, 100, shininess);\n    final ValueSlider roughSlider = new ValueSlider(0.0, 1.0, 100, roughness);\n    final ValueSlider clearSlider = new ValueSlider(0.0, 1.0, 100, cloudiness);\n    final Widget diffPatch = diffuseColor.getSample(50, 30);\n    final Widget specPatch = specularColor.getSample(50, 30);\n    final Widget transPatch = transparentColor.getSample(50, 30);\n    final Widget emissPatch = emissiveColor.getSample(50, 30);\n    final UniformTexture newTexture = (UniformTexture) duplicate();\n    final MaterialPreviewer preview = new MaterialPreviewer(newTexture, null, 200, 160);\n    final ActionProcessor process = new ActionProcessor();\n    final Runnable renderCallback = new Runnable() {\n      public void run()\n      {\n        preview.render();\n      }\n    };\n    diffPatch.addEventLink(MouseClickedEvent.class, new Object() {\n      void processEvent()\n      {\n        new ColorChooser(fr, Translate.text(\"DiffuseColor\"), newTexture.diffuseColor);\n        diffPatch.setBackground(newTexture.diffuseColor.getColor());\n        process.addEvent(renderCallback);\n      }\n    });\n    specPatch.addEventLink(MouseClickedEvent.class, new Object() {\n      void processEvent()\n      {\n        new ColorChooser(fr, Translate.text(\"SpecularColor\"), newTexture.specularColor);\n        specPatch.setBackground(newTexture.specularColor.getColor());\n        process.addEvent(renderCallback);\n      }\n    });\n    transPatch.addEventLink(MouseClickedEvent.class, new Object() {\n      void processEvent()\n      {\n        new ColorChooser(fr, Translate.text(\"TransparentColor\"), newTexture.transparentColor);\n        transPatch.setBackground(newTexture.transparentColor.getColor());\n        process.addEvent(renderCallback);\n      }\n    });\n    emissPatch.addEventLink(MouseClickedEvent.class, new Object() {\n      void processEvent()\n      {\n        new ColorChooser(fr, Translate.text(\"EmissiveColor\"), newTexture.emissiveColor);\n        emissPatch.setBackground(newTexture.emissiveColor.getColor());\n        process.addEvent(renderCallback);\n      }\n    });\n    Object valueListener = new Object() {\n      void processEvent()\n      {\n        newTexture.transparency = (float) transSlider.getValue();\n        newTexture.specularity = (float) specSlider.getValue();\n        newTexture.shininess = (float) shinSlider.getValue();\n        newTexture.roughness = roughSlider.getValue();\n        newTexture.cloudiness = clearSlider.getValue();\n        process.addEvent(renderCallback);\n      }\n    };\n    transSlider.addEventLink(ValueChangedEvent.class, valueListener);\n    specSlider.addEventLink(ValueChangedEvent.class, valueListener);\n    shinSlider.addEventLink(ValueChangedEvent.class, valueListener);\n    roughSlider.addEventLink(ValueChangedEvent.class, valueListener);\n    clearSlider.addEventLink(ValueChangedEvent.class, valueListener);\n    ComponentsDialog dlg = new ComponentsDialog(fr, \"\", new Widget [] {\n        preview, nameField, diffPatch, specPatch, transPatch, emissPatch, transSlider, specSlider,\n        shinSlider, roughSlider, clearSlider}, new String [] {null, Translate.text(\"Name\"),\n        Translate.text(\"DiffuseColor\"), Translate.text(\"SpecularColor\"), Translate.text(\"TransparentColor\"),\n        Translate.text(\"EmissiveColor\"), Translate.text(\"Transparency\"), Translate.text(\"Specularity\"),\n        Translate.text(\"Shininess\"), Translate.text(\"Roughness\"), Translate.text(\"Cloudiness\")});\n    process.stopProcessing();\n    if (!dlg.clickedOk())\n      return;\n    transparency = (float) transSlider.getValue();\n    specularity = (float) specSlider.getValue();\n    shininess = (float) shinSlider.getValue();\n    roughness = roughSlider.getValue();\n    cloudiness = clearSlider.getValue();\n    UniformTexture.this.name = nameField.getText();\n    diffuseColor.copy(newTexture.diffuseColor);\n    specularColor.copy(newTexture.specularColor);\n    transparentColor.copy(newTexture.transparentColor);\n    emissiveColor.copy(newTexture.emissiveColor);\n    int index = sc.indexOf(this);\n    if (index > -1)\n      sc.changeTexture(index);\n  }\n  \n  /** The following two methods are used for reading and writing files.  The first is a\n      constructor which reads the necessary data from an input stream.  The other writes\n      the object's representation to an output stream. */\n  \n  public UniformTexture(DataInputStream in, Scene theScene) throws IOException, InvalidObjectException\n  {\n    short version = in.readShort();\n    \n    if (version < 0 || version > 1)\n      throw new InvalidObjectException(\"\");\n    name = in.readUTF();\n    diffuseColor = new RGBColor(in);\n    specularColor = new RGBColor(in);\n    transparentColor = new RGBColor(in);\n    emissiveColor = new RGBColor(in);\n    roughness = in.readDouble();\n    cloudiness = in.readDouble();\n    transparency = in.readFloat();\n    specularity = in.readFloat();\n    if (version > 0)\n      shininess = in.readFloat();\n    else\n      shininess = specularity;\n  }\n  \n  public void writeToFile(DataOutputStream out, Scene theScene) throws IOException\n  {\n    out.writeShort(1);\n    out.writeUTF(name);\n    diffuseColor.writeToFile(out);\n    specularColor.writeToFile(out);\n    transparentColor.writeToFile(out);\n    emissiveColor.writeToFile(out);\n    out.writeDouble(roughness);\n    out.writeDouble(cloudiness);\n    out.writeFloat(transparency);\n    out.writeFloat(specularity);\n    out.writeFloat(shininess);\n  }\n}", "human_rating": 2.985837400016697, "metadata": {"project": "aoi", "class": "artofillusion.texture.UniformTexture", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/texture/UniformTexture.java", "label_probabilities": {"readability": [1.52152e-14, 0.985838, 0.0141617, 1.66363e-11], "understandability": [0.460705, 0.539294, 2.689e-07, 0.0], "complexity": [0.0, 0.000622909, 0.999377, 9.64097e-14], "modularization": [0.0, 6.99842e-12, 1.0, 3.5074e-16], "overall": [7.43307e-10, 0.999985, 1.48396e-05, 2e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.tools.ArraySpec", "source": "/* The ArrayParam class defines parameters for the array tool.\n   This also sets the default values in the dialog.*/\n\n/* Copyright 2001 Rick van der Meiden\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. \n*/\n\n\npackage artofillusion.tools;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\n\nimport java.util.*;\n\n/** Parameters for creating arrays are stored in the ArraySpec class.\n    From these parameters, an array can be created.\n    @author Rick van der Meiden\n*/\n  \npublic class ArraySpec\n{\n        // --- constants\n\n        /** defines that a linear array is to be created */\n        public static final int METHOD_LINEAR = 0;\n        /** defines that an array along a curve is to be created */\n        public static final int METHOD_CURVE = 1;\n        /** defines that the stepsize determines the number of copies along a curve */\n        public static final int MODE_STEP = 0;\n        /** defines that the number of copying along a curve is explicitly set by the user */\n        public static final int MODE_COPIES = 1;\n\n        private static final int SD_LEVEL = 5;\n\n        // --- private data\n        \n        // where to create this array\n        private LayoutWindow window;\n        // undo record\n        private UndoRecord undo;\n        // froot object for grouping\n        private ObjectInfo arrayRoot;\n\n        // --- public data\n        \n        // general paramters\n\n        /** Set to METHOD_LINEAR to create a liniar array.\n            Set to METHOD_CURVE to create an array along a curve. */\n        public int method;\n        /** the objects that should be copied to create an array */\n        public Vector objectList;         // list of objectInfo's\n\n        // linear paramters\n        /** Number of copies to make for a linar array. */\n        public int linearCopies;                        \n        /** step size in X direction for a linear array. */\n        public double stepX;\n        /** step size in Y direction for a linear array. */\n        public double stepY;\n        /** step size in Z direction for a linear array. */\n        public double stepZ;\n        /** when set, stepX is multiplied by the objects boudingbox x size */\n        public boolean intervalX;\n        /** when set, stepY is multiplied by the objects boudingbox y size */\n        public boolean intervalY;\n        /** when set, stepZ is multiplied by the objects boudingbox z size */\n        public boolean intervalZ;\n\n        // spline parameters\n        /** the curve along which to create an array */\n        public ObjectInfo curve;\n        /** Set to MODE_STEP to determine the number of copies from the step size.\n            Set to MODE_COPIES to use the curveCopies field explicitly */\n        public int curveMode;\n        /** The number of copies to make along a curve.\n                Only used when curveMode = CURVE_COPIES */\n        public int curveCopies;\n        /**  the stepsize between copies.\n                Only used when curveMode = CURVE_COPIES */\n        public double curveStep;\n        /** When set, curveStep is multiplied by the size of the object. Not Used. */\n        public boolean curveInterval;\n        /** When set, the orientationof the object(s) follow the curve.*/\n        public boolean orientation;\n        /** When set, the initial position of the object is ignored.\n                The object will pivot abouts its origin instead of about a point on the path curve */\n        public boolean ignoreOrigin;\n        /** When set, the initial orientation of the object is ignored.\n                The object will have a default orientation at the beginning of the path curve.*/\n        public boolean ignoreOrientation;\n\n        // general options\n\n        /** If set, an instance of the object(s) will be created at\n                first position of the array (linear displacement 0 or the\n                beginning of the splien curve. */\n        public boolean dupFirst;\n        /** If set, group all the objects together as children of a null object. */\n        public boolean group;\n        /** If set, create live copies instead of regular copies) */\n        public boolean live;\n        /** If set, create copies of children too, positioned relative to the parent object(s) */\n        public boolean deep;\n\n        // public methods\n\n        /** create an instance with default settings\n        @param win window in which the array is to be created.\n        */\n        \n        public ArraySpec (LayoutWindow win)\n        {\n                this.window = win;\n\n                // set list of object to copy (all selected objects)\n                Scene scene = window.getScene();\n                int selection[] = window.getSelectedIndices();\n                objectList = new Vector();         // list of objectInfo's\n                for (int sel=0; sel<selection.length;sel++)\n                {\n                        ObjectInfo info = scene.getObject(selection[sel]);\n                        objectList.addElement(info);\n                }\n\n                // set paramters\n                method = METHOD_LINEAR;\n                linearCopies = 10;\n                stepX = 1;\n                stepY = 0;\n                stepZ = 0;\n                intervalX = true;\n                intervalY = false;\n                intervalZ = false;\n        \n                curve = null;\n                curveMode=MODE_COPIES; \n                curveCopies = 10;\n                curveStep = 0.1;\n                orientation = true;\n                ignoreOrigin = true;\n                ignoreOrientation = true;\n        \n                dupFirst = true;\n                group = true;\n                deep = true;\n                live = false;\n\n        }\n        \n  /** create an array of objects with current paramter settings */ \n     \n  public void createArray ()\n  {\n        undo = new UndoRecord(window, false);\n\n        // create a group object, even when not grouping\n        ObjectInfo info = (ObjectInfo)objectList.elementAt(0);\n        String name = \"Array of \" + info.getName();\n\n        CoordinateSystem coords = new CoordinateSystem(new Vec3(0,0,0), Vec3.vz(), Vec3.vy());\n        if (method == METHOD_CURVE && curve != null)\n                coords = curve.getCoords().duplicate();\n        else if (method == METHOD_LINEAR)\n        {\n                Vec3 displacement = new Vec3(stepX, stepY, stepZ);\n                BoundingBox bounds = info.getObject().getBounds();\n                if (intervalX) displacement.x *= bounds.getSize().x;\n                if (intervalY) displacement.y *= bounds.getSize().y;\n                if (intervalZ) displacement.z *= bounds.getSize().z;\n                displacement = displacement.times(((double)linearCopies-1.0)/2.0);\n\n                coords = info.getCoords().duplicate();\n                Mat4 dis = Mat4.translation(displacement.x,\n                                            displacement.y,\n                                            displacement.z);\n                coords.transformOrigin(dis);\n        }\n\n        arrayRoot = new ObjectInfo(new NullObject(), coords, name);\n\n        if (group)\n        {\n                window.addObject (arrayRoot, undo);\n        }\n\n        if (method == METHOD_LINEAR)\n                createLinearArray();\n        else if (method == METHOD_CURVE)\n                createCurveArray();\n\n        window.setUndoRecord(undo);\n        window.rebuildItemList();\n        window.updateImage();\n        \n  }\n\n  /** create an array of linearly translated objects */\n  private void createLinearArray ()\n  {\n        if (method != METHOD_LINEAR)\n                return;\n\n        for (int i=0; i<objectList.size(); i++)\n        {\n                // get object\n                ObjectInfo info = (ObjectInfo)objectList.elementAt(i);\n\n                // calculate displacement vector\n                Vec3 displacement = new Vec3(stepX, stepY, stepZ);\n                BoundingBox bounds = info.getObject().getBounds();\n                if (intervalX) displacement.x *= bounds.getSize().x;\n                if (intervalY) displacement.y *= bounds.getSize().y;\n                if (intervalZ) displacement.z *= bounds.getSize().z;\n\n                int start = (dupFirst==true ? 0 : 1);\n                for (int n=start; n<linearCopies; n++)\n                        createCopy (info, displacement.times(n));\n        }\n\n        window.updateImage();\n  }\n\n  /** create an array of objects tranlated along a curve */\n  private void createCurveArray ()\n  {\n        if (method != METHOD_CURVE)\n                return;\n\n        if (curve == null) return;\n        Curve cv = (Curve) curve.getObject();\n\n        // map curve to global coordinate space\n        MeshVertex vert[] = cv.getVertices();\n        Vec3 v[] = new Vec3 [vert.length];\n        Mat4 trans = curve.getCoords().fromLocal();\n        for (int i = 0; i < v.length; i++)\n          v[i] = trans.times(vert[i].r);\n\n        // subdive curve\n        Vec3 subdiv[] = new Curve(v, cv.getSmoothness(), cv.getSmoothingMethod(), cv.isClosed()).subdivideCurve(SD_LEVEL).getVertexPositions();\n        // Vec3 startPoint = findPointOnCurve(subdiv, cv.isClosed(), 0);\n        // Vec3 startPoint = v[0];\n        int startCount = (dupFirst==true ? 0 : 1);\n        double curveLength = calcCurveLength(cv);\n        if (curveMode == MODE_COPIES)\n        {\n                if (curveCopies < 1) curveCopies = 1;\n                curveStep = curveLength / (curveCopies + (cv.isClosed() ? 1 : 0));\n        }\n        else\n        {\n                if (curveStep / curveLength < 0.001) curveStep = 0.001*curveLength;\n                curveCopies = (int)(curveLength / curveStep);\n        }\n        // find orientation for all subdivision vertices\n        Vec3 zdir[] = new Vec3 [subdiv.length];\n        Vec3 updir[] = new Vec3 [subdiv.length];\n        constructMinRotFrame(subdiv, cv.isClosed(), zdir, updir);\n        // coordinate system at first point on curve\n        CoordinateSystem startCS = new CoordinateSystem(subdiv[0],zdir[0],updir[0]);\n        \n        // for all objects in selection\n        for (int i=0; i<objectList.size(); i++)\n        {\n                // get object\n                ObjectInfo info = (ObjectInfo)objectList.elementAt(i);\n\n                for (int n=startCount; n<curveCopies; n++)\n                {\n                        // determine displacement\n                        Vec3 updir_return = new Vec3(0,0,0), zdir_return = new Vec3(0,0,0);\n                        double relativePos = n*curveLength / ((curveCopies-1) + (cv.isClosed() ? 1 : 0));\n\n                        CoordinateSystem curveCS = findCoordinateSystem(subdiv, cv.isClosed(), relativePos, zdir, updir);\n\n                        CoordinateSystem newCS = info.getCoords().duplicate();\n                        if (ignoreOrigin)\n                                newCS.setOrigin(startCS.getOrigin());\n                        if (ignoreOrientation)\n                                newCS.setOrientation(startCS.getZDirection(), startCS.getUpDirection());    \n\n                        newCS.transformOrigin(startCS.toLocal());\n                        newCS.transformAxes(startCS.toLocal());\n                        newCS.transformOrigin(curveCS.fromLocal());\n                        if (orientation)\n                                newCS.transformAxes(curveCS.fromLocal());\n\n                        createCopy (info, newCS);\n                        \n                }\n        }\n\n        window.updateImage();\n        \n  }\n\n  /** create a copy of an object and displace it. If live = true then make a\n     live duplicate instead of a copy */\n  private ObjectInfo createCopy (ObjectInfo info, Vec3 displacement)\n  {\n        Mat4 trans = Mat4.translation(displacement.x, displacement.y, displacement.z);\n        return createCopy(info, trans);\n  }\n\n  /** create a copy of an object and place it at cs.\n     If live = true then make a live duplicate instead of a copy */\n  private ObjectInfo createCopy (ObjectInfo info, CoordinateSystem cs)\n  {\n        Mat4 trans = cs.fromLocal().times(info.getCoords().toLocal());\n        return createCopy(info, trans);\n  }\n\n  /** create a copy (or live duplicate) of an object,\n      tranform its coordinate system and add it to the group object\n  */\n\n  private ObjectInfo createCopy (ObjectInfo info, Mat4 trans)\n  {\n        ObjectInfo newinfo = info.duplicate();\n        if (!live)\n                newinfo.setObject(info.object.duplicate());\n        newinfo.getCoords().transformCoordinates(trans);\n        window.addObject(newinfo, undo);\n        if (group)\n                arrayRoot.addChild(newinfo, 0);\n\n        if (deep)\n        {\n                for (int i=0; i< info.getChildren().length;i++)\n                {\n                        newinfo.addChild(createChildCopy(info.getChildren()[i], trans),i);\n                }\n        }\n\n        return newinfo;\n  }\n\n  /** create a copy (or live diplicate) of an object, add it to  and tranform\n        its coordinate system. */\n\n  private ObjectInfo createChildCopy (ObjectInfo info, Mat4 trans)\n  {\n        ObjectInfo newinfo = info.duplicate();\n        if (!live)\n                newinfo.setObject(info.getObject().duplicate());\n        newinfo.getCoords().transformCoordinates(trans);\n        window.addObject(newinfo, undo);\n        \n        for (int i=0; i< info.getChildren().length;i++)\n        {\n                newinfo.addChild(createChildCopy(info.getChildren()[i], trans),i);\n        }\n        \n        return newinfo;\n  }\n\n\n  /** calculate the length of a curve given some error determined by SD_LEVEL */\n  private double calcCurveLength(Curve c)\n  {\n        Vec3 subdiv[] = c.subdivideCurve(SD_LEVEL).getVertexPositions();\n        double sum = 0;\n\n        for (int i=1;i<subdiv.length;i++)\n                sum += subdiv[i].distance(subdiv[i-1]);\n\n        if (c.isClosed())\n                sum += subdiv[subdiv.length-1].distance(subdiv[0]);\n\n        return sum;\n  }\n\n  /** determines a point on the curve for which the distance to\n     the first point is given by relativePosition */\n  private Vec3 findPointOnCurve(Vec3 subdiv[], boolean isClosed, double relativePosition)\n  {\n        // find interval around relativePosition\n        int i;\n        double sum=0, prevsum=0;\n        for (i=1;i<subdiv.length;i++)\n        {\n                prevsum = sum;\n                sum += subdiv[i].distance(subdiv[i-1]);\n                if (sum >= relativePosition)\n                        break;\n        }\n        int prev_i = i-1;\n        if (sum < relativePosition)\n        {\n                if (isClosed)\n                {\n                        prevsum = sum;\n                        sum += subdiv[subdiv.length-1].distance(subdiv[0]);\n                        prev_i = subdiv.length-1;\n                        i = 0;\n                }\n                else\n                {\n                        i = i-1;\n                        prev_i = i-2;\n                }\n        }\n\n        // find point by linear interpolation in this interval\n        double interval = sum-prevsum;\n        \n        return subdiv[i].times((relativePosition - prevsum)/interval).plus(subdiv[prev_i].times((sum - relativePosition)/interval));\n  }\n\n  /** Construct the Minimally Rotating Frame at every point along the path.\n       sets values in zdir[] and updir[]\n       reused code from Peter Eastman's Extrude Tool */\n  private void constructMinRotFrame(Vec3 subdiv[], boolean isClosed, Vec3 zdir[], Vec3 updir[])\n  {\n    Vec3 t[];\n    int i, j;\n\n    // subdivide the path and determine its direction at the starting point.\n    \n    t = new Vec3 [subdiv.length];\n    t[0] = subdiv[1].minus(subdiv[0]);\n    t[0].normalize();\n    zdir[0] = Vec3.vz();\n    updir[0] = Vec3.vy();\n    \n    // Now find two vectors perpendicular to the path, and determine how much they\n    // contribute to the z and up directions.\n    \n    Vec3 dir1, dir2;\n    double zfrac1, zfrac2, upfrac1, upfrac2;\n    zfrac1 = t[0].dot(zdir[0]);\n    zfrac2 = Math.sqrt(1.0-zfrac1*zfrac1);\n    dir1 = zdir[0].minus(t[0].times(zfrac1));\n    dir1.normalize();\n    upfrac1 = t[0].dot(updir[0]);\n    upfrac2 = Math.sqrt(1.0-upfrac1*upfrac1);\n    dir2 = updir[0].minus(t[0].times(upfrac1));\n    dir2.normalize();\n    \n    // Propagate the vectors along the path.\n    \n    for (i = 1; i < subdiv.length; i++)\n      {\n\tif (i == subdiv.length-1)\n\t  {\n            if (isClosed)\n\t      t[i] = subdiv[0].minus(subdiv[subdiv.length-2]);\n\t    else\n\t      t[i] = subdiv[subdiv.length-1].minus(subdiv[subdiv.length-2]);\n\t  }\n\telse\n\t  t[i] = subdiv[i+1].minus(subdiv[i-1]);\n\tt[i].normalize();\n\n        dir1 = dir1.minus(t[i].times(t[i].dot(dir1)));\n        dir1.normalize();\n        dir2 = dir2.minus(t[i].times(t[i].dot(dir2)));\n        dir2.normalize();\n        zdir[i] = t[i].times(zfrac1).plus(dir1.times(zfrac2));\n        updir[i] = t[i].times(upfrac1).plus(dir2.times(upfrac2));\n\n      }\n\n\n  }\n\n  /** determines the coordinatesystem that specifies position and\n     orienation vectors at the point on the curve for which the distance to\n     the first point is given by relativePosition */\n\n  private CoordinateSystem findCoordinateSystem(Vec3 subdiv[], boolean isClosed, double relativePosition, Vec3 zdirs[], Vec3 updirs[])\n  {\n        // find interval around relativePosition\n        int i, prev_i;\n        double sum=0, prevsum=0;\n        for (i=1;i<subdiv.length;i++)\n        {\n                prevsum = sum;\n                sum += subdiv[i].distance(subdiv[i-1]);\n                if (sum >= relativePosition)\n                        break;\n        }\n        prev_i = i-1;\n        if (sum < relativePosition)\n        {\n                if (isClosed)\n                {\n                        prevsum = sum;\n                        sum += subdiv[subdiv.length-1].distance(subdiv[0]);\n                        prev_i = subdiv.length-1;\n                        i = 0;\n                }\n                else\n                {\n                        i = i-1;\n                        prev_i = i-2;\n                }\n        }\n\n        // find directions by linear interpolation in this interval\n        double interval = sum-prevsum;\n        Vec3 pos = subdiv[i].times((relativePosition - prevsum)/interval).plus(subdiv[prev_i].times((sum - relativePosition)/interval));\n        Vec3 zdir = zdirs[i].times((relativePosition - prevsum)/interval).plus(zdirs[prev_i].times((sum - relativePosition)/interval));\n        Vec3 updir = updirs[i].times((relativePosition - prevsum)/interval).plus(updirs[prev_i].times((sum - relativePosition)/interval));\n\n        return new CoordinateSystem(pos,zdir,updir);\n      \n  }\n\n}\n", "human_rating": 2.9713830412000006, "metadata": {"project": "aoi", "class": "artofillusion.tools.ArraySpec", "source_path": "aoi/sourcefiles/Tools/src/artofillusion/tools/ArraySpec.java", "label_probabilities": {"readability": [3.9803e-06, 0.971936, 0.0274996, 0.00055992], "understandability": [3.03937e-11, 0.000281536, 0.0959787, 0.90374], "complexity": [0.355497, 0.64448, 2.28355e-05, 8.6e-19], "modularization": [0.850658, 0.149338, 3.73956e-06, 0.0], "overall": [3.2e-19, 6.23694e-05, 0.77851, 0.221427]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.TransformPointsDialog", "source": "/* Copyright (C) 1999-2004 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\nimport java.util.*;\n\n/** This class implements the dialog box which is used for the \"Transform Points\" command.\n    It allows the user enter values by which to translate, rotate, and scale the selected\n    Points.  It also allows them to specify whether the rotation and scaling should be done\n    with respect to the origin of object coordinates, or the center of the selected points. */\n\npublic class TransformPointsDialog extends BDialog\n{\n  private double finalValues[];\n  private ValueField fields[];\n  private BComboBox centerChoice;\n\n  public TransformPointsDialog(BFrame parent)\n  {\n    super(parent, Translate.text(\"transformPoints\"), true);\n    fields = new ValueField [9];\n    layoutDialog();\n    pack();\n    setResizable(false);\n    UIUtilities.centerDialog(this, parent);\n    fields[0].requestFocus();\n    setVisible(true);\n  }\n\n  public double [] getValues()\n  {\n    return finalValues;\n  }\n  \n  public boolean useSelectionCenter()\n  {\n    return (centerChoice.getSelectedIndex() == 0);\n  }\n  \n  private void layoutDialog()\n  {\n    FormContainer content = new FormContainer(4, 6);\n    setContent(content);\n    LayoutInfo eastLayout = new LayoutInfo(LayoutInfo.EAST, LayoutInfo.NONE, new Insets(0, 0, 0, 5), null);\n    content.add(Translate.label(\"Move\"), 0, 1, eastLayout);\n    content.add(Translate.label(\"Rotate\"), 0, 2, eastLayout);\n    content.add(Translate.label(\"Scale\"), 0, 3, eastLayout);\n    content.add(new BLabel(\"X\"), 1, 0);\n    content.add(new BLabel(\"Y\"), 2, 0);\n    content.add(new BLabel(\"Z\"), 3, 0);\n    for (int i = 0; i < 9; i++)\n      content.add(fields[i] = new ValueField(Double.NaN, ValueField.NONE), (i%3)+1, (i/3)+1);\n    RowContainer row = new RowContainer();\n    content.add(row, 0, 4, 4, 1);\n    row.add(Translate.label(\"transformAround\"));\n    row.add(centerChoice = new BComboBox(new String [] {\n      Translate.text(\"centerOfSelection\"),\n      Translate.text(\"objectOrigin\")\n    }));\n    RowContainer buttons = new RowContainer();\n    content.add(buttons, 0, 5, 4, 1);\n    buttons.add(Translate.button(\"ok\", this, \"doOk\"));\n    buttons.add(Translate.button(\"cancel\", this, \"dispose\"));\n    addEventLink(WindowClosingEvent.class, this, \"dispose\");\n    addAsListener(this);\n  }\n\n  private void doOk()\n  {\n    finalValues = new double [9];\n    for (int i = 0; i < finalValues.length; i++)\n    {\n      finalValues[i] = fields[i].getValue();\n      if (Double.isNaN(finalValues[i]))\n        finalValues[i] = (i < 6 ? 0.0 : 1.0);\n    }\n    dispose();\n  }\n    \n  /** Pressing Return and Escape are equivalent to clicking OK and Cancel. */\n    \n  private void keyPressed(KeyPressedEvent ev)\n  {\n    int code = ev.getKeyCode();\n\n    if (code == KeyPressedEvent.VK_ENTER)\n      doOk();\n    if (code == KeyPressedEvent.VK_ESCAPE)\n      dispose();\n  }\n\n  /** Add this as a listener to every Widget. */\n  \n  private void addAsListener(Widget w)\n  {\n    w.addEventLink(KeyPressedEvent.class, this, \"keyPressed\");\n    if (w instanceof WidgetContainer)\n    {\n      Iterator iter = ((WidgetContainer) w).getChildren().iterator();\n      while (iter.hasNext())\n        addAsListener((Widget) iter.next());\n    }\n  }\n}", "human_rating": 3.7243368600000117, "metadata": {"project": "aoi", "class": "artofillusion.TransformPointsDialog", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/TransformPointsDialog.java", "label_probabilities": {"readability": [0.72666, 0.271017, 0.00232293, 1.17467e-14], "understandability": [0.000157681, 0.986879, 0.0129637, 2.60952e-12], "complexity": [2.52283e-12, 0.000291194, 0.0930862, 0.906623], "modularization": [4.91083e-06, 0.040282, 0.91474, 0.0449732], "overall": [0.197425, 0.801695, 0.000880284, 1.53902e-13]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.translators.OBJImporter", "source": "/* Copyright (C) 2002-2012 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.translators;\n\nimport artofillusion.*;\nimport artofillusion.animation.*;\nimport artofillusion.image.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\nimport artofillusion.ui.*;\nimport buoy.widget.*;\nimport java.io.*;\nimport java.util.*;\n\n/** OBJImporter implements the importing of OBJ files. */\n\npublic class OBJImporter\n{\n  public static void importFile(BFrame parent)\n  {\n    BFileChooser bfc = new BFileChooser(BFileChooser.OPEN_FILE, Translate.text(\"importOBJ\"));\n    if (ArtOfIllusion.getCurrentDirectory() != null)\n      bfc.setDirectory(new File(ArtOfIllusion.getCurrentDirectory()));\n    if (!bfc.showDialog(parent))\n      return;\n    File f = bfc.getSelectedFile();\n    ArtOfIllusion.setCurrentDirectory(bfc.getDirectory().getAbsolutePath());\n    String objName = f.getName();\n    if (objName.lastIndexOf('.') > 0)\n      objName = objName.substring(0, objName.lastIndexOf('.'));\n    \n    // Create a scene to add objects to.\n    \n    Scene theScene = new Scene();\n    CoordinateSystem coords = new CoordinateSystem(new Vec3(0.0, 0.0, Camera.DEFAULT_DISTANCE_TO_SCREEN), new Vec3(0.0, 0.0, -1.0), Vec3.vy());\n    ObjectInfo info = new ObjectInfo(new SceneCamera(), coords, \"Camera 1\");\n    info.addTrack(new PositionTrack(info), 0);\n    info.addTrack(new RotationTrack(info), 1);\n    theScene.addObject(info, null);\n    info = new ObjectInfo(new DirectionalLight(new RGBColor(1.0f, 1.0f, 1.0f), 0.8f), coords.duplicate(), \"Light 1\");\n    info.addTrack(new PositionTrack(info), 0);\n    info.addTrack(new RotationTrack(info), 1);\n    theScene.addObject(info, null);\n\n    // Open the file and read the contents.\n    \n    Hashtable<String, Vector<FaceInfo>> groupTable = new Hashtable<String, Vector<FaceInfo>>();\n    Hashtable<String, TextureInfo> textureTable = new Hashtable<String, TextureInfo>();\n    Vector<Vec3> vertex = new Vector<Vec3>();\n    Vector<Vec3> normal = new Vector<Vec3>();\n    Vector<Vec3> texture = new Vector<Vec3>();\n    Vector<Vector<FaceInfo>> face = new Vector<Vector<FaceInfo>>();\n    face.add(new Vector<FaceInfo>());\n    groupTable.put(\"default\", face.get(0));\n    int lineno = 0, smoothingGroup = -1;\n    String currentTexture = null;\n    VertexInfo vertIndex[] = new VertexInfo [3];\n    double val[] = new double [3];\n    double min[] = new double [] {Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE};\n    double max[] = new double [] {-Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE};\n    String s;\n    BufferedReader in = null;\n    try\n      {\n        in = new BufferedReader(new FileReader(f));\n        while ((s = in.readLine()) != null)\n          {\n            lineno++;\n            if (s.startsWith(\"#\"))\n              continue;\n            if (s.endsWith(\"\\\\\"))\n            {\n              String s2;\n              while (s.endsWith(\"\\\\\") && (s2 = in.readLine()) != null)\n                s = s.substring(0, s.length()-1)+s2;\n            }\n            String fields[] = breakLine(s);\n            if (fields.length == 0)\n              continue;\n            if (\"v\".equals(fields[0]) && (fields.length == 4 || fields.length == 5))\n              {\n                // Read in a vertex.\n                \n                for (int i = 0; i < 3; i++)\n                  {\n                    try\n                      {\n                        val[i] = Double.parseDouble(fields[i+1]);\n                        if (val[i] < min[i])\n                          min[i] = val[i];\n                        if (val[i] > max[i])\n                          max[i] = val[i];\n                      }\n                    catch (NumberFormatException ex)\n                      {\n                        throw new Exception(\"Illegal value '\"+fields[i+1]+\n                          \"' found in line \"+lineno+\".\");\n                      }\n                  }\n                vertex.addElement(new Vec3(val[0], val[1], val[2]));\n              }\n            else if (\"vn\".equals(fields[0]) && fields.length == 4)\n              {\n                // Read in a vertex normal.\n                \n                for (int i = 0; i < 3; i++)\n                  {\n                    try\n                      {\n                        val[i] = Double.parseDouble(fields[i+1]);\n                      }\n                    catch (NumberFormatException ex)\n                      {\n                        throw new Exception(\"Illegal value '\"+fields[i+1]+\n                          \"' found in line \"+lineno+\".\");\n                      }\n                  }\n                normal.addElement(new Vec3(val[0], val[1], val[2]));\n              }\n            else if (\"vt\".equals(fields[0]) && fields.length > 1)\n              {\n                // Read in a texture vertex.\n                \n                for (int i = 0; i < 3; i++)\n                  {\n                    try\n                      {\n                        if (i < fields.length-1)\n                          val[i] = Double.parseDouble(fields[i+1]);\n                        else\n                          val[i] = 0.0;\n                      }\n                    catch (NumberFormatException ex)\n                      {\n                        throw new Exception(\"Illegal value '\"+fields[i+1]+\n                          \"' found in line \"+lineno+\".\");\n                      }\n                  }\n                texture.addElement(new Vec3(val[0], val[1], val[2]));\n              }\n            else if (\"f\".equals(fields[0]))\n              {\n                if (vertIndex.length != fields.length-1)\n                  vertIndex = new VertexInfo [fields.length-1];\n                for (int i = 0; i < vertIndex.length; i++)\n                  vertIndex[i] = parseVertexSpec(fields[i+1], vertex, texture, normal, lineno);\n                for (int i = 0; i < face.size(); i++)\n                  {\n                    if (fields.length == 4)\n                      {\n                        // Add a triangular face.\n                        \n                        face.get(i).addElement(new FaceInfo(vertIndex[0], vertIndex[1], vertIndex[2], smoothingGroup, currentTexture));\n                      }\n                    else\n                      {\n                        // Triangulate the outline.\n\n                        Vec3 v[] = new Vec3[fields.length-1];\n                        for (int j = 0; j < v.length; j++)\n                          v[j] = vertex.get(vertIndex[j].vert);\n                        Curve c = new Curve(v, new float[v.length], Mesh.NO_SMOOTHING, true);\n                        TriangleMesh m = c.convertToTriangleMesh(1.0);\n                        if (m != null)\n                          {\n                            for (int j = 0; j < m.getFaceCount(); j++)\n                              face.get(i).addElement(new FaceInfo(vertIndex[m.getFaceVertexIndex(j, 0)], vertIndex[m.getFaceVertexIndex(j, 1)], vertIndex[m.getFaceVertexIndex(j, 2)], smoothingGroup, currentTexture));\n                          }\n                        else\n                          {\n                            // We couldn't triangulate it correctly, so do the best we can.\n\n                            int step, start;\n                            for (step = 1; 2*step < vertIndex.length; step *= 2)\n                              {\n                                for (start = 0; start+2*step < vertIndex.length; start += 2*step)\n                                  face.get(i).addElement(new FaceInfo(vertIndex[start], vertIndex[start+step], vertIndex[start+2*step], smoothingGroup, currentTexture));\n                                if (start+step < vertIndex.length)\n                                  face.get(i).addElement(new FaceInfo(vertIndex[start], vertIndex[start+step], vertIndex[0], smoothingGroup, currentTexture));\n                              }\n                          }\n                      }\n                  }\n              }\n            else if (\"s\".equals(fields[0]))\n              {\n                // Set the smoothing group.\n                \n                if (fields.length == 1 || \"off\".equalsIgnoreCase(fields[1]))\n                  {\n                    smoothingGroup = 0;\n                    continue;\n                  }\n                try\n                  {\n                    smoothingGroup = Integer.parseInt(fields[1]);\n                  }\n                catch (NumberFormatException ex)\n                  {\n                    throw new Exception(\"Illegal value '\"+fields[1]+\n                      \"' found in line \"+lineno+\".\");\n                  }\n              }\n            else if (\"g\".equals(fields[0]))\n              {\n                // Set the current group or groups.\n\n                if (fields.length == 1)\n                  fields = new String[] {\"g\", \"default\"};\n                face.setSize(fields.length-1);\n                for (int i = 0; i < face.size(); i++)\n                  {\n                    face.set(i, groupTable.get(fields[i+1]));\n                    if (face.get(i) == null)\n                      {\n                        face.set(i, new Vector<FaceInfo>());\n                        groupTable.put(fields[i+1], face.get(i));\n                      }\n                  }\n              }\n            else if (\"usemtl\".equals(fields[0]) && fields.length > 1)\n              {\n                // Set the current texture.\n                \n                currentTexture = fields[1];\n              }\n            else if (\"mtllib\".equals(fields[0]))\n              {\n                // Load one or more texture libraries.\n                \n                for (int i = 1; i < fields.length; i++)\n                  parseTextures(fields[i], bfc.getDirectory(), textureTable);\n              }\n          }\n\n        // If no mtl file was specified, but there is one with the same name is the obj file,\n        // go ahead and load it.\n\n        if (textureTable.size() == 0)\n        {\n          File defaultMtl = new File(bfc.getDirectory(), objName+\".mtl\");\n          if (defaultMtl.isFile())\n            parseTextures(objName+\".mtl\", bfc.getDirectory(), textureTable);\n        }\n        \n        // If necessary, rescale the vertices to make the object an appropriate size.\n        \n        double maxSize = Math.max(Math.max(max[0]-min[0], max[1]-min[1]), max[2]-min[2]);\n        double scale = Math.pow(10.0, -Math.floor(Math.log(maxSize)/Math.log(10.0)));\n        for (int i = 0; i < vertex.size(); i++)\n          vertex.elementAt(i).scale(scale);\n        \n        // Create a triangle mesh for each group.\n        \n        Enumeration<String> keys = groupTable.keys();\n        Hashtable<String, Texture> realizedTextures = new Hashtable<String, Texture>();\n        Hashtable<String, ImageMap> imageMaps = new Hashtable<String, ImageMap>();\n        while (keys.hasMoreElements())\n          {\n            String group = keys.nextElement();\n            Vector<FaceInfo> groupFaces = groupTable.get(group);\n            if (groupFaces.size() == 0)\n              continue;\n            \n            // Find which vertices are used by faces in this group.\n            \n            int realIndex[] = new int [vertex.size()];\n            for (int i = 0; i < realIndex.length; i++)\n              realIndex[i] = -1;\n            int fc[][] = new int [groupFaces.size()][], numVert = 0;\n            for (int i = 0; i < fc.length; i++)\n              {\n                FaceInfo fi = groupFaces.elementAt(i);\n                for (int j = 0; j < 3; j++)\n                  if (realIndex[fi.getVertex(j).vert] == -1)\n                    realIndex[fi.getVertex(j).vert] = numVert++;\n                fc[i] = new int [] {realIndex[fi.v1.vert], realIndex[fi.v2.vert], realIndex[fi.v3.vert]};\n              }\n            \n            // Build the list of vertices and center them.\n            \n            Vec3 vert[] = new Vec3 [numVert], center = new Vec3();\n            for (int i = 0; i < realIndex.length; i++)\n              if (realIndex[i] > -1)\n                {\n                  vert[realIndex[i]] = vertex.elementAt(i);\n                  center.add(vert[realIndex[i]]);\n                }\n            center.scale(1.0/vert.length);\n            for (int i = 0; i < vert.length; i++)\n              vert[i] = vert[i].minus(center);\n            coords = new CoordinateSystem(center, Vec3.vz(), Vec3.vy());\n            info = new ObjectInfo(new TriangleMesh(vert, fc), coords, (\"default\".equals(group) ? objName : group));\n            info.addTrack(new PositionTrack(info), 0);\n            info.addTrack(new RotationTrack(info), 1);\n            \n            // Find the smoothness values for the edges.\n            \n            TriangleMesh.Edge edge[] = ((TriangleMesh) info.getObject()).getEdges();\n            for (int i = 0; i < edge.length; i++)\n              {\n                if (edge[i].f2 == -1)\n                  continue;\n                FaceInfo f1 = groupFaces.elementAt(edge[i].f1);\n                FaceInfo f2 = groupFaces.elementAt(edge[i].f2);\n                if (f1.smoothingGroup == 0 || f1.smoothingGroup != f2.smoothingGroup)\n                  {\n                    // They are in different smoothing groups.\n\n                    edge[i].smoothness = 0.0f;\n                    continue;\n                  }\n                \n                // Find matching vertices and compare their normals.\n                \n                for (int j = 0; j < 3; j++)\n                  for (int k = 0; k < 3; k++)\n                    if (f1.getVertex(j).vert == f2.getVertex(k).vert)\n                      {\n                        int n1 = f1.getVertex(j).norm;\n                        int n2 = f2.getVertex(k).norm;\n                        if (n1 != n2 && normal.elementAt(n1).distance(normal.elementAt(n2)) > 1e-10)\n                          edge[i].smoothness = 0.0f;\n                        break;\n                      }\n              }\n            \n            // Set the texture.  Begin by finding all textures used by the group.\n\n            HashSet<String> texNames = new HashSet<String>();\n            for (FaceInfo faceInfo : groupFaces)\n              if (faceInfo.texture != null)\n                texNames.add(faceInfo.texture);\n\n            // If multiple textures are needed, create a layered texture.\n\n            LayeredMapping layered = null;\n            if (texNames.size() > 1)\n            {\n              LayeredTexture tex = new LayeredTexture(info.getObject());\n              layered = (LayeredMapping) tex.getDefaultMapping(info.getObject());\n              info.setTexture(tex, layered);\n            }\n\n            // Now create all the textures.\n\n            for (String texName : texNames)\n            {\n              Texture tex = realizedTextures.get(texName);\n              if (tex == null)\n              {\n                tex = createTexture(textureTable.get(texName), texName, theScene, bfc.getDirectory(), imageMaps);\n                realizedTextures.put(texName, tex);\n              }\n              if (tex instanceof Texture2D)\n              {\n                // Set the UV coordinates.\n\n                UVMapping map = new UVMapping(info.getObject(), tex);\n                if (layered == null)\n                  info.setTexture(tex, map);\n                else\n                {\n                  layered.addLayer(0, tex, map, LayeredMapping.BLEND);\n                  info.setTexture(layered.getTexture(), layered);\n                }\n                Vec2 uv[] = new Vec2 [numVert];\n                boolean needPerFace = false;\n                for (int j = 0; j < groupFaces.size() && !needPerFace; j++)\n                  {\n                    FaceInfo fi = groupFaces.elementAt(j);\n                    for (int k = 0; k < 3; k++)\n                      {\n                        VertexInfo vi = fi.getVertex(k);\n                        Vec3 texCoords = (vi.tex < texture.size() ? texture.elementAt(vi.tex) : vertex.elementAt(vi.vert));\n                        Vec2 tc = new Vec2(texCoords.x, texCoords.y);\n                        if (uv[realIndex[vi.vert]] != null && !uv[realIndex[vi.vert]].equals(tc))\n                          needPerFace = true;\n                        uv[realIndex[vi.vert]] = tc;\n                      }\n                  }\n                TextureParameter uparam = map.getUParameter();\n                TextureParameter vparam = map.getVParameter();\n                if (layered != null)\n                {\n                  uparam = layered.getParameterForLayer(uparam, 0);\n                  vparam = layered.getParameterForLayer(vparam, 0);\n                }\n                if (needPerFace)\n                {\n                  // Different faces have different texture coordinates for the same vertex,\n                  // so we need to use per-face-vertex coordinates.\n\n                  Vec2 uvf[][] = new Vec2 [groupFaces.size()][3];\n                  for (int j = 0; j < groupFaces.size(); j++)\n                  {\n                    FaceInfo fi = groupFaces.elementAt(j);\n                    for (int k = 0; k < 3; k++)\n                      {\n                        VertexInfo vi = fi.getVertex(k);\n                        Vec3 texCoords = (vi.tex < texture.size() ? texture.elementAt(vi.tex) : vertex.elementAt(vi.vert));\n                        uvf[j][k] = new Vec2(texCoords.x, texCoords.y);\n                      }\n                  }\n                  map.setFaceTextureCoordinates(info.getObject(), uvf, uparam, vparam);\n                }\n                else\n                {\n                  map.setTextureCoordinates(info.getObject(), uv, uparam, vparam);\n                }\n              }\n              else\n              {\n                if (layered == null)\n                  info.setTexture(tex, tex.getDefaultMapping(info.getObject()));\n                else\n                {\n                  layered.addLayer(0, tex, tex.getDefaultMapping(info.getObject()), LayeredMapping.BLEND);\n                  info.setTexture(layered.getTexture(), layered);\n                }\n              }\n\n              // If we are using a layered texture, set a parameter defining what layer to use\n              // for each face.\n\n              if (layered != null)\n              {\n                double paramValue[] = new double[groupFaces.size()];\n                for (int i = 0; i < paramValue.length; i++)\n                  paramValue[i] = (texName.equals(groupFaces.get(i).texture) ? 1.0 : 0.0);\n                TextureParameter parameter = layered.getLayerBlendingParameter(0);\n                info.getObject().setParameterValue(parameter, new FaceParameterValue(paramValue));\n              }\n            }\n            theScene.addObject(info, null);\n          }\n      }\n    catch (Exception ex)\n      {\n        try\n          {\n            in.close();\n          }\n        catch (Exception ex2)\n          {\n          }\n        new BStandardDialog(\"\", new String [] {Translate.text(\"errorLoadingFile\"), ex.getMessage() == null ? \"\" : ex.getMessage()}, BStandardDialog.ERROR).showMessageDialog(parent);\n        return;\n      }\n    ArtOfIllusion.newWindow(theScene);\n  }\n  \n  /** Separate a line into pieces divided by whitespace. */\n  \n  private static String [] breakLine(String line)\n  {\n    StringTokenizer st = new StringTokenizer(line);\n    Vector<String> v = new Vector<String>();\n    \n    while (st.hasMoreTokens())\n      v.addElement(st.nextToken());\n    String result[] = new String [v.size()];\n    v.copyInto(result);\n    return result;\n  }\n  \n  /** Parse the specification for a vertex and return the index of the vertex\n      to use. */\n  \n  private static VertexInfo parseVertexSpec(String spec, Vector vertex, Vector texture, Vector normal, int lineno) throws Exception\n  {\n    VertexInfo info = new VertexInfo();\n    StringTokenizer st = new StringTokenizer(spec, \"/\", true);\n    info.tex = info.norm = Integer.MAX_VALUE;\n    int i = 0;\n    while (st.hasMoreTokens())\n      {\n        String value = st.nextToken();\n        if (\"/\".equals(value))\n          {\n            i++;\n            continue;\n          }\n        try\n          {\n            int index = Integer.parseInt(value);\n            int total;\n            if (i == 0)\n              total = vertex.size();\n            else if (i == 1)\n              total = texture.size();\n            else\n              total = normal.size();\n            if (index < 0)\n              index += total;\n            else\n              index--;\n            if (i == 0)\n              info.vert = index;\n            else if (i == 1)\n              info.tex = index;\n            else\n              info.norm = index;\n          }\n        catch (NumberFormatException ex)\n          {\n            throw new Exception(\"Illegal value '\"+spec+\"' found in line \"+lineno+\".\");\n          }\n      }\n    if (info.tex == Integer.MAX_VALUE)\n      info.tex = info.vert;\n    if (info.norm == Integer.MAX_VALUE)\n      info.norm = info.vert;\n    return info;\n  }\n  \n  /** Parse the contents of a .mtl file and add TextureInfo object to a hashtable. */\n  \n  private static void parseTextures(String file, File baseDir, Hashtable<String, TextureInfo> textures) throws Exception\n  {\n    File f = new File(baseDir, file);\n    if (!f.isFile())\n      f = new File(file);\n    if (!f.isFile())\n    {\n      new BStandardDialog(\"Error Importing File\", \"Cannot locate material file '\"+file+\"'.\", BStandardDialog.ERROR).showMessageDialog(null);\n      return;\n    }\n    BufferedReader in = new BufferedReader(new FileReader(f));\n    String line;\n    TextureInfo currentTexture = null;\n    while ((line = in.readLine()) != null)\n      {\n        try\n          {\n            if (line.startsWith(\"#\"))\n              continue;\n            String fields[] = breakLine(line);\n            if (fields.length == 0)\n              continue;\n            if (\"newmtl\".equals(fields[0]))\n              {\n                // This is the start of a new texture.\n                \n                currentTexture = null;\n                if (fields.length == 1 || textures.get(fields[1]) != null)\n                  continue;\n                currentTexture = new TextureInfo();\n                textures.put(fields[1], currentTexture);\n              }\n            if (currentTexture == null || fields.length < 2)\n              continue;\n            if (\"Kd\".equals(fields[0]))\n              currentTexture.diffuse = parseColor(fields);\n            else if (\"Ka\".equals(fields[0]))\n              currentTexture.ambient = parseColor(fields);\n            else if (\"Ks\".equals(fields[0]))\n              currentTexture.specular = parseColor(fields);\n            else if (\"d\".equals(fields[0]) || \"Tr\".equals(fields[0]))\n              currentTexture.transparency = 1.0-Double.parseDouble(fields[1]);\n            else if (\"Ns\".equals(fields[0]))\n              currentTexture.shininess = Double.parseDouble(fields[1]);\n            else if (\"map_Kd\".equals(fields[0]))\n              currentTexture.diffuseMap = fields[1];\n            else if (\"map_Ka\".equals(fields[0]))\n              currentTexture.ambientMap = fields[1];\n            else if (\"map_Ks\".equals(fields[0]))\n              currentTexture.specularMap = fields[1];\n            else if (\"map_d\".equals(fields[0]))\n              currentTexture.transparentMap = fields[1];\n            else if (\"map_Bump\".equals(fields[0]))\n              currentTexture.bumpMap = fields[1];\n          }\n        catch (Exception ex)\n          {\n            in.close();\n            throw new Exception(\"Illegal line '\"+line+\"' found in file '\"+file+\"'.\");\n          }\n      }\n    in.close();\n  }\n  \n  /** Create a texture from a TextureInfo and add it to the scene. */\n  \n  private static Texture createTexture(TextureInfo info, String name, Scene scene, File baseDir, Hashtable<String, ImageMap> imageMaps) throws Exception\n  {\n    if (info == null)\n    {\n      // This texture was not defined in an MTL file.  Create an empty image mapped texture\n      // so that texture coordinates will be preserved and the user can specify the images\n      // later.\n\n      ImageMapTexture tex = new ImageMapTexture();\n      tex.setName(name);\n      scene.addTexture(tex);\n      return tex;\n    }\n    info.resolveColors();\n    ImageMap diffuseMap = loadMap(info.diffuseMap, scene, baseDir, imageMaps);\n    ImageMap specularMap = loadMap(info.specularMap, scene, baseDir, imageMaps);\n    ImageMap transparentMap = loadMap(info.transparentMap, scene, baseDir, imageMaps);\n    ImageMap bumpMap = loadMap(info.bumpMap, scene, baseDir, imageMaps);\n    RGBColor transparentColor =  new RGBColor(info.transparency, info.transparency, info.transparency);\n    if (diffuseMap == null && specularMap == null && transparentMap == null && bumpMap == null)\n      {\n        // Create a uniform texture.\n        \n        UniformTexture tex = new UniformTexture();\n        tex.diffuseColor = info.diffuse.duplicate();\n        tex.specularColor = info.specular.duplicate();\n        tex.transparentColor = transparentColor;\n        tex.shininess = (float) info.specularity;\n        tex.specularity = 0.0f;\n        tex.roughness = info.roughness;\n        tex.setName(name);\n        scene.addTexture(tex);\n        return tex;\n      }\n    else\n      {\n        // Create an image mapped texture.\n\n        ImageMapTexture tex = new ImageMapTexture();\n        tex.diffuseColor = (diffuseMap == null ? new ImageOrColor(info.diffuse) : new ImageOrColor(info.diffuse, diffuseMap));\n        tex.specularColor = (specularMap == null ? new ImageOrColor(info.specular) : new ImageOrColor(info.specular, specularMap));\n        tex.transparentColor = (transparentMap == null ? new ImageOrColor(transparentColor) : new ImageOrColor(transparentColor, transparentMap));\n        if (transparentMap == null && info.transparency == 0.0 && diffuseMap != null && diffuseMap.getComponentCount() == 4)\n        {\n          // Use the diffuse map's alpha channel channel for transparency.\n\n          tex.transparentColor = new ImageOrColor(new RGBColor(1.0, 1.0, 1.0));\n          tex.transparency = new ImageOrValue(1.0f, diffuseMap, 3);\n        }\n        if (bumpMap != null)\n          tex.bump = new ImageOrValue(1.0f, bumpMap, 0);\n        tex.shininess = new ImageOrValue((float) info.specularity);\n        tex.specularity = new ImageOrValue(0.0f);\n        tex.roughness = new ImageOrValue((float) info.roughness);\n        tex.tileX = tex.tileY = true;\n        tex.mirrorX = tex.mirrorY = false;\n        tex.setName(name);\n        scene.addTexture(tex);\n        return tex;\n      }\n  }\n  \n  /** Return the image map corresponding to the specified filename, and add it to the scene. */\n  \n  private static ImageMap loadMap(String name, Scene scene, File baseDir, Hashtable<String, ImageMap> imageMaps) throws Exception\n  {\n    if (name == null)\n      return null;\n    ImageMap map = imageMaps.get(name);\n    if (map != null)\n      return map;\n    File f = new File(baseDir, name);\n    if (!f.isFile())\n      f = new File(name);\n    if (!f.isFile())\n      throw new Exception(\"Cannot locate image map file '\"+name+\"'.\");\n    try\n      {\n        map = ImageMap.loadImage(f);\n      }\n    catch (InterruptedException ex)\n      {\n        throw new Exception(\"Unable to load image map file '\"+f.getAbsolutePath()+\"'.\");\n      }\n    scene.addImage(map);\n    imageMaps.put(name, map);\n    return map;\n  }\n  \n  /** Parse the specification for a color. */\n  \n  private static RGBColor parseColor(String fields[]) throws NumberFormatException\n  {\n    if (fields.length < 4)\n      return null;\n    return new RGBColor(Double.parseDouble(fields[1]),\n        Double.parseDouble(fields[2]),\n        Double.parseDouble(fields[3]));\n  }\n  \n  /** Inner class for storing information about a vertex of a face. */\n  \n  private static class VertexInfo\n  {\n    public int vert, norm, tex;\n  }\n  \n  /** Inner class for storing information about a face. */\n  \n  private static class FaceInfo\n  {\n    public VertexInfo v1, v2, v3;\n    public int smoothingGroup;\n    public String texture;\n    \n    public FaceInfo(VertexInfo v1, VertexInfo v2, VertexInfo v3, int smoothingGroup, String texture)\n    {\n      this.v1 = v1;\n      this.v2 = v2;\n      this.v3 = v3;\n      this.smoothingGroup = smoothingGroup;\n      this.texture = texture;\n    }\n    \n    public VertexInfo getVertex(int which)\n    {\n      switch (which)\n        {\n          case 0: return v1;\n          case 1: return v2;\n          default: return v3;\n        }\n    }\n  }\n  \n  /** Inner class for storing information about a texture in a .mtl file. */\n  \n  private static class TextureInfo\n  {\n    public RGBColor ambient, diffuse, specular;\n    public double shininess, transparency, specularity, roughness;\n    public String ambientMap, diffuseMap, specularMap, transparentMap, bumpMap;\n    \n    /** This should be called once, after the TextureInfo is created but before it is actually used.  It converts from the\n        representation used by .obj files to the one used by Art of Illusion. */\n        \n    public void resolveColors()\n    {\n      if (diffuse == null)\n      {\n        if (diffuseMap == null)\n          diffuse = new RGBColor(0.0, 0.0, 0.0);\n        else\n          diffuse = new RGBColor(1.0, 1.0, 1.0);\n      }\n      if (ambient == null)\n        ambient = new RGBColor(0.0, 0.0, 0.0);\n      if (specular == null)\n        specular = new RGBColor(0.0, 0.0, 0.0);\n      else\n        specularity = 1.0;\n      diffuse.scale(1.0-transparency);\n      specular.scale(1.0-transparency);\n      roughness = 1.0-(shininess-1.0)/128.0;\n      if (roughness > 1.0)\n        roughness = 1.0;\n      checkColorRange(ambient);\n      checkColorRange(diffuse);\n      checkColorRange(specular);\n    }\n    \n    /** Make sure that the components of a color are all between 0 and 1. */\n    \n    private void checkColorRange(RGBColor c)\n    {\n      float r = c.getRed(), g = c.getGreen(), b = c.getBlue();\n      if (r < 0.0f) r = 0.0f;\n      if (r > 1.0f) r = 1.0f;\n      if (g < 0.0f) g = 0.0f;\n      if (g > 1.0f) g = 1.0f;\n      if (b < 0.0f) b = 0.0f;\n      if (b > 1.0f) b = 1.0f;\n      c.setRGB(r, g, b);\n    }\n  }\n}", "human_rating": 2.188569015991616, "metadata": {"project": "aoi", "class": "artofillusion.translators.OBJImporter", "source_path": "aoi/sourcefiles/Translators/src/artofillusion/translators/OBJImporter.java", "label_probabilities": {"readability": [8.53956e-13, 0.188569, 0.811431, 1.59882e-08], "understandability": [2.7656e-09, 1.47172e-11, 7.53095e-07, 0.999999], "complexity": [0.845248, 0.154752, 1.72002e-07, 0.0], "modularization": [0.997098, 0.00290135, 8.83033e-07, 1e-20], "overall": [0.0, 0.0, 7.48167e-07, 0.999999]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.translators.POVExporter", "source": "/* Copyright (C) 2002-2007 by Norbert Krieg and Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.translators;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.ui.*;\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\nimport buoy.widget.*;\nimport java.io.*;\nimport java.util.*;\n\n/** POVExporter contains the actual routines for exporting POV files. */\n\npublic class POVExporter\n{\n    static boolean DEBUG=false;\n    static int DIRECTIONAL_LIGHT_DISTANCE=10000;   // for directional light simulating\n    static int MAXIMAL_LIGHT_FADE_DISTANCE=10000;  // = decay rate is set to zero\n    static int TIGHTNESS=10;  // = decay rate for the spotlight\n    static char CHAR_REPLACE='_';\n    static final String TEXTURE_NAME_PREFIX=\"AOI\";  //  prefix of the texture declaration for povray files\n    static final char REPLACEMENT_CHARACTER='_';   // replacement for non allowed characters in names\n    static final String FIX_SEPARATOR=\".\";   // The separator in file names of suffices and prefices\n\n    static String exportFileName=\"Untitled\";\n\n    public static void exportFile(BFrame parent, Scene theScene)\n    {\n\t// Display a dialog box with options on how to export the scene.\n\t\n\tValueField errorField = new ValueField(0.05, ValueField.POSITIVE);\n\tBCheckBox smoothBox = new BCheckBox(\"Smooth Meshes\", true);\n\tBCheckBox includeBox = new BCheckBox(\"Produce Extra Includefile for Povray textures\", true);\n        BComboBox exportChoice = new BComboBox(new String [] {\n          Translate.text(\"exportWholeScene\"),\n          Translate.text(\"selectedObjectsOnly\")\n        });\n\tComponentsDialog dlg;\n\tif (theScene.getSelection().length > 0)\n\t    dlg = new ComponentsDialog(parent, Translate.text(\"exportToPOV\"), \n\t\t\t\t       new Widget [] {exportChoice, Translate.label(\"maxSurfaceError\"), errorField, includeBox, smoothBox}, \n\t\t\t\t       new String [] {\"\", \"\", \"\", \"\", \"\"});\n\telse\n\t    dlg = new ComponentsDialog(parent, Translate.text(\"exportToPOV\"), \n\t\t\t\t       new Widget [] {Translate.label(\"maxSurfaceError\"), errorField, includeBox, smoothBox}, \n\t\t\t\t       new String [] {\"\", \"\", \"\", \"\"});\n\tif (!dlg.clickedOk())\n\t    return;\n\t\n\t// Ask the user to select the output file.\n\n        BFileChooser fc = new BFileChooser(BFileChooser.SAVE_FILE, Translate.text(\"exportToPOV\"));\n\tString suffix=\".pov\", suffix2=\".inc\";\n\tfc.setSelectedFile(new File(exportFileName+suffix));\n\tif (ArtOfIllusion.getCurrentDirectory() != null)\n\t    fc.setDirectory(new File(ArtOfIllusion.getCurrentDirectory()));\n\t// Get the result\n\tif (!fc.showDialog(parent))\n\t    return;\n        File path = fc.getDirectory();\n\tint endpos=fc.getSelectedFile().getName().indexOf(FIX_SEPARATOR);\n\tif (endpos==-1) endpos=fc.getSelectedFile().getName().length();\n\texportFileName=fc.getSelectedFile().getName().substring(0,endpos);\n\tArtOfIllusion.setCurrentDirectory(fc.getDirectory().getAbsolutePath());\n\t\n\t// Check whether file/s exist/s\n\tFile f=null;\n\tf=new File(path, exportFileName+suffix);\n\tif (f.exists()) {\n\t    //overwrite dialog\n            String options[] = new String [] {Translate.text(\"Yes\"), Translate.text(\"No\")};\n            int choice = new BStandardDialog(\"\", Translate.text(\"overwriteFile\", exportFileName+suffix), BStandardDialog.QUESTION).showOptionDialog(parent, options, options[1]);\n\t    if (choice==1)\n              return;\n\t}\n\t// Check whether to produce an include file or not\n\tboolean bIncludeFile=includeBox.getState();\n\tif (bIncludeFile) {\n\t    f=new File(path, exportFileName+suffix2);\n\t    if (f.exists()) {\n\t\t// overwrite dialog, if not then write a single pov file and inform the user\n                String options[] = new String [] {Translate.text(\"Yes\"), Translate.text(\"No\")};\n                int choice = new BStandardDialog(\"\", Translate.text(\"overwriteFile\", exportFileName+suffix2), BStandardDialog.QUESTION).showOptionDialog(parent, options, options[1]);\n                if (choice==1)\n\t\t    bIncludeFile=false; // Write to the povray file\n\t    }\n\t}\n\n\t// Create the output file.\n\ttry\n\t    {\n\t\tFileOutputStream fos = new FileOutputStream(new File(path, exportFileName+suffix));\n\t\tBufferedOutputStream bos = new BufferedOutputStream(fos);\n\t\tFileOutputStream fos2=null;\n\t\tBufferedOutputStream bos2=null;\n\t\tif (bIncludeFile) {\n\t\t    fos2=new FileOutputStream(new File(path, exportFileName+suffix2));\n\t\t    bos2=new BufferedOutputStream(fos2);\n\t\t}\n\t\twriteScene(theScene, bos,exportChoice.getSelectedIndex() == 0, errorField.getValue(), smoothBox.getState(),bos2,exportFileName+suffix2);\n\t\tbos.close();\n\t\tif (bos2!=null) bos2.close();\n\t\tfos.close();\n\t\tif (fos2!=null) fos2.close();\n\t    }\n\tcatch (IOException ex)\n\t    {\n              new BStandardDialog(\"\", new String [] {Translate.text(\"errorExportingScene\"), ex.getMessage() == null ? \"\" : ex.getMessage()}, BStandardDialog.ERROR).showMessageDialog(parent);\n\t    }\n    }\n    \n    /* Write out the scene in POV format to the specified OutputStream.  The other parameters\n       correspond to the options in the dialog box displayed by exportFile(). */\n    \n    static void writeScene(Scene theScene, OutputStream os, boolean wholeScene, double tol, boolean smooth, OutputStream os2, String includeFileName)\n    {\n\tPrintWriter out = new PrintWriter(os);\n\tPrintWriter out2 = out;\n\tboolean bIncludeFile=false;\n\tif (os2!=null) {\n\t    out2=new PrintWriter(os2);\n\t    bIncludeFile=true;\n\t}\n\t\n\t// Write the header information.\n\t\n\twrite(\"// POV V3.5\", out, 0);\n\twrite(\"// Produced by Art of Illusion (Peter Eastman) \"+ArtOfIllusion.getVersion(), out, 0);\n\twrite(\"//   and POVExporter plugin (Norbert Krieg) version 1.11\", out, 0);\n\twrite(\"//   creation date: \"+new Date().toString(),out,0);\n\twrite(\"\",out,0);\n\tif (bIncludeFile) {\n\t    write(\"// POV V3.5 (include file)\",out2,0);\n\t    write(\"// Produced by Art of Illusion (Peter Eastman) \"+ArtOfIllusion.getVersion(), out2, 0);\n\t    write(\"//   and POVExporter plugin (Norbert Krieg) version 1.11\", out2, 0);\n\t    write(\"//   creation date: \"+new Date().toString(),out2,0);\n\t    write(\"\",out2,0);\n\t}\n\t\n\t// Language spezific settings\n\twrite(\"#version 3.5;\",out,0);\n\twrite(\"\",out,0);\n\t\n\t// Global settings\n\t// only if writeing a whole scene\n\tif (wholeScene) {\n\t    write(\"// Global settings\",out,0);\n\t    // Background color\n\t    RGBColor color = theScene.getEnvironmentColor();\n\t    write(\"background { color rgb <\"+color.getRed()+\",\"+color.getGreen()+\",\"+color.getBlue()+\"> }\", out, 0);\n\t    \n\t    // global settings for povray\n\t    write(\"global_settings {\",out,0);\n\t    \n\t    // ambient color\n\t    color=theScene.getAmbientColor();\n\t    write(\"ambient_light <\"+color.getRed()+\",\"+color.getGreen()+\",\"+color.getBlue()+\">\",out,1);\n\t    \n\t    // global settings for povray end\n\t    write(\"}\",out,0);\n\t    \n\t    // fog if present\n\t    if (theScene.getFogState()) {\n\t\tcolor=theScene.getFogColor();\n\t\twrite(\"fog {\",out,0);\n\t\twrite(\"color <\"+color.getRed()+\",\"+color.getGreen()+\",\"+color.getBlue()+\">\",out,1);\n\t\twrite(\"distance \"+theScene.getFogDistance(),out,1);\n\t\twrite(\"}\",out,0);\n\t    }\n\t}\n\twrite(\"\",out,0);\n\t\n\t// Write declarations, camera, lights and objects into file\n\tint selected[] = theScene.getSelection();\n\tint maxIndex=0;\n\t// writing the declarations\n\twrite(\"// texture declarations\",out2,0);\n\tif (wholeScene) {\n\t    maxIndex=theScene.getNumObjects();\n\t    for (int i = 0; i < maxIndex; i++) writeTexture(theScene,theScene.getObject(i),out2,1);\n\t} else {\n\t    maxIndex=selected.length;\n\t    for (int i = 0; i < maxIndex; i++) writeTexture(theScene,theScene.getObject(selected[i]),out2,1);\n\t}\n\tout2.flush();\n\t// write a language directive to include the texture declarations\n\tif (bIncludeFile) {\n\t    write(\"#include \\\"\"+includeFileName+\"\\\"\",out,0);\n\t}\n\t// writing the objects\n\twrite(\"\",out,0);\n\tif (wholeScene) {\n\t    maxIndex=theScene.getNumObjects();\n\t    for (int i = 0; i < maxIndex; i++) writeObjects(theScene,theScene.getObject(i),out,smooth,tol);\n\t} else {\n\t    maxIndex=selected.length;\n\t    for (int i = 0; i < maxIndex; i++) writeObjects(theScene,theScene.getObject(selected[i]),out,smooth,tol);\n\t}\n\t\n\tout.flush();\n    }\n    \n    /* Write a single line to the PrintWriter, indented by the specified number of tabs. */\n    \n    static void write(String str, PrintWriter out, int indent)\n    {\n\tfor (int i = 0; i < indent; i++)\n\t    out.print(\"\\t\");\n\tout.print(str);\n\tout.println();\n    }\n\n    static String getVec3String(Vec3 vec) {\n        if (vec == null)\n          return \"<1,0,0>\";\n\tdouble x=Math.round(vec.x*1e6)/1e6;\n\tdouble y=Math.round(vec.y*1e6)/1e6;\n\tdouble z=Math.round(vec.z*1e6)/1e6;\n\treturn \"<\"+x+\",\"+y+\",\"+z+\">\";\n    }\n    \n    static private String cleanName (String oldName) {\n\tStringBuffer workString=new StringBuffer(oldName.trim());\n\tfor (int i=0;i<workString.length();i++) {\n\t    char c=workString.charAt(i);\n\t    if (! java.lang.Character.isLetterOrDigit(c)) {\n\t\tworkString.setCharAt(i,CHAR_REPLACE);\n\t    }\n\t}\n\treturn workString.toString();\n    }\n    \n    /* Write out a series of rotations corresponding to a coordinate system. */\n    \n    private static void writeRotation(CoordinateSystem coords, PrintWriter out, int indent)\n    {\n      double [] rot=coords.getRotationAngles();\n      write(\"rotate <0,0,\"+(-rot[2])+\">\",out,indent);\n      write(\"rotate <\"+(-rot[0])+\",0,0>\",out,indent);\n      write(\"rotate <0,\"+(-rot[1])+\",0>\",out,indent);\n    }\n\n    /* Write out an Appearance node describing a Texture. */\n    \n    static void writeTexture(Scene theScene, ObjectInfo obj, PrintWriter out,int indent)\n    {\n\t// ObjectInfo obj=theScene.getObject(index);\n\tTexture tex = obj.getObject().getTexture();\n\tif (tex == null) return;\n\tTextureSpec spec;\n\t\n\tspec = new TextureSpec();\n\ttex.getAverageSpec(spec, theScene.getTime(), obj.getObject().getAverageParameterValues());\n\t\n\tString texName=cleanName(tex.getName());\n\tif (tex.getID()==1) texName=cleanName(obj.getName());\n\tif (DEBUG) {\n\t    System.err.println(\"Texture \"+tex.getName()+\":\\t\"+tex.getID());\n\t}\n\t\n\twrite(\"#declare \"+TEXTURE_NAME_PREFIX+texName+\" = \",out,0);\n\twrite(\"texture {\",out,indent);\n\twrite(\"pigment {\",out,indent+1);\n\twrite(\"color <\"+spec.diffuse.getRed()+\",\"+spec.diffuse.getGreen()+\",\"+spec.diffuse.getBlue()+\">\",out,indent+2);\n\twrite(\"}\",out,indent+1);\n\twrite(\"finish {\",out,indent+1);\n\twrite(\"ambient \"+Math.max(spec.emissive.getRed(), Math.max(spec.emissive.getGreen(), spec.emissive.getBlue())), out, indent+2);\n\twrite(\"specular \"+Math.max(spec.specular.getRed(), Math.max(spec.specular.getGreen(), spec.specular.getBlue())), out, indent+2);\n\twrite(\"roughness \"+spec.roughness,out,indent+2);\n\twrite(\"}\",out,indent+1);\n\twrite(\"}\",out,indent);\n\t\n\t/*\n\t  write(\"emissiveColor \"+spec.emissive.getRed()+\" \"+spec.emissive.getGreen()+\" \"+spec.emissive.getBlue(), out, indent+2);\n\t  write(\"specularColor \"+spec.specular.getRed()+\" \"+spec.specular.getGreen()+\" \"+spec.specular.getBlue(), out, indent+2);\n\t  write(\"shininess \"+(1.0-spec.roughness), out, indent+2);\n\t  write(\"transparency \"+Math.max(spec.transparent.getRed(), Math.max(spec.transparent.getGreen(), spec.transparent.getBlue())), out, indent+2);\n\t  write(\"ambientIntensity 1\", out, indent+2);\n\t  write(\"}\", out, indent+1);\n\t  write(\"}\", out, indent);\n\t*/\n    }\n    \n    static void writeObjects(Scene theScene, ObjectInfo obj, PrintWriter out,boolean smooth,double tolerance) {\n    // Camera setting\n    // (not very good because of extra loop count - but for readability purposes of POV file better)\n\tif (!obj.isVisible()) return;\n\tif (obj.getObject() instanceof SceneCamera) {\n\t    write(\"// Camera settings\",out,0);\n\t    ObjectInfo info = (ObjectInfo)obj;\n\t    CoordinateSystem coords = info.getCoords().duplicate();\n\t    // n�tig ???? obwohl KoSys linksh�ndig????\n\t    //coords.setOrientation(coords.getZDirection().times(-1.0), coords.getUpDirection().times(1.0));\n\t    Vec3 orig=coords.getOrigin();\n\t    String location=\"location \"+getVec3String(orig);\n            Vec3 zdir = coords.getZDirection();\n            Vec3 updir = coords.getUpDirection();\n            Vec3 rightdir = zdir.cross(updir).times(1.33);\n\t    String direction=\"direction <\"+zdir.x+\",\"+zdir.y+\",\"+zdir.z+\">\";\n\t    String up=\"up <\"+updir.x+\",\"+updir.y+\",\"+updir.z+\">\";\n\t    String right=\"right <\"+rightdir.x+\",\"+rightdir.y+\",\"+rightdir.z+\">\";\n\t    String angle=\"angle \"+(((SceneCamera) obj.getObject()).getFieldOfView()*1.33);\n\t    write(\"camera {\",out,0);\n\t    write(\"perspective\",out,1);\n\t    write(location,out,1);\n\t    write(direction,out,1);\n\t    write(up,out,1);\n\t    write(right,out,1);\n\t    write(angle,out,1);\n\t    write(\"}\",out,0);\n\t    if (DEBUG) {\n\t\tSystem.err.println(\"Camera:\");\n\t\tSystem.err.println(\"// Standort:\\t\"+orig.toString());\n\t\tSystem.err.println(\"// Blickrichtung:\\t\"+coords.getZDirection().toString());\n\t\tSystem.err.println(\"// Up-Richtung:\\t\"+coords.getUpDirection().toString());\n\t\tSystem.err.println(\"// Right (for aspect ratio):\\t\"+coords.getUpDirection().cross(coords.getZDirection()).times(1.33).toString());\n\t    }\n\t    write(\"\",out,0);\n\t}\n\t// Light setting\n\t// in extra loop for having it at the beginning of the povray file\n\t// Directional Light\n\t// in POVRAY it is a very far away point light\n\t// i.e. 10000 units should be in most cases far enough\n\telse if (obj.getObject() instanceof DirectionalLight) {\n\t    write(\"// Directional light (simulated as far away point light distance=\"+DIRECTIONAL_LIGHT_DISTANCE+\"units)\",out,0);\n\t    DirectionalLight light=(DirectionalLight) obj.getObject();\n\t    ObjectInfo info=(ObjectInfo)obj.duplicate();\n\t    CoordinateSystem coords = info.getCoords();\n\t    Vec3 zdir=coords.getZDirection();\n\t    float intensity=light.getIntensity();\n\t    RGBColor color=light.getColor().duplicate();\n\t    color.scale(intensity);\n\t    zdir.normalize(); // to get a defined distance\n\t    zdir.scale(-DIRECTIONAL_LIGHT_DISTANCE);\n\t    write(\"// \"+ info.getName(),out,0);\n\t    write(\"light_source {\",out,0);\n\t    write(getVec3String(zdir),out,1);\n\t    write(\"color <\"+color.getRed()+\",\"+color.getGreen()+\",\"+color.getBlue()+\">\",out,1);\n\t    write(\"parallel\",out,1);\n\t    write(\"point_at \"+getVec3String(new Vec3(0,0,0)),out,1);\n\t    write(\"}\",out,0);\n\t    write(\"\",out,0);\n\t    if (DEBUG) {\n\t\tSystem.err.println(\"// Directional Light source\");\n\t\tSystem.err.println(\"// --> point light:\");\n\t\tSystem.err.println(\"// Position:\\t\"+zdir.toString());\n\t\tSystem.err.println(\"// Color:\\t\"+color.toString());\n\t    }\n\t}\n\telse if (obj.getObject() instanceof PointLight) {\n\t    write(\"// Point light\",out,0);\n\t    write(\"// decay is different than in Art Of Illusion\",out,0);\n\t    write(\"// the point light source has actually no \\\"radius\\\"\",out,0);\n\t    PointLight light=(PointLight) obj.getObject();\n\t    ObjectInfo info=(ObjectInfo)obj.duplicate();\n\t    CoordinateSystem coords = info.getCoords();\n\t    Vec3 orig=coords.getOrigin();\n\t    float intensity=light.getIntensity();\n\t    RGBColor color=light.getColor().duplicate();\n\t    color.scale(intensity);\n\t    //double radius=light.getRadius();\n\t    float dr=light.getDecayRate();\n\t    double fadeDistance=MAXIMAL_LIGHT_FADE_DISTANCE;\n\t    if (dr!=0.0) fadeDistance=0.5/(new Float(dr).doubleValue());\n\t    double fadePower=2.0; \n\t    if (fadeDistance>=5.0) fadePower=1.0;  // only linear instead of squared\n\t    write(\"// \"+ info.getName(),out,0);\n\t    write(\"light_source {\",out,0);\n\t    write(getVec3String(orig),out,1);\n\t    write(\"color <\"+color.getRed()+\",\"+color.getGreen()+\",\"+color.getBlue()+\">\",out,1);\n\t    if (light.getType() != Light.TYPE_NORMAL) write(\"shadowless\",out,1);\n\t    write(\"fade_distance \"+fadeDistance,out,1);\n\t    write(\"fade_power \"+fadePower,out,1);\n\t    write(\"}\",out,0);\n\t    write(\"\",out,0);\n\t    if (DEBUG) {\n\t\tSystem.err.println(\"// Point Light source\");\n\t\tSystem.err.println(\"// --> point light:\");\n\t\tSystem.err.println(\"// Position:\\t\"+orig.toString());\n\t\tSystem.err.println(\"// FadeDistance:\\t\"+fadeDistance);\n\t\tSystem.err.println(\"// FadePower:\\t\"+fadePower);\n\t    }\n\t}\n\telse if (obj.getObject() instanceof SpotLight) {\n\t    write(\"// Spot light\",out,0);\n\t    write(\"// the spot light source has actually no \\\"radius\\\"\",out,0);\n\t    SpotLight light=(SpotLight) obj.getObject();\n\t    ObjectInfo info=(ObjectInfo)obj.duplicate();\n\t    CoordinateSystem coords = info.getCoords();\n\t    Vec3 zdir=coords.getZDirection();\n\t    Vec3 orig=coords.getOrigin();\n\t    // get the point to which a spotlight points at (orig + zdir)\n\t    Vec3 pointat=orig.plus(zdir);\n\t    // Adjust Color\n\t    RGBColor color=light.getColor().duplicate();\n\t    float intensity=light.getIntensity();\n\t    color.scale(intensity);\n\t    // calculating the radius and fallof angle for POVRAY\n\t    // not all possibilities of povray's spotlight used\n\t    double radius=light.getAngle()/2.0*(1.0-light.getFalloff());\n\t    double falloff=light.getAngle()/2.0;\n\t    // calculate the decay rate\n\t    float dr=light.getDecayRate();\n\t    double fadeDistance=MAXIMAL_LIGHT_FADE_DISTANCE;\n\t    if (dr!=0.0) fadeDistance=0.5/(new Float(dr).doubleValue());\n\t    double fadePower=2.0;  \n\t    if (fadeDistance>=5.0) fadePower=1.0;  // only linear instead of squared\n\t    write(\"// \"+ info.getName(),out,0);\n\t    write(\"light_source {\",out,0);\n\t    write(getVec3String(orig),out,1);\n\t    write(\"color <\"+color.getRed()+\",\"+color.getGreen()+\",\"+color.getBlue()+\">\",out,1);\n\t    write(\"spotlight\",out,1);\n\t    write(\"point_at \"+getVec3String(pointat),out,1);\n\t    write(\"radius \"+radius,out,1);\n\t    write(\"falloff \"+falloff,out,1);\n\t    write(\"tightness \"+TIGHTNESS,out,1); // simulates the AoI's behavior\n\t    if (light.getType() != Light.TYPE_NORMAL) write(\"shadowless\",out,1);\n\t    write(\"fade_distance \"+fadeDistance,out,1);\n\t    write(\"fade_power \"+fadePower,out,1);\n\t    write(\"}\",out,0);\n\t    write(\"\",out,0);\n\t    if (DEBUG) {\n\t\tSystem.err.println(\"// Spotlight source\");\n\t\tSystem.err.println(\"// --> spot light:\");\n\t\tSystem.err.println(\"// Position:\\t\"+orig.toString());\n\t\tSystem.err.println(\"// Point at:\\t\"+pointat.toString());\n\t\tSystem.err.println(\"// Color:\\t\"+color.toString());\n\t\tSystem.err.println(\"// Radius:\\t\"+radius);\n\t\tSystem.err.println(\"// Falloff:\\t\"+falloff);\n\t\tSystem.err.println(\"// Tightness:\\t\"+TIGHTNESS);\n\t\tif (light.getType() != Light.TYPE_NORMAL) System.err.println(\"shadowless\");\n\t\tSystem.err.println(\"// FadeDistance:\\t\"+fadeDistance);\n\t\tSystem.err.println(\"// FadePower:\\t\"+fadePower);\n\t    }\n\t}\n\t// Cube setting\n\telse if (obj.getObject() instanceof Cube) {\n\t    write(\"// Cube settings\",out,0);\n\t    ObjectInfo info=(ObjectInfo)obj.duplicate();\n\t    CoordinateSystem coords = info.getCoords();\n\t    Vec3 size = info.getBounds().getSize(), orig=coords.getOrigin();\n\t    String texName=cleanName(info.getObject().getTexture().getName());\n\t    if (info.getObject().getTexture().getID()==1) texName=cleanName(info.getName());\n\t    size.scale(0.5);\n\t    write(\"// \"+ info.getName(),out,0);\n\t    write(\"box {\",out,0);\n\t    write(getVec3String(new Vec3(-1,-1,-1))+\", \"+getVec3String(new Vec3(1,1,1)),out,1);\n\t    write(\"scale \"+getVec3String(size),out,1);\n\t    writeRotation(coords,out,1);\n\t    write(\"translate \"+getVec3String(orig),out,1);\n\t    write(\"texture { \"+TEXTURE_NAME_PREFIX+texName+\" }\",out,1);\n\t    write(\"}\",out,0);\n\t    write(\"\",out,0);\n\t    if (DEBUG) {\n\t\tSystem.err.println(\"Box:\");\n\t\tSystem.err.println(\"Mittelpunkt:\"+orig.toString());\n\t\tSystem.err.println(\"Gr��e:\"+size.times(2.0).toString());\n\t\tSystem.err.println(\"Eckpunkte:\\t(lu): \"+getVec3String(orig.minus(size)));\n\t\tSystem.err.println(\"          \\t(ro): \"+getVec3String(orig.plus(size)));\n\t\tSystem.err.println();\n\t    }\n\t}\n\t//  sphere and ellipse setting\n\t// (only for testing purposes in an extra loop)\n\telse if (obj.getObject() instanceof Sphere) {\n\t    write(\"// Sphere settings\",out,0);\n\t    Sphere sphere=(Sphere) obj.getObject();\n\t    ObjectInfo info=(ObjectInfo)obj.duplicate();\n\t    CoordinateSystem coords = info.getCoords();\n\t    //coords.setOrientation(coords.getZDirection().times(-1.0), coords.getUpDirection().times(1.0));\n\t    Vec3 size = sphere.getRadii(), orig=coords.getOrigin();\n\t    String texName=cleanName(info.getObject().getTexture().getName());\n\t    if (info.getObject().getTexture().getID()==1) texName=cleanName(info.getName());\n\t    write(\"// \"+ info.getName(),out,0);\n\t    write(\"sphere {\",out,0);\n\t    write(\"<0,0,0>, 1\",out,1);  // standard sphere\n\t    write(\"scale \"+getVec3String(size),out,1);\n\t    writeRotation(coords,out,1);\n\t    write(\"translate \"+getVec3String(orig),out,1);\n\t    write(\"texture { \"+TEXTURE_NAME_PREFIX+texName+\" }\",out,1);\n\t    write(\"}\",out,0);\n\t    write(\"\",out,0);\n\t    if (DEBUG) {\n                double rot[] = coords.getRotationAngles();\n\t\tSystem.err.println(\"Sphere:\");\n\t\tSystem.err.println(\"// Mittelpunkt:\\t\"+orig.toString());\n\t\tSystem.err.println(\"// Gr��e:\\t\"+size.times(2.0).toString());\n\t\tSystem.err.println(\"// Rotation (x-axis):\\t\"+rot[0]);\n\t\tSystem.err.println(\"//          (y-axis):\\t\"+rot[1]);\n\t\tSystem.err.println(\"//          (z-axis):\\t\"+rot[2]);\n\t\tSystem.err.println();\n\t    }\n\t}\n\t// cylinder setting\n\t// will be transkripted to a cone object\n\t// (only for testing purposes in an extra loop)\n\telse if (obj.getObject() instanceof Cylinder) {\n\t    write(\"// Cylinder settings\",out,0);\n\t    Cylinder cyl=(Cylinder) obj.getObject();\n\t    ObjectInfo info=(ObjectInfo)obj.duplicate();\n\t    CoordinateSystem coords = info.getCoords();\n\t    Vec3 orig=coords.getOrigin();\n\t    double ratio=cyl.getRatio();\n\t    Vec3 size=cyl.getBounds().getSize();\n\t    String texName=cleanName(info.getObject().getTexture().getName());\n\t    if (info.getObject().getTexture().getID()==1) texName=cleanName(info.getName());\n\t    size.scale(0.5); \n\t    write(\"// \"+ info.getName(),out,0);\n\t    write(\"cone {\",out,0);\n\t    write(\"<0,-1,0>, 1, <0,1,0>, \"+ratio,out,1);  // standard sphere\n\t    write(\"scale \"+getVec3String(size),out,1);\n\t    writeRotation(coords,out,1);\n\t    write(\"translate \"+getVec3String(orig),out,1);\n\t    write(\"texture { \"+TEXTURE_NAME_PREFIX+texName+\" }\",out,1);\n\t    write(\"}\",out,0);\n\t    write(\"\",out,0);\n\t    if (DEBUG) {\n                double rot[] = coords.getRotationAngles();\n\t\tSystem.err.println(\"Cone:\");\n\t\tSystem.err.println(\"// Mittelpunkt:\\t\"+orig.toString());\n\t\tSystem.err.println(\"// Gr��e:\\t\"+size.times(2.0).toString());\n\t\tSystem.err.println(\"// Rotation (x-axis):\\t\"+rot[0]);\n\t\tSystem.err.println(\"//          (y-axis):\\t\"+rot[1]);\n\t\tSystem.err.println(\"//          (z-axis):\\t\"+rot[2]);\n\t\tSystem.err.println();\n\t    }\n\t}\n\t// Mesh for not smoothed triangle meshes\n\t// (only for testing purposes in an extra loop)\n\telse if ((obj.getObject() instanceof TriangleMesh) && (!smooth)) {\n\t    write(\"// Triangle Mesh (mesh2) not smoothed\",out,0);\n\t    TriangleMesh trimesh=(TriangleMesh) obj.getObject();\n\t    ObjectInfo info=(ObjectInfo)obj.duplicate();\n\t    CoordinateSystem coords = info.getCoords();\n\t    Vec3 orig=coords.getOrigin();\n\t    String texName=cleanName(info.getObject().getTexture().getName());\n\t    if (info.getObject().getTexture().getID()==1) texName=cleanName(info.getName());\n\t    \n\t    MeshVertex vert[] = trimesh.getVertices();\n\t    TriangleMesh.Face face[] = (trimesh.getFaces());  \n\t    \n\t    write(\"// \"+ info.getName(),out,0);\n\t    write(\"mesh2 {\",out,0);\n\t    write(\"vertex_vectors {\",out,1);\n\t    write(vert.length+\",\",out,2);\n\t    for (int j = 0; j < vert.length; j++)\n\t\t{\n\t\t    if (j!=vert.length-1) {\n\t\t\twrite(getVec3String(vert[j].r)+\",\",out,2);\n\t\t    }\n\t\t    else {\n\t\t\twrite(getVec3String(vert[j].r),out,2);\n\t\t    }\n\t\t}\n\t    write(\"}\",out,1);\n\t    write(\"face_indices {\",out,1);\n\t    write(face.length+\",\",out,2);\n\t    for (int j = 0; j < face.length; j++)\n\t\t{\n\t\t    if (j!=face.length-1) { \n\t\t\twrite(\"<\"+face[j].v1+\",\"+face[j].v2+\",\"+face[j].v3+\"> ,\",out,2); \n\t\t    }\n\t\t    else {\n\t\t\twrite(\"<\"+face[j].v1+\",\"+face[j].v2+\",\"+face[j].v3+\">\",out,2);\n\t\t    }\n\t\t}\n\t    write(\"}\",out,1);\n\t    write(\"texture { \"+TEXTURE_NAME_PREFIX+texName+\" }\",out,1);\n\t    writeRotation(coords,out,1);\n\t    write(\"translate \"+getVec3String(orig),out,1);\n\t    write(\"}\",out,0);\n\t    write(\"\",out,0);\n\t    if (DEBUG) {\n\t\tSystem.err.println(\"Mesh\");\n\t\tSystem.err.println(\"Name:\\t\"+ info.getName());\n\t\tSystem.err.println(\"Mittelpunkt:\\t\"+orig.toString());\n\t\tSystem.err.println();\n\t    }\n\t}\n\t// if it is a grouping object\n\telse if ((obj.getObject()) instanceof ObjectCollection)    {\n\t    Enumeration objects = ((ObjectCollection) obj.getObject()).getObjects(obj, false, theScene);\n\t    while (objects.hasMoreElements())\n\t\twriteObjects(theScene,(ObjectInfo)objects.nextElement(),out,smooth,tolerance);\n\t}\n\t// any other object\n\telse { /* if smoothed mesh or any other object */\n\t    write(\"// smoothed object\",out,0);\n\t    ObjectInfo info=(ObjectInfo)obj.duplicate();\n\t    RenderingMesh mesh = info.getRenderingMesh(tolerance);\n\t    write(\"// \"+ info.getName(),out,0);\n\t    if (mesh != null) {  // only if you can render the mesh\n\t\tVec3 vert[] = mesh.vert, norm[] = mesh.norm;\n\t\tRenderingTriangle face[] = mesh.triangle;\n\t\t\n\t\tCoordinateSystem coords = info.getCoords();\n\t\tVec3 orig=coords.getOrigin();\n\t\tString texName=cleanName(info.getObject().getTexture().getName());\n\t\tif (info.getObject().getTexture().getID()==1) texName=cleanName(info.getName());\n\t\t\n\t\twrite(\"mesh2 {\",out,0);\n\t\twrite(\"vertex_vectors {\",out,1);\n\t\twrite(vert.length+\",\",out,2);\n\t\tfor (int j = 0; j < vert.length; j++)\n\t\t    {\n\t\t\tif (j!=vert.length-1) {\n\t\t\t    write(getVec3String(vert[j])+\",\",out,2);\n\t\t\t}\n\t\t\telse {\n\t\t\t    write(getVec3String(vert[j]),out,2);\n\t\t\t}\n\t\t    }\n\t\twrite(\"}\",out,1);\n\t\twrite(\"normal_vectors {\",out,1);\n\t\twrite(norm.length+\",\",out,2);\n\t\tfor (int j = 0; j < norm.length; j++)\n\t\t    {\n\t\t\tif (j!=norm.length-1) {\n\t\t\t    write(getVec3String(norm[j])+\",\",out,2);\n\t\t\t}\n\t\t\telse {\n\t\t\t    write(getVec3String(norm[j]),out,2);\n\t\t\t}\n\t\t    }\n\t\twrite(\"}\",out,1);\n\t\twrite(\"face_indices {\",out,1);\n\t\twrite(face.length+\",\",out,2);\n\t\tfor (int j = 0; j < face.length; j++)\n\t\t    {\n\t\t\tif (j!=face.length-1) { \n\t\t\t    write(\"<\"+face[j].v1+\",\"+face[j].v2+\",\"+face[j].v3+\"> ,\",out,2); \n\t\t\t}\n\t\t\telse {\n\t\t\t    write(\"<\"+face[j].v1+\",\"+face[j].v2+\",\"+face[j].v3+\">\",out,2);\n\t\t\t}\n\t\t    }\n\t\twrite(\"}\",out,1);\n\t\twrite(\"normal_indices {\",out,1);\n\t\twrite(face.length+\",\",out,2);\n\t\tfor (int j = 0; j < face.length; j++)\n\t\t    {\n\t\t\tif (j!=face.length-1) { \n\t\t\t    write(\"<\"+face[j].n1+\",\"+face[j].n2+\",\"+face[j].n3+\"> ,\",out,2);\n\t\t\t}\n\t\t\telse {\n\t\t\t    write(\"<\"+face[j].n1+\",\"+face[j].n2+\",\"+face[j].n3+\">\",out,2);\n\t\t\t}\n\t\t    }\n\t\twrite(\"}\",out,1);\n\t\t\n\t\twrite(\"texture { \"+TEXTURE_NAME_PREFIX+texName+\" }\",out,1);\n                writeRotation(coords,out,1);\n                write(\"translate \"+getVec3String(orig),out,1);\n\t\twrite(\"}\",out,0);\n\t\twrite(\"\",out,0);\n\t\tif (DEBUG) {\n\t\t    System.err.println(\"Mesh\");\n\t\t    System.err.println(\"Name:\\t\"+ info.getName());\n\t\t    System.err.println(\"Mittelpunkt:\\t\"+orig.toString());\n\t\t    System.err.println();\n\t\t}\n\t    }\n\t    write(\"\",out,0);\n\t}\n    } // Klasse writeObject ende\n}\n", "human_rating": 2.0577970700001766, "metadata": {"project": "aoi", "class": "artofillusion.translators.POVExporter", "source_path": "aoi/sourcefiles/Translators/src/artofillusion/translators/POVExporter.java", "label_probabilities": {"readability": [4.4167e-14, 0.0664275, 0.924942, 0.00863057], "understandability": [1.44588e-09, 0.000644296, 0.469737, 0.529619], "complexity": [0.195395, 0.803749, 0.00084415, 1.21135e-05], "modularization": [0.686819, 0.31067, 0.00251102, 1.40927e-08], "overall": [0.0, 5.81878e-05, 0.26444, 0.735502]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.translators.TextureImageExporter", "source": "/* Copyright (C) 2003 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.translators;\n\nimport artofillusion.image.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.procedural.*;\nimport artofillusion.texture.*;\nimport java.awt.Image;\nimport java.io.*;\nimport java.util.*;\n\n/** This class can be used by various other exporters.  It collects information about the\n    textures used by a set of objects, and writes out image files for the 2D textures. */\n\npublic class TextureImageExporter\n{\n  private Hashtable textureTable;\n  private File dir;\n  private String baseFilename;\n  private int quality, components, width, height;\n  private int nextID;\n\n  public static final int DIFFUSE = 1;\n  public static final int SPECULAR = 2;\n  public static final int HILIGHT = 4;\n  public static final int TRANSPARENT = 8;\n  public static final int EMISSIVE = 16;\n  public static final int BUMP = 32;\n\n  /** Create a new TextureImageExporter.\n      @param dir            the directory in which to save images\n      @param baseFilename   the base filename to use for image files\n      @param quality        the JPEG image quality (from 0 to 100)\n      @param components     specifies which components to write images for (a sum of the flags given above)\n      @param width          the width to use for images\n      @param height         the height to use for images\n  */\n\n  public TextureImageExporter(File dir, String baseFilename, int quality, int components, int width, int height)\n  {\n    textureTable = new Hashtable();\n    this.dir = dir;\n    this.baseFilename = baseFilename;\n    this.quality = quality;\n    this.components = components;\n    this.width = width;\n    this.height = height;\n    nextID = 1;\n  }\n\n  /** Check the texture of an object, and record what information needs to be exported. */\n\n  public void addObject(ObjectInfo obj)\n  {\n    Texture tex = obj.getObject().getTexture();\n    if (tex == null)\n      return;\n    TextureImageInfo info = (TextureImageInfo) textureTable.get(tex);\n    if (info == null)\n      {\n        // We haven't encountered this texture before, so create a new TextureImageInfo for it.\n\n        info = new TextureImageInfo(tex, obj.getObject().getAverageParameterValues());\n        textureTable.put(tex, info);\n        if (tex instanceof ImageMapTexture)\n          {\n            // Go through the image maps, and see which ones are being used.\n\n            ImageMapTexture imt = (ImageMapTexture) tex;\n            info.diffuseFilename = (imt.diffuseColor.getImage() != null ? newName() : null);\n            info.specularFilename = (imt.specularColor.getImage() != null || imt.specularity.getImage() != null ? newName() : null);\n            info.hilightFilename = (imt.specularColor.getImage() != null || imt.shininess.getImage() != null ? newName() : null);\n            info.transparentFilename = (imt.transparentColor.getImage() != null || imt.transparency.getImage() != null ? newName() : null);\n            info.emissiveFilename = (imt.emissiveColor.getImage() != null ? newName() : null);\n          }\n        else if (tex instanceof ProceduralTexture2D)\n          {\n            Module output[] = ((ProceduralTexture2D) tex).getProcedure().getOutputModules();\n            info.diffuseFilename = (output[0].inputConnected(0) ? newName() : null);\n            info.specularFilename = (output[1].inputConnected(0) || output[5].inputConnected(0) ? newName() : null);\n            info.hilightFilename = (output[1].inputConnected(0) || output[6].inputConnected(0) ? newName() : null);\n            info.transparentFilename = (output[2].inputConnected(0) || output[4].inputConnected(0) ? newName() : null);\n            info.emissiveFilename = (output[3].inputConnected(0) ? newName() : null);\n          }\n      }\n\n    // Determine the range of UV coordinates for this object.\n\n    if (tex instanceof ImageMapTexture)\n      {\n        info.minu = info.minv = 0.0;\n        info.maxu = info.maxv = 1.0;\n      }\n    else if (tex instanceof ProceduralTexture2D)\n      {\n        Mesh mesh = (obj.getObject() instanceof Mesh ? (Mesh) obj.getObject() : obj.getObject().convertToTriangleMesh(0.1));\n        Mapping2D map = (Mapping2D) obj.getObject().getTextureMapping();\n        if (map instanceof UVMapping && mesh instanceof FacetedMesh && ((UVMapping) map).isPerFaceVertex((FacetedMesh) mesh))\n        {\n          Vec2 coords[][] = ((UVMapping) map).findFaceTextureCoordinates((FacetedMesh) mesh);\n          for (int i = 0; i < coords.length; i++)\n            for (int j = 0; j < coords[i].length; j++)\n            {\n              if (coords[i][j].x < info.minu)\n                info.minu = coords[i][j].x;\n              if (coords[i][j].x > info.maxu)\n                info.maxu = coords[i][j].x;\n              if (coords[i][j].y < info.minv)\n                info.minv = coords[i][j].y;\n              if (coords[i][j].y > info.maxv)\n                info.maxv = coords[i][j].y;\n            }\n        }\n        else\n        {\n          Vec2 coords[] = map.findTextureCoordinates(mesh);\n          for (int i = 0; i < coords.length; i++)\n          {\n            if (coords[i].x < info.minu)\n              info.minu = coords[i].x;\n            if (coords[i].x > info.maxu)\n              info.maxu = coords[i].x;\n            if (coords[i].y < info.minv)\n              info.minv = coords[i].y;\n            if (coords[i].y > info.maxv)\n              info.maxv = coords[i].y;\n          }\n        }\n      }\n  }\n\n  /** Create a new name for an image file. */\n\n  private String newName()\n  {\n    return baseFilename+(nextID++)+\".jpg\";\n  }\n\n  /** Get the TextureImageInfo (which may be null) for a particular texture. */\n\n  public TextureImageInfo getTextureInfo(Texture tex)\n  {\n    return (tex != null ? (TextureImageInfo) textureTable.get(tex) : null);\n  }\n\n  /** Get an Enumeration of all TextureImageInfos. */\n\n  public Enumeration getTextures()\n  {\n    return textureTable.elements();\n  }\n\n  /** Write out all of the images for the various textures. */\n\n  public void saveImages() throws IOException, InterruptedException\n  {\n    Enumeration e = textureTable.keys();\n    while (e.hasMoreElements())\n      {\n        Texture tex = (Texture) e.nextElement();\n        TextureImageInfo info = (TextureImageInfo) textureTable.get(tex);\n        if ((components&DIFFUSE) != 0)\n          writeComponentImage(info, Texture2D.DIFFUSE_COLOR_COMPONENT, info.diffuseFilename);\n        if ((components&SPECULAR) != 0)\n          writeComponentImage(info, Texture2D.SPECULAR_COLOR_COMPONENT, info.specularFilename);\n        if ((components&HILIGHT) != 0)\n          writeComponentImage(info, Texture2D.HILIGHT_COLOR_COMPONENT, info.hilightFilename);\n        if ((components&TRANSPARENT) != 0)\n          writeComponentImage(info, Texture2D.TRANSPARENT_COLOR_COMPONENT, info.transparentFilename);\n        if ((components&EMISSIVE) != 0)\n          writeComponentImage(info, Texture2D.EMISSIVE_COLOR_COMPONENT, info.emissiveFilename);\n      }\n  }\n\n  /** Write an image file to disk representating a component of a texture. */\n\n  private void writeComponentImage(TextureImageInfo info, int component, String filename) throws IOException, InterruptedException\n  {\n    if (filename == null || !(info.texture instanceof Texture2D))\n      return;\n    Image img = ((Texture2D) info.texture).createComponentImage(info.minu, info.maxu, info.minv, info.maxv,\n        width, height, component, 0.0, info.paramValue);\n    ImageSaver.saveImage(img, new File(dir, filename), ImageSaver.FORMAT_JPEG, quality);\n  }\n}\n", "human_rating": 2.8858724900725705, "metadata": {"project": "aoi", "class": "artofillusion.translators.TextureImageExporter", "source_path": "aoi/sourcefiles/Translators/src/artofillusion/translators/TextureImageExporter.java", "label_probabilities": {"readability": [1.96205e-05, 0.885832, 0.114149, 8.07257e-09], "understandability": [9.81071e-09, 0.0733606, 0.613897, 0.312742], "complexity": [0.107004, 0.84513, 0.0478661, 1.25577e-12], "modularization": [0.0, 2.49883e-14, 0.99519, 0.00481021], "overall": [2.16648e-08, 0.160153, 0.813925, 0.0259221]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.TriMeshSelectionUtilities", "source": "/* Copyright (C) 2005 by Peter Eastman\n\nThis program is free software; you can redistribute it and/or modify it under the\nterms of the GNU General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY \nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \nPARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.object.TriangleMesh.*;\nimport artofillusion.ui.*;\n\nimport java.util.*;\n\n/** This class provides a variety of static methods for selecting parts of TriangleMeshes in different ways. */\n\npublic class TriMeshSelectionUtilities\n{\n  /** Convert one type of selection (point, edge, or face) to a different one.\n      @param mesh        the mesh the selection applies to\n      @param oldMode     the selection mode of the old selection\n      @param selection   the old selection\n      @param newMode     the new selection mode\n      @return a selection in the new mode which corresponds to the old selection as closely as possible\n   */\n\n  public static boolean[] convertSelection(TriangleMesh mesh, int oldMode, boolean selection[], int newMode)\n  {\n    Vertex v[] = (Vertex []) mesh.getVertices();\n    Edge e[] = mesh.getEdges();\n    Face f[] = mesh.getFaces();\n    boolean newSel[];\n    \n    if (newMode == oldMode)\n      return (boolean []) selection.clone();\n    if (newMode == MeshEditController.POINT_MODE)\n    {\n      newSel = new boolean [v.length];\n      if (oldMode == MeshEditController.EDGE_MODE)\n      {\n        for (int i = 0; i < e.length; i++)\n          if (selection[i])\n            newSel[e[i].v1] = newSel[e[i].v2] = true;\n      }\n      else\n      {\n        for (int i = 0; i < f.length; i++)\n          if (selection[i])\n            newSel[f[i].v1] = newSel[f[i].v2] = newSel[f[i].v3] = true;\n      }\n    }\n    else if (newMode == MeshEditController.EDGE_MODE)\n    {\n      newSel = new boolean [e.length];\n      if (oldMode == MeshEditController.POINT_MODE)\n      {\n        for (int i = 0; i < e.length; i++)\n          newSel[i] = (selection[e[i].v1] && selection[e[i].v2]);\n      }\n      else\n      {\n        for (int i = 0; i < f.length; i++)\n          if (selection[i])\n            newSel[f[i].e1] = newSel[f[i].e2] = newSel[f[i].e3] = true;\n      }\n    }\n    else\n    {\n      newSel = new boolean [f.length];\n      if (oldMode == MeshEditController.POINT_MODE)\n      {\n        for (int i = 0; i < f.length; i++)\n          newSel[i] = (selection[f[i].v1] && selection[f[i].v2] && selection[f[i].v3]);\n      }\n      else\n      {\n        for (int i = 0; i < f.length; i++)\n          newSel[i] = (selection[f[i].e1] && selection[f[i].e2] && selection[f[i].e3]);\n      }\n    }\n    return newSel;\n  }\n  \n  /** Find the boundary of the current selection.\n      @param mesh        the mesh the selection applies to\n      @param oldMode     the selection mode of the old selection\n      @param selection   the old selection\n      @return a selection in edge mode which corresponds to the boundary of the old selection\n   */\n  \n  public static boolean[] findSelectionBoundary(TriangleMesh mesh, int oldMode, boolean selection[])\n  {\n    boolean edgeSelection[] = convertSelection(mesh, oldMode, selection, MeshEditController.EDGE_MODE);\n    boolean faceSelection[] = convertSelection(mesh, oldMode, selection, MeshEditController.FACE_MODE);\n    Edge e[] = mesh.getEdges();\n    Face f[] = mesh.getFaces();\n    boolean newSel[] = new boolean [e.length];\n    \n    for (int i = 0; i < e.length; i++)\n      newSel[i] = (edgeSelection[i] && (!faceSelection[e[i].f1] || e[i].f2 == -1 || !faceSelection[e[i].f2]));\n    return newSel;\n  }\n  \n  /** Select an edge loop from a single edge.\n      @param mesh        the mesh the selection applies to\n      @param startEdge   the index of the edge from which to find an edge loop\n      @return a selection containing all the edges in the loop, or null if no loop could be found\n   */\n  \n  private static boolean[] findSingleEdgeLoop(TriangleMesh mesh, int startEdge)\n  {\n    Vertex v[] = (Vertex []) mesh.getVertices();\n    Edge e[] = mesh.getEdges();\n    Face f[] = mesh.getFaces();\n    boolean newSel[] = new boolean [e.length];\n    int currentEdge = startEdge;\n    int currentVert = e[startEdge].v1;\n\n    while (true)\n    {\n      if (newSel[currentEdge])\n      {\n        if (currentEdge == startEdge)\n          return newSel; // This is a good edge loop.\n        return null; // The path looped back on itself without hitting the original edge.\n      }\n      \n      // Find the next edge which is most nearly parallel to this one.\n      \n      newSel[currentEdge] = true;\n      Vec3 dir1 = v[e[currentEdge].v1].r.minus(v[e[currentEdge].v2].r);\n      dir1.normalize();\n      int vertEdges[] = v[currentVert].getEdges();\n      int bestEdge = -1;\n      double maxDot = -1.0;\n      for (int i = 0; i < vertEdges.length; i++)\n      {\n        if (vertEdges[i] == currentEdge)\n          continue;\n        Vec3 dir2 = v[e[vertEdges[i]].v1].r.minus(v[e[vertEdges[i]].v2].r);\n        dir2.normalize();\n        double dot = dir1.dot(dir2);\n        if (e[currentEdge].v1 == e[vertEdges[i]].v1 || e[currentEdge].v2 == e[vertEdges[i]].v2)\n          dot = -dot;\n        if (dot > maxDot)\n        {\n          maxDot = dot;\n          bestEdge = vertEdges[i];\n        }\n      }\n      currentEdge = bestEdge;\n      currentVert = (e[currentEdge].v1 == currentVert ? e[currentEdge].v2 : e[currentEdge].v1);\n    }\n  }\n  \n  /** Select an edge loop from each edge that is currently selected.\n      @param mesh        the mesh the selection applies to\n      @param selection   the current selection (in edge mode)\n      @return a selection containing all the edges in the loops, or null if no loop could be found for one or more edges\n   */\n  \n  public static boolean[] findEdgeLoops(TriangleMesh mesh, boolean selection[])\n  {\n    boolean newSel[] = new boolean [selection.length];\n    for (int i = 0; i < selection.length; i++)\n      if (selection[i])\n      {\n        boolean loop[] = findSingleEdgeLoop(mesh, i);\n        if (loop == null)\n          return null;\n        for (int j = 0; j < loop.length; j++)\n          newSel[j] |= loop[j];\n      }\n    return newSel;\n  }\n  \n  /** Select an edge strip from a single edge.\n      @param mesh        the mesh the selection applies to\n      @param startEdge   the index of the edge from which to find an edge strip\n      @return a selection containing all the edges in the strip, or null if no strip could be found\n   */\n  \n  private static boolean[] findSingleEdgeStrip(TriangleMesh mesh, int startEdge)\n  {\n    Vertex v[] = (Vertex []) mesh.getVertices();\n    Edge e[] = mesh.getEdges();\n    Face f[] = mesh.getFaces();\n    boolean newSel[] = new boolean [e.length];\n    int currentEdge = startEdge;\n    int prevEdge = startEdge;\n\n    while (true)\n    {\n      if (newSel[currentEdge])\n      {\n        if (currentEdge == startEdge)\n          return newSel; // This is a good edge strip.\n        return null; // The path looped back on itself without hitting the original edge.\n      }\n      newSel[currentEdge] = true;\n      Edge ce = e[currentEdge];\n      Vec3 dir1 = v[ce.v1].r.minus(v[ce.v2].r);\n      dir1.normalize();\n      int bestEdge = -1;\n      double maxDot = -1.0;\n      \n      // Record every neighbor of each vertex of the current edge.\n      \n      HashSet v1neighbors = new HashSet();\n      int v1edges[] = v[ce.v1].getEdges();\n      for (int i = 0; i < v1edges.length; i++)\n      {\n        Edge ed = e[v1edges[i]];\n        if (ed != ce)\n          v1neighbors.add(new Integer(ed.v1 == ce.v1 ? ed.v2 : ed.v1));\n      }\n      HashSet v2neighbors = new HashSet();\n      int v2edges[] = v[ce.v2].getEdges();\n      for (int i = 0; i < v2edges.length; i++)\n      {\n        Edge ed = e[v2edges[i]];\n        if (ed != ce)\n          v2neighbors.add(new Integer(ed.v1 == ce.v2 ? ed.v2 : ed.v1));\n      }\n      \n      // Look for candidates to be the next edge in the strip.  A candidate is an edge which connects\n      // a neighbor of v1 to a neighbor of v2.\n      \n      Iterator n2iter = v2neighbors.iterator();\n      while (n2iter.hasNext())\n      {\n        int neighbor = ((Integer) n2iter.next()).intValue();\n        int neighborEdges[] = v[neighbor].getEdges();\n        for (int i = 0; i < neighborEdges.length; i++)\n        {\n          if (neighborEdges[i] == prevEdge)\n            continue;\n          Edge ed = e[neighborEdges[i]];\n          if (v1neighbors.contains(new Integer(ed.v1)) || v1neighbors.contains(new Integer(ed.v2)))\n          {\n            // This edge is a candidate.  See how close it is to being parallel to the current edge.\n            \n            Vec3 dir2 = v[ed.v1].r.minus(v[ed.v2].r);\n            dir2.normalize();\n            double dot = Math.abs(dir1.dot(dir2));\n            if (dot > maxDot)\n            {\n              maxDot = dot;\n              bestEdge = neighborEdges[i];\n            }\n          }\n        }\n      }\n      if (bestEdge == -1)\n        return null;\n      \n      // There may also be a diagonal edge between the current and next edges.  Check for one,\n      // and select it.\n      \n      ArrayList faceList1 = new ArrayList();\n      faceList1.add(f[ce.f1]);\n      if (ce.f2 != -1)\n        faceList1.add(f[ce.f2]);\n      ArrayList faceList2 = new ArrayList();\n      faceList2.add(f[e[bestEdge].f1]);\n      if (e[bestEdge].f2 != -1)\n        faceList2.add(f[e[bestEdge].f2]);\n      for (int i = 0; i < faceList1.size(); i++)\n      {\n        Face fc1 = (Face) faceList1.get(i);\n        for (int j = 0; j < faceList2.size(); j++)\n        {\n          Face fc2 = (Face) faceList2.get(j);\n          if (fc1.e1 == fc2.e1 || fc1.e1 == fc2.e2 || fc1.e1 == fc2.e3)\n          {\n            newSel[fc1.e1] = true;\n            break;\n          }\n          if (fc1.e2 == fc2.e1 || fc1.e2 == fc2.e2 || fc1.e2 == fc2.e3)\n          {\n            newSel[fc1.e2] = true;\n            break;\n          }\n          if (fc1.e3 == fc2.e1 || fc1.e3 == fc2.e2 || fc1.e3 == fc2.e3)\n          {\n            newSel[fc1.e3] = true;\n            break;\n          }\n        }\n      }\n      prevEdge = currentEdge;\n      currentEdge = bestEdge;\n    }\n  }\n  \n  /** Select an edge strip from each edge that is currently selected.\n      @param mesh        the mesh the selection applies to\n      @param selection   the current selection (in edge mode)\n      @return a selection containing all the edges in the strips, or null if no strip could be found for one or more edges\n   */\n  \n  public static boolean[] findEdgeStrips(TriangleMesh mesh, boolean selection[])\n  {\n    boolean newSel[] = new boolean [selection.length];\n    for (int i = 0; i < selection.length; i++)\n      if (selection[i])\n      {\n        boolean loop[] = findSingleEdgeStrip(mesh, i);\n        if (loop == null)\n          return null;\n        for (int j = 0; j < loop.length; j++)\n          newSel[j] |= loop[j];\n      }\n    return newSel;\n  }\n}\n", "human_rating": 2.7073118665999996, "metadata": {"project": "aoi", "class": "artofillusion.TriMeshSelectionUtilities", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/TriMeshSelectionUtilities.java", "label_probabilities": {"readability": [1.87794e-05, 0.708127, 0.291002, 0.000851749], "understandability": [1.09386e-07, 0.0576067, 0.513569, 0.428824], "complexity": [0.128452, 0.779653, 0.091895, 3.92389e-11], "modularization": [0.0705177, 0.911494, 0.0179881, 7.32293e-12], "overall": [2.87826e-12, 0.0110794, 0.92609, 0.0628303]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.TriMeshSimplifier", "source": "/* Copyright (C) 1999-2012 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.object.TriangleMesh.*;\nimport artofillusion.ui.*;\nimport artofillusion.texture.*;\nimport buoy.widget.*;\n\n/** TriMeshSimplifier defines methods for simplifying a TriangleMesh.  The algorithm\n   is based on\n   <p>\n   R. Ronfard and J. Rossignac, \"Full-range Approximation of Triangulated Polyhedra.\"\n   Computer Graphics Forum, vol. 15, no. 3, 1996.\n   <p>\n   I have made the following modifications to their algorithm:\n   <p>\n   1. When calculating the cost for an edge collapse, they arbitrarily choose which direction\n   to collapse it in.  This results in meshes not being simplified as far as they could be.\n   Instead, I always test both collapse directions to see which one has the lower cost.\n   <p>\n   2. After collapsing vertex v1 to v2, they state that it is only necessary to recalculate\n   costs for edges which have been modified, that is, those edges in the star of v1 or v2.\n   This is incorrect.  It is also necessary to recalculate the cost for any edge which shares\n   a vertex with an edge in v1's star.\n   <p>\n   3. They define the local tesselation error for a face as being proportional to its angle\n   of rotation.  I replace the angle by 1-cos(angle).  This has the same effect, and saves\n   the need to evalate an acos.\n   <p>\n   4. Rather than always simplifying the entire mesh, I allow the user to select only a\n   subset of the mesh to be simplified.\n   <p>\n   5. Their algorithm only works for closed meshes (meshes without a boundary).  I have\n   modified it to also work for open meshes.\n   <p>\n   6. I omit the relaxation step, since this would produce bad results for smoothed\n   meshes. */\n\npublic class TriMeshSimplifier implements Runnable\n{\n  private class Constraint\n  {\n    double a, b, c, d;\n  }\n\n  private class Zone\n  {\n    int constraints;\n    Constraint con[];\n    Zone next;\n  }\n    \n  private class MeshEdge\n  {\n    int v1, v2;\n    MeshFace f1, f2;\n    float smoothness;\n    double cost;\n    boolean selected;\n  }\n\n  private class MeshFace\n  {\n    int v1, v2, v3, index, origIndex;\n    MeshEdge e1, e2, e3;\n    Vec3 normal;\n  }\n\n  private class VertexInfo\n  {\n    Vertex theVert;\n    Vec3 pos;\n    int faces, edges;\n    float smoothness;\n    MeshEdge star[];\n    MeshFace crown[];\n    Zone zone;\n  }\n\n  private TriangleMesh mesh;\n  private VertexInfo vertex[];\n  private MeshEdge edge[];\n  private MeshFace face[];\n  private Vec3 temp1, temp2, temp3;\n  private int faces;\n  private BDialog dial;\n  private BButton cancelButton;\n  private BLabel status, numLabel;\n  private boolean cancel;\n  private double tol;\n\n  public TriMeshSimplifier(TriangleMesh theMesh, boolean selection[], double tolerance, BFrame fr)\n  {\n    mesh = theMesh;\n    tol = tolerance*tolerance;\n    buildDataStructures(selection);\n    if (fr == null)\n      run();\n    else\n    {\n      createDialog(fr);\n      new Thread(this).start();\n      Thread update = new Thread() {\n        public void run()\n        {\n          try\n          {\n            while (!cancel)\n            {\n              sleep(200);\n              status.setText(String.valueOf(faces));\n            }\n          }\n          catch (InterruptedException ex)\n          {\n          }\n        }\n      };\n      update.start();\n      dial.setVisible(true);\n    }\n  }\n  \n  public void run()\n  {\n    doSimplification();\n    if (!cancel)\n      buildMesh();\n    cancel = true;\n    if (numLabel != null)\n    {\n      numLabel.setText(Translate.text(\"Final\")+\":\");\n      status.setText(String.valueOf(faces));\n      cancelButton.setText(Translate.text(\"Done\"));\n      dial.setDefaultButton(cancelButton);\n    }\n  }\n\n  /* Put up a status dialog. */\n  \n  private void createDialog(BFrame fr)\n  {\n    dial = new BDialog(fr, true);\n    BorderContainer content = new BorderContainer();\n    dial.setContent(BOutline.createEmptyBorder(content, UIUtilities.getStandardDialogInsets()));\n    content.add(Translate.label(\"numTrianglesInMesh\"), BorderContainer.NORTH);\n    GridContainer grid = new GridContainer(2, 2);\n    grid.add(new BLabel(Translate.text(\"Original\")+\":\"), 0, 0);\n    grid.add(numLabel = new BLabel(Translate.text(\"Current\")+\":\"), 0, 1);\n    grid.add(new BLabel(String.valueOf(faces)), 1, 0);\n    grid.add(status = new BLabel(String.valueOf(faces)), 1, 1);\n    content.add(grid, BorderContainer.CENTER);\n    content.add(cancelButton = Translate.button(\"cancel\", new Object() {\n      void processEvent()\n      {\n        cancel = true;\n        dial.dispose();\n      }\n    }, \"processEvent\"), BorderContainer.SOUTH, new LayoutInfo());\n    dial.pack();\n    dial.setResizable(false);\n    UIUtilities.centerDialog(dial, fr);\n  }\n\n  /* Build the new TriangleMesh. */\n  \n  private void buildMesh()\n  {\n    int index[] = new int [vertex.length], f[][] = new int [faces][];\n    Vertex vert[];\n    Edge ed[];\n\n    // Find the indices of all unique vertices.\n\n    int k = 0;\n    for (int i = 0; i < vertex.length; i++)\n      {\n        index[i] = k++;\n        for (int j = 0; j < i; j++)\n          if (vertex[i] == vertex[j])\n            {\n              index[i] = index[j];\n              k--;\n              break;\n            }\n      }\n    \n    // Update the mesh shape.\n    \n    vert = new Vertex [k];\n    for (int i = 0; i < vertex.length; i++)\n      {\n        vert[index[i]] = mesh.new Vertex(vertex[i].theVert);\n        vert[index[i]].r = new Vec3(vertex[i].pos);\n        vert[index[i]].smoothness = vertex[i].smoothness;\n        vert[index[i]].edges = 0;\n        vert[index[i]].firstEdge = -1;\n      }\n    for (int i = 0; i < faces; i++)\n      f[i] = new int [] {index[face[i].v1], index[face[i].v2], index[face[i].v3]};\n    mesh.setShape(vert, f);\n    \n    // Set the smoothness values for edges.\n    \n    ed = mesh.getEdges();\n    for (int i = 0; i < ed.length; i++)\n      for (int j = 0; j < edge.length; j++)\n        if ((index[edge[j].v1] == ed[i].v1 && index[edge[j].v2] == ed[i].v2) ||\n                (index[edge[j].v2] == ed[i].v1 && index[edge[j].v1] == ed[i].v2))\n          {\n            ed[i].smoothness = edge[j].smoothness;\n            break;\n          }\n\n    // Update surface parameters.\n\n    ParameterValue paramValue[] = mesh.getParameterValues();\n    if (paramValue != null)\n    {\n      for (int i = 0; i < paramValue.length; i++)\n      {\n        if (paramValue[i] instanceof VertexParameterValue)\n        {\n          VertexParameterValue value = (VertexParameterValue) paramValue[i];\n          double oldValue[] = value.getValue();\n          double newValue[] = new double [vertex.length];\n          for (int j = 0; j < newValue.length; j++)\n            newValue[index[j]] = oldValue[j];\n          value.setValue(newValue);\n        }\n        else if (paramValue[i] instanceof FaceParameterValue)\n        {\n          FaceParameterValue value = (FaceParameterValue) paramValue[i];\n          double oldValue[] = value.getValue();\n          double newValue[] = new double [faces];\n          for (int j = 0; j < newValue.length; j++)\n            newValue[j] = oldValue[face[j].origIndex];\n          value.setValue(newValue);\n        }\n        else if (paramValue[i] instanceof FaceVertexParameterValue)\n        {\n          FaceVertexParameterValue value = (FaceVertexParameterValue) paramValue[i];\n          double newValue[][] = new double [faces][3];\n          for (int j = 0; j < newValue.length; j++)\n          {\n            newValue[j][0] = value.getValue(face[j].origIndex, 0);\n            newValue[j][1] = value.getValue(face[j].origIndex, 1);\n            newValue[j][2] = value.getValue(face[j].origIndex, 2);\n          }\n          value.setValue(newValue);\n        }\n      }\n      mesh.setParameterValues(paramValue);\n    }\n  }\n\n  /* Build the data structures necessary for simplifying the mesh. */\n\n  private void buildDataStructures(boolean selection[])\n  {\n    TriangleMesh.Vertex v[] = (Vertex []) mesh.getVertices();\n    TriangleMesh.Edge e[] = mesh.getEdges();\n    TriangleMesh.Face f[] = mesh.getFaces();\n    int i, j, edgeCount[], faceCount[];\n    MeshEdge tempEdge;\n    VertexInfo v1, v2;\n    Constraint con;\n\n    vertex = new VertexInfo [v.length];\n    edge = new MeshEdge [e.length];\n    face = new MeshFace [f.length];\n    edgeCount = new int [v.length];\n    faceCount = new int [v.length];\n    faces = f.length;\n\n    // Create temporary vectors for later use.\n\n    temp1 = new Vec3();\n    temp2 = new Vec3();\n    temp3 = new Vec3();\n\n    // Count the edges and faces touching each vertex, and build the list of vertices.\n\n    for (i = 0; i < e.length; i++)\n      {\n        edgeCount[e[i].v1]++;\n        edgeCount[e[i].v2]++;\n      }\n    for (i = 0; i < f.length; i++)\n      {\n        faceCount[f[i].v1]++;\n        faceCount[f[i].v2]++;\n        faceCount[f[i].v3]++;\n      }\n    for (i = 0; i < v.length; i++)\n      {\n        vertex[i] = new VertexInfo();\n        vertex[i].theVert = v[i];\n        vertex[i].pos = v[i].r;\n        vertex[i].smoothness = v[i].smoothness;\n        vertex[i].star = new MeshEdge [edgeCount[i]];\n        vertex[i].crown = new MeshFace [faceCount[i]];\n        vertex[i].zone = new Zone();\n        if (faceCount[i] == edgeCount[i])\n          vertex[i].zone.con = new Constraint [faceCount[i]];\n        else\n          vertex[i].zone.con = new Constraint [faceCount[i]+2];\n      }\n    \n    // Build the list of edges.\n    \n    for (i = 0; i < e.length; i++)\n      {\n        edge[i] = new MeshEdge();\n        edge[i].v1 = e[i].v1;\n        edge[i].v2 = e[i].v2;\n        edge[i].smoothness = e[i].smoothness;\n        v1 = vertex[e[i].v1];\n        v2 = vertex[e[i].v2];\n        v1.star[v1.edges++] = edge[i];\n        v2.star[v2.edges++] = edge[i];\n        edge[i].selected = selection[i];\n      }\n    \n    // Build the list of faces, and record the constraint associated with each one.\n    \n    for (i = 0; i < f.length; i++)\n      {\n        face[i] = new MeshFace();\n        face[i].v1 = f[i].v1;\n        face[i].v2 = f[i].v2;\n        face[i].v3 = f[i].v3;\n        face[i].e1 = edge[f[i].e1];\n        face[i].e2 = edge[f[i].e2];\n        face[i].e3 = edge[f[i].e3];\n        face[i].index = i;\n        face[i].origIndex = i;\n        face[i].normal = new Vec3();\n        findNormal(vertex[f[i].v1].pos, vertex[f[i].v2].pos, vertex[f[i].v3].pos, face[i].normal);\n        vertex[f[i].v1].crown[vertex[f[i].v1].faces++] = face[i];\n        vertex[f[i].v2].crown[vertex[f[i].v2].faces++] = face[i];\n        vertex[f[i].v3].crown[vertex[f[i].v3].faces++] = face[i];\n        con = new Constraint();\n        if (face[i].normal.length2() == 0.0)\n        {\n          con.a = 1;\n          con.b = 1;\n          con.c = 1;\n        }\n        else\n        {\n          con.a = face[i].normal.x;\n          con.b = face[i].normal.y;\n          con.c = face[i].normal.z;\n        }\n        con.d = -(con.a*v[f[i].v1].r.x + con.b*v[f[i].v1].r.y + con.c*v[f[i].v1].r.z);\n        vertex[f[i].v1].zone.con[vertex[f[i].v1].zone.constraints++] = con;\n        vertex[f[i].v2].zone.con[vertex[f[i].v2].zone.constraints++] = con;\n        vertex[f[i].v3].zone.con[vertex[f[i].v3].zone.constraints++] = con;\n        if (edge[f[i].e1].f1 == null)\n          edge[f[i].e1].f1 = face[i];\n        else\n          edge[f[i].e1].f2 = face[i];\n        if (edge[f[i].e2].f1 == null)\n          edge[f[i].e2].f1 = face[i];\n        else\n          edge[f[i].e2].f2 = face[i];\n        if (edge[f[i].e3].f1 == null)\n          edge[f[i].e3].f1 = face[i];\n        else\n          edge[f[i].e3].f2 = face[i];\n      }\n\n    // Record additional constraints for boundary edges.\n    \n    for (i = 0; i < e.length; i++)\n      if (edge[i].f2 == null)\n        {\n          temp1.set(v[edge[i].v1].r);\n          temp1.subtract(v[edge[i].v2].r);\n          temp2.set(edge[i].f1.normal);\n          con = new Constraint();\n          con.a = temp1.y*temp2.z - temp1.z*temp2.y;\n          con.b = temp1.z*temp2.x - temp1.x*temp2.z;\n          con.c = temp1.x*temp2.y - temp1.y*temp2.x;\n          con.d = -(con.a*v[edge[i].v1].r.x + con.b*v[edge[i].v1].r.y + con.c*v[edge[i].v1].r.z);\n          vertex[edge[i].v1].zone.con[vertex[edge[i].v1].zone.constraints++] = con;\n          vertex[edge[i].v2].zone.con[vertex[edge[i].v2].zone.constraints++] = con;\n        }\n\n    // Record the initial cost associated with each edge, and bring the lowest cost edge\n    // to the front of the list.\n    \n    for (i = 0; i < e.length; i++)\n      updateCost(edge[i]);\n    j = 0;\n    for (i = 0; i < e.length; i++)\n      if (edge[i].cost < edge[j].cost)\n        j = i;\n    tempEdge = edge[j];\n    edge[j] = edge[0];\n    edge[0] = tempEdge;\n  }\n\n  /** Simplify the mesh! */\n\n  private void doSimplification()\n  {\n    int i, j, k, skip;\n    MeshEdge rem1, rem2, rep1, rep2;\n    MeshEdge e, star[], tempEdge;\n    MeshFace tempCrown[];\n    VertexInfo v1, v2, v3, v4, tempVert;\n    Zone zone1, zone2;\n    boolean boundary;\n\n    for (i = 0; i < edge.length; i += skip)\n      {\n        e = edge[i];\n        if (e.cost >= tol || cancel)\n          return;\n        v1 = vertex[e.v1];\n        v2 = vertex[e.v2];\n        boundary = (e.f2 == null);\n\n        // Move v1 to v2.\n        \n        v2.pos = v1.pos;\n\n        // Flag all the edges whose costs must be updated.  This includes all edges in v1's\n        // star or v2's star, and all edges which share a vertex with an edge in v1's star.\n        \n        star = v1.star;\n        for (j = 0; j < v1.edges; j++)\n          {\n            if (vertex[star[j].v1] == v1)\n              tempVert = vertex[star[j].v2];\n            else\n              tempVert = vertex[star[j].v1];\n            for (k = 0; k < tempVert.edges; k++)\n              tempVert.star[k].cost = -1.0;\n          }\n        star = v2.star;\n        for (j = 0; j < v2.edges; j++)\n          star[j].cost = -1.0;\n\n        // Find the two extra edges to remove, and the ones to replace them with.\n        \n        if (e.f1.e1 == e)\n          {\n            if (vertex[e.f1.e2.v1] == v2 || vertex[e.f1.e2.v2] == v2)\n              {\n                rem1 = e.f1.e2;\n                rep1 = e.f1.e3;\n              }\n            else\n              {\n                rem1 = e.f1.e3;\n                rep1 = e.f1.e2;\n              }\n          }\n        else if (e.f1.e2 == e)\n          {\n            if (vertex[e.f1.e3.v1] == v2 || vertex[e.f1.e3.v2] == v2)\n              {\n                rem1 = e.f1.e3;\n                rep1 = e.f1.e1;\n              }\n            else\n              {\n                rem1 = e.f1.e1;\n                rep1 = e.f1.e3;\n              }\n          }\n        else\n          {\n            if (vertex[e.f1.e1.v1] == v2 || vertex[e.f1.e1.v2] == v2)\n              {\n                rem1 = e.f1.e1;\n                rep1 = e.f1.e2;\n              }\n            else\n              {\n                rem1 = e.f1.e2;\n                rep1 = e.f1.e1;\n              }\n          }\n        if (boundary)\n          rem2 = rep2 = null;\n        else\n          {\n            if (e.f2.e1 == e)\n              {\n                if (vertex[e.f2.e2.v1] == v2 || vertex[e.f2.e2.v2] == v2)\n                  {\n                    rem2 = e.f2.e2;\n                    rep2 = e.f2.e3;\n                  }\n                else\n                  {\n                    rem2 = e.f2.e3;\n                    rep2 = e.f2.e2;\n                  }\n              }\n            else if (e.f2.e2 == e)\n              {\n                if (vertex[e.f2.e3.v1] == v2 || vertex[e.f2.e3.v2] == v2)\n                  {\n                    rem2 = e.f2.e3;\n                    rep2 = e.f2.e1;\n                  }\n                else\n                  {\n                    rem2 = e.f2.e1;\n                    rep2 = e.f2.e3;\n                  }\n              }\n            else\n              {\n                if (vertex[e.f2.e1.v1] == v2 || vertex[e.f2.e1.v2] == v2)\n                  {\n                    rem2 = e.f2.e1;\n                    rep2 = e.f2.e2;\n                  }\n                else\n                  {\n                    rem2 = e.f2.e2;\n                    rep2 = e.f2.e1;\n                  }\n              }\n          }\n\n        // Identify the other two points whose stars and crowns must be modified.\n        \n        if (vertex[rep1.v1] == v1)\n          v3 = vertex[rep1.v2];\n        else\n          v3 = vertex[rep1.v1];\n        if (boundary)\n          v4 = null;\n        else\n          {\n            if (vertex[rep2.v1] == v1)\n              v4 = vertex[rep2.v2];\n            else\n              v4 = vertex[rep2.v1];\n          }\n        \n        // Update v1's crown.\n        \n        if (boundary && v1.faces+v2.faces-2 > v1.crown.length)\n          tempCrown = new MeshFace [v1.faces+v2.faces-2];\n        else if (v1.faces+v2.faces-4 > v1.crown.length)\n          tempCrown = new MeshFace [v1.faces+v2.faces-4];\n        else\n          tempCrown = v1.crown;\n        for (j = 0, k = 0; k < v1.faces; k++)\n          if (v1.crown[k] != e.f1 && v1.crown[k] != e.f2)\n            tempCrown[j++] = v1.crown[k];\n        for (k = 0; k < v2.faces; k++)\n          if (v2.crown[k] != e.f1 && v2.crown[k] != e.f2)\n            tempCrown[j++] = v2.crown[k];\n        v1.crown = tempCrown;\n        if (boundary)\n          v1.faces = v1.faces+v2.faces-2;\n        else\n          v1.faces = v1.faces+v2.faces-4;\n\n        // Update v1's star.\n\n        if (v1.edges+v2.edges-2 > v1.star.length)\n          star = new MeshEdge [v1.edges+v2.edges-2];\n        else\n          star = v1.star;\n        for (j = 0, k = 0; k < v1.edges; k++)\n          if (v1.star[k] != e)\n            star[j++] = v1.star[k];\n        for (k = 0; k < v2.edges; k++)\n          if (v2.star[k] != e)\n            star[j++] = v2.star[k];\n        v1.star = star;\n        v1.edges = v1.edges+v2.edges-2;        \n\n        // Update v3 and v4's crowns.\n        \n        for (j = 0, k = 0; k < v3.faces; k++)\n          if (v3.crown[k] != e.f1)\n            v3.crown[j++] = v3.crown[k];\n        v3.faces--;\n        if (!boundary)\n          {\n            for (j = 0, k = 0; k < v4.faces; k++)\n              if (v4.crown[k] != e.f2)\n                v4.crown[j++] = v4.crown[k];\n            v4.faces--;\n          }\n\n        // Update v3 and v4's stars.\n\n        for (j = 0, k = 0; k < v3.edges; k++)\n          if (v3.star[k] != rem1)\n            v3.star[j++] = v3.star[k];\n        v3.edges--;\n        if (!boundary)\n          {\n            for (j = 0, k = 0; k < v4.edges; k++)\n              if (v4.star[k] != rem2)\n                v4.star[j++] = v4.star[k];\n            v4.edges--;\n          }\n\n        // Eliminate the faces which share this edge.\n        \n        if (boundary)\n          {\n            j = e.f1.index;\n            face[j] = face[faces-1];\n            face[j].index = j;\n            faces--;\n          }\n        else\n          {\n            j = e.f1.index;\n            k = e.f2.index;\n            if (j < faces-2 && k < faces-2)\n              {\n                face[j] = face[faces-1];\n                face[k] = face[faces-2];\n              }\n            else\n              {\n                if (j != faces-1 && k != faces-1)\n                  face[Math.min(j,k)] = face[faces-1];\n                else\n                  face[Math.min(j,k)] = face[faces-2];\n              }\n            face[j].index = j;\n            face[k].index = k;\n            faces -= 2;\n          }\n        \n        // Add the constraints from v2 to v1.  We do this by removing any duplicate\n        // constraints, then appending v2's zone to v1's zone.\n        \n        zone2 = v2.zone;\n        while (zone2 != null)\n          {\n            zone1 = v1.zone;\n            while (zone1 != null)\n              {\n                for (j = 0; j < zone2.constraints; j++)\n                  for (k = 0; k < zone1.constraints; k++)\n                    if (zone2.con[j] == zone1.con[k])\n                      zone2.con[j] = zone2.con[--zone2.constraints];\n                zone1 = zone1.next;\n              }\n            zone2 = zone2.next;\n          }\n        \n        // Eliminate any zones which are completely free of constraints.\n        \n        zone2 = v2.zone;\n        while (zone2.next != null)\n          {\n            if (zone2.next.constraints == 0)\n              zone2.next = zone2.next.next;\n            else\n              zone2 = zone2.next;\n          }\n        \n        // Add v2's zone to v1's zone.\n        \n        zone2 = v2.zone;\n        zone1 = v1.zone;\n        while (zone1.next != null)\n          zone1 = zone1.next;\n        if (zone2.constraints == 0)\n          zone1.next = zone2.next;\n        else\n          zone1.next = zone2;\n        \n        // Go through the faces in v2's crown, and replace references to rem1 and rem2\n        // by rep1 and rep2.\n        \n        for (j = 0; j < v2.faces; j++)\n          {\n            if (v2.crown[j].e1 == rem1)\n              v2.crown[j].e1 = rep1;\n            else if (v2.crown[j].e2 == rem1)\n              v2.crown[j].e2 = rep1;\n            else if (v2.crown[j].e3 == rem1)\n              v2.crown[j].e3 = rep1;\n          }\n        if (!boundary)\n          for (j = 0; j < v2.faces; j++)\n            {\n              if (v2.crown[j].e1 == rem2)\n                v2.crown[j].e1 = rep2;\n              else if (v2.crown[j].e2 == rem2)\n                 v2.crown[j].e2 = rep2;\n              else if (v2.crown[j].e3 == rem2)\n                v2.crown[j].e3 = rep2;\n            }\n        \n        // Similarly, go through the edges adjacent to the faces being removed, and\n        // replace references.\n        \n        if (rem1.f1 == e.f1)\n          {\n            if (rep1.f1 == e.f1)\n              rep1.f1 = rem1.f2;\n            else\n              rep1.f2 = rem1.f2;\n          }\n        else\n          {\n            if (rep1.f1 == e.f1)\n              rep1.f1 = rem1.f1;\n            else\n              rep1.f2 = rem1.f1;\n          }\n        if (rep1.f1 == null)\n          {\n            rep1.f1 = rep1.f2;\n            rep1.f2 = null;\n          }\n        if (!boundary)\n          {\n            if (rem2.f1 == e.f2)\n              {\n                if (rep2.f1 == e.f2)\n                  rep2.f1 = rem2.f2;\n                else\n                  rep2.f2 = rem2.f2;\n              }\n            else\n              {\n                if (rep2.f1 == e.f2)\n                  rep2.f1 = rem2.f1;\n                else\n                  rep2.f2 = rem2.f1;\n              }\n            if (rep2.f1 == null)\n              {\n                rep2.f1 = rep2.f2;\n                rep2.f2 = null;\n              }\n          }\n\n        // Replace all references to v2 by v1.\n        \n        for (j = 0; j < vertex.length; j++)\n          if (vertex[j] == v2)\n            vertex[j] = v1;\n\n        // Update smoothness values for vertices and edges.\n        \n        v1.smoothness = Math.min(v1.smoothness, v2.smoothness);\n        rep1.smoothness = Math.min(rep1.smoothness, rem1.smoothness);\n        if (!boundary)\n          rep2.smoothness = Math.min(rep2.smoothness, rem2.smoothness);\n\n        // Remove rem1 and rem2 from the list, then resort it.\n        \n        for (j = edge.length-1, k = edge.length-1; j > i; j--)\n          if (edge[j] != rem1 && edge[j] != rem2)\n            edge[k--] = edge[j];\n\n        // Update the cost for edges which need it.\n\n        if (boundary)\n          skip = 2;\n        else\n          skip = 3;\n        k = i+skip;\n        for (j = i+skip; j < edge.length; j++)\n          {\n            if (edge[j].cost == -1.0)\n              updateCost(edge[j]);\n            if (edge[j].cost < edge[k].cost)\n              k = j;\n          }\n        tempEdge = edge[i+skip];\n        edge[i+skip] = edge[k];\n        edge[k] = tempEdge;\n      }\n  }\n\n  /* Update the cost for an edge.  Try both directions to see which gives a lower cost. */\n  \n  private void updateCost(MeshEdge ed)\n  {\n    double cost = findCost(ed);\n    int v1 = ed.v1;\n\n    ed.v1 = ed.v2;\n    ed.v2 = v1;\n    ed.cost = findCost(ed);\n    if (ed.cost > cost)\n      {\n        ed.v2 = ed.v1;\n        ed.v1 = v1;\n        ed.cost = cost;\n      }\n    if (ed.cost < tol)\n    {\n      // If this edge is adjacent to a face whose other edges are both boundaries, then\n      // collapsing this edge would leave a dangling edge.  This should not be allowed.\n\n      MeshFace f = ed.f1;\n      if ((f.e1 == ed || f.e1.f2 == null) && (f.e2 == ed || f.e2.f2 == null) && (f.e3 == ed || f.e3.f2 == null))\n      {\n        ed.cost = tol;\n        return;\n      }\n      f = ed.f2;\n      if (f != null)\n        if ((f.e1 == ed || f.e1.f2 == null) && (f.e2 == ed || f.e2.f2 == null) && (f.e3 == ed || f.e3.f2 == null))\n        {\n          ed.cost = tol;\n          return;\n        }\n\n      // If this is a non-boundary edge connecting two different boundaries, then contracting it\n      // would produce a non-manifold mesh.  That should not be allowed.\n\n      if (ed.f2 != null)\n      {\n        MeshEdge star[] = vertex[ed.v1].star;\n        boolean v1IsBoundary = false;\n        for (int i = 0; i < star.length; i++)\n          if (star[i].f2 == null)\n          {\n            v1IsBoundary = true;\n            break;\n          }\n        if (v1IsBoundary)\n        {\n          star = vertex[ed.v2].star;\n          for (int i = 0; i < star.length; i++)\n            if (star[i].f2 == null)\n            {\n              ed.cost = tol;\n              return;\n            }\n        }\n      }\n    }\n  }\n\n  /* Find the cost associated with contracting a given edge.  If the cost is determined \n     to be greater than tol, the method simply returns tol.  This allows findCost() to\n     return as soon as it determines the edge will never be contracted, and also speeds \n     up the sorting of edges (since many edges will have identical costs). */\n\n  private double findCost(MeshEdge ed)\n  {\n    VertexInfo v1 = vertex[ed.v1], v2 = vertex[ed.v2];\n    MeshFace f;\n    Zone zone = v2.zone;\n    double cost, max = 0.0;\n    int i;\n    \n    if (!ed.selected)\n      return tol;\n\n    // First calculate the local tesselation error.\n\n    for (i = 0; i < v2.faces; i++)\n      if (v2.crown[i] != ed.f1 && v2.crown[i] != ed.f2)\n        {\n          f = v2.crown[i];\n          if (vertex[f.v1] == v2)\n            findNormal(v1.pos, vertex[f.v2].pos, vertex[f.v3].pos, temp3);\n          else if (vertex[f.v2] == v2)\n            findNormal(vertex[f.v1].pos, v1.pos, vertex[f.v3].pos, temp3);\n          else\n            findNormal(vertex[f.v1].pos, vertex[f.v2].pos, v1.pos, temp3);\n          cost = tol*(1.0-temp3.dot(f.normal));\n          if (cost >= tol || Double.isNaN(cost))\n            return tol;\n          if (cost > max)\n            max = cost;\n        }\n\n    // Now calculate the local geometric error.\n    \n    while (zone != null)\n      {\n        for (i = 0; i < zone.constraints; i++)\n          {\n            cost = zone.con[i].a*v1.pos.x + zone.con[i].b*v1.pos.y + zone.con[i].c*v1.pos.z + zone.con[i].d;\n            cost *= cost;\n            if (cost >= tol)\n              return tol;\n            if (cost > max)\n              max = cost;\n          }\n        zone = zone.next;\n      }\n    return max;\n  }\n\n  /* Given three points which define a face, find the normal vector. */\n\n  private void findNormal(Vec3 v1, Vec3 v2, Vec3 v3, Vec3 normal)\n  {\n    temp1.set(v2.x, v2.y, v2.z);\n    temp1.subtract(v1);\n    temp2.set(v3.x, v3.y, v3.z);\n    temp2.subtract(v1);\n    normal.set(temp1.y*temp2.z-temp1.z*temp2.y, temp1.z*temp2.x-temp1.x*temp2.z, temp1.x*temp2.y-temp1.y*temp2.x);\n    double length = normal.length();\n    if (length < 1e-10)\n      normal.set(0.0, 0.0, 0.0);\n    else\n      normal.scale(1.0/length);\n  }\n}", "human_rating": 1.970131150436, "metadata": {"project": "aoi", "class": "artofillusion.TriMeshSimplifier", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/TriMeshSimplifier.java", "label_probabilities": {"readability": [1e-20, 2.16812e-07, 0.970131, 0.0298685], "understandability": [2.42325e-06, 0.13605, 0.863945, 2.68761e-06], "complexity": [0.981068, 0.0189324, 0.0, 0.0], "modularization": [0.997851, 0.00214871, 6e-20, 0.0], "overall": [0.0, 1.46771e-06, 0.0230749, 0.976924]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.TubeEditorWindow", "source": "/* Copyright (C) 2002-2008 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion;\n\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\nimport artofillusion.ui.*;\nimport buoy.event.*;\nimport buoy.widget.*;\n\nimport java.awt.*;\n\n/** The TubeEditorWindow class represents the window for editing Tube objects. */\n\npublic class TubeEditorWindow extends CurveEditorWindow\n{\n  private BCheckBoxMenuItem endsItem[];\n  private boolean topology;\n\n  public TubeEditorWindow(EditingWindow parent, String title, ObjectInfo obj, Runnable onClose, boolean allowTopology)\n  {\n    super(parent, title, obj);\n    this.onClose = onClose;\n    topology = allowTopology;\n    FormContainer content = new FormContainer(new double [] {0, 1}, new double [] {1, 0, 0});\n    setContent(content);\n    content.setDefaultLayout(new LayoutInfo(LayoutInfo.CENTER, LayoutInfo.BOTH, null, null));\n    content.add(helpText = new BLabel(), 0, 1, 2, 1);\n    content.add(viewsContainer, 1, 0);\n    RowContainer buttons = new RowContainer();\n    buttons.add(Translate.button(\"ok\", this, \"doOk\"));\n    buttons.add(Translate.button(\"cancel\", this, \"doCancel\"));\n    content.add(buttons, 0, 2, 2, 1, new LayoutInfo());\n    content.add(tools = new ToolPalette(1, 7), 0, 0, new LayoutInfo(LayoutInfo.NORTH, LayoutInfo.NONE, null, null));\n    EditingTool metaTool, altTool, compoundTool;\n    tools.addTool(defaultTool = new ReshapeMeshTool(this, this));\n    tools.addTool(new ScaleMeshTool(this, this));\n    tools.addTool(new RotateMeshTool(this, this, false));\n    tools.addTool(new SkewMeshTool(this, this));\n    tools.addTool(new TaperMeshTool(this, this));\n    tools.addTool(compoundTool = new MoveScaleRotateMeshTool(this, this));\n    if (ArtOfIllusion.getPreferences().getUseCompoundMeshTool())\n      defaultTool = compoundTool;\n    tools.addTool(metaTool = new MoveViewTool(this));\n    tools.addTool(altTool = new RotateViewTool(this));\n    tools.setDefaultTool(defaultTool);\n    tools.selectTool(defaultTool);\n    for (int i = 0; i < theView.length; i++)\n    {\n      MeshViewer view = (MeshViewer) theView[i];\n      view.setMetaTool(metaTool);\n      view.setAltTool(altTool);\n      view.setScene(parent.getScene(), obj);\n    }\n    createEditMenu();\n    createMeshMenu((Tube) obj.getObject());\n    createViewMenu();\n    recursivelyAddListeners(this);\n    UIUtilities.applyDefaultFont(content);\n    UIUtilities.applyDefaultBackground(content);\n    Rectangle screenBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();\n    Dimension windowDim = new Dimension((screenBounds.width*3)/4, (screenBounds.height*3)/4);\n    setBounds(new Rectangle((screenBounds.width-windowDim.width)/2, (screenBounds.height-windowDim.height)/2, windowDim.width, windowDim.height));\n    tools.requestFocus();\n    selected = new boolean [((Tube) obj.getObject()).getVertices().length];\n    findSelectionDistance();\n    updateMenus();\n  }\n\n  void createMeshMenu(Tube obj)\n  {\n    meshMenu = Translate.menu(\"tube\");\n    menubar.add(meshMenu);\n    meshMenuItem = new BMenuItem [8];\n    meshMenuItem[0] = Translate.menuItem(\"deletePoints\", this, \"deleteCommand\");\n    if (topology)\n      meshMenu.add(meshMenuItem[0]);\n    meshMenuItem[1] = Translate.menuItem(\"subdivide\", this, \"subdivideCommand\");\n    if (topology)\n      meshMenu.add(meshMenuItem[1]);\n    meshMenu.add(meshMenuItem[2] = Translate.menuItem(\"editPoints\", this, \"setPointsCommand\"));\n    meshMenu.add(meshMenuItem[3] = Translate.menuItem(\"transformPoints\", this, \"transformPointsCommand\"));\n    meshMenu.add(meshMenuItem[4] = Translate.menuItem(\"randomize\", this, \"randomizeCommand\"));\n    meshMenu.add(meshMenuItem[5] = Translate.menuItem(\"parameters\", this, \"setParametersCommand\"));\n    meshMenu.add(meshMenuItem[6] = Translate.menuItem(\"thickness\", this, \"setThicknessCommand\"));\n    meshMenu.add(Translate.menuItem(\"centerTube\", this, \"centerCommand\"));\n    meshMenu.addSeparator();\n    meshMenu.add(meshMenuItem[7] = Translate.menuItem(\"smoothness\", this, \"setSmoothnessCommand\"));\n    meshMenu.add(smoothMenu = Translate.menu(\"smoothingMethod\"));\n    smoothItem = new BCheckBoxMenuItem [3];\n    smoothMenu.add(smoothItem[0] = Translate.checkboxMenuItem(\"none\", this, \"smoothingChanged\", obj.getSmoothingMethod() == Curve.NO_SMOOTHING));\n    smoothMenu.add(smoothItem[1] = Translate.checkboxMenuItem(\"interpolating\", this, \"smoothingChanged\", obj.getSmoothingMethod() == Curve.INTERPOLATING));\n    smoothMenu.add(smoothItem[2] = Translate.checkboxMenuItem(\"approximating\", this, \"smoothingChanged\", obj.getSmoothingMethod() == Curve.APPROXIMATING));\n    endsItem = new BCheckBoxMenuItem [3];\n    BMenu endsMenu = Translate.menu(\"endsStyle\");\n    meshMenu.add(endsMenu);\n    endsMenu.add(endsItem[0] = Translate.checkboxMenuItem(\"openEnds\", this, \"endsStyleChanged\", obj.getEndsStyle() == Tube.OPEN_ENDS));\n    endsMenu.add(endsItem[1] = Translate.checkboxMenuItem(\"closedEnds\", this, \"endsStyleChanged\", obj.getEndsStyle() == Tube.CLOSED_ENDS));\n    endsMenu.add(endsItem[2] = Translate.checkboxMenuItem(\"flatEnds\", this, \"endsStyleChanged\", obj.getEndsStyle() == Tube.FLAT_ENDS));\n  }\n  \n  protected BMenu createShowMenu()\n  {\n    BMenu menu = Translate.menu(\"show\");\n    MeshViewer view = (MeshViewer) theView[currentView];\n    showItem = new BCheckBoxMenuItem [4];\n    menu.add(showItem[0] = Translate.checkboxMenuItem(\"curve\", this, \"shownItemChanged\", view.getMeshVisible()));\n    menu.add(showItem[1] = Translate.checkboxMenuItem(\"surface\", this, \"shownItemChanged\", view.getSurfaceVisible()));\n    menu.add(showItem[3] = Translate.checkboxMenuItem(\"entireScene\", this, \"shownItemChanged\", view.getSceneVisible()));\n    return menu;\n  }\n\n  public void updateMenus()\n  {\n    super.updateMenus();\n    int i;\n    for (i = 0; i < selected.length && !selected[i]; i++);\n    if (i < selected.length)\n    {\n      editMenuItem[0].setEnabled(true);\n      for (i = 0; i < meshMenuItem.length; i++)\n        meshMenuItem[i].setEnabled(true);\n    }\n    else\n    {\n      editMenuItem[0].setEnabled(false);\n      for (i = 0; i < meshMenuItem.length; i++)\n        meshMenuItem[i].setEnabled(false);\n    }\n  }\n  \n  private void endsStyleChanged(WidgetEvent ev)\n  {\n    Widget source = ev.getWidget();\n    for (int i = 0; i < endsItem.length; i++)\n      if (source == endsItem[i])\n      {\n        for (int j = 0; j < endsItem.length; j++)\n          endsItem[j].setState(false);\n        endsItem[i].setState(true);\n        ((Tube) objInfo.getObject()).setEndsStyle(i);\n        objectChanged();\n        updateImage();\n      }\n  }\n\n  protected void doOk()\n  {\n    Tube theMesh = (Tube) objInfo.getObject();\n    if (((Tube) oldMesh).getMaterial() != null)\n    {\n      if (!theMesh.isClosed())\n      {\n        String options[] = new String [] {Translate.text(\"button.ok\"), Translate.text(\"button.cancel\")};\n        BStandardDialog dlg = new BStandardDialog(\"\", UIUtilities.breakString(Translate.text(\"surfaceNoLongerClosed\")), BStandardDialog.WARNING);\n        int choice = dlg.showOptionDialog(this, options, options[0]);\n        if (choice == 1)\n          return;\n        theMesh.setMaterial(null, null);\n      }\n      else\n        theMesh.setMaterial(((Tube) oldMesh).getMaterial(), ((Tube) oldMesh).getMaterialMapping());\n    }\n    oldMesh.copyObject(theMesh);\n    oldMesh = null;\n    dispose();\n    onClose.run();\n  }\n  \n  protected void doCancel()\n  {\n    oldMesh = null;\n    dispose();\n  }\n\n  /** Delete the selected vertices. */\n\n  public void deleteCommand()\n  {\n    if (!topology)\n      return;\n    int i, j, num = 0;\n    Tube theTube = (Tube) objInfo.getObject();\n    boolean newsel[];\n    MeshVertex vt[] = theTube.getVertices(), newv[];\n    double t[] = theTube.getThickness(), newt[];\n    float s[] = theTube.getSmoothness(), news[];\n\n    for (i = 0; i < selected.length; i++)\n      if (selected[i])\n\tnum++;\n    if (num == 0)\n      return;\n    if (theTube.getEndsStyle() != Tube.CLOSED_ENDS && selected.length-num < 2)\n    {\n      new BStandardDialog(\"\", Translate.text(\"tubeNeeds2Points\"), BStandardDialog.INFORMATION).showMessageDialog(this);\n      return;\n    }\n    if (theTube.getEndsStyle() == Tube.CLOSED_ENDS && selected.length-num < 3)\n    {\n      new BStandardDialog(\"\", Translate.text(\"tubeNeeds3Points\"), BStandardDialog.INFORMATION).showMessageDialog(this);\n      return;\n    }\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theTube, theTube.duplicate()}));\n    newv = new MeshVertex [vt.length-num];\n    newt = new double [vt.length-num];\n    news = new float [vt.length-num];\n    newsel = new boolean [vt.length-num];\n    for (i = 0, j = 0; i < vt.length; i++)\n    {\n      if (!selected[i])\n      {\n        newsel[j] = selected[i];\n        newt[j] = t[i];\n        news[j] = s[i];\n        newv[j++] = vt[i];\n      }\n    }\n    theTube.setShape(newv, news, newt);\n    setSelection(newsel);\n    objectChanged();\n    updateImage();\n  }\n\n  /** Subdivide the tube between the selected vertices. */\n\n  public void subdivideCommand()\n  {\n    Tube theTube = (Tube) objInfo.getObject();\n    MeshVertex vt[] = theTube.getVertices(), newpos[];\n    float s[] = theTube.getSmoothness(), news[];\n    double t[] = theTube.getThickness(), newt[];\n    int numParam = (theTube.getParameters() == null ? 0 : theTube.getParameters().length);\n    double param[][], newparam[][], paramTemp[] = new double [numParam];\n    boolean newsel[], split[];\n    int i, j, p1, p3, p4, splitcount = 0, method = theTube.getSmoothingMethod();\n    \n    // Record parameter values.\n    \n    param = new double [vt.length][numParam];\n    ParameterValue paramValue[] = theTube.getParameterValues();\n    for (i = 0; i < numParam; i++)\n    {\n      if (paramValue[i] instanceof VertexParameterValue)\n      {\n        double val[] = ((VertexParameterValue) paramValue[i]).getValue();\n        for (j = 0; j < val.length; j++)\n          param[j][i] = val[j];\n      }\n    }\n    \n    // Determine which parts need to be subdivided.\n    \n    if (theTube.getEndsStyle() == Tube.CLOSED_ENDS)\n      split = new boolean [vt.length];\n    else\n      split = new boolean [vt.length-1];\n    for (i = 0; i < split.length; i++)\n      if (selected[i] && selected[(i+1)%selected.length])\n      {\n        split[i] = true;\n        splitcount++;\n      }\n    newpos = new MeshVertex [vt.length+splitcount];\n    news = new float [vt.length+splitcount];\n    newt = new double [vt.length+splitcount];\n    newparam = new double [vt.length+splitcount][numParam];\n    newsel = new boolean [vt.length+splitcount];\n    \n    // Do the subdivision.\n\n    for (i = 0, j = 0; i < split.length; i++)\n    {\n      newsel[j] = selected[i];\n      p1 = i-1;\n      if (p1 < 0)\n      {\n        if (theTube.getEndsStyle() == Tube.CLOSED_ENDS)\n          p1 = vt.length-1;\n        else\n          p1 = 0;\n      }\n      if (i < vt.length-1)\n        p3 = i+1;\n      else\n      {\n        if (theTube.getEndsStyle() == Tube.CLOSED_ENDS)\n          p3 = 0;\n        else\n          p3 = vt.length-1;\n      }\n      if (selected[i] && method == Mesh.APPROXIMATING)\n      {\n        newpos[j] = SplineMesh.calcApproxPoint(vt, s, param, paramTemp, p1, i, p3);\n        newt[j] = Tube.calcApproxThickness(t, s, p1, i, p3);\n        for (int k = 0; k < numParam; k++)\n          newparam[j][k] = paramTemp[k];\n      }\n      else\n      {\n        newpos[j] = vt[i];\n        newt[j] = t[i];\n        newparam[j] = param[i];\n      }\n      if (selected[i])\n        news[j] = Math.min(s[i]*2.0f, 1.0f);\n      else\n        news[j] = s[i];\n      if (!split[i])\n      {\n        j++;\n        continue;\n      }\n      if (method == Mesh.NO_SMOOTHING)\n      {\n        newpos[j+1] = MeshVertex.blend(vt[i], vt[p3], 0.5, 0.5);\n        for (int k = 0; k < numParam; k++)\n          newparam[j+1][k] = 0.5*(param[i][k]+param[p3][k]);\n      }\n      else if (method == Mesh.INTERPOLATING)\n      {\n        if (i < vt.length-2)\n          p4 = i+2;\n        else\n        {\n          if (theTube.getEndsStyle() == Tube.CLOSED_ENDS)\n            p4 = (i+2)%vt.length;\n          else\n            p4 = vt.length-1;\n        }\n        newpos[j+1] = SplineMesh.calcInterpPoint(vt, s, param, paramTemp, p1, i, p3, p4);\n        newt[j+1] = Tube.calcInterpThickness(t, s, p1, i, p3, p4);\n        for (int k = 0; k < numParam; k++)\n          newparam[j+1][k] = paramTemp[k];\n      }\n      else\n      {\n        newpos[j+1] = MeshVertex.blend(vt[i], vt[p3], 0.5, 0.5);\n        newt[j+1] = 0.5*(t[i]+t[p3]);\n        for (int k = 0; k < numParam; k++)\n          newparam[j+1][k] = 0.5*(param[i][k]+param[p3][k]);\n      }\n      news[j+1] = 1.0f;\n      newsel[j+1] = true;\n      j += 2;\n    }\n    if (theTube.getEndsStyle() != Tube.CLOSED_ENDS)\n    {\n      newpos[0] = vt[0];\n      newpos[j] = vt[i];\n      newt[0] = t[0];\n      newt[j] = t[i];\n      news[j] = s[i];\n      newparam[0] = param[0];\n      newparam[j] = param[i];\n      newsel[j] = selected[i];\n    }\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theTube, theTube.duplicate()}));\n    theTube.setShape(newpos, news, newt);\n    for (i = 0; i < numParam; i++)\n    {\n      if (paramValue[i] instanceof VertexParameterValue)\n      {\n        double val[] = new double [newpos.length];\n        for (j = 0; j < val.length; j++)\n          val[j] = newparam[j][i];\n        paramValue[i] = new VertexParameterValue(val);\n      }\n    }\n    theTube.setParameterValues(paramValue);\n    setSelection(newsel);\n    objectChanged();\n    updateImage();\n  }\n  \n  /** Allow the user to set the thickness for selected vertices. */\n  \n  public void setThicknessCommand()\n  {\n    Tube theTube = (Tube) objInfo.getObject();\n    double thickness[] = theTube.getThickness(), initial = -1;\n    int selectDist[] = getSelectionDistance();\n\n    for (int i = 0; i < selectDist.length; i++)\n      if (selectDist[i] == 0)\n      {\n        if (initial == -1)\n          initial = thickness[i];\n        else if (initial != thickness[i])\n          initial = Double.NaN;\n      }\n    if (initial == -1)\n      return;  // No selected vertices.\n    ValueField thicknessField = new ValueField(initial, ValueField.NONNEGATIVE, 5);\n    ComponentsDialog dlg = new ComponentsDialog(this, Translate.text(\"setThicknessTitle\"),\n      new Widget [] {thicknessField}, new String [] {Translate.text(\"Thickness\")});\n    if (!dlg.clickedOk() || Double.isNaN(thicknessField.getValue()))\n      return;\n    setUndoRecord(new UndoRecord(this, false, UndoRecord.COPY_OBJECT, new Object [] {theTube, theTube.duplicate()}));\n    for (int i = 0; i < selectDist.length; i++)\n      if (selectDist[i] == 0)\n        thickness[i] = thicknessField.getValue();\n    theTube.setThickness(thickness);\n    objectChanged();\n    updateImage();\n  }\n}", "human_rating": 2.0745713470000484, "metadata": {"project": "aoi", "class": "artofillusion.TubeEditorWindow", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/TubeEditorWindow.java", "label_probabilities": {"readability": [1.21433e-14, 0.0754961, 0.923579, 0.000925047], "understandability": [1.59903e-11, 0.000136793, 0.273906, 0.725957], "complexity": [0.922185, 0.0778145, 1.5278e-07, 1e-20], "modularization": [0.967674, 0.0323213, 4.41241e-06, 1.77e-18], "overall": [0.0, 9.35963e-07, 0.126096, 0.873903]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.ui.DefaultDockableWidget", "source": "/* Copyright (C) 2007 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.ui;\n\nimport buoyx.docking.*;\nimport buoy.widget.*;\n\nimport java.awt.*;\n\n/**\n * This is a DockableWidget subclass that paints its border using colors obtained from ThemeManager.\n */\n\npublic class DefaultDockableWidget extends DockableWidget\n{\n  public DefaultDockableWidget()\n  {\n  }\n\n  public DefaultDockableWidget(Widget content, String label)\n  {\n    super(content, label);\n  }\n\n  protected void paintBorder(Graphics2D g)\n  {\n    Rectangle bounds = getBounds();\n    Insets insets = getBorderInsets();\n    g.setPaint(new GradientPaint(0, 0, ThemeManager.getDockableBarColor1(), 0, insets.top, ThemeManager.getDockableBarColor2()));\n    g.fillRect(0, 0, bounds.width, insets.top);\n    g.setColor(ThemeManager.getDockableBarColor2().darker());\n    g.drawLine(0, insets.top-1, bounds.width, insets.top-1);\n    g.setColor(ThemeManager.getDockableTitleColor());\n    if (getLabel() != null)\n    {\n      FontMetrics fm = getComponent().getFontMetrics(getComponent().getFont());\n      g.drawString(getLabel(), 2, fm.getMaxAscent()+2);\n    }\n  }\n}\n", "human_rating": 3.2526544800253188, "metadata": {"project": "aoi", "class": "artofillusion.ui.DefaultDockableWidget", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/ui/DefaultDockableWidget.java", "label_probabilities": {"readability": [0.253554, 0.745548, 0.00089724, 2.53185e-11], "understandability": [0.00320941, 0.870862, 0.125928, 3.91373e-07], "complexity": [0.0, 4.74023e-14, 0.00503831, 0.994962], "modularization": [0.0, 0.00021786, 0.263401, 0.736381], "overall": [0.16281, 0.837076, 0.000113757, 8.74057e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.ui.DefaultToolButton", "source": "/* Copyright (C) 2007 by Fran�ois Guillet\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY\n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A\n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.ui;\n\nimport artofillusion.util.IconGenerator;\nimport java.awt.*;\nimport java.awt.image.BufferedImage;\nimport javax.swing.ImageIcon;\n\nimport java.util.HashMap;\n\n/**\n * This ToolButton is the classic button with one icon for standard representation\n * and another one for selected state.\n * \n * @author Francois Guillet\n *\n */\npublic class DefaultToolButton extends ToolButton\n{\n    protected Image icon;\n    protected Image selectedIcon;\n\n    /*\n    public DefaultToolButton(Object owner, String iconFileName, String selectedIconFilename) {\n        this(owner, ThemeManager.getIcon(iconFileName), ThemeManager.getIcon(selectedIconFilename));\n    }\n    */\n\n    /**\n     * create a DefaultToolButton for the specified owner, and the icon\n     * specified by the <i>image</i>, by applying the correct style to the\n     * image to generate theme-consistent <i>normal</i> and <i>selected</i>\n     * icons.\n     *\n     * This ctor is the preferred ctor, as it ensures the greatest consistency\n     * of all icons with the theme.\n     *\n     *  @param owner the owning object for this button\n     *\n     *  @param image the image to use with the style to generate the normal and\n     *                selected icons for this button.\n     */\n    public DefaultToolButton(Object owner, ImageIcon image)\n    {\n        super(owner);\n\n        ThemeManager.ButtonStyle bstyle = ThemeManager.getButtonStyle(owner);\n        if (bstyle != null) {\n            try {\n                icon = applyStyle(bstyle, \"normal\", owner, image);\n                selectedIcon = applyStyle(bstyle, \"selected\", owner, image);\n            } catch (Exception e) {\n                System.out.println(\"Applying style: \" + e);\n            }\n        }\n\n        // if the style failed to apply, just use the icon as it is\n        if (icon == null || icon.getWidth(null) <= 0)\n            icon = image.getImage();\n\n        // last resort: set icon to notFoundIcon\n        if (icon == null || icon.getWidth(null) <= 0)\n            icon = ThemeManager.getNotFoundIcon(owner).getImage();\n\n        // selectedIcon defaults to icon with a red \"wash\"\n        if (selectedIcon == null)  {\n            selectedIcon = IconGenerator.copy(icon);\n            IconGenerator.multiply((BufferedImage) selectedIcon, 1.0f, 1.0f, 0.5f, 0.5f);\n        }\n\n        width = icon.getWidth(null);\n        height = icon.getHeight(null);\n    }\n\n    /**\n     *  create a new DefaultToolButton using the specified icons for\n     *  <i>normal</i> and <i>selected</i> icons.\n     *\n     *<b><em>No</em> style is applied - the icons are used as-is.\n     *\n     *  This is the least-preferred ctor, since it applies no consistency\n     *  at all, and relies on the icon creator to have made the icons\n     *  consistent. This normally works well for icons that are part of the\n     *  theme, but usually works very poorly for icons associated with plugins.\n     *\n     *  @param icon the icon to use for normal button display\n     *  @param selectedIcon the icon to use for selected display.\n     */\n    public DefaultToolButton(Object owner, ImageIcon icon, ImageIcon selectedIcon) {\n        super(owner);\n        this.icon = icon.getImage();\n        this.selectedIcon = selectedIcon.getImage();\n        height = icon.getIconHeight();\n        width = icon.getIconWidth();\n    }\n\n    public void paint(Graphics2D g) {\n        switch(state) {\n        case NORMAL_STATE:\n        case HIGHLIGHTED_STATE:\n            g.drawImage(icon, position.x, position.y, null);\n            break;\n        case SELECTED_STATE:\n            g.drawImage(selectedIcon, position.x, position.y, null);\n            break;\n        }\n    }\n\n\n  /**\n   *  apply a style for the specified type and owner, to the specified\n   *  icon url.\n   *\n   *  If the style defined no <code>type.icon</code> attribute, then\n   *  a definition is generated using the <code>type.background</i> and\n   *  <code>type.overlay</code> attributes. If no style definition can\n   *  be foudn or generated, the icon from <i>image</i> is returned.\n   *\n   *  @param style the ButtonStyle to apply\n   *  @param type the type of icon to create. Current values are\n   *        <em>normal</em> and <em>selected</em>.\n   *        In theory <em>highlighted</em> can also be specified, but\n   *        currently no code recognises this type.\n   *\n   *  @param owner the owner of this style.\n   *\n   *  @param image the image to use with the style to generate the final\n   *                icon.\n   *\n   *  @return the generated icon.\n   */\n  public Image applyStyle(ThemeManager.ButtonStyle style, String type, Object owner, ImageIcon image)\n          throws Exception\n  {\n      // can default the macro from other attributes\n      String macro = style.attributes.get(type + \".icon\");\n      if (macro == null || macro.length() == 0) {\n          StringBuffer sb = new StringBuffer(64);\n\n          String att = style.attributes.get(type + \".background\");\n          if (att == null) att = style.attributes.get(\"background\");\n\n          if (att != null) {\n              sb.append(att);\n              sb.append(\"; {icon};\");\n\n              att = (String) style.attributes.get(type + \".overlay\");\n              if (att == null) att = style.attributes.get(\"overlay\");\n              if (att != null) sb.append(att);\n\n              macro = sb.toString();\n          }\n          else\n              // no macro possible, just return the image\n              return image.getImage();\n      }\n\n      // we're still here, so apply the style...\n\n      // initialise the namespace\n      HashMap<String, Object> namespace = new HashMap<String, Object>(style.attributes);\n\n      if (image != null) {\n          Image img = image.getImage();\n          namespace.put(\"{icon}\", img);\n          namespace.put('{' + type + \".icon}\", img);\n      }\n\n      namespace.put(\"{owner}\", owner);\n\n      // get the classloader from the selected theme\n      ClassLoader loader = ThemeManager.getSelectedTheme().loader;\n\n      // return the result of applying the style\n      return IconGenerator.apply(macro, null, namespace, loader, style.width, style.height);\n  }\n}", "human_rating": 3.999998843376399, "metadata": {"project": "aoi", "class": "artofillusion.ui.DefaultToolButton", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/ui/DefaultToolButton.java", "label_probabilities": {"readability": [0.999999, 9.47792e-07, 1.99676e-13, 0.0], "understandability": [0.942242, 0.0552206, 0.00253737, 4.73798e-12], "complexity": [0.0, 1.9404e-08, 0.95305, 0.0469499], "modularization": [5.081e-17, 2.59347e-09, 0.0877939, 0.912206], "overall": [0.980362, 0.0183597, 0.000943958, 0.000334124]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.ui.ToolPalette", "source": "/* Copyright (C) 1999-2006 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.ui;\n\nimport artofillusion.*;\nimport buoy.event.*;\nimport buoy.widget.*;\nimport java.awt.*;\n\n/** A ToolPalette is drawn as a grid of images, one for each EditingTool that is added to\n    the palette.  It allows a single tool to be selected at any time. */\n\npublic class ToolPalette extends CustomWidget\n{\n  private int width, height, numTools, selected, lastSelected, defaultTool;\n  private EditingTool tool[];\n  private Dimension maxsize;\n\n  /** Create a new ToolPalette.  w and h give the width and height of the tool palette,\n      measured in icons. */\n\n  public ToolPalette(int w, int h)\n  {\n    width = w;\n    height = h;\n    tool = new EditingTool [w*h];\n    numTools = 0;\n    selected = 0;\n    defaultTool = 0;\n    maxsize = new Dimension(0, 0);\n    addEventLink(MousePressedEvent.class, this, \"mousePressed\");\n    addEventLink(MouseClickedEvent.class, this, \"mouseClicked\");\n    addEventLink(MouseEnteredEvent.class, this, \"mouseEntered\");\n    addEventLink(MouseExitedEvent.class, this, \"mouseExited\");\n    addEventLink(MouseMovedEvent.class, this, \"mouseMoved\");\n    addEventLink(RepaintEvent.class, this, \"paint\");\n    addEventLink(ToolTipEvent.class, this, \"showToolTip\");\n    setBackground(ThemeManager.getPaletteBackgroundColor());\n  }\n\n  /** Add a new tool. */\n\n  public void addTool(EditingTool t)\n  {\n    addTool(numTools, t);\n  }\n\n  /** Add a new tool. */\n\n  public void addTool(int position, EditingTool t)\n  {\n    if (numTools == tool.length)\n    {\n      // We need to extend the palette.\n\n      height++;\n      EditingTool newTool[] = new EditingTool [width*height];\n      System.arraycopy(tool, 0, newTool, 0, tool.length);\n      tool = newTool;\n      invalidateSize();\n    }\n    for (int i = numTools; i > position; i--)\n      tool[i] = tool[i-1];\n    tool[position] = t;\n    numTools++;\n    int buttonMargin = ThemeManager.getButtonMargin();\n    int paletteMargin = ThemeManager.getPaletteMargin();\n    int w = t.getButton().getWidth() + 2*buttonMargin;\n    int h = t.getButton().getHeight() + 2*buttonMargin;\n    if (w > maxsize.width)\n      maxsize.width = w;\n    if (h > maxsize.height)\n      maxsize.height = h;\n    for (int i = 0; i < numTools; i++)\n      tool[i].getButton().setPosition((i%width)*maxsize.width + paletteMargin + buttonMargin,\n          (i/width)*maxsize.height + paletteMargin + buttonMargin);\n    if (numTools == 1)\n      t.activate();\n  }\n\n  /** Get the number of tools in palette. */\n\n  public int getNumTools()\n  {\n    return numTools;\n  }\n\n  /** Get a tool by index. */\n\n  public EditingTool getTool(int index)\n  {\n    return tool[index];\n  }\n\n  /** Get the default tool. */\n\n  public EditingTool getDefaultTool()\n  {\n    return tool[defaultTool];\n  }\n\n  /** Set the default tool. */\n\n  public void setDefaultTool(EditingTool t)\n  {\n    for (int i = 0; i < tool.length; i++)\n      if (tool[i] == t)\n        defaultTool = i;\n  }\n\n  /** Return the number of the currently selected tool. */\n\n  public int getSelection()\n  {\n    return selected;\n  }\n\n  /** Return the currently selected tool. */\n\n  public EditingTool getSelectedTool()\n  {\n    return tool[selected];\n  }\n\n  private void paint(RepaintEvent ev)\n  {\n    Graphics2D g = ev.getGraphics();\n    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);\n    int paletteMargin = ThemeManager.getPaletteMargin();\n    g.setColor(ThemeManager.getPaletteBackgroundColor());\n    g.fillRoundRect(0, 0, width*maxsize.width + 2*paletteMargin, height*maxsize.height + 2*paletteMargin, 8, 8);\n    //So as to ensure graphical consistency, buttons must be drawn following a certain order:\n    //normal buttons first\n    for (int i = 0; i < numTools; i++)\n      if (!tool[i].getButton().isSelected() && !tool[i].getButton().isHighlighted())\n          tool[i].getButton().paint(g);\n    //highlighted buttons next\n    for (int i = 0; i < numTools; i++)\n      if (!tool[i].getButton().isSelected() && tool[i].getButton().isHighlighted())\n          tool[i].getButton().paint(g);\n    //then the selected one.\n    for (int i = 0; i < numTools; i++)\n      if (tool[i].getButton().isSelected())\n          tool[i].getButton().paint(g);\n  }\n\n  private void showToolTip(ToolTipEvent ev)\n  {\n    int i = findClickedTool(ev.getPoint());\n    if (i > -1 && i < numTools)\n    {\n      String text = tool[i].getToolTipText();\n      if (text == null)\n        BToolTip.hide();\n      else\n        new BToolTip(text).processEvent(ev);\n    }\n  }\n\n  public Dimension getPreferredSize()\n  {\n    int paletteMargin = ThemeManager.getPaletteMargin();\n    return new Dimension(width*maxsize.width+2*paletteMargin, height*maxsize.height+2*paletteMargin);\n  }\n\n  public Dimension getMinimumSize()\n  {\n    return getPreferredSize();\n  }\n\n  private void mousePressed(MousePressedEvent e)\n  {\n    int i = findClickedTool(e.getPoint());\n    if (i > -1 && i < numTools && i != selected)\n    {\n      if (selected < tool.length)\n        tool[selected].deactivate();\n      selected = lastSelected = i;\n      repaint();\n      tool[i].activate();\n    }\n  }\n\n  private void mouseClicked(MouseClickedEvent e)\n  {\n    int i = findClickedTool(e.getPoint());\n    if (i > -1 && i < numTools && e.getClickCount() == 2)\n      tool[i].iconDoubleClicked();\n  }\n\n  private void mouseEntered(MouseEnteredEvent ev)\n  {\n    int t = findClickedTool(ev.getPoint());\n    for (int i = 0; i < numTools; i++)\n      tool[i].getButton().setHighlighted(t == i);\n    repaint();\n  }\n\n  private void mouseExited()\n  {\n    for (int i = 0; i < numTools; i++)\n\t  tool[i].getButton().setHighlighted(false);\n    repaint();\n  }\n\n  private void mouseMoved(MouseMovedEvent ev)\n  {\n    int t = findClickedTool(ev.getPoint());\n    for (int i = 0; i < numTools; i++)\n      tool[i].getButton().setHighlighted(t == i);\n    repaint();\n  }\n\n  private int findClickedTool(Point p)\n  {\n    Rectangle r = new Rectangle();\n    for (int i = 0; i < numTools; i++)\n    {\n      Point pos = tool[i].getButton().getPosition();\n      r.x = pos.x;\n      r.y = pos.y;\n      r.width = tool[i].getButton().getWidth();\n      r.height = tool[i].getButton().getHeight();\n      if (r.contains(p))\n        return i;\n    }\n    return -1;\n  }\n\n  /** Change the currently selected tool. */\n\n  public void selectTool(EditingTool which)\n  {\n    selectToolInternal(which);\n    lastSelected = selected;\n  }\n\n  /** This is used internally to actually change the selected tool. */\n\n  private void selectToolInternal(EditingTool which)\n  {\n    for (int i = 0; i < numTools; i++)\n      if (tool[i] == which)\n      {\n        tool[selected].deactivate();\n        selected = i;\n        repaint();\n        tool[i].activate();\n      }\n  }\n\n  /** Allow the user to change tools with the keyboard. */\n\n  public void keyPressed(KeyPressedEvent ev)\n  {\n    int code = ev.getKeyCode();\n    int newtool;\n\n    if (code == KeyPressedEvent.VK_LEFT)\n      newtool = selected-1;\n    else if (code == KeyPressedEvent.VK_RIGHT)\n      newtool = selected+1;\n    else if (code == KeyPressedEvent.VK_UP)\n      newtool = selected-width;\n    else if (code == KeyPressedEvent.VK_DOWN)\n      newtool = selected+width;\n    else\n      return;\n    if (newtool < 0)\n      newtool += numTools;\n    if (newtool >= numTools)\n      newtool -= numTools;\n    tool[selected].deactivate();\n    selected = lastSelected = newtool;\n    repaint();\n    tool[selected].activate();\n  }\n\n  /** Calling this method will toggle between the default tool and the last tool which was\n      explicitly selected. */\n\n  public void toggleDefaultTool()\n  {\n    selectToolInternal(tool[selected == lastSelected ? defaultTool : lastSelected]);\n  }\n}", "human_rating": 2.48995987, "metadata": {"project": "aoi", "class": "artofillusion.ui.ToolPalette", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/ui/ToolPalette.java", "label_probabilities": {"readability": [0.0138065, 0.464325, 0.519891, 0.00197687], "understandability": [6.87484e-06, 0.390459, 0.608976, 0.000557745], "complexity": [1.12405e-08, 0.115805, 0.882317, 0.00187836], "modularization": [3.0863e-05, 0.0453484, 0.909886, 0.0447346], "overall": [0.0114379, 0.91303, 0.075532, 1.20478e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.view.FlatVertexShader", "source": "/* Copyright (C) 2004 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.view;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\n\n/** This is a VertexShader which renders a mesh in a solid color with flat shading. */\n\npublic class FlatVertexShader implements VertexShader\n{\n  private RGBColor meshColor;\n  private RenderingMesh mesh;\n  private Vec3 viewDir;\n  \n  /** Create a FlatVertexShader for a mesh.\n      @param mesh      the mesh to render\n      @param object    the object to which the mesh corresponds\n      @param time      the current time\n      @param viewDir   the direction from which it is being viewed\n  */\n  \n  public FlatVertexShader(RenderingMesh mesh, Object3D object, double time, Vec3 viewDir)\n  {\n    this.mesh = mesh;\n    this.viewDir = viewDir;\n    TextureSpec spec = new TextureSpec();\n    object.getTexture().getAverageSpec(spec, time, object.getAverageParameterValues());\n    meshColor = new RGBColor(spec.diffuse.getRed()+0.5*spec.specular.getRed(), \n        spec.diffuse.getGreen()+0.5*spec.specular.getGreen(), \n        spec.diffuse.getBlue()+0.5*spec.specular.getBlue());\n    meshColor.clip();\n  }\n  \n  /** Create a FlatVertexShader for a mesh.\n      @param mesh      the mesh to render\n      @param color     the color in which to draw the mesh\n      @param viewDir   the direction from which it is being viewed\n  */\n  \n  public FlatVertexShader(RenderingMesh mesh, RGBColor color, Vec3 viewDir)\n  {\n    this.mesh = mesh;\n    meshColor = color;\n    this.viewDir = viewDir;\n  }\n  \n  /** Select the color for a vertex.\n      @param face     the index of the triangle being rendered\n      @param vertex   the index of the vertex to color\n      @param color    the vertex color will be returned in this object\n  */\n  \n  public void getColor(int face, int vertex, RGBColor color)\n  {\n    color.copy(meshColor);\n    color.scale(0.1f+0.8f*Math.abs((float) viewDir.dot(mesh.faceNorm[face])));\n  }\n  \n  /** Get whether a particular face should be rendered with a single uniform color.\n      @param face    the index of the triangle being rendered\n  */\n  \n  public boolean isUniformFace(int face)\n  {\n    return true;\n  }\n  \n  /** Get whether this shader represents a uniform texture.  If this returns true, all\n      texture properties are uniform over the entire surface (although different parts\n      may still be colored differently due to lighting).\n   */\n  \n  public boolean isUniformTexture()\n  {\n    return true;\n  }\n  \n  /** Get the texture properties of the surface.  This should only be called if isUniformTexture() returns true.\n      @param spec     the surface properties will be returned in this object\n   */\n\n  public void getTextureSpec(TextureSpec spec)\n  {\n    spec.diffuse.copy(meshColor);\n    spec.hilight.setRGB(0.0f, 0.0f, 0.0f);\n    spec.emissive.setRGB(0.0f, 0.0f, 0.0f);    \n  }\n}\n", "human_rating": 3.9083528664202603, "metadata": {"project": "aoi", "class": "artofillusion.view.FlatVertexShader", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/view/FlatVertexShader.java", "label_probabilities": {"readability": [0.908353, 0.0916467, 3.8321e-07, 2.60088e-13], "understandability": [0.406137, 0.590753, 0.00310968, 3.11464e-08], "complexity": [6.76992e-06, 0.0105432, 0.379533, 0.609917], "modularization": [0.0, 2.44921e-10, 0.0861324, 0.913868], "overall": [0.655007, 0.344991, 2.02603e-06, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.view.GLCanvasDrawer", "source": "/* Copyright (C) 2005-2012 by Peter Eastman\n\nThis program is free software; you can redistribute it and/or modify it under the\nterms of the GNU General Public License as published by the Free Software\nFoundation; either version 2 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY \nWARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \nPARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.view;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.texture.TextureSpec;\n\nimport java.awt.*;\nimport java.awt.geom.*;\nimport java.awt.image.*;\nimport java.nio.*;\nimport java.util.*;\nimport java.lang.ref.*;\n\nimport javax.media.opengl.*;\n\nimport buoy.event.*;\nimport com.sun.opengl.util.*;\n\n/** This is a CanvasDrawer which uses OpenGL to render the contents of a ViewerCanvas. */\n\npublic class GLCanvasDrawer implements CanvasDrawer\n{\n  private ViewerCanvas view;\n  private GLCanvas canvas;\n  private GL gl;\n  private Rectangle bounds;\n  private Mat4 lastObjectTransform;\n  private Color lastColor;\n  private double minDepth, maxDepth;\n  private boolean depthEnabled, lightingEnabled, cullingEnabled;\n  private FloatBuffer vertBuffer, normBuffer;\n  private Shape draggedShape;\n  private GLImage template;\n  private WeakHashMap<Image, GLTexture> textureMap = new WeakHashMap<Image, GLTexture>();\n  private ReferenceQueue textureCleanupQueue = new ReferenceQueue();\n  private HashSet<TextureReference> textureReferences = new HashSet<TextureReference>();\n\n  private static final float COLOR_SCALE = 1.0f/255.0f;\n  private static HashMap<String, SoftReference<GLImage>> textImageMap = new HashMap<String, SoftReference<GLImage>>();\n  private static WeakHashMap<Image, SoftReference<GLImage>> imageMap = new WeakHashMap<Image, SoftReference<GLImage>>();\n  private static Color lastTextColor;\n  private static int imageRenderMode = -1;\n  private static boolean useTextureRectangle;\n\n  public GLCanvasDrawer(ViewerCanvas view)\n  {\n    this.view = view;\n    canvas = new GLCanvas();\n    canvas.addGLEventListener(new CanvasListener());\n  }\n  \n  /** Get the GLCanvas into which this draws. */\n  \n  public Component getGLCanvas()\n  {\n    return canvas;\n  }\n\n  /** Set the template image. */\n  \n  public void setTemplateImage(Image im)\n  {\n    if (im == null)\n    {\n      template = null;\n      return;\n    }\n    try\n    {\n      template = new GLImage(im);\n    }\n    catch (InterruptedException ex)\n    {\n      ex.printStackTrace();\n    }\n  }\n  \n  /** Show feedback to the user in response to a mouse drag, by drawing a Shape over the image.\n      Unlike the other methods of this class, this method may be called at arbitrary times\n      (though always from the event dispatch thread), not during the process of rendering\n      the image. */\n\n  public void drawDraggedShape(Shape shape)\n  {\n    draggedShape = shape;\n    canvas.display();\n  }\n\n  /** Prepare for rendering from the camera's current viewpoint.*/\n  \n  private void prepareView3D(Camera camera)\n  {\n    if (camera.getObjectToView() == lastObjectTransform)\n      return;\n    lastObjectTransform = camera.getObjectToView();\n    gl.glMatrixMode(GL.GL_PROJECTION);\n    gl.glLoadIdentity();\n    double scale = -1.0/camera.getViewToScreen().m11;\n    if (view.isPerspective())\n      gl.glFrustum(-0.5*bounds.width*scale, 0.5*bounds.width*scale, -0.5*bounds.height*scale, 0.5*bounds.height*scale, minDepth, maxDepth);\n    else\n      gl.glOrtho(-0.5*bounds.width*scale, 0.5*bounds.width*scale, -0.5*bounds.height*scale, 0.5*bounds.height*scale, minDepth, maxDepth);\n    Mat4 toView = lastObjectTransform;\n    gl.glMatrixMode(GL.GL_MODELVIEW);\n    gl.glLoadMatrixd(new double [] {\n        -toView.m11, toView.m21, -toView.m31, toView.m41,\n        -toView.m12, toView.m22, -toView.m32, toView.m42,\n        -toView.m13, toView.m23, -toView.m33, toView.m43,\n        -toView.m14, toView.m24, -toView.m34, toView.m44\n    }, 0);\n  }\n  \n  /** Prepare for drawing 2D primitives. */\n  \n  private void prepareView2D()\n  {\n    if (lastObjectTransform == null)\n      return;\n    lastObjectTransform = null;\n    gl.glMatrixMode(GL.GL_PROJECTION);\n    gl.glLoadIdentity();\n    if (view.isPerspective())\n      gl.glFrustum(0.0, bounds.width, 0.0, bounds.height, minDepth, maxDepth);\n    else\n      gl.glOrtho(0.0, bounds.width, 0.0, bounds.height, minDepth, maxDepth);\n    gl.glMatrixMode(GL.GL_MODELVIEW);\n    gl.glLoadIdentity();\n  }\n  \n  /** Prepare for drawing with or without depth testing. */\n  \n  private void prepareDepthTest(boolean depthTest)\n  {\n    if (depthTest != depthEnabled)\n    {\n      depthEnabled = depthTest;\n      if (depthEnabled)\n        gl.glEnable(GL.GL_DEPTH_TEST);\n      else\n        gl.glDisable(GL.GL_DEPTH_TEST);\n    }\n  }\n  \n  /** Prepare for drawing in a solid color. */\n  \n  private void prepareSolidColor(Color color)\n  {\n    if (lastColor == color)\n      return;\n    if (lightingEnabled)\n    {\n      lightingEnabled = false;\n      gl.glDisable(GL.GL_LIGHTING);\n    }\n    lastColor = color;\n    gl.glColor3f(color.getRed()*COLOR_SCALE, color.getGreen()*COLOR_SCALE, color.getBlue()*COLOR_SCALE);\n  }\n  \n  /** Prepare for drawing a shaded surface. */\n  \n  private void prepareShading(boolean lighting)\n  {\n    if (lightingEnabled != lighting)\n    {\n      lightingEnabled = lighting;\n      if (lighting)\n        gl.glEnable(GL.GL_LIGHTING);\n      else\n        gl.glDisable(GL.GL_LIGHTING);\n    }\n    lastColor = null;\n  }\n  \n  /** Prepare for drawing with or without backface culling. */\n  \n  private void prepareCulling(boolean hideBackfaces)\n  {\n    if (cullingEnabled == hideBackfaces)\n      return;\n    cullingEnabled = hideBackfaces;\n    if (cullingEnabled)\n      gl.glEnable(GL.GL_CULL_FACE);\n    else\n      gl.glDisable(GL.GL_CULL_FACE);\n  }\n  \n  /** Prepare the buffers used for storing vertex and normal arrays. */\n  \n  private void prepareBuffers(int requiredSize)\n  {\n    if (vertBuffer == null || vertBuffer.capacity() < requiredSize)\n    {\n      vertBuffer = BufferUtil.newFloatBuffer(requiredSize);\n      normBuffer = BufferUtil.newFloatBuffer(requiredSize);\n      gl.glVertexPointer(3, GL.GL_FLOAT, 0, vertBuffer);\n      gl.glNormalPointer(GL.GL_FLOAT, 0, normBuffer);\n    }\n  }\n  \n  /** Draw a border around the rendered image. */\n  \n  public void drawBorder()\n  {\n    prepareView2D();\n    prepareDepthTest(false);\n    prepareSolidColor(Color.black);\n    double d = -(minDepth+0.001);\n    double scale = (view.isPerspective() ? -d/minDepth : 1.0);\n    gl.glBegin(GL.GL_LINE_STRIP);\n    gl.glVertex3d(0.0f, 0.0f, d);\n    gl.glVertex3d((bounds.width-1)*scale, 0.0f, d);\n    gl.glVertex3d((bounds.width-1)*scale, (bounds.height-1)*scale, d);\n    gl.glVertex3d(0.0f, (bounds.height-1)*scale, d);\n    gl.glVertex3d(0.0f, 0.0f, d);\n    gl.glEnd();\n    if (view.getDrawFocus())\n    {\n      prepareSolidColor(ViewerCanvas.lineColor);\n      gl.glBegin(GL.GL_LINE_STRIP);\n      gl.glVertex3d(scale, scale, d);\n      gl.glVertex3d((bounds.width-2)*scale, scale, d);\n      gl.glVertex3d((bounds.width-2)*scale, (bounds.height-2)*scale, d);\n      gl.glVertex3d(scale, (bounds.height-2)*scale, d);\n      gl.glVertex3d(scale, scale, d);\n      gl.glEnd();\n    }\n  }\n\n  /** Draw a horizontal line across the rendered image.  The parameters are the y coordinate\n      of the line and the line color. */\n  \n  public void drawHRule(int y, Color color)\n  {\n    prepareView2D();\n    prepareDepthTest(false);\n    prepareSolidColor(color);\n    double d = -(minDepth+0.001);\n    double scale = (view.isPerspective() ? -d/minDepth : 1.0);\n    gl.glBegin(GL.GL_LINES);\n    gl.glVertex3d(0.0, (bounds.height-y)*scale, d);\n    gl.glVertex3d(bounds.width*scale, (bounds.height-y)*scale, d);\n    gl.glEnd();\n  }\n\n  /** Draw a vertical line across the rendered image.  The parameters are the x coordinate\n      of the line and the line color. */\n  \n  public void drawVRule(int x, Color color)\n  {\n    prepareView2D();\n    prepareDepthTest(false);\n    prepareSolidColor(color);\n    double d = -(minDepth+0.001);\n    double scale = (view.isPerspective() ? -d/minDepth : 1.0);\n    gl.glBegin(GL.GL_LINES);\n    gl.glVertex3d(x*scale, 0.0, d);\n    gl.glVertex3d(x*scale, bounds.height*scale, d);\n    gl.glEnd();\n  }\n\n  /** Draw a filled box in the rendered image. */\n  \n  public void drawBox(int x, int y, int width, int height, Color color)\n  {\n    prepareView2D();\n    prepareDepthTest(false);\n    prepareSolidColor(color);\n    float y1 = bounds.height-y;\n    double d = -(minDepth+0.001);\n    double scale = (view.isPerspective() ? -d/minDepth : 1.0);\n    gl.glBegin(GL.GL_QUADS);\n    gl.glVertex3d(x*scale, y1*scale, d);\n    gl.glVertex3d(x*scale, (y1-height)*scale, d);\n    gl.glVertex3d((x+width)*scale, (y1-height)*scale, d);\n    gl.glVertex3d((x+width)*scale, y1*scale, d);\n    gl.glEnd();\n  }\n\n  /** Draw a set of filled boxes in the rendered image. */\n\n  public void drawBoxes(java.util.List<Rectangle> box, Color color)\n  {\n    prepareView2D();\n    prepareDepthTest(false);\n    prepareSolidColor(color);\n    prepareBuffers(box.size()*12);\n    vertBuffer.clear();\n    float d = (float) -(minDepth+0.001);\n    for (Rectangle r : box)\n    {\n      float y1 = bounds.height-r.y;\n      float scale = (float) (view.isPerspective() ? -d/minDepth : 1.0);\n      vertBuffer.put(r.x*scale);\n      vertBuffer.put(y1*scale);\n      vertBuffer.put(d);\n      vertBuffer.put(r.x*scale);\n      vertBuffer.put((y1-r.height)*scale);\n      vertBuffer.put(d);\n      vertBuffer.put((r.x+r.width)*scale);\n      vertBuffer.put((y1-r.height)*scale);\n      vertBuffer.put(d);\n      vertBuffer.put((r.x+r.width)*scale);\n      vertBuffer.put(y1*scale);\n      vertBuffer.put(d);\n    }\n    gl.glDrawArrays(GL.GL_QUADS, 0, box.size()*4);\n  }\n\n  /** Render a filled box at a specified depth in the rendered image. */\n  \n  public void renderBox(int x, int y, int width, int height, double depth, Color color)\n  {\n    prepareView2D();\n    prepareDepthTest(true);\n    prepareSolidColor(color);\n    float y1 = bounds.height-y;\n    float d = (float) -depth;\n    gl.glBegin(GL.GL_QUADS);\n    float scale = (float) (view.isPerspective() ? depth/minDepth : 1.0);\n    gl.glVertex3f(x*scale, y1*scale, d);\n    gl.glVertex3f(x*scale, (y1-height)*scale, d);\n    gl.glVertex3f((x+width)*scale, (y1-height)*scale, d);\n    gl.glVertex3f((x+width)*scale, y1*scale, d);\n    gl.glEnd();\n  }\n\n  /** Render a set of filled boxes at specified depths in the rendered image. */\n\n  public void renderBoxes(java.util.List<Rectangle> box, java.util.List<Double>depth, Color color)\n  {\n    prepareView2D();\n    prepareDepthTest(true);\n    prepareSolidColor(color);\n    prepareBuffers(box.size()*12);\n    vertBuffer.clear();\n    for (int i = 0; i < box.size(); i++)\n    {\n      Rectangle r = box.get(i);\n      float y1 = bounds.height-r.y;\n      float d = -depth.get(i).floatValue();\n      float scale = (float) (view.isPerspective() ? -d/minDepth : 1.0);\n      vertBuffer.put(r.x*scale);\n      vertBuffer.put(y1*scale);\n      vertBuffer.put(d);\n      vertBuffer.put(r.x*scale);\n      vertBuffer.put((y1-r.height)*scale);\n      vertBuffer.put(d);\n      vertBuffer.put((r.x+r.width)*scale);\n      vertBuffer.put((y1-r.height)*scale);\n      vertBuffer.put(d);\n      vertBuffer.put((r.x+r.width)*scale);\n      vertBuffer.put(y1*scale);\n      vertBuffer.put(d);\n    }\n    gl.glDrawArrays(GL.GL_QUADS, 0, box.size()*4);\n  }\n\n  /** Draw a line into the rendered image. */\n  \n  public void drawLine(Point p1, Point p2, Color color)\n  {\n    prepareView2D();\n    prepareDepthTest(false);\n    prepareSolidColor(color);\n    double d = -(minDepth+0.001);\n    double scale = (view.isPerspective() ? -d/minDepth : 1.0);\n    gl.glBegin(GL.GL_LINES);\n    gl.glVertex3d(p1.x*scale, (bounds.height-p1.y)*scale, d);\n    gl.glVertex3d(p2.x*scale, (bounds.height-p2.y)*scale, d);\n    gl.glEnd();\n  }\n  \n  /** Render a line into the image.\n      @param p1     the first endpoint of the line\n      @param p2     the second endpoint of the line\n      @param cam    the camera from which to draw the line\n      @param color  the line color\n  */\n  \n  public void renderLine(Vec3 p1, Vec3 p2, Camera cam, Color color)\n  {\n    prepareView3D(cam);\n    prepareDepthTest(true);\n    prepareSolidColor(color);\n    gl.glBegin(GL.GL_LINES);\n    gl.glVertex3d(p1.x, p1.y, p1.z);\n    gl.glVertex3d(p2.x, p2.y, p2.z);\n    gl.glEnd();\n  }\n\n  /** Render a line into the image.\n      @param p1     the first endpoint of the line, in screen coordinates\n      @param zf1    the z coordinate of the first endpoint, in view coordinates\n      @param p2     the second endpoint of the line, in screen coordinates\n      @param zf2    the z coordinate of the second endpoint, in view coordinates\n      @param cam    the camera from which to draw the line\n      @param color  the line color\n  */\n  \n  public void renderLine(Vec2 p1, double zf1, Vec2 p2, double zf2, Camera cam, Color color)\n  {\n    prepareView2D();\n    prepareDepthTest(true);\n    prepareSolidColor(color);\n    gl.glBegin(GL.GL_LINES);\n    if (view.isPerspective())\n    {\n      double scale1 = zf1/minDepth;\n      double scale2 = zf2/minDepth;\n      gl.glVertex3d(p1.x*scale1, (bounds.height-p1.y)*scale1, -zf1);\n      gl.glVertex3d(p2.x*scale2, (bounds.height-p2.y)*scale2, -zf2);\n    }\n    else\n    {\n      gl.glVertex3d(p1.x, bounds.height-p1.y, -zf1);\n      gl.glVertex3d(p2.x, bounds.height-p2.y, -zf2);\n    }\n    gl.glEnd();\n  }\n  \n  /** Render a wireframe object. */\n  \n  public void renderWireframe(WireframeMesh mesh, Camera cam, Color color)\n  {\n    prepareView3D(cam);\n    prepareDepthTest(true);\n    prepareSolidColor(color);\n    prepareBuffers(mesh.vert.length*3);\n    vertBuffer.clear();\n    for (int i = 0; i < mesh.vert.length; i++)\n    {\n      Vec3 v = mesh.vert[i];\n      vertBuffer.put((float) v.x);\n      vertBuffer.put((float) v.y);\n      vertBuffer.put((float) v.z);\n    }\n    int vertexIndices[] = new int [mesh.from.length*2];\n    for (int i = 0, j = 0; i < mesh.from.length; i++)\n    {\n      vertexIndices[j++] = mesh.from[i];\n      vertexIndices[j++] = mesh.to[i];\n    }\n    gl.glDrawElements(GL.GL_LINES, vertexIndices.length, GL.GL_UNSIGNED_INT, IntBuffer.wrap(vertexIndices));\n  }\n\n  /** Render an object with flat shading in subtractive (transparent) mode. */\n  \n  public void renderMeshTransparent(RenderingMesh mesh, VertexShader shader, Camera cam, Vec3 viewDir, boolean hideFace[])\n  {\n    prepareView3D(cam);\n    prepareDepthTest(false);\n    prepareCulling(false);\n    prepareShading(false);\n    boolean invertColor = (ViewerCanvas.backgroundColor.getGreen() > 127);\n    if (invertColor)\n      gl.glBlendFunc(GL.GL_ZERO, GL.GL_ONE_MINUS_SRC_COLOR);\n    else\n      gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE);\n    gl.glEnable(GL.GL_BLEND);\n    gl.glBegin(GL.GL_TRIANGLES);\n    RGBColor faceColor = new RGBColor();\n    for (int i = 0; i < mesh.triangle.length; i++)\n    {\n      if (hideFace != null && hideFace[i])\n        continue;\n      RenderingTriangle tri = mesh.triangle[i];\n      Vec3 vert1 = mesh.vert[tri.v1];\n      Vec3 vert2 = mesh.vert[tri.v2];\n      Vec3 vert3 = mesh.vert[tri.v3];\n      double dot = (float) viewDir.dot(mesh.faceNorm[i]);\n      shader.getColor(i, 0, faceColor);\n      if (invertColor)\n        faceColor.setRGB(1.0f-faceColor.getRed(), 1.0f-faceColor.getGreen(), 1.0f-faceColor.getBlue());\n      faceColor.scale(1.0f-0.8f*Math.abs(dot));\n      gl.glColor3f(faceColor.getRed(), faceColor.getGreen(), faceColor.getBlue());\n      gl.glVertex3d(vert1.x, vert1.y, vert1.z);\n      gl.glVertex3d(vert2.x, vert2.y, vert2.z);\n      gl.glVertex3d(vert3.x, vert3.y, vert3.z);\n    }\n    gl.glEnd();\n    gl.glDisable(GL.GL_BLEND);\n  }\n  \n  /** Render a mesh to the canvas. */\n  \n  public void renderMesh(RenderingMesh mesh, VertexShader shader, Camera cam, boolean closed, boolean hideFace[])\n  {\n    prepareView3D(cam);\n    prepareDepthTest(true);\n    prepareCulling(closed && hideFace == null);\n    boolean uniform = shader.isUniformTexture();\n    if (uniform)\n    {\n      // Set up the material properties to let OpenGL shade the surface.\n      \n      prepareShading(true);\n      TextureSpec spec = new TextureSpec();\n      shader.getTextureSpec(spec);\n      gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_AMBIENT_AND_DIFFUSE, FloatBuffer.wrap(new float [] {spec.diffuse.getRed(), spec.diffuse.getGreen(), spec.diffuse.getBlue(), 1.0f}));\n      gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_SPECULAR, FloatBuffer.wrap(new float [] {spec.hilight.getRed(), spec.hilight.getGreen(), spec.hilight.getBlue(), 1.0f}));\n      gl.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_EMISSION, FloatBuffer.wrap(new float [] {spec.emissive.getRed(), spec.emissive.getGreen(), spec.emissive.getBlue(), 1.0f}));\n      gl.glMaterialf(GL.GL_FRONT_AND_BACK, GL.GL_SHININESS, (float) ((1.0-spec.roughness)*127.0+1.0));\n      \n      // Fill in buffers with the vertices and normals.\n      \n      int vertexIndices[] = null;\n      boolean flat = (shader instanceof FlatVertexShader);\n      if (hideFace == null && !flat)\n        vertexIndices = mesh.getVertexIndices();\n      if (vertexIndices != null)\n      {\n        // This is a fully smoothed mesh, so we can use glDrawElements().\n        \n        prepareBuffers(mesh.vert.length*3);\n        vertBuffer.clear();\n        normBuffer.clear();\n        for (int i = 0; i < mesh.vert.length; i++)\n        {\n          Vec3 v = mesh.vert[i];\n          vertBuffer.put((float) v.x);\n          vertBuffer.put((float) v.y);\n          vertBuffer.put((float) v.z);\n        }\n        for (int i = 0; i < mesh.norm.length; i++)\n        {\n          Vec3 v = mesh.norm[i];\n          normBuffer.put((float) v.x);\n          normBuffer.put((float) v.y);\n          normBuffer.put((float) v.z);\n        }\n        gl.glDrawElements(GL.GL_TRIANGLES, vertexIndices.length, GL.GL_UNSIGNED_INT, IntBuffer.wrap(vertexIndices));\n      }\n      else\n      {\n        // We need a separate normal for each face-vertex.\n        \n        prepareBuffers(mesh.triangle.length*9);\n        vertBuffer.clear();\n        normBuffer.clear();\n        int faceCount = 0;\n        for (int i = 0; i < mesh.triangle.length; i++)\n        {\n          if (hideFace != null && hideFace[i])\n            continue;\n          faceCount++;\n          RenderingTriangle tri = mesh.triangle[i];\n          Vec3 v = mesh.vert[tri.v1];\n          vertBuffer.put((float) v.x);\n          vertBuffer.put((float) v.y);\n          vertBuffer.put((float) v.z);\n          v = mesh.vert[tri.v2];\n          vertBuffer.put((float) v.x);\n          vertBuffer.put((float) v.y);\n          vertBuffer.put((float) v.z);\n          v = mesh.vert[tri.v3];\n          vertBuffer.put((float) v.x);\n          vertBuffer.put((float) v.y);\n          vertBuffer.put((float) v.z);\n          if (flat)\n          {\n            // Force flat shading.\n\n            v = mesh.faceNorm[i];\n            normBuffer.put((float) v.x);\n            normBuffer.put((float) v.y);\n            normBuffer.put((float) v.z);\n            normBuffer.put((float) v.x);\n            normBuffer.put((float) v.y);\n            normBuffer.put((float) v.z);\n            normBuffer.put((float) v.x);\n            normBuffer.put((float) v.y);\n            normBuffer.put((float) v.z);\n          }\n          else\n          {\n            // Set the normals from the mesh.\n\n            v = mesh.norm[tri.n1];\n            normBuffer.put((float) v.x);\n            normBuffer.put((float) v.y);\n            normBuffer.put((float) v.z);\n            v = mesh.norm[tri.n2];\n            normBuffer.put((float) v.x);\n            normBuffer.put((float) v.y);\n            normBuffer.put((float) v.z);\n            v = mesh.norm[tri.n3];\n            normBuffer.put((float) v.x);\n            normBuffer.put((float) v.y);\n            normBuffer.put((float) v.z);\n          }\n        }\n        gl.glDrawArrays(GL.GL_TRIANGLES, 0, faceCount*3);\n      }\n    }\n    else\n    {\n      // We will need to calculate the color of each face/vertex ourselves.\n      \n      prepareShading(false);\n      gl.glBegin(GL.GL_TRIANGLES);\n      RGBColor surfaceColor = new RGBColor();\n      for (int i = 0; i < mesh.triangle.length; i++)\n      {\n        if (hideFace != null && hideFace[i])\n          continue;\n        RenderingTriangle tri = mesh.triangle[i];\n        Vec3 vert1 = mesh.vert[tri.v1];\n        Vec3 vert2 = mesh.vert[tri.v2];\n        Vec3 vert3 = mesh.vert[tri.v3];\n        shader.getColor(i, 0, surfaceColor);\n        gl.glColor3f(surfaceColor.getRed(), surfaceColor.getGreen(), surfaceColor.getBlue());\n        gl.glVertex3d(vert1.x, vert1.y, vert1.z);\n        if (shader.isUniformFace(i))\n        {\n          gl.glVertex3d(vert2.x, vert2.y, vert2.z);\n          gl.glVertex3d(vert3.x, vert3.y, vert3.z);\n        }\n        else\n        {\n          shader.getColor(i, 1, surfaceColor);\n          gl.glColor3f(surfaceColor.getRed(), surfaceColor.getGreen(), surfaceColor.getBlue());\n          gl.glVertex3d(vert2.x, vert2.y, vert2.z);\n          shader.getColor(i, 2, surfaceColor);\n          gl.glColor3f(surfaceColor.getRed(), surfaceColor.getGreen(), surfaceColor.getBlue());\n          gl.glVertex3d(vert3.x, vert3.y, vert3.z);\n        }\n      }\n      gl.glEnd();\n    }\n  }\n\n  /** Draw a piece of text onto the canvas. */\n\n  public void drawString(String text, int x, int y, Color color)\n  {\n    if (color != lastTextColor)\n    {\n      textImageMap.clear();\n      lastTextColor = color;\n    }\n    Font font = view.getComponent().getFont();\n    FontMetrics fm = view.getComponent().getFontMetrics(font);\n    int ascent = fm.getMaxAscent();\n    int descent = fm.getMaxDescent();\n    SoftReference<GLImage> ref = textImageMap.get(text);\n    GLImage image = (ref == null ? null : ref.get());\n    if (image == null)\n    {\n      // Create an image of the text.\n\n      int width = fm.stringWidth(text);\n      int height = ascent+descent;\n      Image im = view.getComponent().createImage(width, height);\n      Graphics g = im.getGraphics();\n      g.setColor(ViewerCanvas.backgroundColor);\n      g.fillRect(0, 0, width, height);\n      g.setColor(color);\n      g.setFont(font);\n      g.drawString(text, 0, ascent);\n      g.dispose();\n      try\n      {\n        image = new GLImage(im);\n      }\n      catch (InterruptedException ex)\n      {\n        ex.printStackTrace();\n        return;\n      }\n      textImageMap.put(text, new SoftReference<GLImage>(image));\n    }\n    drawImage(image, x, y-ascent);\n  }\n\n  /** Draw an image onto the canvas. */\n\n  public void drawImage(Image image, int x, int y)\n  {\n    try\n    {\n      drawImage(getCachedImage(image, false), x, y);\n    }\n    catch (InterruptedException ex)\n    {\n      ex.printStackTrace();\n    }\n  }\n\n  /**\n   * Render an image onto the canvas.\n   *\n   * @param image  the image to render\n   * @param p1     the coordinates of the first corner of the image\n   * @param p2     the coordinates of the second corner of the image\n   * @param p3     the coordinates of the third corner of the image\n   * @param p4     the coordinates of the fourth corner of the image\n   * @param camera the camera from which to draw the image\n   */\n\n  public void renderImage(Image image, Vec3 p1, Vec3 p2, Vec3 p3, Vec3 p4, Camera camera)\n  {\n    GLTexture record;\n    try\n    {\n      record = getCachedTexture(image);\n    }\n    catch (InterruptedException ex)\n    {\n      ex.printStackTrace();\n      return;\n    }\n    prepareView3D(camera);\n    prepareDepthTest(true);\n    prepareCulling(false);\n    prepareShading(false);\n    double width = (useTextureRectangle ? record.width : 1.0);\n    double height = (useTextureRectangle ? record.height : 1.0);\n    gl.glEnable(imageRenderMode);\n    gl.glBindTexture(imageRenderMode, record.getTextureId());\n    gl.glBegin(GL.GL_QUADS);\n    gl.glVertex3d(p1.x, p1.y, p1.z);\n    gl.glTexCoord2d(width, 0.0);\n    gl.glVertex3d(p2.x, p2.y, p2.z);\n    gl.glTexCoord2d(width, height);\n    gl.glVertex3d(p3.x, p3.y, p3.z);\n    gl.glTexCoord2d(0.0, height);\n    gl.glVertex3d(p4.x, p4.y, p4.z);\n    gl.glTexCoord2d(0.0, 0.0);\n    gl.glEnd();\n    gl.glDisable(imageRenderMode);\n  }\n\n  public void imageChanged(Image image)\n  {\n    imageMap.remove(image);\n  }\n\n  /** Get a GLImage for an Image, attempting to reuse objects for efficiency. */\n\n  private GLImage getCachedImage(Image image, boolean texture) throws InterruptedException\n  {\n    GLImage record = null;\n    SoftReference<GLImage> ref = imageMap.get(image);\n    if (ref != null)\n      record = ref.get();\n    if (record == null)\n    {\n      Image sourceImage = image;\n      if (texture && !useTextureRectangle)\n      {\n        // Scale the image so its dimensions are powers of 2.\n\n        int width = image.getWidth(null);\n        int height = image.getHeight(null);\n        int newWidth = (int) Math.pow(2, Math.ceil(Math.log(width)/Math.log(2)));\n        int newHeight = (int) Math.pow(2, Math.ceil(Math.log(height)/Math.log(2)));\n        if (newWidth != width || newHeight != height)\n        {\n          sourceImage = image.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);\n          MediaTracker mt = new MediaTracker(canvas);\n          mt.addImage(sourceImage, 0);\n          mt.waitForID(0);\n        }\n      }\n\n      // Grab the pixels from the image and cache them.\n\n      record = new GLImage(sourceImage);\n      imageMap.put(image, new SoftReference<GLImage>(record));\n    }\n    return record;\n  }\n\n  /** Get a GLTexture for an Image, attempting to reuse objects for efficiency. */\n\n  private GLTexture getCachedTexture(Image image) throws InterruptedException\n  {\n    GLTexture record = textureMap.get(image);\n    if (record == null)\n    {\n      // Create a texture from the image and cache it.\n\n      record = new GLTexture(image);\n      textureMap.put(image, record);\n    }\n    return record;\n  }\n\n  /** Draw an image into the rendered image. */\n\n  private void drawImage(GLImage image, int x, int y)\n  {\n    prepareView2D();\n    prepareDepthTest(false);\n    gl.glEnable(GL.GL_ALPHA_TEST);\n    double d = -(minDepth+0.001);\n    gl.glRasterPos3d(x, Math.max(0, bounds.height-image.height-y), d);\n    gl.glDrawPixels(image.width, image.height, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, image.data);\n    gl.glDisable(GL.GL_ALPHA_TEST);\n  }\n\n  /** Draw the outline of a Shape into the canvas. */\n  \n  public void drawShape(Shape shape, Color color)\n  {\n    drawShape(shape, color, GL.GL_LINE_STRIP);\n  }\n\n  /** Draw a filled Shape onto the canvas. */\n\n  public void fillShape(Shape shape, Color color)\n  {\n    drawShape(shape, color, GL.GL_POLYGON);\n  }\n\n  /** This is called by both drawShape() and fillShape(). */\n\n  public void drawShape(Shape shape, Color color, int mode)\n  {\n    prepareView2D();\n    prepareDepthTest(false);\n    prepareSolidColor(color);\n    Point lastMove = null;\n    PathIterator path = shape.getPathIterator(null);\n    float coords[] = new float [6];\n    double d = -(minDepth+0.001);\n    double scale = (view.isPerspective() ? -d/minDepth : 1.0);\n    gl.glBegin(mode);\n    while (!path.isDone())\n    {\n      int type = path.currentSegment(coords);\n      if (type == PathIterator.SEG_MOVETO)\n      {\n        gl.glEnd();\n        gl.glBegin(mode);\n        lastMove = new Point((int) coords[0], (int) coords[1]);\n        gl.glVertex3d(lastMove.x*scale, (bounds.height-lastMove.y)*scale, d);\n      }\n      else if (type == PathIterator.SEG_LINETO)\n        gl.glVertex3d(coords[0]*scale, (bounds.height-coords[1])*scale, d);\n      else if (type == PathIterator.SEG_CLOSE)\n        gl.glVertex3d(lastMove.x*scale, (bounds.height-lastMove.y)*scale, d);\n      path.next();\n    }\n    gl.glEnd();\n  }\n\n  /** This inner class implements the callbacks to perform drawing with Jogl. */\n  \n  private class CanvasListener implements GLEventListener\n  {\n    public void init(GLAutoDrawable drawable)\n    {\n      GL gl = drawable.getGL();\n      gl.glShadeModel(GL.GL_SMOOTH);\n      gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, FloatBuffer.wrap(new float [] {0.0f, 0.0f, 1.0f, 0.0f}));\n      gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, FloatBuffer.wrap(new float [] {0.8f, 0.8f, 0.8f, 1.0f}));\n      gl.glEnable(GL.GL_LIGHT0);\n      gl.glLightModelfv(GL.GL_LIGHT_MODEL_AMBIENT, FloatBuffer.wrap(new float [] {0.1f, 0.1f, 0.1f, 1.0f}));\n      gl.glLightModeli(GL.GL_LIGHT_MODEL_TWO_SIDE, GL.GL_TRUE);\n      gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);\n      gl.glEnableClientState(GL.GL_VERTEX_ARRAY);\n      gl.glEnableClientState(GL.GL_NORMAL_ARRAY);\n      gl.glAlphaFunc(GL.GL_GREATER, 0.0f);\n      if (imageRenderMode == -1)\n      {\n        // Determine whether non-power-of-2 textures are supported.\n\n        if (gl.glGetString(GL.GL_EXTENSIONS).indexOf(\"GL_EXT_texture_rectangle\") > -1)\n        {\n          imageRenderMode = GL.GL_TEXTURE_RECTANGLE_ARB;\n          useTextureRectangle = true;\n        }\n        else\n        {\n          imageRenderMode = GL.GL_TEXTURE_2D;\n          useTextureRectangle = false;\n        }\n      }\n    }\n\n    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height)\n    {\n    }\n\n    public void display(GLAutoDrawable drawable)\n    {\n      view.prepareCameraForRendering();\n      gl = drawable.getGL();\n      Color background = ViewerCanvas.backgroundColor;\n      gl.glClearColor(background.getRed()/255.0f, background.getGreen()/255.0f, background.getBlue()/255.0f, 0.0f);\n      gl.glClear(GL.GL_COLOR_BUFFER_BIT+GL.GL_DEPTH_BUFFER_BIT);\n      bounds = canvas.getBounds();\n      gl.glEnable(GL.GL_DEPTH_TEST);\n      depthEnabled = true;\n      lastObjectTransform = Mat4.identity(); // ensure the view will get initialized\n      lastColor = new Color(0); // ensure the color/material will get initialized\n      double depthRange[] = view.estimateDepthRange();\n      if (view.getShowGrid() && view.isPerspective())\n      {\n        double maxGridSize = 10.0*Math.sqrt(2.0);\n        double gridCenterDist = view.getCamera().getWorldToView().times(new Vec3()).length();\n        depthRange[0] = Math.min(depthRange[0], gridCenterDist-maxGridSize);\n        depthRange[1] = Math.max(depthRange[1], gridCenterDist+maxGridSize);\n      }\n      if (view.isPerspective())\n        minDepth = view.getCamera().getDistToScreen()/20.0;\n      else\n        minDepth = Math.min(-0.01, depthRange[0]);\n      minDepth -= 0.01;\n      maxDepth = depthRange[1]+0.01;\n      if (view.getTemplateShown())\n        drawImage(template, 0, 0);\n      gl.glClear(GL.GL_DEPTH_BUFFER_BIT);\n      view.updateImage();\n      view.getCurrentTool().drawOverlay(view);\n      if (draggedShape != null)\n        drawShape(draggedShape, ViewerCanvas.lineColor);\n      draggedShape = null;\n\n      // Clean up unused textures.\n\n      Reference ref;\n      while ((ref = textureCleanupQueue.poll()) != null)\n      {\n        gl.glDeleteTextures(1, new int[] {((TextureReference) ref).textureId}, 0);\n        textureReferences.remove(ref);\n      }\n\n      // Send out a RepaintEvent so anyone who is listening will know the view has been repainted.\n\n      view.dispatchEvent(new RepaintEvent(view, null));\n    }\n\n    public void displayChanged(GLAutoDrawable drawable, boolean arg1, boolean arg2)\n    {\n    }\n  }\n\n  /** This inner class represents an image that is ready to be drawn into the GLCanvas. */\n\n  private static class GLImage\n  {\n    public ByteBuffer data;\n    public int width, height;\n\n    /** Create a GLImage from a regular Image object. */\n\n    public GLImage(Image image) throws InterruptedException\n    {\n      width = image.getWidth(null);\n      height = image.getHeight(null);\n\n      // Extract the image data and convert it to the proper format.\n\n      PixelGrabber pg = new PixelGrabber(image, 0, 0, -1, -1, true);\n      pg.grabPixels();\n      int templatePixel[] = (int []) pg.getPixels();\n      byte dataArray[] = new byte [templatePixel.length*4];\n      int pos = 0;\n      for (int row = 0; row < height; row++)\n        for (int col = 0; col < width; col++)\n        {\n          int argb = templatePixel[width*(height-row-1)+col];\n          dataArray[pos++] = (byte) (argb>>16);\n          dataArray[pos++] = (byte) (argb>>8);\n          dataArray[pos++] = (byte) (argb);\n          dataArray[pos++] = (byte) (argb>>24);\n        }\n      data = ByteBuffer.wrap(dataArray);\n    }\n  }\n\n  /** This inner class represents an image that is ready to be used as a texture in the GLCanvas. */\n\n  private class GLTexture\n  {\n    public int width, height;\n    private int textureId[];\n\n    /** Create a GLTexture from a regular Image object. */\n\n    public GLTexture(Image image) throws InterruptedException\n    {\n      GLImage glImage = getCachedImage(image, true);\n      width = glImage.width;\n      height = glImage.height;\n      textureId = new int[1];\n      gl.glGenTextures(1, textureId, 0);\n      gl.glBindTexture(imageRenderMode, textureId[0]);\n      gl.glPixelStorei(GL.GL_UNPACK_ALIGNMENT, 1);\n      gl.glTexParameteri(imageRenderMode, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP);\n      gl.glTexParameteri(imageRenderMode, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP);\n      gl.glTexParameteri(imageRenderMode, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST);\n      gl.glTexParameteri(imageRenderMode, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST);\n      gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_DECAL);\n      gl.glTexImage2D(imageRenderMode, 0, GL.GL_RGBA, width, height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, glImage.data);\n      textureReferences.add(new TextureReference(this));\n    }\n\n    public int getTextureId()\n    {\n      return textureId[0];\n    }\n  }\n\n  /** This inner class is used for cleaning up textures once they are no longer needed. */\n\n  private class TextureReference extends PhantomReference<GLTexture>\n  {\n    private int textureId;\n\n    TextureReference(GLTexture texture)\n    {\n      super(texture, textureCleanupQueue);\n      textureId = texture.getTextureId();\n    }\n  }\n}\n", "human_rating": 1.9155604000000002, "metadata": {"project": "aoi", "class": "artofillusion.view.GLCanvasDrawer", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/view/GLCanvasDrawer.java", "label_probabilities": {"readability": [0.0, 2.08e-18, 0.91556, 0.0844404], "understandability": [0.0, 0.0, 1.0, 0.0], "complexity": [1.0, 0.0, 0.0, 0.0], "modularization": [1.0, 0.0, 0.0, 0.0], "overall": [0.0, 0.0, 0.508818, 0.491182]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/artofillusion.view.TexturedVertexShader", "source": "/* Copyright (C) 2004-2012 by Peter Eastman\n\n   This program is free software; you can redistribute it and/or modify it under the\n   terms of the GNU General Public License as published by the Free Software\n   Foundation; either version 2 of the License, or (at your option) any later version.\n\n   This program is distributed in the hope that it will be useful, but WITHOUT ANY \n   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A \n   PARTICULAR PURPOSE.  See the GNU General Public License for more details. */\n\npackage artofillusion.view;\n\nimport artofillusion.*;\nimport artofillusion.math.*;\nimport artofillusion.object.*;\nimport artofillusion.texture.*;\n\nimport java.util.*;\nimport java.lang.ref.*;\n\n/** This is a VertexShader which renders a textured mesh with smooth shading. */\n\npublic class TexturedVertexShader implements VertexShader\n{\n  private TextureSpec spec;\n  private RenderingMesh mesh;\n  private Vec3 viewDir;\n  private double time, roughnessCache[];\n  private RGBColor diffuseCache[], emissiveCache[], hilightCache[];\n  private boolean cache;\n  private int textureID;\n\n  private static final WeakHashMap<RenderingMesh, SoftReference<TexturedVertexShader>> cachedShaderMap = new WeakHashMap<RenderingMesh, SoftReference<TexturedVertexShader>>();\n\n  /** Create a TexturedVertexShader for a mesh.\n      @param mesh      the mesh to render\n      @param object    the object to which the mesh corresponds\n      @param time      the current time\n      @param viewDir   the direction from which it is being viewed\n  */\n  \n  public TexturedVertexShader(RenderingMesh mesh, Object3D object, double time, Vec3 viewDir)\n  {\n    this.mesh = mesh;\n    this.time = time;\n    this.viewDir = viewDir;\n    spec = new TextureSpec();\n    textureID = mesh.mapping.getTexture().getID();\n\n    // Determine whether we can cache the color components for each vertex.\n    \n    cache = true;\n    ParameterValue value[] = object.getParameterValues();\n    for (int i = 0; i < value.length; i++)\n      if (!(value[i] instanceof ConstantParameterValue || value[i] instanceof VertexParameterValue))\n      {\n        cache = false;\n        return;\n      }\n  }\n  \n  /** In some cases, a texture can be represented by a simpler shader.  In addition, it is\n      sometimes possible to reuse shaders, thus avoiding having to repeat texture calculations.\n      This method returns a shader which produces identical results to this one, but may or may\n      not actually be the same object. */\n  \n  public VertexShader optimize()\n  {\n    if (mesh.mapping instanceof UniformMapping && !mesh.mapping.getTexture().hasComponent(Texture.HILIGHT_COLOR_COMPONENT))\n    {\n      // We can use a SmoothVertexShader instead.\n\n      mesh.mapping.getTexture().getAverageSpec(spec, time, null);\n      RGBColor color = new RGBColor(spec.diffuse.getRed()+spec.emissive.getRed()+0.5*spec.specular.getRed(), \n          spec.diffuse.getGreen()+spec.emissive.getGreen()+0.5*spec.specular.getGreen(), \n          spec.diffuse.getBlue()+spec.emissive.getBlue()+0.5*spec.specular.getBlue());\n      color.clip();\n      return new SmoothVertexShader(mesh, color, viewDir);\n    }\n    if (cache)\n    {\n      // See if we already have a cached shader for this mesh.  To ensure that we never tie up memory with this\n      // cache, the key is stored behind a weak reference and the value behind a soft reference.\n\n      SoftReference<TexturedVertexShader> ref = cachedShaderMap.get(mesh);\n      if (ref != null)\n      {\n        TexturedVertexShader shader = ref.get();\n        if (shader != null && shader.textureID == textureID)\n        {\n          shader.viewDir = viewDir;\n          return shader;\n        }\n      }\n      cachedShaderMap.put(mesh, new SoftReference<TexturedVertexShader>(this));\n    }\n    return this;\n  }\n  \n  /** Select the color for a vertex.\n      @param face     the index of the triangle being rendered\n      @param vertex   the index of the vertex to color\n      @param color    the vertex color will be returned in this object\n  */\n  \n  public void getColor(int face, int vertex, RGBColor color)\n  {\n    RenderingTriangle tri = mesh.triangle[face];\n    RGBColor diffuse, emissive, hilight;\n    double dot, roughness;\n    if (cache)\n    {\n      // Use cached texture information.\n      \n      if (diffuseCache == null)\n      {\n        diffuseCache = new RGBColor [mesh.vert.length];\n        emissiveCache = new RGBColor [mesh.vert.length];\n        hilightCache = new RGBColor [mesh.vert.length];\n        roughnessCache = new double [mesh.vert.length];\n      }\n      int vert;\n      switch (vertex)\n      {\n        case 0:\n          vert = tri.v1;\n          dot = viewDir.dot(mesh.norm[tri.n1]);\n          if (diffuseCache[vert] == null)\n          {\n            tri.getTextureSpec(spec, dot, 1.0, 0.0, 0.0, 0.1, time);\n            diffuseCache[vert] = spec.diffuse.duplicate();\n            emissiveCache[vert] = spec.emissive.duplicate();\n            hilightCache[vert] = spec.hilight.duplicate();\n            roughnessCache[vert] = spec.roughness;\n          }\n          break;\n        case 1:\n          vert = tri.v2;\n          dot = viewDir.dot(mesh.norm[tri.n2]);\n          if (diffuseCache[vert] == null)\n          {\n            tri.getTextureSpec(spec, dot, 0.0, 1.0, 0.0, 0.1, time);\n            diffuseCache[vert] = spec.diffuse.duplicate();\n            emissiveCache[vert] = spec.emissive.duplicate();\n            hilightCache[vert] = spec.hilight.duplicate();\n            roughnessCache[vert] = spec.roughness;\n          }\n          break;\n        default:\n          vert = tri.v3;\n          dot = viewDir.dot(mesh.norm[tri.n3]);\n          if (diffuseCache[vert] == null)\n          {\n            tri.getTextureSpec(spec, dot, 0.0, 0.0, 1.0, 0.1, time);\n            diffuseCache[vert] = spec.diffuse.duplicate();\n            emissiveCache[vert] = spec.emissive.duplicate();\n            hilightCache[vert] = spec.hilight.duplicate();\n            roughnessCache[vert] = spec.roughness;\n          }\n      }\n      diffuse = diffuseCache[vert];\n      emissive = emissiveCache[vert];\n      hilight = hilightCache[vert];\n      roughness = roughnessCache[vert];\n    }\n    else\n    {\n      // The texture needs to be recalculated for every face that uses a vertex.\n      \n      switch (vertex)\n      {\n        case 0:\n          dot = viewDir.dot(mesh.norm[tri.n1]);\n          tri.getTextureSpec(spec, dot, 1.0, 0.0, 0.0, 0.01, time);\n          break;\n        case 1:\n          dot = viewDir.dot(mesh.norm[tri.n2]);\n          tri.getTextureSpec(spec, dot, 0.0, 1.0, 0.0, 0.01, time);\n          break;\n        default:\n          dot = viewDir.dot(mesh.norm[tri.n3]);\n          tri.getTextureSpec(spec, dot, 0.0, 0.0, 1.0, 0.01, time);\n      }\n      diffuse = spec.diffuse;\n      emissive = spec.emissive;\n      hilight = spec.hilight;\n      roughness = spec.roughness;\n    }\n    \n    // Select the color.\n    \n    double absDot = (dot > 0.0f ? dot : -dot);\n    color.setRGB(diffuse.getRed()*absDot + emissive.getRed(),\n        diffuse.getGreen()*absDot + emissive.getGreen(),\n        diffuse.getBlue()*absDot + emissive.getBlue());\n    if (hilight.getRed()+hilight.getGreen()+hilight.getBlue() > 0.0)\n    {\n      float intensity = (float) FastMath.pow(absDot, (int) ((1.0-roughness)*128.0)+1);\n      color.add(hilight.getRed()*intensity, hilight.getGreen()*intensity, hilight.getBlue()*intensity);\n    }\n    color.clip();\n  }\n  \n  /** Get whether a particular face should be rendered with a single uniform color.\n      @param face    the index of the triangle being rendered\n  */\n  \n  public boolean isUniformFace(int face)\n  {\n    return false;\n  }\n  \n  /** Get whether this shader represents a uniform texture.  If this returns true, all\n      texture properties are uniform over the entire surface (although different parts\n      may still be colored differently due to lighting).\n   */\n  \n  public boolean isUniformTexture()\n  {\n    return (mesh.mapping instanceof UniformMapping);\n  }\n  \n  \n  /** Get the color of the surface.  This should only be called if isUniformTexture() returns true.\n      @param spec     the surface color will be returned in this object\n   */\n\n  public void getTextureSpec(TextureSpec spec)\n  {\n    mesh.mapping.getTexture().getAverageSpec(spec, time, null);\n  }\n\n  /**\n   * Clear any cached information about a RenderingMesh.\n   */\n  public static void clearCachedShaders(RenderingMesh mesh)\n  {\n    cachedShaderMap.remove(mesh);\n  }\n}\n", "human_rating": 2.056445939496012, "metadata": {"project": "aoi", "class": "artofillusion.view.TexturedVertexShader", "source_path": "aoi/sourcefiles/ArtOfIllusion/src/artofillusion/view/TexturedVertexShader.java", "label_probabilities": {"readability": [3.06711e-15, 0.0564465, 0.943553, 4.39496e-07], "understandability": [4.39941e-06, 0.00397586, 0.913184, 0.0828352], "complexity": [0.95757, 0.0424293, 2.47204e-07, 0.0], "modularization": [3.36761e-05, 0.838282, 0.161663, 2.09e-05], "overall": [5.38969e-13, 0.00247362, 0.934699, 0.0628272]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/nik777.aoi.HelpPlugin", "source": "/*  HelpPlugin.java  */\n\npackage nik777.aoi;\n\n/*\n * HelpPlugin: Help system plugin for AOI\n *\n * Copyright (C) 2006 - 2007 Nik Trevallyn-Jones, Sydney, Australia\n *\n * Author: Nik Trevallyn-Jones, nik777@users.sourceforge.net\n * $Id: Exp $\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of version 2 of the GNU General Public License as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of \n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See version 2 of the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * with this program. If not, the license, including version 2, is available\n * from the GNU project, at http://www.gnu.org.\n */\n\n/*\n *  Credits: Some code for this has been copied from the ArtOfIllusion base\n *  code written and Copyright (C) Peter Eastman.\n */\n\nimport artofillusion.*;\nimport artofillusion.ui.*;\nimport artofillusion.keystroke.*;\nimport artofillusion.util.SearchlistClassLoader;\nimport buoy.widget.*;\nimport buoy.event.*;\nimport buoyx.docking.*;\nimport java.util.*;\nimport java.util.zip.*;\nimport java.awt.*;\nimport java.awt.event.KeyEvent;\nimport java.net.*;\nimport java.io.*;\n\nimport java.lang.reflect.*;\n\nimport javax.help.*;\nimport javax.swing.*;\nimport javax.imageio.*;\n\nimport com.jstatcom.component.*;\n\n// the HelpGUI classes\nimport net.sourceforge.helpgui.gui.*;\nimport net.sourceforge.helpgui.page.*;\nimport net.sourceforge.helpgui.parser.*;\n\nimport nik777.chat.*;\n\n/**\n */\n\npublic class HelpPlugin implements Plugin\n{\n    /*\n    public static final int REGISTER\t= -1;\n    public static final int UNREGISTER\t= -2;\n\n    public static final int HELP\t= -3;\n    public static final int WHAT\t= -4;\n    public static final int HUH\t\t= -5;\n\n    public static final int CONTEXT\t= -6;\n    */\n\n    //static HashMap pending = new HashMap(1024);\n    //static HashMap registered = new HashMap(1024);\n\n    static int helplib = 0;\n    static boolean initialised=false, enabled=false;\n\n    static HelpSet global;\n    static HelpBroker broker;\n\n    static DocSet docset;\n    static String theme=null;\n\n    protected static Properties helpprefs;\n\n    //static HashMap loop = new HashMap(128);\n\n    static Writer map = null;\n\n    static BWindow aboutWin;\n\n    protected static BFrame curr;\n\n    StringBuffer buff = null;\n\n    protected static final int JAVAHELP_LIB\t= 1;\n    protected static final int HELPGUI_LIB\t= 2;\n\n    protected static final int MB = 1024*1024;\n\n    protected static final String mapHeader =\n\t\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<!DOCTYPE map PUBLIC \\\"-//Sun Microsystems Inc.//DTD JavaHelp Map Version 1.0//EN\\\" \\\"http://java.sun.com/products/javahelp/map_2_0.dtd\\\"><!-- generated by ArtOfIllusion HelpPlugin Version: 1.0, see aoisp.sourceforge.net -->\\n<map version=\\\"1.0\\\">\\n\";\n\n    protected File prefdir;\n    protected File AppDir;\n\n    protected boolean inChat = false;\n\n    /**\n     *  respond to events sent by AOI\n     */\n    public void processMessage(int message, Object args[])\n    {\n\tLayoutWindow win;\n\tint i, k, c;\n\tif (AppDir == null)\n\t    AppDir = new File(ArtOfIllusion.APP_DIRECTORY);\n\n\tswitch (message) {\n\tcase Plugin.APPLICATION_STARTING:\n\n\t    // map F3 to 'huh?' mode\n\t    String script = load(\"/huh.bsh\");\n\t    if (script != null)\n\t\tKeystrokeManager\n\t\t    .addRecord(new KeystrokeRecord(KeyEvent.VK_F3, 0,\n\t\t\t\t\t\t   \"Huh Focus (HelpPlugin)\",\n\t\t\t\t\t\t   script));\n\n\t    // map F2 to help mode\t\t\t\t\t     \n\t    script = load(\"/help.bsh\");\n\t    if (script != null)\n\t\tKeystrokeManager\n\t\t    .addRecord(new KeystrokeRecord(KeyEvent.VK_F2, 0,\n\t\t\t\t\t\t   \"Help (HelpPlugin)\",\n\t\t\t\t\t\t   script));\n\n\t    // map F1 to 'whats this?' mode\n\t    script = load(\"/what.bsh\");\n\t    if (script != null)\n\t\tKeystrokeManager\n\t\t    .addRecord(new KeystrokeRecord(KeyEvent.VK_F1, 0,\n\t\t\t\t\t\t   \"What's This? (HelpPlugin)\",\n\t\t\t\t\t\t   script));\n\n\t    // initialise this HelpPlugin object\n\t    init();\n\n\t    break;\n\n\tcase Plugin.APPLICATION_STOPPING:\n\t    if (map != null) {\n\t\ttry {\n\t\t    map.write(\"\\n</map>\");\n\t\t    map.flush();\n\t\t} catch (Exception e) {}\n\t\tfinally {\n\t\t    try {\n\t\t\tmap.close();\n\t\t    } catch (IOException e1) {}\n\t\t}\n\t    }\n\t    break;\n\n\tcase Plugin.SCENE_WINDOW_CREATED:\n\t    win = (LayoutWindow) args[0];\n\n\t    if (!initialised) {\n\t\tinitialised = true;\n\n\t\t/*\n\t\tClassLoader myldr = getClass().getClassLoader();\n\t\tif (myldr instanceof SearchlistClassLoader) {\n\t\t    URL[] srch =\n\t\t\t((SearchlistClassLoader) myldr).getSearchPath();\n\n\t\t    for (i = 0; i < srch.length; i++)\n\t\t\tSystem.out.println(\"search: \" + srch[i]);\n\t\t}\n\t\t*/\n\n\t\tLocale local = Translate.getLocale();\n\n\t\t// HACK!! make the AOI-selected locale the default\n\t\tLocale.setDefault(local);\n\n\t\tHelpSet helpset;\n\t\tPage parent;\n\t\tURL helpurl;\n\t\tSearchlistClassLoader loader = new\n\t\t    SearchlistClassLoader(this.getClass().getClassLoader());\n\t\t//    (SearchlistClassLoader) this.getClass().getClassLoader();\n\t\t    \n\t\tFile dir = new File(ArtOfIllusion.PLUGIN_DIRECTORY, \"Help\");\n\n\t\t/*\n\t\t *  NTJ: hack to get library files working for the EA\n\n\t\tString[] jars = new String[] { \"helpgui-1.1a.jar\",\n\t\t    \"jhall.jar\", \"jhelpaction.jar\", \"pircbot.jar\",\n\t            \"AOIHelp.zip\"\n\t\t};\n\n\t\tURLClassLoader myldr = null;\n\t\tMethod addURL = null;\n\t\tFile urlfile = null;\n\t\tObject[] urlarg = new Object[1];\n\t\ttry {\n\t\t    myldr = (URLClassLoader) getClass().getClassLoader();\n\t\t    Class [] sig = new Class[] { URL.class };\n\t\t    addURL = URLClassLoader.class.getDeclaredMethod(\"addURL\",\n\t\t\t\t\t\t\t\t    sig);\n\t\t    addURL.setAccessible(true);\n\t\t} catch (Exception e) {\n\t\t    System.out.println(\"failed to get addURL: \" + e);\n\t\t}\n\n\t\tfor (i = 0; i < jars.length; i++) {\n\t\t    try {\n\t\t\turlfile = new File(dir, jars[i]);\n\t\t\turlarg[0] = urlfile.toURI().toURL();\n\t\t\taddURL.invoke(myldr, urlarg);\n\t\t    } catch (Exception e) {\n\t\t\tSystem.out.println(\"failed to update classloader: \" +\n\t\t\t\t\t   e);\n\t\t    }\n\t\t}\n\t\t*/\n\n\t\ttry {\n\t\t    if (loader.getResource(\"helpset/AOIHelp.hs\") == null) {\n\n\t\t\tthrow new RuntimeException(\"cannot load global helpset\");\n\t\t    }\n\n\t\t    /*\n\t\t     *  NTJ: JavaHelp is optional.\n\t\t     *  If we fail to find it in the classpath, fall back to\n\t\t     *  HelpGUI\n\t\t     */\n\t\t    try {\n\t\t\tJHelpAction.startHelpWorker(\"helpset/AOIHelp.hs\");\n\n\t\t\tMethod getbroker =\n\t\t\t    JHelpAction.class.getDeclaredMethod(\"getHelpBroker\",\n\t\t\t\t\t\t\t    null);\n\t\t\tgetbroker.setAccessible(true);\n\n\t\t\tglobal = (HelpSet)\n\t\t\t    ((HelpBroker) getbroker.invoke(null, null)).getHelpSet();\n\t\t\thelplib = JAVAHELP_LIB;\n\t\t    } catch (Throwable e) {\n\t\t\tSystem.out.println(\"HelpPlugin: could not initialise JavaHelp\");\n\t\t    }\n\n\t\t    /*\n\t\t     *  NTJ: drive HelpSet manually\n\t\t    helpurl = HelpSet.findHelpSet(loader, \"helpset/AOIHelp\",\n\t\t\t\t\t\t  local);\n\n\t\t    global = new HelpSet(helpurl);\n\t\t    broker = global.createHelpBroker();\n\n\t\t    final HelpBroker brok = broker;\n\n\t\t    (new Thread() {\n\t\t\t    public void run()\n\t\t\t    { brok.initPresentation(); }\n\t\t\t}).start();\n\t\t    */\n\n\t\t    /*\n\t\t     *  NTJ: Using (open-source) HelpGui derivative as fallback\n\t\t     */\n\t\t    java.util.List list;\n\t\t    if (helplib == 0) {\n\t\t\ttry {\n\t\t\t    docset = new DocSet(Translate.getLocale());\n\n\t\t\t    list =\n\t\t\t\tPluginRegistry.getPlugins(DocSet.Parser.class);\n\n\t\t\t    DocSet.Parser parser;\n\t\t\t    for (i = 0; i < list.size(); i++) {\n\t\t\t\tparser = (DocSet.Parser) list.get(i);\n\t\t\t\tSystem.out.println(\"HelpPlugin.INIT: \" +\n\t\t\t\t\t\t   \"registering parser: \" +\n\t\t\t\t\t\t   parser.getClass().getName());\n\t\t\t\tDocSet.registerParser(parser);\n\t\t\t    }\n\n\t\t\t    docset.setLoader(loader);\n\t\t\t    docset.add(\"helpset/AOIHelp.hs\", null);\n\t\t\t    \n\t\t\t    helplib = HELPGUI_LIB;\n\t\t\t} catch (Throwable t) {\n\t\t\t    System.out.println(\"HelpPlugin: could not initialise HelpGUI\");\n\t\t\t}\n\t\t    }\n\n\t\t    helpset = global;\n\t\t    parent = null;\n\n\t\t    enabled = (helplib != 0);\n\n\t\t    /*\n\t\t     *  scan Plugins/Help and add any help resources found.\n\t\t     */\n\n\t\t    File files[] = dir.listFiles();\n\t\t    File subdir[], helpfile;\n\t\t    int cut, subcount;\n\n\t\t    ZipFile zf = null;\n\t\t    ZipEntry ze = null;\n\t\t    String basename;\n\t\t    ClassLoader ldr;\n\t\t    URL url[] = new URL[1];\n\n\t\t    for (i = 0; i < files.length; i++) {\n\n\t\t\t// create a subsection for each subdirectory\n\t\t\tif (files[i].isDirectory()) {\n\t\t\t    subdir = files[i].listFiles();\n\t\t\t    subcount = subdir.length;\n\n\t\t\t    if (subcount > 0) {\n\t\t\t\tif (helplib == JAVAHELP_LIB) {\n\t\t\t\t    helpset = new HelpSet(loader);\n\t\t\t\t    global.add(helpset);\n\t\t\t\t}\n\t\t\t\telse if (helplib == HELPGUI_LIB) {\n\t\t\t\t    parent = docset.addSection(files[i].getName(), null);\n\t\t\t\t}\n\t\t\t    }\n\t\t\t}\n\t\t\telse {\n\t\t\t    subdir = null;\n\t\t\t    subcount = 1;\n\t\t\t    helpset = global;\n\t\t\t    parent = null;\n\t\t\t}\n\n\t\t\tfor (k = 0; k < subcount; k++) {\n\t\t\t    helpfile = (subdir != null ? subdir[k] : files[i]);\n\n\t\t\t    try {\n\t\t\t\t// look inside all zip files\n\t\t\t\tzf = new ZipFile(helpfile);\n\n\t\t\t\t// look for a helpset entry (*.hs)\n\t\t\t\tEnumeration iter = zf.entries();\n\t\t\t\twhile (iter.hasMoreElements()) {\n\t\t\t\t    ze = (ZipEntry) iter.nextElement();\n\t\t\t\t    if (ze.isDirectory()) continue;\n\t\t\t\t    if (ze.getName().endsWith(\".hs\")) break;\n\t\t\t\t    ze = null;\n\t\t\t\t}\n\n\t\t\t\t// no helpset entry found, try next...\n\t\t\t\tif (ze == null) continue;\n\n\t\t\t\tbasename = ze.getName();\n\t\t\t\tcut = basename.lastIndexOf('.');\n\t\t\t\tif (cut > 0)\n\t\t\t\t    basename = basename.substring(0, cut);\n\n\t\t\t\t// if it's a helpset, add it to the resources\n\t\t\t\tSystem.out.println(\"HelpPlugin.ADD: \" +\n\t\t\t\t\t\t   basename);\n\n\n\t\t\t\turl[0] = helpfile.toURI().toURL();\n\t\t\t\tldr = new URLClassLoader(url);\n\t\t\t\tPluginRegistry.registerResource(\"help\",\n\t\t\t\t\t\t\t\tbasename,\n\t\t\t\t\t\t\t\tldr,\n\t\t\t\t\t\t\t\tze.getName(),\n\t\t\t\t\t\t\t\tnull);\n\n\t\t\t    } catch (Exception e) {}\n\t\t\t    finally {\n\t\t\t\tif (zf != null) {\n\t\t\t\t    zf.close();\n\t\t\t\t    zf = null;\n\t\t\t\t}\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\n\t\t    HelpSet plugset=null;\n\t\t    if (helplib == JAVAHELP_LIB) plugset = new HelpSet(loader);\n\n\t\t    // load all the registered help resources\n\t\t    list = PluginRegistry.getResources(\"help\");\n\n\t\t    System.out.println(\"resources found=\" + list.size());\n\n\t\t    if (list.size() > 0) {\n\t\t\tif (docset != null)\n\t\t\t    parent = docset.addSection(\"Plugins\", null);\n\n\t\t\tPluginRegistry.PluginResource resource;\n\t\t\tfor (i = 0; i < list.size(); i++) {\n\t\t\t    resource =\n\t\t\t\t(PluginRegistry.PluginResource) list.get(i);\n\n\t\t\t    // don't load global help a second time\n\t\t\t    if (resource.getId().equals(\"helpset/AOIHelp\"))\n\t\t\t\tcontinue;\n\n\t\t\t    System.out.println(\"Help: linking: \" +\n\t\t\t\t\t       resource.getURL().getPath());\n\n\t\t\t    loader.add(resource.getClassLoader());\n\n\t\t\t    System.out.println(\"loading: \" + resource.getId() +\n\t\t\t\t\t       \" from \" +\n\t\t\t\t\t       resource.getURL().getPath());\n\n\t\t\t    /*\n\t\t\t     * NTJ: *ugh* After all that work, something in\n\t\t\t     *   in JavaHelp is only using the loader of the\n\t\t\t     *   plugin. I suspect it is JHelpDev...\n\t\t\t     */\n\n\t\t\t    if (plugset != null)\n\t\t\t\t//plugset.add(new HelpSet(resource.getClassLoader(), resource.getURL()));\n\t\t\t\tplugset.add(new HelpSet(loader, resource.getURL()));\n\t\t\t    else {\n\t\t\t\tloader.add(resource.getClassLoader());\n\t\t\t\tdocset.add(resource.getURL().getPath(),parent);\n\t\t\t    }\n\t\t\t}\n\t\t    }\n\n\t\t    if (helpset != null) helpset.add(plugset);\n\n\t\t} catch (Exception e) {\n\t\t    System.out.println(\"HelpPlugin.INIT: \" + e);\n\t\t    e.printStackTrace(System.out);\n\t\t}\n\t    }\n\n\t    // now register the new LayoutWindow\n\t    try {\n\t\tBMenuItem item;\n\n\t\tBMenuBar mbar = win.getMenuBar();\n\t\tBMenu helpmenu = Translate.menu(\"HelpPlugin:Help\");\n\t\tmbar.add(helpmenu);\n\n\t\thelpmenu.add(item=Translate.menuItem(\"HelpPlugin:AOIHelp\",\n\t\t\t\t\t\t     this, \"show\"));\n\t\titem.setEnabled(enabled);\n\n\t\thelpmenu.add(item=Translate.menuItem(\"HelpPlugin:WhatsThis\",\n\t\t\t\t\t\t     this, \"what\"));\n\n\t\titem.setEnabled(enabled && (helplib == JAVAHELP_LIB));\n\n\t\thelpmenu.add(item=Translate.menuItem(\"HelpPlugin:LiveHelp\",\n\t\t\t\t\t\t     this, \"chat\"));\n\n\t\thelpmenu.addSeparator();\n\n\t\thelpmenu.add(item=Translate.menuItem(\"HelpPlugin:About\",\n\t\t\t\t\t\t     this, \"about\"));\n\n\t    } catch (Exception e) {\n\t\tSystem.out.println(\"HelpPlugin: error adding menu: \" + e);\n\t    } catch (Throwable t) {\n\t\tSystem.out.println(\"HelpPlugin: error adding menu: \" + t);\n\t\tt.printStackTrace(System.out);\n\t\treturn;\n\t    }\n\n\t    // register all unregistered DockableWidgets\n\t    DockingContainer dock;\n\t    DockableWidget dockable;\n\t    Component comp;\n\t    Object obj;\n\n\t    for (i = 0; i < 4; i++) {\n\t\tswitch (i) {\n\t\tcase 0: \n\t\t    dock = win.getDockingContainer(BTabbedPane.TOP);\n\t\t    break;\n\n\t\tcase 1: \n\t\t    dock = win.getDockingContainer(BTabbedPane.BOTTOM);\n\t\t    break;\n\n\t\tcase 2: \n\t\t    dock = win.getDockingContainer(BTabbedPane.LEFT);\n\t\t    break;\n\n\t\tcase 3: \n\t\t    dock = win.getDockingContainer(BTabbedPane.RIGHT);\n\t\t    break;\n\n\t\tdefault:\n\t\t    return;\n\t\t}\n\n\t\tIterator iter = dock.getChildren().iterator();\n\t\twhile (iter.hasNext()) {\n\t\t    obj = iter.next();\n\t\t    if (obj instanceof DockableWidget)\n\t\t\tdockable = (DockableWidget) obj;\n\t\t    else continue;\n\t\t    \n\t\t    comp = dockable.getComponent();\n\n\t\t    //System.out.println(\"dockable ID=\" +\n\t\t    //\t       CSH.getHelpIDString(comp));\n\n\t\t    // only if JavaHelp is being used\n\t\t    if (helplib == JAVAHELP_LIB &&\n\t\t\tCSH.getHelpIDString(comp) == null) {\n\n\t\t\tregister(comp, \"Docking.\" + dockable.getLabel(), null);\n\t\t    }\n\t\t}\n\t    }\n\n\t    // register the window\n\t    register(args[0], \"LayoutWindow\", null);\n\n\t    break;\n\n\tcase Plugin.SCENE_WINDOW_CLOSING:\n\t    // unregister window\n\t    register(args[0], null, null);\n\t    break;\n\n\t    /*\n\tcase REGISTER:\n\t    //pending.put(args[0], (String) args[1]);\n\t    register(args[0], (String) args[1], null);\n\t    break;\n\n\tcase UNREGISTER:\n\t    register(args[0], null, null);\n\t    */\n\t    /*\n\t    {\n\t\tString id = (String) args[1];\n\t\tString regid = (String) pending.get(args[0]);\n\t\tif (id.equals(regid)) {\n\t\t    pending.remove(args[0]);\n\t\t}\n\t\telse {\n\t\t    regid = (String) registered.get(args[0]);\n\t\t    if (id.equals(regid)) {\n\t\t\tregister(args[0], null, null);\n\n\t\t\tregistered.remove(args[0]);\n\t\t    }\n\t\t}\n\t    }\n\t    */\n\n\t    /*\n\t    break;\n\n\tcase HELP:\n\t    show(null);\n\t    break;\n\n\tcase HUH:\n\t    huh(null);\n\t    break;\n\n\tcase WHAT:\n\t    what(null);\n\t    break;\n\n\tcase CONTEXT:\n\t    System.out.println(\"Help.CONTEXT: \" + curr);\n\t    args[0] = curr;\n\t    break;\n\t    */\n\t}\n    }\n\n    public void init()\n    {\n\tif (prefdir == null)\n\t    prefdir = ApplicationPreferences.getPreferencesDirectory();\n\n\tFile helpflags = new File(prefdir, \"HelpPlugin.props\");\n\n\tif (helpflags.exists()) {\n\t    System.out.println(\"HelpPlugin.init: processing prefs\");\n\t    InputStream in = null;\n\t\t\n\t    try {\n\t\thelpprefs = new Properties();\n\t\tin = new FileInputStream(helpflags);\n\t\thelpprefs.load(in);\n\n\t\tString mapfile = helpprefs.getProperty(\"MapFile\");\n\t\tif (mapfile != null && mapfile.length() > 0) {\n\t\t    System.out.println(\"HelpPlugin.init: mapfile=\" +\n\t\t\t\t       mapfile);\n\n\t\t    map = new OutputStreamWriter(new FileOutputStream(mapfile), \"UTF-8\");\n\t\t    map.write(mapHeader);\n\t\t}\n\t\t\n\t\ttheme = helpprefs.getProperty(\"Theme\");\n\t\t\n\t    } catch (IOException e) {\n\t\tSystem.out.println(\"HelpPlugin: reading HelpFlags: \" + e);\n\t    }\n\t    finally {\n\t\tif (in != null) try { in.close(); } catch (IOException e){}\n\t    }\n\t}\n\n\tif (theme == null) theme = \"plastic\";\n\n\ttry {\n\t    PluginRegistry.registerResource(\"TranslateBundle\", \"HelpPlugin\",\n\t\t\t\t\t    getClass().getClassLoader(),\n\t\t\t\t\t    \"helpplugin\", null);\n\n\t} catch (Exception e) {}\n\n\t// register the best-match for the current locale\n\ttry {\n\t    Locale local = Translate.getLocale();\n\t    ClassLoader loader = getClass().getClassLoader();\n\n\t    PluginRegistry.invokeExportedMethod(\"artofillusion.SPManager.registerResource\", new Object[] { \"TranslateBundle\", \"HelpPlugin\", loader, \"helpplugin\", local});\n\n\t} catch (Exception e) {}\n    }\n\n    public BFrame getContext()\n    { return curr; }\n\n    public void show(WidgetEvent ev)\n    {\n\tif (ev != null) curr = UIUtilities.findFrame(ev.getWidget());\n\tSystem.out.println(\"Help.show: curr=\" + curr);\n\n\tif (helplib == JAVAHELP_LIB) JHelpAction.showHelp();\n\telse if (helplib == HELPGUI_LIB) {\n\t    HelpFrame helpframe = new HelpFrame(docset, theme);\n\n\t    try {\n\t\tURL url = getClass().getResource(\"/artofillusion/Icons/appIcon.png\");\n\t\tif (url != null) helpframe.setIconImage(ImageIO.read(url.openStream()));\n\t\telse System.out.println(\"HelpPlugin.show: cannot find icon\");\n\t    } catch (Exception e) {\n\t\tSystem.out.println(\"HelpPlugin.show: \" + e);\n\t    }\n\t    //UIUtilities.centerWindow(helpframe);\n\t    helpframe.setVisible(true);\n\t}\n    }\n\n    public void huh(WidgetEvent ev)\n    {\n\tif (ev != null) curr = UIUtilities.findFrame(ev.getWidget());\n\tif (helplib == JAVAHELP_LIB) JHelpAction.showHelpFromFocus();\n    }\n\n    public void what(WidgetEvent ev)\n    {\n\t//long now = System.currentTimeMillis();\n\n\t/*\n\t// perform any outstanding registrations\n\tif (pending.size() > 0) {\n\t    java.util.Map.Entry entry;\n\t    Iterator iter = pending.entrySet().iterator();\n\t    while (iter.hasNext()) {\n\t\tentry = (java.util.Map.Entry) iter.next();\n\t\tloop.clear();\n\t\tregister(entry.getKey(), (String) entry.getValue(), null);\n\t    }\n\t    \n\t    System.out.println(\"HelpPlugin.what: \" + pending.size() +\n\t\t\t       \" registrations done in \" +\n\t\t\t       ((System.currentTimeMillis() - now)/1000) +\n\t\t\t       \" secs\");\n\n\t    registered.putAll(pending);\n\t    pending.clear();\n\t}\n\t*/\n\n\tif (ev != null) curr = UIUtilities.findFrame(ev.getWidget());\n\tif (helplib == JAVAHELP_LIB) JHelpAction.trackFieldHelp();\n    }\n\n    public void chat(WidgetEvent ev)\n    {\n\tFile path = new File(AppDir, \"Plugins\");\n\tpath = new File(path, \"HelpPlugin.jar\");\n\n\ttry {\n\t    String[] cmd = new String[] {\n\t\t\"java\", \"-jar\", path.getAbsolutePath(), \"-c\", \"chat\"\n\t    };\n\n\t    Runtime.getRuntime().exec(cmd);\n\t} catch (Throwable t) {\n\t    System.out.println(\"Error invoking help: \" + t);\n\t}\n    }\n\n    public void chat()\n    {\n\t//WindowWidget parent = UIUtilities.findWindow(ev.getWidget());\n\tColor frameColour=null;\n\tFont font=null;\n\tString tmp, id=null, chan=\"#aoi\";\n\n\tSystem.out.println(\"helpprefs=\" + helpprefs);\n\n\tif (helpprefs != null) {\n\t    try {\n\t\ttmp = helpprefs.getProperty(\"chat.colour\");\n\t\tif (tmp != null) frameColour = Color.decode(tmp);\n\t    } catch (Exception e) {}\n\n\t    try {\n\t\ttmp = helpprefs.getProperty(\"chat.font\");\n\t\tif (tmp != null) font = Font.decode(tmp);\n\t    } catch (Exception e) {}\n\n\t    chan = helpprefs.getProperty(\"chat.channel\");\n\t    id = helpprefs.getProperty(\"chat.id\");\n\t}\n\tif (frameColour == null) frameColour = new Color(204, 204, 255);\n\tif (font == null) font = Font.decode(\"Arial-PLAIN-12\");\n\tif (chan == null) chan = \"#aoi\";\n\n\t// get (id) and password\n\tBTextField chanField = new BTextField(chan, 15);\n\tBTextField idField = new BTextField(id, 15);\n\tBPasswordField pwField = new BPasswordField(\"\", 15);\n\tpwField.setEchoChar('*');\n\n\tidField.requestFocus();\n\n\tWidget[] widgets = new Widget[] { chanField, idField, pwField };\n\tString[] labels = new String[] {\n\t    Translate.text(\"HelpPlugin:channel\"),\n\t    Translate.text(\"HelpPlugin:name\"),\n\t    Translate.text(\"HelpPlugin:password\")\n\t};\n\n\tinChat = false;\n\t\n\tComponentsWindow dlg = new\n\t    ComponentsWindow(Translate.text(\"HelpPlugin:login\"), widgets,\n\t\t\t     labels);\n\n\tSystem.out.println(\"window closed...\");\n\n\tif (!dlg.clickedOk()) return;\n\n\tinChat = true;\n\tSystem.out.println(\"ok, connecting to IRC...\");\n\n\tchan = chanField.getText();\n\tid = idField.getText();\n\t\n\tChatFrame chat = new ChatFrame(frameColour, font, id, chan, true);\n\tif (theme != null) chat.iconsPath = theme;\n\n\tIRCConnector irc = new IRCConnector();\n\tchat.open(irc);\n\tchat.join(chan, id, pwField.getText());\n\tchat.semaphore(this);\n\n\t//UIUtilities.centerDialog(chat);\n\tchat.setVisible(true);\n\n\t// update the prefs\n\tif (prefdir != null) {\n\t    if (helpprefs == null) helpprefs = new Properties();\n\n\t    helpprefs.setProperty(\"chat.channel\", chan);\n\t    helpprefs.setProperty(\"chat.id\", id);\n\t    helpprefs.setProperty(\"chat.font\", font.getFontName() +\n\t\t\t\t  \" \" + font.getSize());\n\n\t    try {\n\t\tFile helpprops = new File(prefdir, \"HelpPlugin.props\");\n\n\t\tOutputStream os = new FileOutputStream(helpprops);\n\t\thelpprefs.store(os, \"# (re)generated by HelpPlugin\");\n\n\t\tos.flush();\n\t\tos.close();\n\n\t    } catch (Exception e) {\n\t\tSystem.out.println(\"HelpPlugin.chat: savinf prefs: \" + e);\n\t    }\n\t}\n    }\n\n    /**\n     *  display an About window.\n     *\n     *  Base code flagrantly copied from the AOI TitleWindow, written and\n     *  Copyright (C) Peter Eastman.\n     */\n    public void about()\n    {\n\ttry {\n\t    aboutWin = new BWindow();\n\t    aboutWin.addEventLink(MouseClickedEvent.class, new Object(){\n\t\t\tvoid processEvent()\n\t\t\t{\n\t\t\t    aboutWin.setVisible(false);\n\t\t\t    aboutWin.dispose();\n\t\t\t}\n\t\t    });\n\n\t    // collect useful information\n\t    Runtime runtime = Runtime.getRuntime();\n\t    int cpus = 1;\n\t    try {\n\t\tcpus = runtime.availableProcessors();\n\t    } catch (Exception e) {}\n\n\t    String vname = ArtOfIllusion.getVersion();\n\n\t    int imageNumber = new Random(System.currentTimeMillis()).nextInt(8);\n\t    ImageIcon image = new ImageIcon(getClass().getResource(\"/artofillusion/titleImages/titleImage\"+imageNumber+\".jpg\"));\n\n\t    String text = \"<html><div align='center'>\" +\n\t\t\"Art Of Illusion v\" + vname +\n\t\t\"<br>Copyright 1999-2013 by Peter Eastman and others\"+\n\t\t\"<br>(See the README file for details.)\"+\n\t\t\"<br>This program may be freely distributed under\"+\n\t\t\"<br>the terms of the accompanying license.</div>\" +\n\t\t\"<p><div align='left'><hr>\" +\n\t\tTranslate.text(\"HelpPlugin:java\",\n\t\t\t       System.getProperty(\"java.version\"),\n\t\t\t       System.getProperty(\"java.vendor\")) +\n\t        \"<br>\" + Translate.text(\"HelpPlugin:OS\", new Object[] {\n\t\t\tSystem.getProperty(\"os.name\"),\n\t\t\tSystem.getProperty(\"os.version\"),\n\t\t\tSystem.getProperty(\"os.arch\")\n\t\t    }) +\n\t\t\"<br>\" + Translate.text(\"HelpPlugin:memory\", new Object[] {\n\t\t\tnew Long((runtime.totalMemory()\n\t\t\t\t     - runtime.freeMemory()) / MB),\n\t\t\tnew Long(runtime.totalMemory() / MB),\n\t\t\tnew Long(runtime.maxMemory() / MB),\n\t\t    }) +\n\t\t\"<br>\" + Translate.text(\"HelpPlugin:cpus\", new Integer(cpus)) +\n\t\t\"<br>\" + Translate.text(\"HelpPlugin:opengl\",\n\t\t\t\t\t(ViewerCanvas.isOpenGLAvailable()\n\t\t\t\t\t ? Translate.text(\"HelpPlugin:available\")\n\t\t\t\t\t : Translate.text(\"HelpPlugin:unavailable\")),\n\t\t\t\t\t(ArtOfIllusion.getPreferences().getUseOpenGL()\n\t\t\t\t\t ? Translate.text(\"HelpPlugin:enabled\")\n\t\t\t\t\t : Translate.text(\"HelpPlugin:disabled\"))) +\n\t\t\"</div></html>\";\n\n\t    BLabel label = new BLabel(text, image, BLabel.NORTH, BLabel.SOUTH);\n\t    label.setFont(new Font(\"Serif\", Font.PLAIN, 12));\n\t    BOutline content = BOutline.createLineBorder(new BOutline(label, BorderFactory.createEmptyBorder(0, 0, 5, 0)), Color.BLACK, 1);\n\t    Color background = Color.white;\n\t    if (imageNumber == 4)\n\t\tbackground = new Color(204, 204, 255);\n\t    else if (imageNumber == 6)\n\t\tbackground = new Color(232, 255, 232);\n\t    UIUtilities.applyBackground(content, background);\n\t    aboutWin.setContent(content);\n\t    aboutWin.pack();\n\t    Rectangle bounds = aboutWin.getBounds();\n\t    bounds.height++;\n\t    aboutWin.setBounds(bounds); // Workaround for Windows bug\n\t    UIUtilities.centerWindow(aboutWin);\n\t    aboutWin.setVisible(true);\n\n\t} catch (Exception e) {\n\t    System.out.println(\"HelpPlugin.about: \" + e);\n\t}\n    }\n\n    public static void register(Object obj, String id)\n    { register(obj, id, null); }\n\n    public static void unregister(Object obj)\n    { register(obj, null, null); }\n\n    /**\n     *  register the specified object with the Help system\n     */\n    public static void register(Object obj, String id, HelpSet helpset)\n    {\n\tSystem.out.println(id != null ? \"registering \" + id : \"unregistering\");\n\n\tif (helplib != JAVAHELP_LIB) return;\n\n\tComponent component = null;\n\n\t// register the object if it is a component itself\n\n\tif (obj instanceof Component)\n\t    component = (Component) obj;\n\telse if (obj instanceof Widget)\n\t    component = ((Widget) obj).getComponent();\n\n\tif (component != null) {\n\n\t    System.out.println(\"component= \" +\n\t\t\t       component.getClass().getName());\n\n\t    CSH.setHelpIDString(component, id);\n\n\t    if (id != null) {\n\t\tif (global == null) System.out.println(\"global is null\");\n\n\t\tif (helpset != null) CSH.setHelpSet(component, helpset);\n\t\telse if (global != null) CSH.setHelpSet(component, global);\n\n\t\tSystem.out.println(\"Mapped ID=\" +\n\t\t\t\t   CSH.getHelpIDString(component));\n\n\t\tif (map != null) {\n\t\t    try {\n\t\t\tmap.write(\"\\n<mapID target=\\\"\");\n\t\t\tmap.write(id);\n\t\t\tmap.write(\"\\\" url=\\\"\\\" />\");\n\t\t    } catch (IOException e) {\n\t\t\tSystem.out.println(\"HelpPlugin.register writing map: \"+\n\t\t\t\t\t   e);\n\t\t    }\n\t\t}\n\t    }\n\t}\n\n\t/*\n\t *  NTJ - no need to recurse, let Help system do it at runtime\n\t *\n\t// now register any fields that are components\n\tField field[] = obj.getClass().getDeclaredFields();\n\tField fld;\n\tClass type;\n\tObject child;\n\n\tfor (int i = 0; i < field.length; i++) {\n\t    fld = field[i];\n\n\t    if (Modifier.isStatic(fld.getModifiers())\n\t\t|| fld.getName().indexOf('$') >= 0)\n\t\tcontinue;\n\n\t    try {\n\t\ttype = fld.getType();\n\n\t\tif (Widget.class.isAssignableFrom(type)\n\t\t    || Component.class.isAssignableFrom(type)) {\n\n\t\t    fld.setAccessible(true);\n\t\t    child = fld.get(obj);\n\n\t\t    if (child != null && child != obj\n\t\t\t&& !loop.containsKey(child)) {\n\t\t\t\n\t\t\tSystem.out.println(\"Help.register: child=\" +\n\t\t\t\t\t   fld.getName());\n\n\t\t\tloop.put(child, obj);\n\n\t\t\tregister(child, id + \".\" + fld.getName(), helpset);\n\t\t    }\n\t\t}\n\t    } catch (Exception e) {\n\t\tSystem.out.println(\"HelpPlugin.register (\" + id + \"): \" + e);\n\t    }\n\t}\n\t*/\n    }\n\n    /**\n     *  create a map of IDs\n     */\n    public static void makeMap_dont_use(String id, Object obj, Writer map)\n    {\n\tField field[] = null;\n\tField fld;\n\tObject child;\n\tWidget widget = null;\n\tComponent component = null;\n\n\tint i;\n\n\t// find the top-level container\n\tif (obj instanceof Widget) {\n\t    widget = (Widget) obj;\n\t    Widget parent = widget.getParent();\n\n\t    try {\n\t\twhile (parent != null) {\n\t\t    System.out.println(\"Help.makeMap: parent=\" +\n\t\t\t\t       parent.getClass().getName());\n\n\t\t    System.out.println(\"pop\");\n\t\t    widget = parent;\n\t\t    parent = widget.getParent();\n\n\t\t    /*\n\t\t    field = parent.getClass().getDeclaredFields();\n\n\t\t    for (i = 0; i < field.length; i++) {\n\t\t\tfld = field[i];\n\n\t\t\tfld.setAccessible(true);\n\t\t\tif (fld.get(parent) == widget) {\n\t\t\t    System.out.println(\"Help.makeMap: popping...\");\n\t\t\t    widget = parent;\n\t\t\t    parent = widget.getParent();\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\t\t    \n\t\t    // we fell through so this is our top-most level\n\t\t    if (i >= field.length) break;\n\t\t    */\n\t\t}\n\n\t    } catch (Exception e) {\n\t\tSystem.out.println(\"HelpPlugin.makeMap: finding top: \" +e);\n\t    }\n\n\t    obj = widget;\n\t}\n\n\telse if (obj instanceof Component) {\n\t    component = (Component) obj;\n\t    Component parent = component.getParent();\n\n\t    try {\n\t\twhile (parent != null) {\n\t\t    field = parent.getClass().getDeclaredFields();\n\n\t\t    System.out.println(\"Help.makeMap: parent=\" +\n\t\t\t\t       parent.getClass().getName());\n\n\t\t    System.out.println(\"pop\");\n\t\t    component = parent;\n\t\t    parent = component.getParent();\n\n\t\t    for (i = 0; i < field.length; i++) {\n\t\t\tfld = field[i];\n\n\t\t\tfld.setAccessible(true);\n\t\t\tif (fld.get(parent) == component) {\n\t\t\t    System.out.println(\"Help.makeMap: found top\");\n\t\t\t    parent = null;\n\t\t\t    break;\n\t\t\t}\n\t\t    }\n\n\t\t    // we fell through so pop a level\n\t\t    if (i >= field.length) {\n\t\t\tSystem.out.println(\"pop...\");\n\t\t\tcomponent = parent;\n\t\t\tparent = component.getParent();\n\t\t    }\n\t\t}\n\t    } catch (Exception e) {\n\t\tSystem.out.println(\"HelpPlugin.makeMap: finding top: \" +e);\n\t    }\n\n\t    obj = component;\n\t}\n\n\tSystem.out.println(\"HelpPlugin.makeMap: top level is a \" +\n\t\t\t   obj.getClass().getName());\n\n\ttry {\n\t    // map the object if it is a component itself\n\t    if (widget != null || component != null) {\n\t\tmap.write(\"\\n<mapID target='\");\n\t\tmap.write(id);\n\t\tmap.write(\"' url='' />\");\n\t    }\n\n\t    // now map any fields that are components\n\t    field = obj.getClass().getDeclaredFields();\n\t    Class type;\n\t    String name;\n\n\t    for (i = 0; i < field.length; i++) {\n\t\tfld = field[i];\n\n\t\tname = fld.getName();\n\t\tSystem.out.println(\"Help.makeMap: field=\" + name);\n\n\t\tif (Modifier.isStatic(fld.getModifiers())\n\t\t    || name.length() == 0 || name.indexOf('$') >= 0)\n\t\t    continue;\n\n\t\ttry {\n\t\t    type = fld.getType();\n\n\t\t    if (Widget.class.isAssignableFrom(type)\n\t\t\t|| Component.class.isAssignableFrom(type)) {\n\n\t\t\tfld.setAccessible(true);\n\t\t\t\n\t\t\tchild = fld.get(obj);\n\n\t\t\tif (child != null && child != obj)\n\t\t\t    makeMap_dont_use(id + \".\" + name, child, map);\n\t\t    }\n\t\t} catch (Exception e) {\n\t\t    System.out.println(\"HelpPlugin.makeMap (\" + id + \"): \" +e);\n\t\t}\n\t    }\n\n\t} catch (IOException e) {\n\t    System.out.println(\"HelpPlugin.makeMap: \" + e);\n\t}\n    }\n\n    protected String load(String path)\n    {\n\tif (buff == null) buff = new StringBuffer(512);\n\telse buff.setLength(0);\n\n\tInputStream is = null;\n\n\ttry {\n\t    is = getClass().getResourceAsStream(path);\n\t    if (is == null) return null;\n\n\t    InputStreamReader in = new InputStreamReader(is, \"UTF-8\");\n\n\t    int c;\n\t    while ((c = in.read()) != -1) buff.append((char) c);\n\n\t} catch (IOException e) {\n\t    System.out.println(\"HelpPlugin: unable to load resource: \" + e);\n\t} finally {\n\t    try { is.close(); } catch (Exception e1) {}\n\t}\n\n\treturn (buff.length() > 0 ? buff.toString() : null);\n    }\n\n    /**\n     *  main, so Help can be run standalone.\n     */\n    public static void main(String[] argv)\n    {\n\tchar slash = File.separatorChar;\n\n\tString AppDir = System.getProperty(\"user.dir\");\n\ttry {\n\t    URL url = HelpPlugin.class\n\t\t.getResource(\"/nik777/aoi/HelpPlugin.class\");\n\n\t    System.out.println(\"HelpPlugin.main: url=\" + url);\n\n\t    System.out.println(\"HelpPlugin.main: path=\" + url.getPath());\n\n\t    String furl = url.getPath();\n\t    if (furl.indexOf('!') < 0) furl = url.toString();\n\n\t    int cut = furl.indexOf('!');\n\n\t    if (cut > 0) {\n\n\t\tfurl = furl.substring(0, cut);\n\n\t\tcut = furl.indexOf(\"jar:\");\n\t\tif (cut >= 0)\n\t\t    furl = furl.substring(cut+\"jar:\".length());\n\n\t\tif (!furl.startsWith(\"file:\")) furl = \"file:\" + furl;\n\n\t\tSystem.out.println(\"HelpPlugin.main: furl=\" + furl);\n\n\t\tFile dir = new File(new URL(furl).getPath()).getParentFile()\n\t\t    .getParentFile();\n\n\t\tSystem.out.println(\"HelpPlugin.main: dir=\" +\n\t\t\t\t   dir.getAbsolutePath());\n\n\t\tif (dir.exists())\n\t\t    AppDir = dir.getAbsolutePath();\n\t\telse\n\t\t    AppDir = System.getProperty(\"user.dir\");\n\n\t\tSystem.out.println(\"HelpPlugin.main: app_dir=\" + AppDir);\n\t    }\n\t}\n\tcatch (Exception ex) {\n\t    System.out.println(\"Error looking up app_dir: \" + ex);\n\t}\n\n\tHelpPlugin help = new HelpPlugin();\n\thelp.AppDir = new File(AppDir);\n\thelp.init();\n\n\tString cmd = null;\n\tfor (int i = 0; i < argv.length; i++) {\n\t    if (argv[i].equalsIgnoreCase(\"-c\")) {\n\t\tif (i < argv.length-1) cmd = argv[i+1];\n\n\t\tbreak;\n\t    }\n\t}\n\n\tif (cmd.equalsIgnoreCase(\"chat\")) help.chat();\n\telse if (cmd.equalsIgnoreCase(\"show\"));\n\n\tif (help.inChat) {\n\t    synchronized (help) {\n\t\ttry {\n\t\t    help.wait();\n\t\t} catch (Exception e) {}\n\t    }\n\t}\n\n\tSystem.exit(0);\n    }\n}\n", "human_rating": 1.813575694, "metadata": {"project": "aoi", "class": "nik777.aoi.HelpPlugin", "source_path": "aoi/sourcefiles/HelpPlugin/src/HelpPlugin.java", "label_probabilities": {"readability": [0.0, 0.000410898, 0.812754, 0.186835], "understandability": [4.55247e-11, 7.26479e-06, 1.4386e-06, 0.999991], "complexity": [0.625967, 0.374033, 0.0, 0.0], "modularization": [1.0, 0.0, 0.0, 0.0], "overall": [0.0, 0.0, 2.77468e-08, 1.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/nik777.chat.ChatTextPane", "source": "/*  ChatTextPane.java  */\n\npackage nik777.chat;\n\n/*\n * ChatTextPane: text area widget to display chat history in\n *\n * Copyright (C) 2006 Nik Trevallyn-Jones, Sydney, Australia\n *\n * Author: Nik Trevallyn-Jones, nik777@users.sourceforge.net\n * $Id: Exp $\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of version 2 of the GNU General Public License as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of \n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See version 2 of the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * with this program. If not, the license, including version 2, is available\n * from the GNU project, at http://www.gnu.org.\n */\n\n/*\n *  This is a derivative work. The GUI design and base logic is based on\n *  org.jabber.applet.awt.ChatTextArea, portions of which are copyrighted by \n *  the Jabber foundation as per the included notice below:\n *\n * Portions created by or assigned to Jabber.com, Inc. are\n * Copyright (c) 1999-2000 Jabber.com, Inc.  All Rights Reserved.  Contact\n * information for Jabber.com, Inc. is available at http://www.jabber.com/.\n * \n */\n\nimport java.awt.*;\nimport java.util.*;\nimport java.awt.event.*;\n\nimport javax.swing.SwingUtilities;\nimport javax.swing.JTextPane;\nimport javax.swing.JEditorPane;\nimport javax.swing.JScrollPane;\nimport javax.swing.JScrollBar;\n\nimport javax.swing.event.ChangeListener;\nimport javax.swing.event.ChangeEvent;\n\nimport java.io.StringReader;\nimport java.io.Reader;\nimport java.io.IOException;\n\nimport nik777.xlate.StringEditor;\n\n/**\n * MULTIPLE COLOR CHAT TEXT AREA\n *\n * This AWT TextArea like multi-color control is designed to be used as a Chat Window\n * that automatically aligns chat messages in a different column from the user name.  This\n * control allows you to to use a different color for the users name and message.\n *\n * This control can also act TextArea with different color fonts for each line as \n * well as a as a normal TextArea.\n *\n * @author\tJonathan Paulson\n * @version \t$ 1.1.2 $\n */\n \npublic class ChatTextPane extends JTextPane\n\timplements ChangeListener, MouseWheelListener\n{\n    private final static int        NAME\t\t\t\t=  0;\n    private final static int        NAMECOLOR\t\t\t=  1;\n    private final static int        MSG\t\t\t\t\t=  2;\n    private final static int        MSGCOLOR\t\t\t=  3;\n\n\t/*\n\t *  NTJ - disable auto-images until image display sidget is complete\n\t */\n\n\t// define the editing rules for incoming text, before display\n\tprotected static final String urlEdit = \n\t    \"gs/</&lt;/gs/>/&gt;/\" +\n\t    /*\"gs;(^| )(http://.*?\\\\.(jpg|png|gif))( |$);$1<img src=\\\"$2\\\"/>$4;\" +*/\n\t    \"gs;(^| )(http://.*?)( |$);$1<a href=\\\"$2\\\">$2</a>$3;\" /* +\n\t\t\"gs;(^| )image://(.*?)( |$);$1<img src=\\\"http://$2\\\"/>$3;\" */;\n\n    private int\t\t\t\t\t\tmiRows;\t\t\t\t\t\t// number of rows in the text area\n    private int\t\t\t\t\t\tmiColumns;\t\t\t\t\t// number of rows in the text area\n\tprivate int\t\t\t\t\t\tmiNbrLinesPerPage;\t\t\t// how many lines of text can be seen on the control\n\tprivate int\t\t\t\t\t\tmiWidth, miHeight;\t\t\t// size, minus the scrollbar\n\tprivate int\t\t\t\t\t\tmiNameColWidth;\t\t\t\t// the width to use for the Name Column\n\tprivate int\t\t\t\t\t\tmiTopLine\t\t\t= 0;\t// what the index of the top line of text is\n\tprivate int\t\t\t\t\t\tmiFontHeight;\t\t\t\t// font height\n\tprivate boolean\t\t\t\t\tmbReformatLines\t\t= true;\t// If True, vector of lines will be reformatted\n\tprivate boolean\t\t\t\t\tmbHangingIndent\t\t= true;\t// If True, Chat messages will wrap with hanging indent\n\tprivate Image\t\t\t\t\tmImage;\t\t\t\t\t\t// backing image\n\tprivate Graphics\t\t\t\tmGraphics;\t\t\t\t\t// backing graphics\n\tprivate Font\t\t\t\t\tmFont;\n\tprivate FontMetrics\t\t\t\tmFontMetrics;\t\t\t\t// drawing font size\n\tprivate Scrollbar\t\t\t\tmScrollbar;\t\t\t\t\t// scrollbar at the right side\n\tprivate Vector\t\t\t\t\tmvLines;\t\t\t\t\t// Unformatted lines as they were received\n\tprivate Vector\t\t\t\t\tmvFormatedLines;\t\t\t// Viewable lines (word wrapped where necessary)\n\n\t// stringbuffer for formatting\n\tprotected StringBuffer\t\tfmtBuffer;\n\n\t// text pane\n\tprotected JTextPane textPanel;\n\n\t// containing JScrollPane\n\tprotected JScrollBar scroll = null;\n\tprotected boolean scrollSet = false;\n\n\t// for content editing\n\tprotected StringEditor editor;\n\n\tprotected boolean wheelScrolling = false;\n\tprotected boolean isAtBottom = true;\n\n    /**\n     * Constructs a new Color text area.\n     */\n    public ChatTextPane() {\n\t\tthis(\"\", 0, 0, false);\n    }\n    \n    /**\n     * Constructs a new Color text area with the specified text.\n     *\n     * @param     text the text to be displayed. \n     */\n    public ChatTextPane(String text) {\n\t\tthis(text, 0, 0, false);\n    }\n    \t\t\n    /**\n     * Constructs a new Color text area. \n     * This text area is created a vertical scroll bar.\n     *\n     * @param rows\t\t\t\tthe number of rows\n     * @param columns\t\t\tthe number of columns \n\t * @param hangingIndent\t\ttrue if you want the chat messages to having a hanging indent\n     */\n    public ChatTextPane(int rows, int cols, boolean hangingIndent)\t{\n\t\tthis(\"\", rows, cols, hangingIndent);\n\t}\n    \t\n    /**\n     * Constructs a new text area with the specified text,\n     * and with the specified number of rows and columns.\n     * This text area is created with both vertical and\n     * horizontal scroll bars.\n     * @param     text\t\t\tthe text to be displayed.\n     * @param     rows\t\t\tthe number of rows.\n     * @param     columns\t\tthe number of columns.\n\t * @param hangingIndent\t\ttrue if you want the chat messages to having a hanging indent\n     */\t\n    public ChatTextPane(String Text, int rows, int cols, boolean hangingIndent)\n\t{\n\t\tmiRows = rows;\n\t\tmiColumns = cols;\n\t\tmbHangingIndent = hangingIndent;\n\n\t\teditor = new StringEditor(urlEdit);\n\n\t\t//setLayout(new BorderLayout());\n\t\tsetEditable(false);\n\t\tsetContentType(\"text/html\");\n\n\t\t//add(textPanel);\n\t\t//validate();\n\n\t\t//Default Font\n\t\tmFont = new Font(\"Dialog\", Font.PLAIN, 12);\n\n\t\t//setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);\n\t\t\n\t\tmScrollbar = new Scrollbar(Scrollbar.VERTICAL, 0, 1, 0, 0);\n\n\t\t/*\n\t\tadd(\"East\",mScrollbar);\n\t\tmScrollbar.setValues(0, 1, 0, 100);\n\t\tmScrollbar.setUnitIncrement(10); \n\t\tmScrollbar.setUnitIncrement(30); \n\t\t*/\n\n\t\tmvLines = new Vector();\n\t\tmvFormatedLines = new Vector();\n\t\tfmtBuffer = new StringBuffer(4096);\n\n\t\t//repaint();\n\n\t\t//Catch scroll events\n\t\t/*\n\t\tmScrollbar.addAdjustmentListener(\n\t\t\tnew AdjustmentListener() { \n\t\t\t\tpublic void adjustmentValueChanged(AdjustmentEvent e) { \n\t\t\t\t\tcomputeScrollbar(false);\n\t\t\t\t\trepaint(); \t\t\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t\t*/\n\n\t\tif (Text.length() > 0)\n\t\t\tappend(Text);\n\t}\t\n    \n    /**\n\t * Appends the given text to the text area's current text (using black)\n\t * \n\t * @param str\t\tthe text to append. \n\t */\t\n\tpublic void append(String str){\n\t\t//Append plan black text\n\t\tappendChatText(str, \"000000\", \"\", \"\");\n\t}\n\n    /**\n\t * Appends the given text to the text area's current text using the color specified\n\t * \n\t * @param str\t\tthe text to append. \n\t * @param RGB\t\tthe RGB color in HEX format (example \"00FF77\")\n\t */\t\t\n\tpublic void append(String str, String RGB){\n\t\t//Append colored text\n\t\tappendChatText(str, RGB, \"\", \"\");\n\t}\n\n    /**\n\t * Appends the given chat message to the text area's current text with the message in\n\t * its own column using the color specified\n\t * \n\t * @param name\t\tthe person who said the message \n\t * @param msg\t\twhat the person said \n\t * @param RGB\t\tthe RGB color in HEX format (example \"00FF77\")\n\t *\t\t\t\t\tto use for the name and msg\n\t */\t\t\n\tpublic void appendChatText(String name, String msg, String RGB){\n\t\t//Append colored text\n\t\tappendChatText(name, RGB, msg, RGB);\n\t}\n\n\t\t\n    /**\n\t * Appends the given chat message to the text area's current text with the message in\n\t * its own column using the colors specified\n\t * \n\t * @param name\t\tthe person who said the message \n\t * @param nameRGB\tthe RGB color in HEX format (example \"00FF77\") to use for name\n\t * @param msg\t\twhat the person said \n\t * @param msgRGB\tthe RGB color in HEX format (example \"00FF77\") to use for msg\n\t */\t\n\tpublic void appendChatText(String name, String nameRGB, String msg, String msgRGB){\n\t\tString line[] = new String[4];\n\n\t\tline[NAME] = name;\n\t\tline[NAMECOLOR] = nameRGB;\n\t\tline[MSG] = msg;\n\t\tline[MSGCOLOR] = msgRGB;\n\t\t\n\t\tmvLines.addElement(line);\n\n\t\tRectangle rect = getBounds();\n\n\t\tif (rect.width > 0){\n\t\t\t//Wrap the element just added\n\t\t\t//wordWrap(mvLines.size() - 1);\n\n\t\t\t//New text, so adjust scrollbar\n\t\t\t//computeScrollbar(true);\n\t\t\t//repaint();\n\t\t\trender();\n\t\t}\n\t}\n\n    /**\n     * Gets the text that is presented by this text component. \n     */\t\t\n\tpublic String getText()\t{\n\t\tStringBuffer sBuffer = new StringBuffer(1024);\n\t\tString[] saNextLine;\n\t\tfor (int i = 0; i<mvLines.size(); i++) {\n\t\t\tsaNextLine = (String[])mvLines.elementAt(i);\n\t\t\tsBuffer.append(saNextLine[NAME])\n\t\t\t\t.append(\" \").append(saNextLine[MSG]).append(\"\\n\");\n\t\t}\n\t\treturn sBuffer.toString();\n    }\n    \n    /**\n     * Clear the contents of the text area\n     */\t\t\n\tpublic void clearText()\t{\n\t\tmvLines.removeAllElements();\n\t\tmvFormatedLines.removeAllElements();\n\t\t//repaint();\n    }\n\n\t/**\n\t * Paints this component. This method is called when the contents of the component should be painted \n\t * in response to the component first being shown or damage needing repair. The clip rectangle in the \n\t * Graphics parameter will be set to the area which needs to be painted. \n\t * \n\t * @param g\t\t\tThe graphics context to use for painting.\n\t */\n\t/*\n\tpublic void paint(Graphics g) {\n\t\tsuper.paint(g);\n\n\t\tif (mImage == null) {\n\t\n\t\t\tmImage = createImage(miWidth, miHeight);\n\t\t\tmGraphics = mImage.getGraphics();\n\t\t\tmGraphics.setFont(mFont);\n\t\t\tmFontMetrics = mGraphics.getFontMetrics();\n\t\t\tmiFontHeight = mFontMetrics.getHeight();\n\t\t\tmiNbrLinesPerPage = miHeight / miFontHeight;\n            //g.draw3DRect(2,4,this.getBounds().width-4,this.getBounds().height-8, false);\n\t\t\trender();\n\n\t\t}\n\n\t\t//g.drawImage(mImage, 0, 0, this);\n\t}\n\t*/\n\n\t/**\n\t * The AWT calls the update method in response to a call to repaint.\n\t */\t\n\t/*\n\tpublic void update() {\n\t\tupdate(this.getGraphics());\n\t}\n\t*/\n\t/**\n\t * The AWT calls the update method in response to a call to repaint. The appearance of the \n\t * component on the screen has not changed since the last call to update or paint. You can \n\t * assume that the background is not cleared. \n\t * \n\t * @param g\t\t\tthe specified context to use for updating.\n\t */\n\t/*\n\tpublic void update(Graphics g) {\n\t\tif (mFontMetrics != null) {\n\t\t\trender();\n\t\t\t//paint(g);\n\t\t}\n\t}\n\t*/\n\n    /**\n     * Returns the number of rows in the text area.\n     *\n     * @return\t\tthe number of columns in this text area. \n     */\n\t/*\n    public int getRows() {\n\t\treturn miRows;\n    }\n\t*/\n    /**\n     * Returns the number of columns in the text area.\n     *\n     * @return\t\tthe number of columns in this text area. \n     */\n\t/*\n    public int getColumns() {\n\t\treturn miColumns;\n    }\n\t*/\n\n\t/**\n\t * Determines the preferred size of a text area with the specified number of rows and columns. \n\t * \n     * @param rows\t\tthe number of rows\n     * @param columns\tthe number of columns \n     * @return\t\t\tthe preferred dimensions required to display the text area with \n     *\t\t\t\t\tthe specified number of rows and columns. \n\t */\n\t/*\n    public Dimension getPreferredSize(int rows, int cols) {\n\t\treturn super.getPreferredSize();\n    }\n\t*/\n\t/**\n\t * Determines the preferred size of this text area.  \n\t * \n     * @return\t\t\tthe preferred dimensions needed for this text area\n\t */\n\t/*\n    public Dimension getPreferredSize()\t{\n\t\treturn ((miRows > 0) && (miColumns > 0)) ? getPreferredSize(miRows, miColumns) : super.getPreferredSize();\n    }\n\t*/\n\n    /**\n     * Returns the specified minimum size Dimensions of the text area.\n     *\n     * @param rows\t\tthe minimum row size\n     * @param cols\t\tthe minimum column size\n     *\n\t * @return\t\t\tA dimension object indicating this component's minimum size. \n     */\n\t/*\n    public Dimension getMinimumSize(int rows, int cols)\t{\n\t\treturn super.getMinimumSize();\n    }\n\t*/\n\n    /**\n     * Returns the minimum size Dimensions of the text area.\n     *\n\t * @return\t\t\tA dimension object indicating this component's minimum size.      \n     */\n\t/*\n    public Dimension getMinimumSize(){\n\t\treturn super.getMinimumSize();\n    }\n\t*/\n\n\t/**\n\t * Moves and resizes this component. The new location of the top-left corner is specified by x and y, \n\t * and the new size is specified by width and height. (fired when resized)\n\t * \n\t * @param x\t\t\tThe new x-coordinate of this component.\n\t * @param y\t\t\tThe new y-coordinate of this component.\n\t * @param w\t\t\tThe new width of this component. \n\t * @param h\t\t\tThe new height of this component. \n\t */\n\t/*\n\tpublic void setBounds(int x, int y, int w, int h){\n\t\tif (w != miWidth || h != miHeight) {  \n\t\t\tmiWidth = w; \n\t\t\tmiHeight = h; \n\n\t\t\t//Recalculate the size of name column\n\t\t\tsetNameColumnWidth(miColSize, mbColSizeIsPercent);\n\n\t\t\t// Force creation of a new backing image and re-painting\n\t\t\tmImage = null;\n\t\t\tmbReformatLines = true;\n\t\t\trepaint();\n\t\t}\n\t\tsuper.setBounds(x, y, w, h);\n\t}\n\t*/\n\n    /**\n\t * Sets the font of this component. \n\t * \n\t * @param str\t\tThe font to become this component's font. \n\t */\t\t\n\tpublic void setFont(Font font){\n\t\tmFont = font;\n\t\trepaint();\n\t}\n\n    /**\n\t * Sets the text that is presented by this text component to be the specified text. (using black)\n\t * \n\t * @param str\t\tnew text for this component. \n\t */\t\n\tpublic synchronized void setText(String str){\n\t\tsetText(str, \"000000\");\n\t}\n\n    /**\n\t * Sets the text that is presented by this text component to be the specified text. \n\t * using the specified color.\n\t * \n\t * @param str\t\tnew text for this component. \n\t * @param RGB\t\tthe RGB color in HEX format (example \"00FF77\")\t \n\t */\t\t\n\tpublic synchronized void setText(String str, String RGB){\n\t\tclearText();\n\t\tif (str.length() > 0)\n\t\t\tappend(str, RGB);\n\t}\n\t\n\t\n    /**\n\t * Sets the width for the first column generally used for the name\n\t * \n\t * @param width\t\t\tWidth or Width Percent depending on value of isPercent\n\t * @param isPercent\t\tIf true, then width indicates a percent of the total (1-95)\n\t */\t\t\n\tprivate int\t\t\tmiColSize\t\t\t= 20;\t// width last time setNameColumnWidth called \n\tprivate boolean\t\tmbColSizeIsPercent\t= true;\t// isPercent last time setNameColumnWidth called \n\tpublic synchronized void setNameColumnWidth(int width, boolean isPercent){\n\t\tmiColSize = width;\n\t\tmbColSizeIsPercent = isPercent;\n\t\t\n\t\tif (isPercent){\n\t\t\tif (width < 0 || width > 95){\n\t\t\t\twidth = 20;\n\t\t\t}\n\t\t\n\t\t\t//Make the number a percent\n\t\t\tdouble dNameColWidthPercent = width * .01;\n\t\t\t\n\t\t\t//Now set exact width\n\t\t\tmiNameColWidth = (int)(miWidth * dNameColWidthPercent);\n\t\t}\n\t\telse{\n\t\t\tif (width < 0 || width > miWidth){\n\t\t\t\t//Must be positive value, set to 1/3 width\n\t\t\t\twidth = (int) miWidth / 3;\n\t\t\t}\n\t\t\tmiNameColWidth = width;\n\t\t}\n\t}\n\t\t\t\n    /**\n\t * Automatically wrap the text that is too long to display on one line\n\t * \n\t * @param lineIndex\t\tthe vector index of the line to wrap \n\t */\t\t\t\n\tprivate void wordWrap(int lineIndex) {\n\t\tString[] saNewLine = (String[])mvLines.elementAt(lineIndex);\n\n\t\tboolean bChatMsg = saNewLine[MSG].length() > 0;\t\t\n\n\t\ttry\t{\n\t\t\t//If this is a chat msg then the username is stored in [NAME] and the msg is stored in {MSG]\n\t\t\t//otherwise the contents are stored in [NAME] and [MSG] is left blank\n\t\t\tStringTokenizer\t\ttokenizer;\n\t\t\tStringBuffer\t\tbuffer;\n\t\t\tString\t\t\t\tsNextWord\t\t= new String();\n\t\t\tString\t\t\t\tsChopped\t\t= new String();\n\t\t\tboolean\t\t\t\tbAddUserName\t= true;\n\t\t\tboolean\t\t\t\tbWasChatMsg\t\t= false;\n\t\t\tint\t\t\t\t\tiBodyWidth;\n\t\t\t\n\t\t\tif (bChatMsg){\n\t\t\t\tif (mbHangingIndent){\n\t\t\t\t\t// chat msg width is fixed:  calculated by subtracting the name column width and 5% for scroll bar\n\t\t\t\t\tiBodyWidth = (int)((miWidth - miNameColWidth) - 50);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// text comes right after name, so figure out how much room we have to work on\n\t\t\t\t\t// since name is variable length\n\t\t\t\t\tiBodyWidth = miWidth - (50 + mFontMetrics.stringWidth(saNewLine[NAME]));\t\t\t\t\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// No user name so make width of msg is 95% of width (5% for scrollbar)\n\t\t\t\tiBodyWidth = (int)(miWidth - 50);\n\t\t\t}\n\n\t\t\t//Go thru the words one by one and make sure each word will fit inside the TextArea\n\t\t\t//If a word is found that doesn't fit, use chopWord to dice the word up.\n\t\t\ttokenizer = new StringTokenizer(bChatMsg ? saNewLine[MSG] : saNewLine[NAME]);\n\t\t\twhile (tokenizer.hasMoreTokens()) {\n\t\t\t\tsNextWord = tokenizer.nextToken().toString();\n\t\t\t\tif (mFontMetrics.stringWidth(sNextWord) > iBodyWidth)\n\t\t\t\t\tsChopped += \" \" + chopWord(sNextWord, iBodyWidth);\n\t\t\t\telse\n\t\t\t\t\tsChopped += \" \" + sNextWord;\n\t\t\t}\n \n\t\t\t//No retokenize the string that has been chopped where necessary\n\t\t\ttokenizer = new StringTokenizer(sChopped);\n\t\t\tbuffer = new StringBuffer(tokenizer.nextToken());\n\n\t\t\t\t\t\n\t\t\twhile (tokenizer.hasMoreTokens()) { \n\t\t\t\tsNextWord = tokenizer.nextToken();\n\t\t\t\t\n\t\t\t\tif (mFontMetrics.stringWidth(buffer.toString()) + mFontMetrics.stringWidth(sNextWord) > iBodyWidth) {\n\t\t\t\t\t//The line doesn't fit on one row, so we have to \"wrap it\" by creating a new line\n\t\t\t\t\tString NewLine[] = new String[4];\n\t\t\t\t\tNewLine[NAMECOLOR] = saNewLine[NAMECOLOR];\n\t\t\t\t\tNewLine[MSGCOLOR] = saNewLine[MSGCOLOR];\n\t\t\t\t\tif (!mbHangingIndent && bWasChatMsg){\n\t\t\t\t\t\t//2nd line will be stored in the [NAME] field, so color it as a [MSG]\n\t\t\t\t\t\tNewLine[NAMECOLOR] = saNewLine[MSGCOLOR];\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t//You wrap the body NewLine[MSG] for a chat message\n\t\t\t\t\t//if it's regular message (no user name) you have to wrap the NewLine[NAME]\n\t\t\t\t\tif (bChatMsg) {\n\t\t\t\t\t\tNewLine[NAME] = bAddUserName ? saNewLine[NAME] : \"\";\n\t\t\t\t\t\tNewLine[MSG] = buffer.toString(); \n\t\t\t\t\t\tbWasChatMsg = true;\n\t\t\t\t\t}\n\t\t\t\t\telse { // wrap non chat message \n\t\t\t\t\t\tNewLine[NAME] = buffer.toString();\n\t\t\t\t\t\tNewLine[MSG] = \"\";\n\t\t\t\t\t}\n\t\t\t\t\tmvFormatedLines.addElement(NewLine);\n\n\t\t\t\t\tbuffer = new StringBuffer(sNextWord);\n\t\t\t\t\tbAddUserName = false;\n\t\t\t\t\tif (!mbHangingIndent && bWasChatMsg){\n\t\t\t\t\t\t//use full width and treat as non chat message (don't use Hanging Indents)\n\t\t\t\t\t\tiBodyWidth = (int)(miWidth - 50);\n\t\t\t\t\t\tbChatMsg = false;\t\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tbuffer.append(\" \" + sNextWord);\n\t\t\t\t}\n\t\t\t}\t\n\n\t\t\tString NewLine[] = new String[4];\n\t\t\tNewLine[NAMECOLOR] = saNewLine[NAMECOLOR];\n\t\t\tNewLine[MSGCOLOR] = saNewLine[MSGCOLOR];\n\t\t\tif (!mbHangingIndent && bWasChatMsg){\n\t\t\t\t//2nd line will be stored in the [NAME] field, so color it as a [MSG]\n\t\t\t\tNewLine[NAMECOLOR] = saNewLine[MSGCOLOR];\n\t\t\t}\t\t\t\n\t\t\t\n\t\t\tif (bChatMsg) {\n\t\t\t\tNewLine[NAME] = bAddUserName ? saNewLine[NAME] : \"\";\n\t\t\t\tNewLine[MSG] = \"\" + buffer;\n\t\t\t}\n\t\t\telse { // wrap name \n\t\t\t\tNewLine[NAME] = \"\" + buffer;\t\t\t\n\t\t\t\tNewLine[MSG] = \"\";\n\t\t\t}\n\n\t\t\tmvFormatedLines.addElement(NewLine);\n\t\t}\n\t\tcatch(Exception e) {\n\t\t\t//print it out without wordwrapping\n\t\t\tString UnformattedLine[] = new String[4];\n\t\t\tUnformattedLine[NAMECOLOR] = saNewLine[NAMECOLOR];\n\t\t\tUnformattedLine[MSGCOLOR] = saNewLine[MSGCOLOR];\n\t\t\tUnformattedLine[NAME] = saNewLine[NAME];\n\t\t\tUnformattedLine[MSG] = saNewLine[MSG];\n\n\t\t\tmvFormatedLines.addElement(UnformattedLine);\n\t\t}\n    }\n\n\t/**\n\t * This is called when a single word is too wide to fit on one line.  The word is\n\t * is broken apart as many times as needed so that each piece will fit correctly\n\t * inside the width of the Text Area\n\t *\n\t * @param\tword\t\tThe word to chop up\n\t * @param\tbodyWidth\tThe width of the body of text within the TextArea\n\t *\n\t * @return\tThe word chopped up into bodyWidth sized pieces (separated by a space)\n\t */    \n\tprivate String chopWord(String word, int bodyWidth){\n\t\tString\tsChoppedWord = \"\";\n\t\t\t\t\n\t\tfor (int i = 0; i < word.length(); ++i){\n\t\t\t//see how many letters of the word will fit on the first line\n\t\t\tif (mFontMetrics.stringWidth(sChoppedWord + word.substring(i, i + 1)) < bodyWidth){\n\t\t\t\tsChoppedWord += word.substring(i, i + 1);\t\n\t\t\t}\n\t\t\telse{\n\t\t\t\t//chop of the beginning letters that fit \n\t\t\t\tword = word.substring(i-1);\n\t\t\t\t//now recursively call chopWord to chop the rest\n\t\t\t\tsChoppedWord += \" \" + chopWord(word, bodyWidth);\n\t\t\t\treturn sChoppedWord;\n\t\t\t}\n\t\t}\n\t\treturn sChoppedWord;\n\t}\n\n\t/**\n\t * Display the formatted lines of text\n\t */\t\n\tprivate void render() {\n\t\tif (mbReformatLines) {\n\t\t\t//Reformat the lines since the size of the control has changed\n\t\t\t/*\n\t\t\tmvFormatedLines.removeAllElements();\n\t\t\tfor (int i = 0; i<mvLines.size(); i++) {\n\t\t\t\twordWrap(i);\n\t\t\t}\n\t\t\t*/\n\n\t\t\t//computeScrollbar(true);\n\t\t\tmbReformatLines = false;\n\t\t}\n\n\t\t//miTopLine = mScrollbar.getValue();\n\t\t//System.out.println(\"miTopLine=\" + miTopLine);\n\n\t\t//mGraphics.setColor(Color.white);\n\t\t//mGraphics.fillRect(0, 0, miWidth, miHeight);\n\t\t// set scroll if it has not been set\n\n\t\t// set up auto-scroll processing\n\t\tif (!scrollSet) {\n\t\t\tscrollSet = true;\n\n\t\t\tComponent parent = getParent();\n\t\t\twhile (parent != null && (!(parent instanceof JScrollPane)))\n\t\t\t\tparent = parent.getParent();\n\n\t\t\tif (parent != null) {\n\t\t\t\tJScrollPane pane = (JScrollPane) parent;\n\t\t\t\tpane.getViewport().addChangeListener(this);\n\t\t\t\tpane.addMouseWheelListener(this);\n\n\t\t\t\tscroll = ((JScrollPane) parent).getVerticalScrollBar();\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\tif (isAtBottom == true && scroll != null)\n\t\t\tscroll.setValue(scroll.getValue());\n\t\t*/\n\n\t\tfmtBuffer.setLength(0);\n\t\tfmtBuffer.append(\"<html><table>\");\n\n\t\tfor (int i=miTopLine; i<mvLines.size(); i++) {\n\t\t\tString[] saCurrentLine = (String[])mvLines.elementAt(i);\n\t\t\t//mGraphics.setColor(getColor(saCurrentLine[NAMECOLOR])); \t\t\t\n\n\t\t\t//mGraphics.drawString(saCurrentLine[NAME], 2, (i - miTopLine + 1) * miFontHeight);\n\n\t\t\tfmtBuffer.append(\"\\n<tr valign=\\\"top\\\">\")\n\t\t\t\t.append(\"<td\");\n\n\t\t\tif (saCurrentLine[MSG].length() == 0)\n\t\t\t\tfmtBuffer.append(\" colspan=\\\"2\\\"\");\n\t\t\telse if (saCurrentLine[NAME].length() < 25)\n\t\t\t\tfmtBuffer.append(\" nowrap=\\\"true\\\"\");\n\n\t\t\tfmtBuffer.append(\"><font name=\\\"\")\n\t\t\t\t.append(mFont.getFontName()).append(\"\\\" color=\\\"\")\n\t\t\t\t.append(saCurrentLine[NAMECOLOR]).append(\"\\\">\")\n\t\t\t\t.append(editor.edit(saCurrentLine[NAME]))\n\t\t\t\t.append(\"</font></td>\");\n\n\t\t\t/*\n\t\t\t *  maybe not... ??\n\t\t\tif (saCurrentLine[MSG].length() == 0) {\n\t\t\t\t//for non chat messages (no user name) don't erase with white rect\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t*/\n\n\t\t\tfmtBuffer.append(\"<td><font name=\\\"\")\n\t\t\t\t.append(mFont.getFontName()).append(\"\\\" color=\\\"\")\n\t\t\t\t.append(saCurrentLine[MSGCOLOR]).append(\"\\\" >\")\n\t\t\t\t.append(breakLongWords(editor.edit(saCurrentLine[MSG]), 30))\n\t\t\t\t.append(\"</font></td></tr>\");\n\n\t\t}\n\n\t\tfmtBuffer.append(\"</table></html>\");\n\n\t\t//System.out.println(\"chat=\" + fmtBuffer.toString());\n\n\t\ttry {\n\t\t\tread(new StringReader(fmtBuffer.toString()), null);\n\t\t} catch (IOException e) {}\n\t}\n\n\t/**\n\t *  break long words up\n\t */\n\tpublic String breakLongWords(String str, int len)\n\t{\n\t\tint max = str.length();\n\n\t\t// nothing to do?\n\t\tif (max <= len) return str;\n\n\t\tint i, from, to=0;\n\t\tchar c;\n\t\tStringBuffer sb = new StringBuffer(max + 100);\n\n\t\tfor (from = 0; to < max; from = to) {\n\n\t\t\t//System.out.println(\"from=\" + from + \"; to=\" + to);\n\n\t\t\tc = str.charAt(from);\n\n\t\t\tto = from+1;\n\n\t\t\t// find end of next \"word\"\n\t\t\twhile (to < max && \" <>\\\"'\".indexOf(str.charAt(to)) < 0) to++;\n\n\t\t\t//System.out.println(\"word (size=\" + (to-from) + \")=\" +\n\t\t\t//\t\t\t   str.substring(from, to));\n\n\n\t\t\t// **DEBUG**\n\t\t\t//if (to == from) break;\n\n\t\t\tif (to-from > len) {\n\t\t\t\tSystem.out.println(\"word is too big\");\n\t\t\t\tif (\"'\\\"\".indexOf(c) >= 0 && str.charAt(to) == c)\n\t\t\t\t\tsb.append(str.substring(from, to));\n\t\t\t\telse {\n\t\t\t\t\t//System.out.println(\"inserting <wbr> at \" + to);\n\t\t\t\t\tto = from + len;\n\t\t\t\t\t\n\t\t\t\t\t// try to find a good place for the break\n\t\t\t\t\tfor (i = 0; i < 5 && i < to-from; i++) {\n\t\t\t\t\t\tif (!Character.isLetterOrDigit(str.charAt(to-i))) {\n\t\t\t\t\t\t\tto -= i;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tsb.append(str.substring(from, to)).append(\"<wr>\");\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// include whitespace\n\t\t\t\twhile (to < max && Character.isWhitespace(str.charAt(to)))\n\t\t\t\t\tto++;\n\n\t\t\t\tsb.append(str.substring(from, to));\n\t\t\t}\n\t\t}\n\n\t\tif (from < max) sb.append(str.substring(from));\n\n\t\t//System.out.println(\"wordified: \" + sb.toString());\n\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t *  display at bottom (again)\n\t */\n\tpublic void isAtBottom(boolean tf)\n\t{ isAtBottom = tf; }\n\n\t/**\n\t *  scroll to the bottom once the content has been changed\n\t */\n\tpublic void stateChanged(ChangeEvent ev)\n\t{\n\t\t// keep scroll at the bottom\n\t\tif (isAtBottom == true && scroll != null\n\t\t\t&& (wheelScrolling == true \n\t\t\t\t|| scroll.getValueIsAdjusting() == false)) {\n\n\t\t\tscroll.setValue(scroll.getMaximum() - scroll.getVisibleAmount());\n\t\t\tisAtBottom = true;\n\t\t}\n\t\telse \n\t\t\tisAtBottom = (scroll.getValue() >=\n\t\t\t\t\t\t  (scroll.getMaximum() - scroll.getVisibleAmount()));\n\n\t\tSystem.out.println(\"change: isAtBottom=\" + isAtBottom);\n\n\t\twheelScrolling = false;\n\n\t\t/*\n\t\t * This rigmarole is to reset the ValueIsAdjusting() value *after*\n\t\t * the value has actually been set *sigh*\n\t\t */\n\t\t/*\n\t\tif (wheelScrolling) {\n\t\t\twheelScrolling = false;\n\t\t\tscroll.setValue(scroll.getValue());\n\t\t}\n\t\telse scroll.setValueIsAdjusting(false);\n\t\t*/\n\n\t}\n\n\t/**\n\t */\n\tpublic void mouseWheelMoved(MouseWheelEvent ev)\n\t{\n\t\tif (scroll == null) return;\n\n\t\twheelScrolling = true;\n\t\t//scroll.setValueIsAdjusting(true);\n\n\t\tint max = scroll.getMaximum() - scroll.getVisibleAmount();\n\t\tint pos = scroll.getValue() + ev.getUnitsToScroll();\n\n\t\tscroll.setValue(pos);\n\n\t\tisAtBottom = (pos >= max);\n\t}\n\n\t/**\n\t * Compute the Scrollbar value\n\t * \n     * @param scrollToBottom\t\ttrue if you should scroll to bottom of the text area\n\t */\t\n\tvoid computeScrollbar(boolean scrollToBottom) {\n\t\tif (mFontMetrics == null) {\n\t\t\treturn;\t\t// not visible\n\t\t}\n\n\t\tint iSBTop;\n\n\t\tif (scrollToBottom) {\n\t\t\tiSBTop = mvFormatedLines.size() - miNbrLinesPerPage + 1;\n\t\t}\n\t\telse if (mvFormatedLines.size() > miNbrLinesPerPage) {\n\t\t\tiSBTop = mScrollbar.getValue();\n\t\t}\n\t\telse {\n\t\t\tiSBTop = 0;\n\t\t}\n\t\t\n\t\tmScrollbar.setValues(iSBTop, 10, 0, mvFormatedLines.size());\n\t}\n\n\t/**\n\t * Converts a string formatted as \"rrggbb\" to an awt.Color object\n\t *\n     * @return\t\t\tawt.Color object (black if invalid color)\n\t */\n    private Color getColor(String RGB) {\n\t\tint red;\n\t\tint green;\n\t\tint blue;\n\t\n\t\ttry{\n\t\t\tred = (Integer.decode(\"0x\" + RGB.substring(0,2))).intValue();\n\t\t\tgreen = (Integer.decode(\"0x\" + RGB.substring(2,4))).intValue();\n\t\t\tblue = (Integer.decode(\"0x\" + RGB.substring(4,6))).intValue();\n\t\t\treturn new Color(red,green,blue);\n\t\t} \n\t\tcatch (Exception e){\n\t\t\t//Default to black on none RGB values\n\t\t\treturn Color.black;\n\t\t}\n    }\t\n}\n", "human_rating": 2.9571171929300215, "metadata": {"project": "aoi", "class": "nik777.chat.ChatTextPane", "source_path": "aoi/sourcefiles/HelpPlugin/src/ChatTextPane.java", "label_probabilities": {"readability": [1.00053e-11, 0.95712, 0.0428768, 3.59289e-06], "understandability": [9.93292e-13, 0.322445, 0.63569, 0.0418648], "complexity": [0.458368, 0.15113, 0.387471, 0.00303148], "modularization": [0.99974, 0.00025978, 0.0, 0.0], "overall": [5.19486e-10, 0.0402193, 0.717704, 0.242077]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/aoi/nik777.xlate.StringEditor", "source": "/*  StringEditor.java  */\n\npackage nik777.xlate;\n\n/*\n * StringEditor: apply stored edit commands to strings.\n *\n * Copyright (C) 2000-2006, Nik Trevallyn-Jones, Sydney Australia\n *\n * Author: Nik Trevallyn-Jones, nik777@users.sourceforge.net\n * $Id: Exp $\n *\n * This program is free software; you can redistribute it and/or modify\n * it under the terms of version 2 of the GNU General Public License as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of \n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See version 2 of the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * with this program. If not, version 2 of the license is available\n * from the GNU project, at http://www.gnu.org.\n */\n\nimport java.util.*;\nimport java.util.regex.*;\n\n/**\n *  the string editor class.\n *\n *  Provides efficient, repeated editing functions specified by\n *  commands which can include regular expressions.\n *\n *  The editing command syntax is based loosely on the 'sed' commands, and uses\n *  the java.util.regex regular expression handler in\n *  {@link java.util.regex#Pattern} - see {@link #compile(String)} for details.\n *\n *  To invoke the editor, see\n *  {@link #edit(java.lang.String)}.\n */\npublic class StringEditor\n{\n    protected Pattern pattern;\n    protected String value;\n    protected char op;\n    protected boolean global;\n\n    protected StringEditor next;\n\n    public static final StringEditor EMPTY = new StringEditor() {\n\t    public String edit(String str)\n\t    { return str; }\n\n\t    public void compile()\n\t    { next = null; }\n\t};\n\n    public StringEditor()\n    { next = null; }\n\n    public StringEditor(String cmd)\n    {\n\tnext = null;\n\tcompile(cmd);\n    }\n\n    /**\n     *  return the number of edit rules in this editor\n     */\n    public int size()\n    {\n\tint result = (pattern != null ? 1 : 0);\n\tfor (StringEditor nx = next; nx != null; nx = nx.next) result++;\n\n\treturn result;\n    }\n\n    /**\n     *  edit a string.\n     *\n     *  @return the result of applying this editor to <i>str</i>.\n     */\n    public String edit(String str)\n    {\n\tif (pattern == null) return str;\n\n\tString result = \"\";\n\n\tint pos=0, group=0, max;\n\tStringBuffer sb;\n\tMatcher matcher = pattern.matcher(str);\n\n\tswitch (op) {\n\tcase 's':\n\tcase 'S':\n\tcase 'd':\n\tcase 'D':\n\t    // s,d - replace matched text with value or null\n\t    if (global)\n\t\tresult = matcher.replaceAll(value);\n\t    else\n\t\tresult = matcher.replaceFirst(value);\n\t    break;\n\n\tcase 'a':\n\tcase 'A':\n\tcase 'i':\n\tcase 'I':\n\t    // a,i append/insert value\n\t    sb = new StringBuffer(str.length()*2);\n\n\t    while (matcher.find()) {\n\t\tmatcher.appendReplacement(sb, value);\n\n\t\tif (!global) break;\n\t    }\n\n\t    matcher.appendTail(sb);\n\t    result = sb.toString();\n\t    break;\n\n\tcase 'p':\n\tcase 'P':\n\t    // p return the specified matched group\n\t    sb = (global ? new StringBuffer(str.length()) : null);\n\n\t    // get the group number\n\t    max = value.length();\n\t    while (pos < max && Character.isDigit(value.charAt(pos++)))\n\t\tgroup = (group*10) + Character.digit(value.charAt(pos), 10);\n\t    \n\t    while (matcher.find()) {\n\t\tresult = matcher.group(group);\n\n\t\tif (!global) break;\n\n\t\tsb.append(result);\n\t    }\n\n\t    if (global) result = sb.toString();\n\t}\n\n\treturn (next != null ? next.edit(result) : result);\n    }\n\n    /**\n     *  add an editor to this editor. The added editor will be invoked by\n     *  this.edit() <i>after</i> all this editor's edits have been applied.\n     */\n    public void add(StringEditor editor)\n    {\n\tif (next != null) next.add(editor);\n\telse next = editor;\n    }\n\n    /**\n     *  add the specified editing commands to this editor.\n     *\n     *  The command(s) will be compiled and then executed <i>after</i> this\n     *  editor's edits (if any) have been applied.\n     */\n    public void add(String cmd)\n    {\n\tif (pattern == null) compile(cmd);\n\telse add(new StringEditor(cmd));\n    }\n\n    /**\n     *  compile an edit command.\n     *\n     *  Causes any previous editing command to be replaced with the\n     *  newly compiled command.\n     *\n     *<br>The format of an editing command is:\n     *<br>[qual] op delim pattern [delim arg] [delim cmd]\n     *\n     *<br>Eg: gs/(dog|hound)/canine/s;cat;feline\n     *\n     *<br>Where:\n     *<br>qual is a qualifier. The only qualifier currently is <i>g</i> which\n     *    causes the associated operation to be applied to <i>all</i> matches.\n     *<br>op is an editing operation, and is one of\n     *\n     *<ul>\n     *<li> s - switch; replace matched text with <i>arg</i>\n     *<li> a - append; append <i>arg</i> to the matched text\n     *<li> i - insert; insert <i>arg</i> to the matched text\n     *<li> d - delete; delete the matched text\n     *<li> p - print; return the <i>arg</i>th match group (0 => all)\n     *</ul>\n     *\n     *<br>delim is a single character (ie the character immediately following\n     *\tthe <i>op</i>).\n     *\n     *<br>pattern is a regular expression for matching substrings in the text\n     *\tFor an explanation of the valid regular expressions see\n     *\t{@link java.util.regex.Pattern}.\n     *\n     *<br>arg is an argument for the operation.\n     *<br>Note also that the 's,a,i' commands allows <i>arg</i> to contain\n     *  references to sequences of the matched data\n     *  (see {@link java.util.regex.Matcher#appendReplacement()}).\n     *  In particular the token '$0' will be replaced with the entire matched\n     *  text. Hence a literal '$' char will need to be escaped as in '\\$'.\n     *</ul>\n     *  \n     *<br>As can be seen, multiple commands can be concatenated, each\n     *  separated by the current delimiter char. In addition, the delimiter can\n     *  be different for each command. By definition, the delimiter for each\n     *  commmand is  the character <i>immediately following</i> the editing op.\n     *\n     *<br>So from this, the example command(s) above replace <i>all</i>\n     *  occurences of 'dog' or 'hound' with 'canine, and then the first\n     *  occurence of 'cat' with 'feline'. (In this example, the delimiter for\n     *  the first op is '/', and for the second op is ';', although the one\n     *  delimiter could just as easily be used for all commands).\n     *\n     *<br>Changes are applied in the same order as the commands, so\n     *  if an earlier edit inserts a pieces of text which can match a later\n     *  edit's pattern, then that newly added text may be modified by the\n     *  later command.\n     *\n     *  @param cmd the editing command string.\n     */\n    public void compile(String cmd)\n\tthrows PatternSyntaxException\n    {\n\tcmd = cmd.trim();\n\tint len = (cmd != null ? cmd.length() : 0);\n\n\tchar qual = cmd.charAt(0);\n\tif (qual == 'g' || qual == 'G') {\n\t    global = true;\n\t    cmd = cmd.substring(1);\n\t    len--;\n\t}\n\n\tif (len == 2) return;\n\n\tint cut, cut2;\n\tchar delim;\n\top = cmd.charAt(0);\n\tdelim = cmd.charAt(1);\n\n\t// get the edit pattern\n\tcut = cmd.indexOf(delim, 2);\n\tif (cut < 0) pattern = Pattern.compile(cmd.substring(2));\n\telse pattern = Pattern.compile(cmd.substring(2, cut));\n\n\tswitch (op) {\n\tcase 's':\n\tcase 'S':\n\tcase 'a':\n\tcase 'A':\n\tcase 'i':\n\tcase 'I':\n\tcase 'p':\n\tcase 'P':\n\t    if (cut > 0) {\n\t\tcut++;\n\n\t\t// find the replacement string\n\t\tcut2 = cmd.indexOf(delim, cut);\n\t\tif (cut2 > cut) value = cmd.substring(cut, cut2);\n\t\telse value = cmd.substring(cut);\n\n\t\t// null string\n\t\tif (value.length() == 1 && value.charAt(0) == delim)\n\t\t    value = \"\";\n\n\t\tcut = cut2;\t\t// advance cut\n\t    }\n\t    else value = \"\";\n\n\t    // for insert/append, include the matched string (group-0)\n\t    switch (\"aAiI\".indexOf(op)) {\n\t    case 0:\n\t    case 1:\n\t\tvalue = \"$0\" + value;\n\t\tbreak;\n\n\t    case 2:\n\t    case 3:\n\t\tvalue = value + \"$0\";\n\t\tbreak;\n\t    }\n\n\t    break;\n\n\tcase 'd':\n\tcase 'D':\n\t    value = \"\";\n\t    break;\n\n\tdefault:\n\t    throw new PatternSyntaxException(\"Unrecognised cmd: \" +\n\t\t\t\t\t     op, cmd, 0);\n\t}\n\n\t// if there is more, chain to next editor\n\tif (cut > 0 && cut+2 < len)\n\t    next = new StringEditor(cmd.substring(cut+1));\n\n\telse\n\t    next = null;\n    }\n\n}\n\n", "human_rating": 2.9918330001415643, "metadata": {"project": "aoi", "class": "nik777.xlate.StringEditor", "source_path": "aoi/sourcefiles/HelpPlugin/src/StringEditor.java", "label_probabilities": {"readability": [0.0121558, 0.967521, 0.0203234, 1.41564e-10], "understandability": [0.0227708, 0.146763, 1.68779e-06, 0.830465], "complexity": [0.0873049, 0.633623, 0.279036, 3.60028e-05], "modularization": [0.00475364, 0.224089, 0.681884, 0.0892735], "overall": [3e-20, 0.017712, 0.899637, 0.082651]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.application.api.Argo", "source": "/* $Id: Argo.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *******************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *******************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.application.api;\n\nimport org.argouml.configuration.Configuration;\nimport org.argouml.configuration.ConfigurationKey;\n\n/**\n * The <code>Argo</code> class provides static methods and definitions\n * that can be used as helpers throughout the Argo code.<p>\n *\n * This class is a variation of the <em>Expert</em> design pattern\n * [Grand].  By incorporating a number of unrelated but commonly\n * used methods in a single class, it attempts to decrease the\n * complexity of the overall code while increasing its own complexity.<p>\n *\n * These include\n * <ul>\n * <li>definitions of configuration keys\n * <li>definitions of resource bundle identifier strings\n * <li>methods for localization using <code>gef</code>\n * <li>methods for environment manipulation\n * </ul>\n *\n */\npublic final class Argo {\n\n    /**\n     * argo.ini path.\n     * @deprecated for 0.25.4 by tfmorris.  No longer used.\n     */\n    @Deprecated\n    public static final String ARGOINI = \"/org/argouml/argo.ini\";\n\n    /**\n     * Key for default startup directory.\n     */\n    public static final ConfigurationKey KEY_STARTUP_DIR =\n\tConfiguration.makeKey(\"default\", \"user\", \"dir\");\n\n    /**\n     * Key to show splash screen.\n     */\n    public static final ConfigurationKey KEY_SPLASH =\n\tConfiguration.makeKey(\"init\", \"splash\");\n\n    /**\n     * Key to report usage statistics.\n     */\n    public static final ConfigurationKey KEY_EDEM =\n\tConfiguration.makeKey(\"init\", \"edem\");\n\n    /**\n     * Key for last saved project URI.\n     */\n    public static final ConfigurationKey KEY_MOST_RECENT_PROJECT_FILE =\n\tConfiguration.makeKey(\"project\", \"mostrecent\", \"file\");\n\n    /**\n     * Key for last generated class/classes directory.\n     */\n    public static final ConfigurationKey KEY_MOST_RECENT_EXPORT_DIRECTORY =\n        Configuration.makeKey(\"project\", \"mostrecent\", \"exportdirectory\");\n\n    /**\n     * Key to reload last saved project on startup.\n     */\n    public static final ConfigurationKey KEY_RELOAD_RECENT_PROJECT =\n\tConfiguration.makeKey(\"init\", \"project\", \"loadmostrecent\");\n\n    /**\n     * Key for number of last recently used file entries in menu list.\n     */\n    public static final ConfigurationKey KEY_NUMBER_LAST_RECENT_USED =\n\tConfiguration.makeKey(\"project\", \"mostrecent\", \"maxNumber\");\n\n    /**\n     * Key for screen top.\n     */\n    public static final ConfigurationKey KEY_SCREEN_TOP_Y =\n\tConfiguration.makeKey(\"screen\", \"top\");\n\n    /**\n     * Key for screen left.\n     */\n    public static final ConfigurationKey KEY_SCREEN_LEFT_X =\n\tConfiguration.makeKey(\"screen\", \"left\");\n\n    /**\n     * Key for screen width.\n     */\n    public static final ConfigurationKey KEY_SCREEN_WIDTH =\n\tConfiguration.makeKey(\"screen\", \"width\");\n\n    /**\n     * Key for screen height.\n     */\n    public static final ConfigurationKey KEY_SCREEN_HEIGHT =\n\tConfiguration.makeKey(\"screen\", \"height\");\n\n    /**\n     * Key for screen extended state, i.e. NORMAL, MAXIMIZED;\n     * (see Frame documentation).\n     */\n    public static final ConfigurationKey KEY_SCREEN_MAXIMIZED =\n        Configuration.makeKey(\"screen\", \"maximized\");\n\n    /**\n     * Key for southwest pane width.\n     */\n    public static final ConfigurationKey KEY_SCREEN_SOUTHWEST_WIDTH =\n\tConfiguration.makeKey(\"screen\", \"southwest\", \"width\");\n\n    /**\n     * Key for northwest pane width.\n     */\n    public static final ConfigurationKey KEY_SCREEN_NORTHWEST_WIDTH =\n\tConfiguration.makeKey(\"screen\", \"northwest\", \"width\");\n\n    /**\n     * Key for southeast pane width.\n     */\n    public static final ConfigurationKey KEY_SCREEN_SOUTHEAST_WIDTH =\n\tConfiguration.makeKey(\"screen\", \"southeast\", \"width\");\n\n    /**\n     * Key for northeast pane width.\n     */\n    public static final ConfigurationKey KEY_SCREEN_NORTHEAST_WIDTH =\n\tConfiguration.makeKey(\"screen\", \"northeast\", \"width\");\n\n    /**\n     * Key for west pane width.\n     */\n    public static final ConfigurationKey KEY_SCREEN_WEST_WIDTH =\n\tConfiguration.makeKey(\"screen\", \"west\", \"width\");\n\n    /**\n     * Key for east pane width.\n     */\n    public static final ConfigurationKey KEY_SCREEN_EAST_WIDTH =\n\tConfiguration.makeKey(\"screen\", \"east\", \"width\");\n\n    /**\n     * Key for south pane height.\n     */\n    public static final ConfigurationKey KEY_SCREEN_SOUTH_HEIGHT =\n\tConfiguration.makeKey(\"screen\", \"south\", \"height\");\n\n    /**\n     * Key for north pane height.\n     */\n    public static final ConfigurationKey KEY_SCREEN_NORTH_HEIGHT =\n\tConfiguration.makeKey(\"screen\", \"north\", \"height\");\n\n    /**\n     * Key for theme.\n     */\n    public static final ConfigurationKey KEY_SCREEN_THEME =\n\tConfiguration.makeKey(\"screen\", \"theme\");\n\n    /**\n     * Key for look and feel class name.\n     */\n    public static final ConfigurationKey KEY_LOOK_AND_FEEL_CLASS =\n        Configuration.makeKey(\"screen\", \"lookAndFeelClass\");\n\n    /**\n     * Key for theme class name.\n     */\n    public static final ConfigurationKey KEY_THEME_CLASS =\n        Configuration.makeKey(\"screen\", \"themeClass\");\n\n    /**\n     * Key to enable smooth edges of diagram text and lines (anti-aliasing).\n     */\n    public static final ConfigurationKey KEY_SMOOTH_EDGES =\n        Configuration.makeKey(\"screen\", \"diagram-antialiasing\");\n\n    /**\n     * Key for user email address.\n     */\n    public static final ConfigurationKey KEY_USER_EMAIL =\n\tConfiguration.makeKey(\"user\", \"email\");\n\n    /**\n     * Key for user full name.\n     */\n    public static final ConfigurationKey KEY_USER_FULLNAME =\n\tConfiguration.makeKey(\"user\", \"fullname\");\n\n    /**\n     * Key for user java reverse engineering classpath.\n     */\n    public static final ConfigurationKey KEY_USER_IMPORT_CLASSPATH =\n\tConfiguration.makeKey(\"import\", \"clazzpath\");\n\n    /**\n     * Key for RE general settings checkbox values.\n     * CSV format (values are true/false):\n     * 1. descend directories recursively\n     * 2. changed/new files only\n     * 3. create diagrams from imported code\n     * 4. minimise class icons in diagrams\n     * 5. perform automatic diagram layout\n     */\n    public static final ConfigurationKey KEY_IMPORT_GENERAL_SETTINGS_FLAGS =\n        Configuration.makeKey(\"import\", \"general\", \"flags\");\n\n    /**\n     * Key for RE general settings: level of import detail. Values:\n     * 0: classifiers only\n     * 1: classifiers plus feature specifications\n     * 2: full import\n     */\n    public static final ConfigurationKey KEY_IMPORT_GENERAL_DETAIL_LEVEL =\n        Configuration.makeKey(\"import\", \"general\", \"detail\", \"level\");\n\n    /**\n     * Key for input source file encoding used in RE.\n     *  Will be used for generated file also.\n     */\n    public static final ConfigurationKey KEY_INPUT_SOURCE_ENCODING =\n\tConfiguration.makeKey(\"import\", \"file\", \"encoding\");\n\n    /**\n     * Key to store setting of stripping diagrams on XMI import.\n     */\n    public static final ConfigurationKey KEY_XMI_STRIP_DIAGRAMS =\n        Configuration.makeKey(\"import\", \"xmi\", \"stripDiagrams\");\n\n    /**\n     * Key to store profile/default model.\n     */\n    public static final ConfigurationKey KEY_DEFAULT_MODEL =\n        Configuration.makeKey(\"defaultModel\");\n\n    /**\n     * Key for user explorer perspectives.\n     *<pre>\n     * format:\n     * perspective name,rule,rule,rule;perspective name, etc\n     *</pre>\n     */\n    public static final ConfigurationKey KEY_USER_EXPLORER_PERSPECTIVES =\n\tConfiguration.makeKey(\"explorer\", \"perspectives\");\n\n    /**\n     * Key for selecting the locale.\n     */\n    public static final ConfigurationKey KEY_LOCALE =\n        Configuration.makeKey(\"locale\");\n\n    /**\n     * Key for selecting the grid size and if it shows lines, dots or none.\n     */\n    public static final ConfigurationKey KEY_GRID =\n        Configuration.makeKey(\"grid\");\n\n    /**\n     * Key for selecting the snap size.\n     */\n    public static final ConfigurationKey KEY_SNAP =\n        Configuration.makeKey(\"snap\");\n\n    /**\n     * Standard definition of the logging category for the console. (unused)\n     */\n    public static final String CONSOLE_LOG = \"argo.console.log\";\n\n    /**\n     * Standard definition of the logging category for the console.\n     */\n    public static final String ARGO_CONSOLE_SUPPRESS = \"argo.console.suppress\";\n\n    /**\n     * Standard definition of system variable to add text prefix to\n     * console log. (unused)\n     */\n    public static final String ARGO_CONSOLE_PREFIX = \"argo.console.prefix\";\n\n    /**\n     * Name of the TagDefinition which is used as the type of tagged values\n     * containing documentation for a model element.\n     */\n    public static final String DOCUMENTATION_TAG = \"documentation\";\n\n    /**\n     * Name of the TagDefinition for tagged values containing\n     * the author's name.\n     */\n    public static final String AUTHOR_TAG = \"author\";\n\n    /**\n     * Name of the TagDefinition for tagged values containing\n     * since date.\n     */\n    public static final String SINCE_TAG = \"since\";\n\n    /**\n     * Name of the TagDefinition for tagged values containing\n     * \"see\" reference.\n     */\n    public static final String SEE_TAG = \"see\";\n\n    /**\n     * Name of the TagDefinition for tagged values containing\n     * deprecated flag.\n     */\n    public static final String DEPRECATED_TAG = \"deprecated\";\n\n    /**\n     * Name of the TagDefinition for tagged values containing\n     * version string.\n     */\n    public static final String VERSION_TAG = \"version\";\n\n    /**\n     * Alternate name for the TagDefinition which presumably was used at some\n     * point in the past to contain documentation for a model element.  Only\n     * used for backward compatibilty.\n     * @deprecated for 0.25.1 by tfmorris - don't use for new code.\n     */\n    @Deprecated\n    public static final String DOCUMENTATION_TAG_ALT = \"javadocs\";\n\n    /**\n     * The scope of the settings: this setting is stored\n     * in the userdirectory and valid for the application.\n     */\n    public static final int SCOPE_APPLICATION = 0;\n\n    /**\n     * The scope of the setting: this setting is stored with the project,\n     * i.e. in e.g. a zargo file. This setting will also apply\n     * when the zargo file is opened by another user,\n     * on another computer.\n     */\n    public static final int SCOPE_PROJECT = 1;\n\n    /**\n     * Don't let this class be instantiated.\n     */\n    private Argo() {\n    }\n\n    /**\n     * Change the default startup directory.\n     *\n     * @param dir the directory to save\n     */\n    public static void setDirectory(String dir) {\n\t// Store in the user configuration, and\n\t// let gef know also.\n\torg.tigris.gef.base.Globals.setLastDirectory(dir);\n\n\t// Configuration.setString(KEY_STARTUP_DIR, dir);\n    }\n\n    /**\n     * Get the default startup directory.\n     *\n     * @return the startup directory\n     */\n    public static String getDirectory() {\n\t// Use the configuration if it exists, otherwise\n\t// use what gef thinks.\n\treturn Configuration.getString(KEY_STARTUP_DIR,\n\t\t\t\t       org.tigris.gef.base.Globals\n\t\t\t\t           .getLastDirectory());\n    }\n\n    static {\n\tif (System.getProperty(ARGO_CONSOLE_SUPPRESS) != null) {\n//            Category.getRoot().getLoggerRepository().setThreshold(Level.OFF);\n// TODO: Find the proper implementation in java.util.logging API\t    \n\t}\n    }\n\n    /**\n     * Supply the encoding to be used throughout the persistence\n     * mechanism.\n     * @return the encoding.\n     */\n    public static String getEncoding() {\n        return \"UTF-8\";\n    }\n}\n", "human_rating": 4.000000061113, "metadata": {"project": "argoUML", "class": "org.argouml.application.api.Argo", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/application/api/Argo.java", "label_probabilities": {"readability": [1.0, 2.0371e-08, 0.0, 0.0], "understandability": [3e-20, 0.73303, 0.26697, 2.94839e-15], "complexity": [0.0, 7.25812e-09, 9.84271e-06, 0.99999], "modularization": [0.0, 0.0, 6.93e-18, 1.0], "overall": [9.05749e-12, 1.0, 5.86872e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.application.events.ArgoEventPump", "source": "/* $Id: ArgoEventPump.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *******************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *******************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.application.events;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.SwingUtilities;\n\nimport org.argouml.application.api.ArgoEventListener;\n\n/**\n * ArgoEventPump is an event dispatcher which handles events that are global\n * in nature for the entire application.\n * <p>\n * TODO: DiagramAppearance and Notation events are not application-wide and will\n * be moved from here to someplace more specific in the future so that they can\n * be managed on a per-project or per-diagram basis.\n */\npublic final class ArgoEventPump {\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(ArgoEventPump.class.getName());\n\n    /**\n     * <code>listeners</code> contains the list of register listeners.\n     *\n     * It is a list of {@link Pair}.\n     */\n    private List<Pair> listeners;\n\n    /**\n     * The singleton.\n     */\n    static final ArgoEventPump SINGLETON = new ArgoEventPump();\n\n    /**\n     * @return the singleton\n     */\n    public static ArgoEventPump getInstance() {\n        return SINGLETON;\n    }\n\n    /**\n     * Constructor.\n     */\n    private ArgoEventPump() {\n    }\n\n    /**\n     * @param listener The listener to be added.\n     */\n    public static void addListener(ArgoEventListener listener) {\n        SINGLETON.doAddListener(ArgoEventTypes.ANY_EVENT, listener);\n    }\n\n    /**\n     * @param event the event-type to what the listener will listen\n     * @param listener the listener to be added\n     */\n    public static void addListener(int event, ArgoEventListener listener) {\n        SINGLETON.doAddListener(event, listener);\n    }\n\n    /**\n     * @param listener the listener to be removed\n     */\n    public static void removeListener(ArgoEventListener listener) {\n        SINGLETON.doRemoveListener(ArgoEventTypes.ANY_EVENT, listener);\n    }\n\n    /**\n     * @param event the event to which the listener will not listen any more\n     * @param listener the listener to be removed\n     */\n    public static void removeListener(int event, ArgoEventListener listener) {\n        SINGLETON.doRemoveListener(event, listener);\n    }\n\n    /**\n     * @param event the event to what the listener will listen (?)\n     * @param listener the listener to be added\n     */\n    protected void doAddListener(int event, ArgoEventListener listener) {\n        if (listeners == null) {\n            listeners = new ArrayList<Pair>();\n        }\n        synchronized (listeners) {\n            listeners.add(new Pair(event, listener));\n        }\n    }\n\n    /**\n     * Removes a listener, eventtype pair from the listener list.\n     *\n     * TODO: replace the listener implementation with a EventListenerList\n     * for better performance\n     *\n     * @param event the event to which the listener will not listen any more\n     * @param listener the listener to be removed\n     */\n    protected void doRemoveListener(int event, ArgoEventListener listener) {\n        if (listeners == null) {\n            return;\n        }\n        synchronized (listeners) {\n            List<Pair> removeList = new ArrayList<Pair>();\n            if (event == ArgoEventTypes.ANY_EVENT) {\n                // TODO: This is a linear search of a list that contain many\n                // thousands of items (one for every Fig in the entire project)\n                for (Pair p : listeners) {\n                    if (p.listener == listener) {\n                        removeList.add(p);\n                    }\n                }\n            } else {\n                Pair test = new Pair(event, listener);\n                // TODO: This is a linear search of a list that contain many\n                // thousands of items (one for every Fig in the entire project)\n                for (Pair p : listeners) {\n                    if (p.equals(test)) {\n                        removeList.add(p);\n                    }\n                }\n            }\n            listeners.removeAll(removeList);\n        }\n    }\n\n    /**\n     * Handle firing a notation event.\n     * <p>\n     * TODO: This needs to be managed on a per-diagram or per-project basis.\n     *\n     * @param event The event to be fired.\n     * @param listener The listener.\n     */\n    private void handleFireNotationEvent(\n        final ArgoNotationEvent event,\n        final ArgoNotationEventListener listener) {\n\n        // Notation events are likely to cause GEF/Swing operations, so we\n        // dispatch them on the Swing event thread as a convenience so that\n        // the receiving notationChanged() methods don't need to deal with it\n        if (SwingUtilities.isEventDispatchThread()) {\n            fireNotationEventInternal(event, listener);\n        } else {\n            SwingUtilities.invokeLater(new Runnable() {\n                public void run() {\n                    fireNotationEventInternal(event, listener);\n                }\n            });\n        }\n    }\n\n    private void fireNotationEventInternal(ArgoNotationEvent event,\n            ArgoNotationEventListener listener) {\n        switch (event.getEventType()) {\n        case ArgoEventTypes.NOTATION_CHANGED :\n            listener.notationChanged(event);\n            /* Remark: The code in\n             * ProjectSettings.init() currently presumes\n             * that nobody is using this event. */\n            break;\n\n        case ArgoEventTypes.NOTATION_ADDED :\n            listener.notationAdded(event);\n            break;\n\n        case ArgoEventTypes.NOTATION_REMOVED :\n            listener.notationRemoved(event);\n            break;\n\n        case ArgoEventTypes.NOTATION_PROVIDER_ADDED :\n            listener.notationProviderAdded(event);\n            break;\n\n        case ArgoEventTypes.NOTATION_PROVIDER_REMOVED :\n            listener.notationProviderRemoved(event);\n            break;\n\n\tdefault :\n            LOG.log(Level.SEVERE, \"Invalid event:\" + event.getEventType());\n\t    break;\n        }\n    }\n\n    /**\n     * Handle firing a diagram appearance event.\n     * <p>\n     * TODO: This needs to be managed on a per-diagram or per-project basis.\n     *\n     * @param event The event to be fired.\n     * @param listener The listener.\n     */\n    private void handleFireDiagramAppearanceEvent(\n        final ArgoDiagramAppearanceEvent event,\n        final ArgoDiagramAppearanceEventListener listener) {\n        if (SwingUtilities.isEventDispatchThread()) {\n            fireDiagramAppearanceEventInternal(event, listener);\n        } else {\n            SwingUtilities.invokeLater(new Runnable() {\n                public void run() {\n                    fireDiagramAppearanceEventInternal(event, listener);\n                }\n            });\n        }\n    }\n\n    private void fireDiagramAppearanceEventInternal(\n            final ArgoDiagramAppearanceEvent event,\n            final ArgoDiagramAppearanceEventListener listener) {\n        switch (event.getEventType()) {\n        case ArgoEventTypes.DIAGRAM_FONT_CHANGED :\n            listener.diagramFontChanged(event);\n            break;\n        default :\n            LOG.log(Level.SEVERE, \"Invalid event:\" + event.getEventType());\n            break;\n        }\n    }\n\n    /**\n     * Handle firing a help text event.\n     *\n     * @param event The event to be fired.\n     * @param listener The listener.\n     */\n    private void handleFireHelpEvent(\n        ArgoHelpEvent event,\n        ArgoHelpEventListener listener) {\n        switch (event.getEventType()) {\n        case ArgoEventTypes.HELP_CHANGED :\n            listener.helpChanged(event);\n            break;\n\n        case ArgoEventTypes.HELP_REMOVED :\n            listener.helpRemoved(event);\n            break;\n\n        default :\n            LOG.log(Level.SEVERE, \"Invalid event:\" + event.getEventType());\n            break;\n        }\n    }\n\n\n    /**\n     * Handle firing a status text event.\n     *\n     * @param event The event to be fired.\n     * @param listener The listener.\n     */\n    private void handleFireStatusEvent(\n        ArgoStatusEvent event,\n        ArgoStatusEventListener listener) {\n        switch (event.getEventType()) {\n        case ArgoEventTypes.STATUS_TEXT :\n            listener.statusText(event);\n            break;\n\n        case ArgoEventTypes.STATUS_CLEARED :\n            listener.statusCleared(event);\n            break;\n\n        case ArgoEventTypes.STATUS_PROJECT_SAVED :\n            listener.projectSaved(event);\n            break;\n\n        case ArgoEventTypes.STATUS_PROJECT_LOADED :\n            listener.projectLoaded(event);\n            break;\n\n        case ArgoEventTypes.STATUS_PROJECT_MODIFIED :\n            listener.projectModified(event);\n            break;\n\n        default :\n            LOG.log(Level.SEVERE, \"Invalid event:\" + event.getEventType());\n            break;\n        }\n    }\n\n    /**\n     * Handle firing a profile event.\n     *\n     * @param event The event to be fired.\n     * @param listener The listener.\n     */\n    private void handleFireProfileEvent(\n        ArgoProfileEvent event,\n        ArgoProfileEventListener listener) {\n        switch (event.getEventType()) {\n        case ArgoEventTypes.PROFILE_ADDED:\n            listener.profileAdded(event);\n            break;\n\n        case ArgoEventTypes.PROFILE_REMOVED:\n            listener.profileRemoved(event);\n            break;\n\n        default:\n            LOG.log(Level.SEVERE, \"Invalid event:\" + event.getEventType());\n            break;\n        }\n    }\n\n    /**\n     * Handle firing a generator event.\n     *\n     * @param event The event to be fired.\n     * @param listener The listener.\n     */\n    private void handleFireGeneratorEvent(\n        ArgoGeneratorEvent event,\n        ArgoGeneratorEventListener listener) {\n        switch (event.getEventType()) {\n        case ArgoEventTypes.GENERATOR_CHANGED:\n            listener.generatorChanged(event);\n            break;\n\n        case ArgoEventTypes.GENERATOR_ADDED:\n            listener.generatorAdded(event);\n            break;\n\n        case ArgoEventTypes.GENERATOR_REMOVED:\n            listener.generatorRemoved(event);\n            break;\n\n        default:\n            LOG.log(Level.SEVERE, \"Invalid event:\" + event.getEventType());\n            break;\n        }\n    }\n\n    private void handleFireEvent(ArgoEvent event, ArgoEventListener listener) {\n        if (event.getEventType() == ArgoEventTypes.ANY_EVENT) {\n            if (listener instanceof ArgoNotationEventListener) {\n                handleFireNotationEvent((ArgoNotationEvent) event,\n\t\t\t\t\t(ArgoNotationEventListener) listener);\n            }\n            if (listener instanceof ArgoHelpEventListener) {\n                handleFireHelpEvent((ArgoHelpEvent) event,\n                                        (ArgoHelpEventListener) listener);\n            }\n            if (listener instanceof ArgoStatusEventListener) {\n                handleFireStatusEvent((ArgoStatusEvent) event,\n                        (ArgoStatusEventListener) listener);\n            }\n        } else {\n            if (event.getEventType() >= ArgoEventTypes.ANY_NOTATION_EVENT\n                && event.getEventType() < ArgoEventTypes.LAST_NOTATION_EVENT) {\n                if (listener instanceof ArgoNotationEventListener) {\n                    handleFireNotationEvent((ArgoNotationEvent) event,\n\t\t\t\t\t(ArgoNotationEventListener) listener);\n                }\n            }\n            if (event.getEventType() >= ArgoEventTypes\n                            .ANY_DIAGRAM_APPEARANCE_EVENT\n                    && event.getEventType() < ArgoEventTypes\n                            .LAST_DIAGRAM_APPEARANCE_EVENT) {\n                if (listener instanceof ArgoDiagramAppearanceEventListener) {\n                    handleFireDiagramAppearanceEvent(\n                            (ArgoDiagramAppearanceEvent) event,\n                            (ArgoDiagramAppearanceEventListener) listener);\n                }\n            }\n            if (event.getEventType() >= ArgoEventTypes.ANY_HELP_EVENT\n                    && event.getEventType() < ArgoEventTypes.LAST_HELP_EVENT) {\n                if (listener instanceof ArgoHelpEventListener) {\n                    handleFireHelpEvent((ArgoHelpEvent) event,\n                            (ArgoHelpEventListener) listener);\n                }\n            }\n            if (event.getEventType() >= ArgoEventTypes.ANY_GENERATOR_EVENT\n                && event.getEventType() < ArgoEventTypes.LAST_GENERATOR_EVENT) {\n                if (listener instanceof ArgoGeneratorEventListener) {\n                    handleFireGeneratorEvent((ArgoGeneratorEvent) event,\n                            (ArgoGeneratorEventListener) listener);\n                }\n            }\n            if (event.getEventType() >= ArgoEventTypes.ANY_STATUS_EVENT\n                    && event.getEventType() < ArgoEventTypes\n                            .LAST_STATUS_EVENT) {\n                if (listener instanceof ArgoStatusEventListener) {\n                    handleFireStatusEvent((ArgoStatusEvent) event,\n                            (ArgoStatusEventListener) listener);\n                }\n            }\n            if (event.getEventType() >= ArgoEventTypes.ANY_PROFILE_EVENT\n                    && event.getEventType() < ArgoEventTypes\n                            .LAST_PROFILE_EVENT) {\n                if (listener instanceof ArgoProfileEventListener) {\n                    handleFireProfileEvent((ArgoProfileEvent) event,\n                            (ArgoProfileEventListener) listener);\n                }\n            }\n        }\n    }\n\n    /**\n     * @param event the event to be fired\n     */\n    public static void fireEvent(ArgoEvent event) {\n        SINGLETON.doFireEvent(event);\n    }\n\n    /**\n     * @param event the event to be fired\n     */\n    protected void doFireEvent(ArgoEvent event) {\n        if (listeners == null) {\n            return;\n        }\n\n        // Make a read-only copy of the listeners list so that reentrant calls\n        // back to add/removeListener won't mess us up.\n        // TODO: Potential performance issue, but we need the correctness - tfm\n        List<Pair> readOnlyListeners;\n        synchronized (listeners) {\n            readOnlyListeners = new ArrayList<Pair>(listeners);\n        }\n\n        for (Pair pair : readOnlyListeners) {\n            if (pair.getEventType() == ArgoEventTypes.ANY_EVENT) {\n                handleFireEvent(event, pair.getListener());\n            } else if (pair.getEventType() == event.getEventStartRange()\n                    || pair.getEventType() == event.getEventType()) {\n                handleFireEvent(event, pair.getListener());\n            }\n        }\n\n    }\n\n    /**\n     * Data structure handling listener registrations.\n     */\n    static class Pair {\n        private int eventType;\n        private ArgoEventListener listener;\n\n        /**\n         * Constructor.\n         *\n         * @param myEventType The event type.\n         * @param myListener The listener.\n         */\n        Pair(int myEventType, ArgoEventListener myListener) {\n            eventType = myEventType;\n            listener = myListener;\n        }\n\n        /**\n         * @return The event type.\n         */\n        int getEventType() {\n            return eventType;\n        }\n\n        /**\n         * @return The listener.\n         */\n        ArgoEventListener getListener() {\n            return listener;\n        }\n\n\n        @Override\n        public String toString() {\n            return \"{Pair(\" + eventType + \",\" + listener + \")}\";\n        }\n\n\n        @Override\n        public int hashCode() {\n            if (listener != null) {\n                return eventType + listener.hashCode();\n            }\n            return eventType;\n        }\n\n\n        @Override\n        public boolean equals(Object o) {\n            if (o instanceof Pair) {\n                Pair p = (Pair) o;\n                if (p.eventType == eventType && p.listener == listener) {\n                    return true;\n                }\n            }\n            return false;\n        }\n    }\n}\n", "human_rating": 4.000000000031203, "metadata": {"project": "argoUML", "class": "org.argouml.application.events.ArgoEventPump", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/application/events/ArgoEventPump.java", "label_probabilities": {"readability": [1.0, 1.04008e-11, 0.0, 0.0], "understandability": [3.26325e-08, 1.0, 0.0, 0.0], "complexity": [1.41e-18, 1.0, 0.0, 0.0], "modularization": [0.0, 1.2e-19, 0.253971, 0.746029], "overall": [0.00854576, 0.991454, 1.03802e-14, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.cognitive.ui.PriorityNode", "source": "/* $Id: PriorityNode.java 17818 2010-01-12 18:39:46Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.cognitive.ui;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.argouml.cognitive.ToDoItem;\nimport org.argouml.cognitive.Translator;\n\n/**\n * This class represents a \"priority\". Which is a classification for critics.\n *\n */\npublic class PriorityNode {\n\n    private static final String HIGH = \n        Translator.localize(\"misc.level.high\");\n\n    private static final String MEDIUM = \n        Translator.localize(\"misc.level.medium\");\n\n    private static final String LOW =\n        Translator.localize(\"misc.level.low\");\n\n    private static List<PriorityNode> priorities = null;\n\n    private String name;\n\n    private int priority;\n\n    /**\n     * The constructor.\n     *\n     * @param n the name of this priority\n     * @param pri the priority number\n     */\n    public PriorityNode(String n, int pri) {\n\tname = n;\n\tpriority = pri;\n    }\n\n\n    /**\n     * @return the list of all the priorities\n     */\n    public static List<PriorityNode> getPriorityList() {\n        if (priorities == null) {\n            List<PriorityNode> p =  new ArrayList<PriorityNode>();\n            p.add(new PriorityNode(HIGH,\n                    ToDoItem.HIGH_PRIORITY));\n            p.add(new PriorityNode(MEDIUM,\n                    ToDoItem.MED_PRIORITY));\n            p.add(new PriorityNode(LOW,\n                    ToDoItem.LOW_PRIORITY));\n            /* Correct lazy initialization of static field \n             * without further updates: */\n            priorities = p;\n        }\n        return priorities;\n    }\n\n\n    /**\n     * @return the name\n     */\n    public String getName() {\n        return name;\n    }\n\n    /**\n     * @return the priority\n     */\n    public int getPriority() {\n        return priority;\n    }\n\n    /*\n     * @see java.lang.Object#toString()\n     */\n    @Override\n    public String toString() {\n        return getName();\n    }\n\n}\n", "human_rating": 3.449731753198, "metadata": {"project": "argoUML", "class": "org.argouml.cognitive.ui.PriorityNode", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/cognitive/ui/PriorityNode.java", "label_probabilities": {"readability": [0.451338, 0.547055, 0.00160728, 1.93198e-07], "understandability": [0.952804, 0.0471939, 1.75681e-06, 1.34915e-11], "complexity": [5.09599e-12, 1.00485e-05, 0.0691067, 0.930883], "modularization": [0.0, 3.02134e-11, 0.0140928, 0.985907], "overall": [0.993417, 0.00658346, 7.92256e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.cognitive.ui.ToDoByType", "source": "/* $Id: ToDoByType.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.cognitive.ui;\n\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.argouml.cognitive.Designer;\nimport org.argouml.cognitive.ToDoItem;\nimport org.argouml.cognitive.ToDoListEvent;\nimport org.argouml.cognitive.ToDoListListener;\n\n/**\n * Represents a perspective for ToDo items: grouping by type.\n *\n */\npublic class ToDoByType extends ToDoPerspective\n    implements ToDoListListener {\n    private static final Logger LOG =\n        Logger.getLogger(ToDoByType.class.getName());\n\n    /**\n     * The constructor.\n     *\n     */\n    public ToDoByType() {\n\tsuper(\"combobox.todo-perspective-type\");\n\taddSubTreeModel(new GoListToTypeToItem());\n    }\n\n\n    ////////////////////////////////////////////////////////////////\n    // ToDoListListener implementation\n\n    /*\n     * @see org.argouml.cognitive.ToDoListListener#toDoItemsChanged(org.argouml.cognitive.ToDoListEvent)\n     */\n    public void toDoItemsChanged(ToDoListEvent tde) {\n        LOG.log(Level.FINE, \"toDoItemsChanged\");\n        List<ToDoItem> items = tde.getToDoItemList();\n\tObject[] path = new Object[2];\n\tpath[0] = Designer.theDesigner().getToDoList();\n\n        for (KnowledgeTypeNode ktn : KnowledgeTypeNode.getTypeList()) {\n\t    String kt = ktn.getName();\n\t    path[1] = ktn;\n\t    int nMatchingItems = 0;\n            for (ToDoItem item : items) {\n\t\tif (!item.containsKnowledgeType(kt)) {\n                    continue;\n                }\n\t\tnMatchingItems++;\n\t    }\n\t    if (nMatchingItems == 0) {\n                continue;\n            }\n\t    int[] childIndices = new int[nMatchingItems];\n\t    Object[] children = new Object[nMatchingItems];\n\t    nMatchingItems = 0;\n            for (ToDoItem item : items) {\n\t\tif (!item.containsKnowledgeType(kt)) {\n                    continue;\n                }\n\t\tchildIndices[nMatchingItems] = getIndexOfChild(ktn, item);\n\t\tchildren[nMatchingItems] = item;\n\t\tnMatchingItems++;\n\t    }\n\t    fireTreeNodesChanged(this, path, childIndices, children);\n\t}\n    }\n\n    /*\n     * @see org.argouml.cognitive.ToDoListListener#toDoItemsAdded(org.argouml.cognitive.ToDoListEvent)\n     */\n    public void toDoItemsAdded(ToDoListEvent tde) {\n        LOG.log(Level.FINE, \"toDoItemAdded\");\n        List<ToDoItem> items = tde.getToDoItemList();\n\tObject[] path = new Object[2];\n\tpath[0] = Designer.theDesigner().getToDoList();\n\n        for (KnowledgeTypeNode ktn : KnowledgeTypeNode.getTypeList()) {\n\t    String kt = ktn.getName();\n\t    path[1] = ktn;\n\t    int nMatchingItems = 0;\n            for (ToDoItem item : items) {\n\t\tif (!item.containsKnowledgeType(kt)) {\n                    continue;\n                }\n\t\tnMatchingItems++;\n\t    }\n\t    if (nMatchingItems == 0) {\n                continue;\n            }\n\t    int[] childIndices = new int[nMatchingItems];\n\t    Object[] children = new Object[nMatchingItems];\n\t    nMatchingItems = 0;\n            for (ToDoItem item : items) {\n\t\tif (!item.containsKnowledgeType(kt)) {\n                    continue;\n                }\n\t\tchildIndices[nMatchingItems] = getIndexOfChild(ktn, item);\n\t\tchildren[nMatchingItems] = item;\n\t\tnMatchingItems++;\n\t    }\n\t    fireTreeNodesInserted(this, path, childIndices, children);\n\t}\n    }\n\n    /*\n     * @see org.argouml.cognitive.ToDoListListener#toDoItemsRemoved(org.argouml.cognitive.ToDoListEvent)\n     */\n    public void toDoItemsRemoved(ToDoListEvent tde) {\n        LOG.log(Level.FINE, \"toDoItemRemoved\");\n        List<ToDoItem> items = tde.getToDoItemList();\n\tObject[] path = new Object[2];\n\tpath[0] = Designer.theDesigner().getToDoList();\n\n        for (KnowledgeTypeNode ktn : KnowledgeTypeNode.getTypeList()) {\n\t    boolean anyInKT = false;\n\t    String kt = ktn.getName();\n            for (ToDoItem item : items) {\n\t\tif (item.containsKnowledgeType(kt)) {\n                    anyInKT = true;\n                }\n\t    }\n\t    if (!anyInKT) {\n                continue;\n            }\n            LOG.log(Level.FINE, \"toDoItemRemoved updating PriorityNode\");\n\t    path[1] = ktn;\n\t    //fireTreeNodesChanged(this, path, childIndices, children);\n\t    fireTreeStructureChanged(path);\n\t}\n    }\n\n    /*\n     * @see org.argouml.cognitive.ToDoListListener#toDoListChanged(org.argouml.cognitive.ToDoListEvent)\n     */\n    public void toDoListChanged(ToDoListEvent tde) { }\n\n}\n", "human_rating": 2.1077981152099317, "metadata": {"project": "argoUML", "class": "org.argouml.cognitive.ui.ToDoByType", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/cognitive/ui/ToDoByType.java", "label_probabilities": {"readability": [3.02483e-10, 0.107828, 0.892142, 3.0114e-05], "understandability": [4.99807e-07, 0.209156, 0.780232, 0.010612], "complexity": [8.32469e-13, 0.0213792, 0.978618, 2.54479e-06], "modularization": [0.00017693, 0.700924, 0.298899, 4.31073e-09], "overall": [1.14533e-12, 0.00502143, 0.974591, 0.0203876]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.cognitive.UnresolvableException", "source": "/* $Id: UnresolvableException.java 17813 2010-01-12 18:33:21Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.cognitive;\n\n/**\n * Thrown to indicate a failure to resolve a critic.\n */\npublic class UnresolvableException extends Exception\n{\n    /**\n     * Creates a new UnresolvableException with message msg.\n     *\n     * @param\tmsg\tA message describing what caused the exception.\n     */\n    public UnresolvableException(String msg)\n    {\n\tsuper(msg);\n    }\n}\n\n", "human_rating": 3.9082239103467358, "metadata": {"project": "argoUML", "class": "org.argouml.cognitive.UnresolvableException", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/cognitive/UnresolvableException.java", "label_probabilities": {"readability": [0.908249, 0.0917257, 2.54051e-05, 1.46736e-10], "understandability": [0.958839, 0.0411602, 7.4424e-07, 1.67293e-14], "complexity": [1.14206e-12, 2.11612e-06, 0.0338668, 0.966131], "modularization": [0.0, 2.33187e-10, 0.0263247, 0.973675], "overall": [0.992887, 0.007113, 1.14254e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.EnumerationListModel", "source": "/* $Id: EnumerationListModel.java 17896 2010-01-12 21:36:11Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport org.argouml.model.Model;\n\n/**\n * The list model for the enumeration of a literal.\n *\n * @author mvw@tigris.org\n */\nclass EnumerationListModel extends UMLModelElementListModel {\n\n    /**\n     * Constructor for EnumerationListModel.\n     */\n    public EnumerationListModel(Object target, String propertyName) {\n        super(propertyName);\n        setTarget(target);\n    }\n\n    @Override\n    protected void buildModelList() {\n        addElement(Model.getFacade().getEnumeration(getTarget()));\n    }\n\n    @Override\n    protected boolean isValidElement(Object element) {\n        return Model.getFacade().isAEnumeration(element);\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.EnumerationListModel", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/EnumerationListModel.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.LabelledLayout", "source": "/* $Id: LabelledLayout.java 17896 2010-01-12 21:36:11Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2008-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport java.awt.Component;\nimport java.awt.Container;\nimport java.awt.Dimension;\nimport java.awt.Insets;\nimport java.awt.LayoutManager;\nimport java.util.ArrayList;\nimport javax.swing.JComboBox;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.UIManager;\n\n/**\n * This layout manager lines up components in 2 columns. All JLabels\n * are the first column and any component the JLabel is registered\n * with is in a second column next to the label. <p>\n *\n * Components are sized automatically to fill available space in the container\n * when it is resized. <p>\n * \n * All JLabel widths will be the largest of the JLabel preferred widths (unless\n * the container is too narrow). <p>\n * \n * The components will take up any left over width unless they are\n * restricted themselves by a maximum width. <p>\n * \n * The height of each component is either fixed or will resize to use up any\n * available space in the container. Whether a components height is resizable\n * is determined by checking whether the preferred height of that component is\n * greater then its minimum height. This is the case for components such as\n * JList which would require to expand to show the maximum number or items. <p>\n * \n * If a component is not to have its height resized then its preferred\n * height and minimum height should be the same. This is the case for\n * components such as JTextField and JComboBox* which should always stay the\n * same height. <p>\n * \n * [There is known bug in JRE5 where the prefered height and minimum height of\n * a JComboBox can differ. LabelledLayout has coded a workaround for this bug.\n * See - http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6255154 ] <p>\n * \n * LabelledLayout can show multiple panels of label/component\n * pairs. The seperation of these panels is indicated by adding a\n * Seperator component to the container. Labelled layout starts\n * a new panel when detecting this Seperator. <p>\n * \n * When there are multiple panels, each panel is given equal width.\n * The width restriction of JLabels and components described above are then\n * dependent on panel width rather than container width.\n *\n * @author Bob Tarling\n */\nclass LabelledLayout implements LayoutManager, java.io.Serializable {\n\n    /**\n     * The class uid\n     */\n    private static final long serialVersionUID = -5596655602155151443L;\n\n    /**\n     * This is the horizontal gap (in pixels) which specifies the space\n     * between sections.  They can be changed at any time.\n     * This should be a non negative integer.\n     *\n     * @serial\n     * @see #getHgap()\n     * @see #setHgap(int)\n     */\n    private int hgap;\n    \n    /**\n     * This is the vertical gap (in pixels) which specifies the space\n     * between rows.  They can be changed at any time.\n     * This should be a non negative integer.\n     *\n     * @serial\n     * @see #getVgap()\n     * @see #setVgap(int)\n     */\n    private int vgap;\n\n    private boolean ignoreSplitters;\n\n    /**\n     * Construct a new LabelledLayout.\n     */\n    public LabelledLayout() {\n        ignoreSplitters = false;\n        hgap = 0;\n        vgap = 0;\n    }\n\n    /**\n     * Construct a new LabelledLayout.\n     */\n    public LabelledLayout(boolean ignoreSplitters) {\n        this.ignoreSplitters = ignoreSplitters;\n        this.hgap = 0;\n        this.vgap = 0;\n    }\n\n    /**\n     * Construct a new horizontal LabelledLayout with the specified\n     * cell spacing.\n     * @param hgap The horizontal gap between components\n     * @param vgap The vertical gap between components\n     */\n    public LabelledLayout(int hgap, int vgap) {\n        this.ignoreSplitters = false;\n        this.hgap = hgap;\n        this.vgap = vgap;\n    }\n\n    /** \n     * Adds the specified component with the specified name to the\n     * layout. This is included to satisfy the LayoutManager interface\n     * but is not actually used in this layout implementation.\n     *\n     * @param name the name of the component\n     * @param comp the component to be added\n     */\n    public void addLayoutComponent(String name, Component comp) {\n    }\n\n    /** \n     * Removes the specified component from\n     * the layout. This is included to satisfy the LayoutManager\n     * interface but is not actually used in this layout\n     * implementation.\n     *\n     * @param comp the component\n     */\n    public void removeLayoutComponent(Component comp) {\n    }\n\n    /**\n     * Determines the preferred size of the container argument using\n     * this labelled layout.  The preferred size is that all child\n     * components are in one section at their own preferred size with\n     * gaps and border indents.\n     */\n    public Dimension preferredLayoutSize(Container parent) {\n        synchronized (parent.getTreeLock()) {\n            final Insets insets = parent.getInsets();\n            int preferredWidth = 0;\n            int preferredHeight = 0;\n            int widestLabel = 0;\n\n            final int componentCount = parent.getComponentCount();\n            for (int i = 0; i < componentCount; ++i) {\n                Component childComp = parent.getComponent(i);\n                if (childComp.isVisible()\n                        && !(childComp instanceof Seperator)) {\n                    int childHeight = getPreferredHeight(childComp);\n                    preferredHeight += childHeight + this.vgap;\n                }\n            }\n            preferredWidth += insets.left + widestLabel + insets.right;\n            preferredHeight += insets.top + insets.bottom;\n            return new Dimension(\n                    insets.left + widestLabel + preferredWidth + insets.right,\n                    preferredHeight);\n        }\n    }\n    \n    /** \n     * Required by LayoutManager.\n     * \n     * @see java.awt.LayoutManager#minimumLayoutSize(java.awt.Container)\n     */\n    public Dimension minimumLayoutSize(Container parent) {\n        synchronized (parent.getTreeLock()) {\n            final Insets insets = parent.getInsets();\n            int minimumHeight = insets.top + insets.bottom;\n            return new Dimension(0, minimumHeight);\n        }\n    }\n\n    /**\n     * @see java.awt.LayoutManager#layoutContainer(java.awt.Container)\n     */\n    public void layoutContainer(Container parent) {\n        synchronized (parent.getTreeLock()) {\n            int sectionX = parent.getInsets().left;\n\n            final ArrayList<Component> components = new ArrayList<Component>();\n            final int sectionCount = getSectionCount(parent);\n            final int sectionWidth = getSectionWidth(parent, sectionCount);\n            int sectionNo = 0;\n            for (int i = 0; i < parent.getComponentCount(); ++i) {\n                final Component childComp = parent.getComponent(i);\n                if (childComp instanceof Seperator) {\n                    if (!this.ignoreSplitters) {\n                        layoutSection(\n                                parent, \n                                sectionX, \n                                sectionWidth, \n                                components, \n                                sectionNo++);\n                        sectionX += sectionWidth + this.hgap;\n                        components.clear();\n                    }\n                } else {\n                    components.add(parent.getComponent(i));\n                }\n            }\n            layoutSection(\n                    parent, \n                    sectionX, \n                    sectionWidth, \n                    components, \n                    sectionNo);\n        }\n    }\n\n    /** Determine the number of sections.  There is only ever one\n     * section if oriented vertically.  If oriented horizontally the\n     * number of sections is deduced from the number of Splitters in\n     * the parent container.\n     */\n    private int getSectionCount(Container parent) {\n        int sectionCount = 1;\n        final int componentCount = parent.getComponentCount();\n        if (!ignoreSplitters) {\n            for (int i = 0; i < componentCount; ++i) {\n                if (parent.getComponent(i) instanceof Seperator) {\n                    ++sectionCount;\n                }\n            }\n        }\n        return sectionCount;\n    }\n    \n    /**\n     * Determine the width of each section from the section count.\n     * This is the working width minus the gaps between sections. This\n     * result is then divided equally by the section count.\n     */\n    private int getSectionWidth(Container parent, int sectionCount) {\n        return (getUsableWidth(parent) - (sectionCount - 1) * this.hgap)\n                / sectionCount;\n    }\n\n    /**\n     * Determine the usable width of the parent.\n     * This is the full width minus any borders.\n     */\n    private int getUsableWidth(Container parent) {\n        final Insets insets = parent.getInsets();\n        return parent.getWidth() - (insets.left + insets.right);\n    }\n    \n    /**\n     * Layout a single section\n     */\n    private void layoutSection(\n            final Container parent,\n            final int sectionX,\n            final int sectionWidth,\n            final ArrayList components,\n            final int sectionNo) {\n        final ArrayList<Integer> rowHeights = new ArrayList<Integer>();\n\n        final int componentCount = components.size();\n        if (componentCount == 0) {\n            return;\n        }\n\n        int labelWidth = 0;\n        int unknownHeightCount = 0;\n        int totalHeight = 0;\n\n        // Build up an array list of the heights of each label/component pair.\n        // Heights of zero indicate a proportional height.\n        for (int i = 0; i < componentCount; ++i) {\n            final Component childComp = (Component) components.get(i);\n            if (childComp instanceof LabelledComponent) {\n                LabelledComponent lc = (LabelledComponent) childComp;\n                final JLabel label = lc.getLabel();\n                if (label != null) {\n                    if (label.getMinimumSize().width > labelWidth) {\n                        labelWidth = label.getMinimumSize().width;\n                    }\n                }\n            }\n            final int childHeight = getChildHeight(childComp);\n            if (childHeight == 0) {\n                ++unknownHeightCount;\n            }\n            \n            totalHeight += childHeight + this.vgap;\n            rowHeights.add(new Integer(childHeight));\n        }\n        totalHeight -= this.vgap;\n        \n        final Insets insets = parent.getInsets();\n        final int parentHeight = \n            parent.getHeight() - (insets.top + insets.bottom);\n        // Set the child components to the heights in the array list\n        // calculating the height of any proportional component on the\n        // fly.\n        int y = insets.top;\n        int row = 0;\n        for (int i = 0; i < componentCount; ++i) {\n            Component childComp = (Component) components.get(i);\n            if (childComp.isVisible()) {\n                if (childComp instanceof LabelledComponent) {\n                    final LabelledComponent lc = (LabelledComponent) childComp;\n                    final JLabel label = lc.getLabel();\n                    if (label != null) {\n                        label.setPreferredSize(\n                                new Dimension(\n                                        labelWidth,\n                                        label.getPreferredSize().height));\n                    }\n                }\n                int rowHeight;\n                int componentWidth = sectionWidth;\n                int componentX = sectionX;\n                // If the component is a JLabel which has another\n                // component assigned then position/size the label and\n                // calculate the size of the registered component\n                rowHeight = rowHeights.get(row).intValue();\n                if (rowHeight == 0) {\n                    try {\n                        rowHeight = calculateHeight(\n                                parentHeight, \n                                totalHeight, \n                                unknownHeightCount--, \n                                childComp);\n                    } catch (ArithmeticException e) {\n                        final String lookAndFeel = \n                            UIManager.getLookAndFeel().getClass().getName();\n                        throw new IllegalStateException(\n                                \"Division by zero laying out \"\n                                + childComp.getClass().getName()\n                                + \" on \" + parent.getClass().getName()\n                                + \" in section \" + sectionNo\n                                + \" using \"\n                                + lookAndFeel,\n                                e);\n                    }\n                    totalHeight += rowHeight;\n                }\n                // Make sure the component width isn't any greater\n                // than its maximum allowed width\n                if (childComp.getMaximumSize() != null\n                        && getMaximumWidth(childComp) < componentWidth) {\n                    componentWidth = getMaximumWidth(childComp);\n                }\n                childComp.setBounds(componentX, y, componentWidth, rowHeight);\n                y += rowHeight + this.vgap;\n                ++row;\n            }\n        }\n    }\n    \n    /**\n     * @param childComp a component\n     * @return 0 for a resizable component or a positive value for its fixed\n     * height\n     */\n    private int getChildHeight(Component childComp) {\n        if (isResizable(childComp)) {\n            // If the child component is resizable then\n            // we don't know it's actual size yet.\n            // It will be calculated later as a\n            // proportion of the available left over\n            // space.  For now this is flagged as zero.\n            return 0;\n        } else {\n            // If a preferred height is not given or is\n            // the same as the minimum height then fix the\n            // height of this row.\n            return getMinimumHeight(childComp);\n        }\n    }\n\n    /**\n     * A component is resizable if its minimum size is less than\n     * its preferred size.\n     * There is a workaround here for a bug introduced in JRE5\n     * where JComboBox minimum and preferred size now differ.\n     * JComboBox is not resizable.\n     * Anything in a JScrollPane is considered resizable\n     * @param comp the component to check for resizability.\n     * @return true if the given component should be resized to take u[p empty\n     * space.\n     */\n    private boolean isResizable(Component comp) {\n        if (comp == null) {\n            return false;\n        }\n        if (comp instanceof JComboBox) {\n            return false;\n        }\n        if (comp.getPreferredSize() == null) {\n            return false;\n        }\n        if (comp.getMinimumSize() == null) {\n            return false;\n        }\n        return (getMinimumHeight(comp) < getPreferredHeight(comp));\n    }\n\n    private final int calculateHeight(\n            final int parentHeight, \n            final int totalHeight,\n            final int unknownHeightsLeft, \n            final Component childComp) {\n        return Math.max(\n                (parentHeight - totalHeight) / unknownHeightsLeft,\n                getMinimumHeight(childComp));\n    }\n    \n    private int getPreferredHeight(final Component comp) {\n        return (int) comp.getPreferredSize().getHeight();\n    }\n    \n    private int getPreferredWidth(final Component comp) {\n        return (int) comp.getPreferredSize().getWidth();\n    }\n\n    private int getMinimumHeight(final Component comp) {\n        return (int) comp.getMinimumSize().getHeight();\n    }\n    \n    private int getMaximumWidth(final Component comp) {\n        return (int) comp.getMaximumSize().getWidth();\n    }\n    \n    /**\n     * Create a new instance of the Separator that splits the layout in columns\n     * @return the separator\n     */\n    public static Seperator getSeparator() {\n        return new Seperator();\n    }\n\n    /**\n     * @return the horizontal gaps between components\n     */\n    public int getHgap() {\n        return this.hgap;\n    }\n\n    /**\n     * Set the horizontal gaps between components\n     * @param hgap the horizontal gap\n     */\n    public void setHgap(int hgap) {\n        this.hgap = hgap;\n    }\n\n    /**\n     * @return the vertical gaps between components\n     */\n    public int getVgap() {\n        return this.vgap;\n    }\n\n    /**\n     * Set the vertical gaps between components\n     * @param vgap the horizontal gap\n     */\n    public void setVgap(int vgap) {\n        this.vgap = vgap;\n    }\n}\n\nclass Seperator extends JPanel {\n    \n    private static final long serialVersionUID = -4143634500959911688L;\n\n    Seperator() {\n        super.setVisible(false);\n    }\n}\n", "human_rating": 2.8956598596300003, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.LabelledLayout", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/LabelledLayout.java", "label_probabilities": {"readability": [2.3451e-06, 0.895663, 0.104327, 7.47923e-06], "understandability": [6.70177e-06, 0.548659, 0.426607, 0.0247276], "complexity": [0.0348354, 0.900313, 0.0648513, 6.05533e-07], "modularization": [0.0264967, 0.755517, 0.217957, 2.86141e-05], "overall": [1.6717e-10, 0.522658, 0.477342, 9.50927e-08]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.UMLDiscriminatorNameDocument", "source": "/* $Id: UMLDiscriminatorNameDocument.java 17896 2010-01-12 21:36:11Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport org.argouml.model.Model;\n\n/**\n * The document that is edited in the discriminator field of a generalization.\n *\n * @since Oct 10, 2002\n * @author jaap.branderhorst@xs4all.nl\n */\nclass UMLDiscriminatorNameDocument extends UMLPlainTextDocument {\n\n    /**\n     * The class uid\n     */\n    private static final long serialVersionUID = -9181779607372279972L;\n\n    /**\n     * Constructor for UMLModelElementNameDocument.\n     */\n    public UMLDiscriminatorNameDocument(\n            final String propertyName, \n            final Object target) {\n        super(propertyName, target);\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLPlainTextDocument#setProperty(java.lang.String)\n     */\n    protected void setProperty(String text) {\n        Model.getCoreHelper().setDiscriminator(getTarget(), text);\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLPlainTextDocument#getProperty()\n     */\n    protected String getProperty() {\n        return (String) Model.getFacade().getDiscriminator(getTarget());\n    }\n\n}\n", "human_rating": 3.90988374897, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.UMLDiscriminatorNameDocument", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/UMLDiscriminatorNameDocument.java", "label_probabilities": {"readability": [0.909891, 0.090104, 3.24958e-06, 1.24981e-06], "understandability": [0.952804, 0.0471939, 1.75681e-06, 1.34915e-11], "complexity": [0.0, 1.9923e-14, 0.00453665, 0.995463], "modularization": [0.0, 3.02134e-11, 0.0140928, 0.985907], "overall": [0.993417, 0.00658346, 7.92256e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.UMLExpressionPanel", "source": "/* $Id: UMLExpressionPanel.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *    Thomas Neustupny\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2008-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.JPanel;\nimport javax.swing.JScrollPane;\nimport javax.swing.border.TitledBorder;\nimport javax.swing.event.ChangeEvent;\nimport javax.swing.event.ChangeListener;\n\nimport org.tigris.swidgets.LabelledLayout;\n\n\n/**\n * The panel that shows an Expression for an other UML element.\n * There are 8 kinds of Expressions defined in the UML 1.4.2.\n *\n * @author penyaskito\n */\nclass UMLExpressionPanel extends JPanel\n\timplements ChangeListener {\n\n    private static final Logger LOG =\n        Logger.getLogger(UMLExpressionPanel.class.getName());\n\n    private final UMLExpressionModel model;\n    private final UMLExpressionLanguageField languageField;\n    private final UMLExpressionBodyField bodyField;\n\n    public UMLExpressionPanel(UMLExpressionModel model, String title) {\n\n        super(new LabelledLayout());\n        LOG.log(Level.FINE, \">>New Expression panel created\");\n\n        TitledBorder border = new TitledBorder(title);\n        this.setBorder(border);\n\n        this.model = model;\n        this.languageField = new UMLExpressionLanguageField(model,\n                false);\n        this.bodyField = new UMLExpressionBodyField(\n                model, true);\n\n        boolean isReadOnly = !languageField.isEditable();\n        if (isReadOnly) {\n            bodyField.setEditable(false);\n        } else {\n            add(languageField);\n        }\n        add(new JScrollPane(bodyField));\n\n        model.addChangeListener(this);\n    }\n\n    @Override\n    public void removeNotify() {\n\tmodel.removeChangeListener(this);\n\tsuper.removeNotify();\n    }\n\n    public void stateChanged(ChangeEvent e) {\n        LOG.log(Level.FINE, \">>Values shown on panel are changed\");\n\tbodyField.update();\n\tlanguageField.update();\n    }\n}\n", "human_rating": 3.9305142124, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.UMLExpressionPanel", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/UMLExpressionPanel.java", "label_probabilities": {"readability": [0.930529, 0.0694565, 1.43562e-05, 0.0], "understandability": [0.90414, 0.09586, 5.30072e-08, 0.0], "complexity": [0.0, 1.34765e-10, 0.0548876, 0.945112], "modularization": [0.0, 0.0221371, 0.583714, 0.394149], "overall": [0.985931, 0.0140686, 8.42778e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.UMLIncludeBaseListModel", "source": "/* $Id: UMLIncludeBaseListModel.java 17896 2010-01-12 21:36:11Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport org.argouml.model.Model;\n\n/**\n * List model to hold use cases of an includes bases.\n * \n * @author MarkusK\n */\nclass UMLIncludeBaseListModel extends UMLIncludeListModel {\n\n    /**\n     * Constructor for UMLIncludeBaseListModel.\n     */\n    public UMLIncludeBaseListModel() {\n        super(\"base\");\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLModelElementListModel2#buildModelList()\n     */\n    protected void buildModelList() {\n        super.buildModelList();\n        addElement(Model.getFacade().getBase(getTarget()));\n    }\n}\n", "human_rating": 3.9000431234099997, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.UMLIncludeBaseListModel", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/UMLIncludeBaseListModel.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.UMLMessageActivatorComboBoxModel", "source": "/* $Id: UMLMessageActivatorComboBoxModel.java 18691 2010-08-28 00:41:40Z bobtarling $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport javax.swing.Action;\n\nimport org.argouml.model.Model;\n\n/**\n * The model behind the UMLMessageActivatorComboBox.\n */\nclass UMLMessageActivatorComboBoxModel extends UMLComboBoxModel {\n\n    /**\n     * The class uid\n     */\n    private static final long serialVersionUID = 5785236557511670953L;\n    \n    private Object interaction = null;\n\n    /**\n     * Constructor for UMLMessageActivatorComboBoxModel.\n     */\n    public UMLMessageActivatorComboBoxModel(\n            final String propertyName,\n            final Object target) {\n        super(target, propertyName, false);\n        if (Model.getFacade().isAMessage(target)) {\n            interaction = Model.getFacade().getInteraction(target);\n            if (interaction != null) {\n                Model.getPump().addModelEventListener(\n                    this,\n                    interaction,\n                    \"message\");\n            }\n        }\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel#buildModelList()\n     */\n    protected void buildModelList() {\n        Object target = getTarget();\n        if (Model.getFacade().isAMessage(target)) {\n            Object mes = target;\n            removeAllElements();\n            // fill the list with items\n            setElements(Model.getCollaborationsHelper()\n                    .getAllPossibleActivators(mes));\n        }\n    }\n\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel#isValidElement(Object)\n     */\n    protected boolean isValidElement(Object m) {\n        return ((Model.getFacade().isAMessage(m))\n                && m != getTarget()\n                && !Model.getFacade().getPredecessors((getTarget())).contains(m)\n                && Model.getFacade().getInteraction(m)\n                    == Model.getFacade().getInteraction((getTarget())));\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel#getSelectedModelElement()\n     */\n    protected Object getSelectedModelElement() {\n        if (getTarget() != null) {\n            return Model.getFacade().getActivator(getTarget());\n        }\n        return null;\n    }\n    \n    public Action getAction() {\n        return null;\n    }\n}\n\n", "human_rating": 3.6602051729099996, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.UMLMessageActivatorComboBoxModel", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/UMLMessageActivatorComboBoxModel.java", "label_probabilities": {"readability": [0.660229, 0.339753, 1.24548e-05, 5.26331e-06], "understandability": [0.0175904, 0.921934, 0.0604722, 3.00636e-06], "complexity": [0.000160653, 0.0448081, 0.925749, 0.0292827], "modularization": [0.0, 2.22454e-10, 0.0464159, 0.953584], "overall": [0.0240528, 0.975938, 8.91338e-06, 2e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.UMLModelElementSourceFlowListModel", "source": "/* $Id: UMLModelElementSourceFlowListModel.java 19904 2012-12-27 00:46:17Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2002-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport org.argouml.model.Model;\n\n/**\n * @since Oct 12, 2002\n * @author jaap.branderhorst@xs4all.nl\n */\nclass UMLModelElementSourceFlowListModel\n    extends UMLModelElementListModel {\n\n    /**\n     * Constructor for UMLModelElementSourceFlowListModel.\n     */\n    public UMLModelElementSourceFlowListModel() {\n        super(\"sourceFlow\");\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLModelElementListModel2#buildModelList()\n     */\n    protected void buildModelList() {\n        if (getTarget() != null) {\n\t    setAllElements(Model.getFacade().getSourceFlows(getTarget()));\n        }\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLModelElementListModel2#isValidElement(Object)\n     */\n    protected boolean isValidElement(Object o) {\n        return Model.getFacade().isAFlow(o)\n            && Model.getFacade().getSourceFlows(getTarget()).contains(o);\n    }\n\n}\n", "human_rating": 3.8707873388799996, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.UMLModelElementSourceFlowListModel", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/UMLModelElementSourceFlowListModel.java", "label_probabilities": {"readability": [0.870871, 0.129047, 8.0319e-05, 1.70088e-06], "understandability": [0.931635, 0.0683612, 3.47957e-06, 1.74392e-10], "complexity": [3.29649e-12, 3.50398e-06, 0.0360278, 0.963969], "modularization": [0.0, 2.63917e-10, 0.0263247, 0.973675], "overall": [0.988667, 0.0113334, 2.46646e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.UMLOFSStateListModel", "source": "/* $Id: UMLOFSStateListModel.java 17896 2010-01-12 21:36:11Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport java.awt.event.ActionEvent;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.Model;\nimport org.argouml.uml.ui.AbstractActionAddModelElement2;\nimport org.argouml.uml.ui.AbstractActionRemoveElement;\n\n/**\n * @author mkl\n */\nclass UMLOFSStateListModel extends UMLModelElementListModel {\n\n    /**\n     * The class uid\n     */\n    private static final long serialVersionUID = -9214579555300746872L;\n\n    /**\n     * Constructor for UMLOFSStateListModel.\n     */\n    public UMLOFSStateListModel(Object modelElement) {\n        /* TODO: This needs work...\n         * We also need to listen to addition/removal\n         * of states to/from a ClassifierInState.\n         */\n        super(\"type\", modelElement.getClass(),\n            new ActionAddOFSState(),\n            new ActionRemoveOFSState());\n        setTarget(modelElement);\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLModelElementListModel2#buildModelList()\n     */\n    protected void buildModelList() {\n        if (getTarget() != null) {\n            Object classifier = Model.getFacade().getType(getTarget());\n            if (Model.getFacade().isAClassifierInState(classifier)) {\n                Collection c = Model.getFacade().getInStates(classifier);\n                setAllElements(c);\n            }\n        }\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLModelElementListModel2#isValidElement(java.lang.Object)\n     */\n    protected boolean isValidElement(Object elem) {\n        Object t = getTarget();\n        if (Model.getFacade().isAState(elem)\n                && Model.getFacade().isAObjectFlowState(t)) {\n            Object type = Model.getFacade().getType(t);\n            if (Model.getFacade().isAClassifierInState(type)) {\n                Collection c = Model.getFacade().getInStates(type);\n                if (c.contains(elem)) {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n    \n    /**\n     * @author mkl\n     */\n    private static class ActionAddOFSState extends AbstractActionAddModelElement2 {\n        private Object choiceClass = Model.getMetaTypes().getState();\n\n\n        /**\n         * The constructor.\n         */\n        public ActionAddOFSState() {\n            super();\n            setMultiSelect(true);\n        }\n\n\n        protected void doIt(Collection selected) {\n            Object t = getTarget();\n            if (Model.getFacade().isAObjectFlowState(t)) {\n                Object type = Model.getFacade().getType(t);\n                if (Model.getFacade().isAClassifierInState(type)) {\n                    Model.getActivityGraphsHelper().setInStates(type, selected);\n                } else if (Model.getFacade().isAClassifier(type)\n                        && (selected != null)\n                        && (selected.size() > 0)) {\n                    /* So, we found a Classifier\n                     * that is not a ClassifierInState.\n                     * And at least one state has been selected.\n                     * Well, let's correct that:\n                     */\n                    Object cis =\n                        Model.getActivityGraphsFactory()\n                            .buildClassifierInState(type, selected);\n                    Model.getCoreHelper().setType(t, cis);\n                }\n            }\n        }\n\n\n        protected List getChoices() {\n            List ret = new ArrayList();\n            Object t = getTarget();\n            if (Model.getFacade().isAObjectFlowState(t)) {\n                Object classifier = getType(t);\n                if (Model.getFacade().isAClassifier(classifier)) {\n                    ret.addAll(Model.getModelManagementHelper()\n                            .getAllModelElementsOfKindWithModel(classifier,\n                                    choiceClass));\n                }\n                removeTopStateFrom(ret);\n            }\n            return ret;\n        }\n\n\n        protected String getDialogTitle() {\n            return Translator.localize(\"dialog.title.add-state\");\n        }\n\n\n        protected List getSelected() {\n            Object t = getTarget();\n            if (Model.getFacade().isAObjectFlowState(t)) {\n                Object type = Model.getFacade().getType(t);\n                if (Model.getFacade().isAClassifierInState(type)) {\n                    return new ArrayList(Model.getFacade().getInStates(type));\n                }\n            }\n            return new ArrayList();\n        }\n        \n        private static Object getType(Object target) {\n            Object type = Model.getFacade().getType(target);\n            if (Model.getFacade().isAClassifierInState(type)) {\n                type = Model.getFacade().getType(type);\n            }\n            return type;\n        }\n        /**\n         * Utility function to remove the top states\n         * from a given collection of states.\n         *\n         * @param ret a collection of states\n         */\n        static void removeTopStateFrom(Collection ret) {\n            Collection tops = new ArrayList();\n            for (Object state : ret) {\n                if (Model.getFacade().isACompositeState(state)\n                        && Model.getFacade().isTop(state)) {\n                    tops.add(state);\n                }\n            }\n            ret.removeAll(tops);\n        }\n    }\n    \n    /**\n     * @author mkl\n     */\n    private static class ActionRemoveOFSState extends AbstractActionRemoveElement {\n\n        /**\n         * The class uid\n         */\n        private static final long serialVersionUID = 4745674604611374936L;\n\n        /**\n         * Constructor.\n         */\n        public ActionRemoveOFSState() {\n            super(Translator.localize(\"menu.popup.remove\"));\n        }\n\n        @Override\n        public void actionPerformed(ActionEvent e) {\n            super.actionPerformed(e);\n            Object state = getObjectToRemove();\n            if (state != null) {\n                Object t = getTarget();\n                if (Model.getFacade().isAObjectFlowState(t)) {\n                    Object type = Model.getFacade().getType(t);\n                    if (Model.getFacade().isAClassifierInState(type)) {\n                        Collection states =\n                            new ArrayList(\n                                Model.getFacade().getInStates(type));\n                        states.remove(state);\n                        Model.getActivityGraphsHelper()\n                                .setInStates(type, states);\n                    }\n                }\n            }\n        }\n    }\n}\n", "human_rating": 3.0162894800000783, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.UMLOFSStateListModel", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/UMLOFSStateListModel.java", "label_probabilities": {"readability": [0.0184965, 0.979296, 0.00220774, 7.79887e-14], "understandability": [0.000508959, 0.999489, 2.48152e-06, 7.01998e-14], "complexity": [4.86185e-11, 0.484136, 0.515857, 6.9754e-06], "modularization": [1.25343e-14, 0.110723, 0.841031, 0.0482467], "overall": [2.89434e-06, 0.73082, 0.269177, 5.706e-17]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.UMLSignalComboBoxModel", "source": "/* $Id: UMLSignalComboBoxModel.java 19906 2012-12-28 18:30:46Z linus $\n *****************************************************************************\n * Copyright (c) 2009-2010 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Bob Tarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport java.awt.event.ActionEvent;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\n\nimport javax.swing.Action;\n\nimport org.argouml.kernel.Project;\nimport org.argouml.kernel.ProjectManager;\nimport org.argouml.model.Model;\nimport org.argouml.model.RemoveAssociationEvent;\nimport org.argouml.model.UmlChangeEvent;\nimport org.argouml.ui.ActionCreateContainedModelElement;\nimport org.argouml.ui.UndoableAction;\n\n\n/**\n * The model for the signal combobox on the reception proppanel.\n */\npublic class UMLSignalComboBoxModel extends UMLComboBoxModel {\n\n    /**\n     * Constructor for UMLReceptionSignalComboBoxModel.\n     */\n    public UMLSignalComboBoxModel(\n        final String propertyName,\n        final Object target) {\n        super(target, propertyName, false);\n        Model.getPump().addClassModelEventListener(this,\n                Model.getMetaTypes().getNamespace(), propertyName);\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel2#buildModelList()\n     */\n    protected void buildModelList() {\n        Object target = getTarget();\n        if (Model.getFacade().isAReception(target) || Model.getFacade().isASignalEvent(target)) {\n            removeAllElements();\n            Project p = ProjectManager.getManager().getCurrentProject();\n            Object model = p.getRoot();\n            setElements(Model.getModelManagementHelper()\n                    .getAllModelElementsOfKindWithModel(\n                            model,\n                            Model.getMetaTypes().getSignal()));\n            setSelectedItem(Model.getFacade().getSignal(target));\n        } else {\n        \tthrow new IllegalStateException(\n        \t\t\t\"Expected a Reception or SignalEvent - got a \" + target);\n        }\n\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel2#isValidElement(Object)\n     */\n    protected boolean isValidElement(Object m) {\n        return Model.getFacade().isASignal(m);\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel2#getSelectedModelElement()\n     */\n    protected Object getSelectedModelElement() {\n        if (getTarget() != null) {\n            return Model.getFacade().getSignal(getTarget());\n        }\n        return null;\n    }\n\n    /**\n     * Override UMLComboBoxModel2's default handling of RemoveAssociation. We\n     * get this from MDR for the previous signal when a different signal is\n     * selected. Don't let that remove it from the combo box. Only remove it if\n     * the signal was removed from the namespace.\n     * <p>\n     * @param evt the event describing the property change\n     */\n    public void modelChanged(UmlChangeEvent evt) {\n        if (evt instanceof RemoveAssociationEvent) {\n            Object o = getChangedElement(evt);\n            if (contains(o)) {\n                if (o instanceof Collection) {\n                    removeAll((Collection) o);\n                } else {\n                    removeElement(o);\n                }\n            }\n        } else {\n            super.propertyChange(evt);\n        }\n    }\n    \n    public List<Action> getActions() {\n        final ArrayList<Action> actions = new ArrayList<Action>();\n        actions.add(new ActionCreateContainedModelElement(\n                Model.getMetaTypes().getSignal(), getTarget()));\n        return actions;\n    }\n    \n    public Action getAction() {\n        \n        return new SetAction();\n    }\n    \n    class SetAction extends UndoableAction {\n        \n        /**\n         * The class uid\n         */\n        private static final long serialVersionUID = 6281434994800778660L;\n\n        /**\n         * Constructor for ActionSetModelElementNamespace.\n         */\n        public SetAction() {\n            super();\n        }\n\n        /*\n         * @see java.awt.event.ActionListener#actionPerformed(\n         * java.awt.event.ActionEvent)\n         */\n        public void actionPerformed(ActionEvent e) {\n            Object source = e.getSource();\n            UMLComboBox box = (UMLComboBox) source;\n            Object o = getTarget();\n            o = box.getSelectedItem();\n            Object signal = o;\n            if (signal != Model.getFacade().getSignal(getTarget())) {\n                super.actionPerformed(e);\n                Model.getCommonBehaviorHelper().setSignal(getTarget(), signal);\n            }\n        }\n    }\n}\n", "human_rating": 3.9082239103467358, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.UMLSignalComboBoxModel", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/UMLSignalComboBoxModel.java", "label_probabilities": {"readability": [0.908249, 0.0917257, 2.54051e-05, 1.46736e-10], "understandability": [0.179121, 0.820582, 0.000297076, 8.43235e-10], "complexity": [5.80912e-07, 0.0125005, 0.811657, 0.175842], "modularization": [0.0, 2.26276e-05, 0.193123, 0.806855], "overall": [0.771724, 0.228276, 2.48338e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.core.propertypanels.ui.UMLTemplateParameterParameterComboBoxModel", "source": "/* $Id: UMLTemplateParameterParameterComboBoxModel.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Bob Tarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.core.propertypanels.ui;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Set;\nimport java.util.TreeSet;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.Action;\n\nimport org.argouml.kernel.Project;\nimport org.argouml.kernel.ProjectManager;\nimport org.argouml.model.Model;\nimport org.argouml.uml.util.PathComparator;\n\n/**\n * The combobox model for the parameter belonging to some TemplateParameter.\n */\nclass UMLTemplateParameterParameterComboBoxModel\n        extends UMLComboBoxModel {\n\n    /**\n     * The class uid.\n     */\n    private static final long serialVersionUID = -1295242702819038923L;\n\n    private static final Logger LOG =\n        Logger.getLogger(UMLTemplateParameterParameterComboBoxModel.class\n                         .getName());\n\n    /**\n     * Constructor for UMLStructuralFeatureTypeComboBoxModel.\n     */\n    public UMLTemplateParameterParameterComboBoxModel(Object target) {\n        super(target, \"parameter\", true); // Allow null\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel#isValidElement(Object)\n     */\n    protected boolean isValidElement(Object element) {\n        return Model.getFacade().isAModelElement(element);\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel#buildModelList()\n     */\n    @SuppressWarnings(\"unchecked\")\n    protected void buildModelList() {\n        Set<Object> elements = new TreeSet<Object>(new PathComparator());\n\n        Project p = ProjectManager.getManager().getCurrentProject();\n        if (p == null) {\n            return;\n        }\n\n        for (Object model : p.getUserDefinedModelList()) {\n            elements.addAll(Model.getModelManagementHelper()\n                    .getAllModelElementsOfKind(\n                            model, Model.getMetaTypes().getModelElement()));\n        }\n\n        elements.addAll(p.getProfileConfiguration().findByMetaType(\n                        Model.getMetaTypes().getClassifier()));\n\n        setElements(elements);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    @Override\n    protected void buildMinimalModelList() {\n        Collection list = new ArrayList(1);\n        Object element = getSelectedModelElement();\n        \n        LOG.log(Level.INFO, \"The selected element is {0}\", element);\n        \n        if (element != null) {\n            LOG.log(Level.INFO,\n                    \"The selected element is {0}\",\n                    Model.getFacade().getName(element));\n        }\n        if (element != null) {\n            list.add(element);\n        }\n        setElements(list);\n    }\n\n    @Override\n    protected boolean isLazy() {\n        return true;\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLComboBoxModel#getSelectedModelElement()\n     */\n    protected Object getSelectedModelElement() {\n        Object o = null;\n        if (getTarget() != null) {\n            o = Model.getFacade().getParameter(getTarget());\n        }\n        return o;\n    }\n\n    public Action getAction() {\n        return null;\n    }\n}\n", "human_rating": 3.2700307779999997, "metadata": {"project": "argoUML", "class": "org.argouml.core.propertypanels.ui.UMLTemplateParameterParameterComboBoxModel", "source_path": "argoUML/sourcefiles/src/argouml-core-umlpropertypanels/src/org/argouml/core/propertypanels/ui/UMLTemplateParameterParameterComboBoxModel.java", "label_probabilities": {"readability": [0.272821, 0.725711, 0.000145759, 0.00132226], "understandability": [0.0460975, 0.944291, 0.00961016, 1.44539e-06], "complexity": [5.7327e-09, 0.00100024, 0.981157, 0.0178424], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.191239, 0.808751, 9.92388e-06, 9e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.dev.UndoManagerWrapper", "source": "/* $Id: UndoManagerWrapper.java 17807 2010-01-12 18:29:32Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2006-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.dev;\n\n/**\n * By using this wrapper we are able to show the contents of the Undo stack.\n */\n//public class UndoManagerWrapper extends UndoManager {\npublic class UndoManagerWrapper {\n\n    /**\n     * The Constructor.\n     */\n    public UndoManagerWrapper() {\n    }\n\n//    /*\n//     * @see org.tigris.gef.undo.UndoManager#addMemento(org.tigris.gef.undo.Memento)\n//     */\n//    public void addMemento(Memento memento) {\n//        super.addMemento(memento);\n//        UndoLogPanel.getInstance().addMemento(memento);\n//    }\n//\n//    /**\n//     * @see org.tigris.gef.undo.UndoManager#empty()\n//     */\n//    public void empty() {\n//        super.empty();\n//        UndoLogPanel.getInstance().removeAll();\n//    }\n//\n//    /**\n//     * @see org.tigris.gef.undo.UndoManager#emptyUndo()\n//     */\n//    public void emptyUndo() {\n//        super.emptyUndo();\n//    }\n//\n//    /*\n//     * @see org.tigris.gef.undo.UndoManager#redo(org.tigris.gef.undo.Memento)\n//     */\n//    protected void redo(Memento memento) {\n//        UndoLogPanel.getInstance().addMemento(memento);\n//        super.redo(memento);\n//    }\n//\n//    /*\n//     * @see org.tigris.gef.undo.UndoManager#undo(org.tigris.gef.undo.Memento)\n//     */\n//    protected void undo(Memento memento) {\n//        UndoLogPanel.getInstance().removeMemento(memento);\n//        super.undo(memento);\n//    }\n//\n\n}\n", "human_rating": 3.2856903138, "metadata": {"project": "argoUML", "class": "org.argouml.dev.UndoManagerWrapper", "source_path": "argoUML/sourcefiles/modules/dev/src/org/argouml/dev/UndoManagerWrapper.java", "label_probabilities": {"readability": [0.285718, 0.714255, 2.66569e-05, 3.6e-19], "understandability": [0.981283, 0.0187168, 5.83081e-11, 0.0], "complexity": [0.0, 1.96715e-08, 0.0150126, 0.984987], "modularization": [0.0, 5.60188e-11, 0.0292183, 0.970782], "overall": [7.11734e-11, 0.999999, 8.72392e-07, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.gefext.ArgoFigRect", "source": "/* $Id: ArgoFigRect.java 17820 2010-01-12 18:42:20Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.gefext;\n\nimport javax.management.ListenerNotFoundException;\nimport javax.management.MBeanNotificationInfo;\nimport javax.management.Notification;\nimport javax.management.NotificationBroadcasterSupport;\nimport javax.management.NotificationEmitter;\nimport javax.management.NotificationFilter;\nimport javax.management.NotificationListener;\n\nimport org.tigris.gef.presentation.FigRect;\n\n/**\n * Primitive Fig to paint rectangles on a Diagram.\n *\n * @author Michiel\n */\npublic class ArgoFigRect extends FigRect  implements NotificationEmitter {\n\n    private NotificationBroadcasterSupport notifier = \n        new NotificationBroadcasterSupport();\n    \n    public ArgoFigRect(int x, int y, int w, int h) {\n        super(x, y, w, h);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#deleteFromModel()\n     */\n    @Override\n    public void deleteFromModel() {\n        super.deleteFromModel();\n        firePropChange(\"remove\", null, null);\n        notifier.sendNotification(new Notification(\"remove\", this, 0));\n    }\n\n    /*\n     * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)\n     */\n    public void removeNotificationListener(NotificationListener listener,\n        NotificationFilter filter, Object handback) \n        throws ListenerNotFoundException {\n        notifier.removeNotificationListener(listener, filter, handback);\n    }\n\n    /*\n     * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object)\n     */\n    public void addNotificationListener(NotificationListener listener, \n        NotificationFilter filter, Object handback) \n        throws IllegalArgumentException {\n        notifier.addNotificationListener(listener, filter, handback);\n    }\n\n    /*\n     * @see javax.management.NotificationBroadcaster#getNotificationInfo()\n     */\n    public MBeanNotificationInfo[] getNotificationInfo() {\n        return notifier.getNotificationInfo();\n    }\n\n    /*\n     * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)\n     */\n    public void removeNotificationListener(NotificationListener listener) \n        throws ListenerNotFoundException {\n        notifier.removeNotificationListener(listener);\n    }\n\n}\n", "human_rating": 3.9571827370002413, "metadata": {"project": "argoUML", "class": "org.argouml.gefext.ArgoFigRect", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/gefext/ArgoFigRect.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.gefext.ArgoModeCreateFigLine", "source": "/* $Id: ArgoModeCreateFigLine.java 19614 2011-07-20 12:10:13Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.gefext;\n\nimport java.awt.event.MouseEvent;\n\nimport org.argouml.i18n.Translator;\nimport org.tigris.gef.base.ModeCreateFigLine;\nimport org.tigris.gef.presentation.Fig;\n\n/**\n * A Mode to interpret user input while creating a FigLine. All of\n *  the actual event handling is inherited from ModeCreate. This class\n *  just implements the differences needed to make it specific to\n *  lines.\n *\n * @author Michiel\n */\npublic class ArgoModeCreateFigLine extends ModeCreateFigLine {\n\n    @Override\n    public Fig createNewItem(MouseEvent me, int snapX, int snapY) {\n        Fig line = new ArgoFigLine(snapX, snapY, snapX, snapY);\n        // TODO: We need a way to set the line color and width here, but\n        // TestDependencies thinks this creates a dependency cycle\n        //        Fig line = new ArgoFigLine(snapX, snapY, snapX, snapY, \n//                ArgoFig.LINE_COLOR);\n//        line.setLineWidth(ArgoFig.LINE_WIDTH);\n        return line;\n    }\n\n    @Override\n    public String instructions() { \n        return Translator.localize(\"statusmsg.help.create.line\"); \n    }\n}\n", "human_rating": 3.9755259290762104, "metadata": {"project": "argoUML", "class": "org.argouml.gefext.ArgoModeCreateFigLine", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/gefext/ArgoModeCreateFigLine.java", "label_probabilities": {"readability": [0.975527, 0.0244723, 5.14538e-07, 2.10541e-13], "understandability": [0.939929, 0.0600695, 1.16069e-06, 6.04743e-11], "complexity": [2.3646e-16, 4.09431e-06, 0.0292064, 0.970789], "modularization": [0.0, 3.51971e-10, 0.0660224, 0.933978], "overall": [0.966917, 0.0330828, 3.61609e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.kernel.ProfileConfiguration", "source": "/* $Id: ProfileConfiguration.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    thn\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.kernel;\n\nimport java.awt.Image;\nimport java.beans.PropertyChangeEvent;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.argouml.application.events.ArgoEventPump;\nimport org.argouml.application.events.ArgoEventTypes;\nimport org.argouml.application.events.ArgoProfileEvent;\nimport org.argouml.cognitive.Translator;\nimport org.argouml.configuration.Configuration;\nimport org.argouml.configuration.ConfigurationKey;\nimport org.argouml.model.Model;\nimport org.argouml.profile.DefaultTypeStrategy;\nimport org.argouml.profile.FigNodeStrategy;\nimport org.argouml.profile.FormatingStrategy;\nimport org.argouml.profile.Profile;\nimport org.argouml.profile.ProfileException;\nimport org.argouml.profile.ProfileFacade;\n\n/**\n *   This class captures represents the unique access point for the\n *   configurability allowed by the use of profiles.\n *\n *   @author maurelio1234\n */\npublic class ProfileConfiguration extends AbstractProjectMember {\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(ProfileConfiguration.class.getName());\n\n    private FormatingStrategy formatingStrategy;\n\n    private DefaultTypeStrategy defaultTypeStrategy;\n\n    private List figNodeStrategies = new ArrayList();\n\n    private List<Profile> profiles = new ArrayList<Profile>();\n\n    private List<Object> profileModels = new ArrayList<Object>();\n\n    /**\n     * The extension used in serialization and returned by {@link #getType()}\n     */\n    public static final String EXTENSION = \"profile\";\n\n\n    /**\n     * The configuration key for the default stereotype view.\n     */\n    public static final ConfigurationKey KEY_DEFAULT_STEREOTYPE_VIEW =\n        Configuration.makeKey(\"profiles\", \"stereotypeView\");\n\n    /**\n     * The default constructor for this class. Sets the default profiles as\n     * given by {@link org.argouml.profile.ProfileManager} as the profiles of\n     * the project.\n     *\n     * @param project the project that contains this configuration\n     */\n    public ProfileConfiguration(Project project) {\n        super(EXTENSION, project);\n        List c = project.getUserDefinedModelList();\n        Object m = c.isEmpty() ? null : c.get(0);\n        if (project.getProjectType() != Project.PROFILE_PROJECT) {\n            // a profile initially has no applied profiles, we go bottom-up\n            for (Profile p : ProfileFacade.getManager().getDefaultProfiles()) {\n                addProfile(p, m);\n            }\n        }\n\n        updateStrategies();\n    }\n\n    /**\n     * The constructor for pre-defined profile configurations, such as when a\n     * project is read from a saved file.\n     * @param project the project that contains this configuration\n     * @param configuredProfiles the {@link Profile}s that will be the project\n     *        profiles\n     */\n    public ProfileConfiguration(Project project,\n            Collection<Profile> configuredProfiles) {\n        super(EXTENSION, project);\n        List c = project.getUserDefinedModelList();\n        Object m = c.isEmpty() ? null : c.get(0);\n        for (Profile profile : configuredProfiles) {\n            addProfile(profile, m);\n        }\n        updateStrategies();\n    }\n\n    private void updateStrategies() {\n        for (Profile profile : profiles) {\n            activateFormatingStrategy(profile);\n            activateDefaultTypeStrategy(profile);\n        }\n    }\n\n    /**\n     * @return the current formating strategy\n     */\n    public FormatingStrategy getFormatingStrategy() {\n        return formatingStrategy;\n    }\n\n    /**\n     * @return the current default type strategy\n     */\n    public DefaultTypeStrategy getDefaultTypeStrategy() {\n        return defaultTypeStrategy;\n    }\n\n    /**\n     * Updates the current strategy to the strategy provided by the\n     * passed profile. The profile should have been previously registered.\n     *\n     * @param profile the profile providing the current default type strategy\n     */\n    public void activateDefaultTypeStrategy(Profile profile) {\n        if (profile != null && profile.getDefaultTypeStrategy() != null\n                && getProfiles().contains(profile)) {\n            this.defaultTypeStrategy = profile.getDefaultTypeStrategy();\n        }\n    }\n\n    /**\n     * Updates the current strategy to the strategy provided by the\n     * passed profile. The profile should have been previously registered.\n     *\n     * @param profile the profile providing the current formating strategy\n     */\n    public void activateFormatingStrategy(Profile profile) {\n\tif (profile != null && profile.getFormatingStrategy() != null\n\t\t&& getProfiles().contains(profile)) {\n\t    this.formatingStrategy = profile.getFormatingStrategy();\n\t}\n    }\n\n    /**\n     * @return the list of applied profiles\n     */\n    public List<Profile> getProfiles() {\n        return profiles;\n    }\n\n    /**\n     * Applies a new profile to this configuration.\n     *\n     * @param p the profile to be applied\n     * @deprecated for 0.29.2, because since UML2 a profile must be applied to\n     * a model\n     */\n    @Deprecated\n    public void addProfile(Profile p) {\n        addProfile(p, null);\n    }\n\n    /**\n     * Applies a new profile to this configuration and to the given model (or\n     * other profile, which could be later a collection).\n     *\n     * @param p the profile to be applied\n     * @param m the model (or profile) to which the profile will be applied\n     */\n    @SuppressWarnings(\"unchecked\")\n    public void addProfile(Profile p, Object m) {\n        if (!profiles.contains(p)) {\n            profiles.add(p);\n            try {\n                for (Object profile : p.getProfilePackages()) {\n                    Model.getExtensionMechanismsHelper().applyProfile(\n                            m, profile);\n                }\n                profileModels.addAll(p.getProfilePackages());\n            } catch (ProfileException e) {\n                LOG.log(Level.WARNING,\n                        \"Error retrieving profile's \" + p + \" packages.\",\n                        e);\n            }\n\n            FigNodeStrategy fns = p.getFigureStrategy();\n            if (fns != null) {\n                figNodeStrategies.add(fns);\n            }\n\n            for (Profile dependency : p.getDependencies()) {\n                addProfile(dependency, m);\n            }\n\n            updateStrategies();\n            ArgoEventPump.fireEvent(new ArgoProfileEvent(\n                    ArgoEventTypes.PROFILE_ADDED, new PropertyChangeEvent(this,\n                            \"profile\", null, p)));\n        }\n    }\n\n    /**\n     * @return the list of models of the currently applied profile.\n     */\n    private List getProfileModels() {\n        return profileModels;\n    }\n\n    /**\n     * Removes the passed profile from this configuration.\n     *\n     * @param p the profile to be applied\n     * @deprecated for 0.29.2, because since UML2 a profile must be unapplied\n     * from a model\n     */\n    @Deprecated\n    public void removeProfile(Profile p) {\n        removeProfile(p, null);\n    }\n\n    /**\n     * Removes the passed profile from the configuration and unapplies it from\n     * the given model (or other profile, which could be later a collection).\n     *\n     * @param p the profile to be removed/unapplied\n     * @param m the model (or profile) to which the profile will be unapplied\n     */\n    public void removeProfile(Profile p, Object m) {\n        profiles.remove(p);\n        try {\n            for (Object profile : p.getProfilePackages()) {\n                Model.getExtensionMechanismsHelper().unapplyProfile(m, profile);\n            }\n            profileModels.removeAll(p.getProfilePackages());\n        } catch (ProfileException e) {\n            LOG.log(Level.SEVERE, \"Exception\", e);\n        }\n\n        FigNodeStrategy fns = p.getFigureStrategy();\n        if (fns != null) {\n            figNodeStrategies.remove(fns);\n        }\n\n        if (formatingStrategy == p.getFormatingStrategy()) {\n            formatingStrategy = null;\n        }\n\n        List<Profile> markForRemoval = new ArrayList<Profile>();\n        for (Profile profile : profiles) {\n            if (profile.getDependencies().contains(p)) {\n                markForRemoval.add(profile);\n            }\n        }\n\n        for (Profile profile : markForRemoval) {\n            removeProfile(profile, m);\n        }\n\n        updateStrategies();\n        ArgoEventPump.fireEvent(new ArgoProfileEvent(\n                ArgoEventTypes.PROFILE_REMOVED, new PropertyChangeEvent(this,\n                        \"profile\", p, null)));\n    }\n\n    private FigNodeStrategy compositeFigNodeStrategy = new FigNodeStrategy() {\n\n\tpublic Image getIconForStereotype(Object element) {\n\t    Iterator it = figNodeStrategies.iterator();\n\n\t    while (it.hasNext()) {\n\t\tFigNodeStrategy strat = (FigNodeStrategy) it.next();\n\t\tImage extra = strat.getIconForStereotype(element);\n\n\t\tif (extra != null) {\n\t\t    return extra;\n\t\t}\n\t    }\n\t    return null;\n\t}\n\n    };\n\n    /**\n     * @return the current FigNodeStrategy\n     */\n    public FigNodeStrategy getFigNodeStrategy() {\n\treturn compositeFigNodeStrategy;\n    }\n\n    /**\n     * @return the extension for this project member\n     * @see org.argouml.kernel.AbstractProjectMember#getType()\n     */\n    public String getType() {\n\treturn EXTENSION;\n    }\n\n    /**\n     * Objects of this class are always consistent, there's no need\n     * to repair them.\n     *\n     * @return the empty string.\n     * @see org.argouml.kernel.ProjectMember#repair()\n     */\n    public String repair() {\n\treturn \"\";\n    }\n\n    /**\n     * @return the \"Profile Configuration\" string\n     * @see java.lang.Object#toString()\n     */\n    @Override\n    public String toString() {\n        return Translator.localize(\"misc.project.profileconfigurationname\");\n    }\n\n\n    /**\n     * Find a stereotype with the given name which is applicable to the given\n     * element.\n     *\n     * @param name name of stereotype to look for\n     * @param element model element to which the stereotype must be applicable\n     * @return the stereotype or null if none found\n     */\n    public Object findStereotypeForObject(String name, Object element) {\n        Iterator iter = null;\n\n        for (Object model : profileModels) {\n            iter = Model.getFacade().getOwnedElements(model).iterator();\n\n            while (iter.hasNext()) {\n                Object stereo = iter.next();\n                if (!Model.getFacade().isAStereotype(stereo)\n                        || !name.equals(Model.getFacade().getName(stereo))) {\n                    continue;\n                }\n\n                if (Model.getExtensionMechanismsHelper().isValidStereotype(\n                        element, stereo)) {\n                    return stereo;\n                }\n            }\n        }\n\n        return null;\n    }\n\n    /**\n     * Search for the given type in all of the profile models.\n     *\n     * @param name name of type to be found\n     * @return the type or null\n     */\n    public Object findType(String name) {\n        for (Object model : getProfileModels()) {\n            Object result = findTypeInModel(name, model);\n            if (result != null) {\n                return result;\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Finds a type in a model by name\n     *\n     * FIXME: duplicated from the method with the same name in\n     * org.argouml.profile.internal.ModelUtils.\n     *\n     * @param s the type name\n     * @param model the model\n     * @return the type or <code>null</code> if the type has not been found.\n     */\n    public static Object findTypeInModel(String s, Object model) {\n\n        if (!Model.getFacade().isANamespace(model)) {\n            throw new IllegalArgumentException(\n                    \"Looking for the classifier \" + s\n                    + \" in a non-namespace object of \" + model\n                    + \". A namespace was expected.\");\n        }\n\n        Collection allClassifiers =\n            Model.getModelManagementHelper()\n                .getAllModelElementsOfKind(model,\n                        Model.getMetaTypes().getClassifier());\n\n        Object[] classifiers = allClassifiers.toArray();\n        Object classifier = null;\n\n        for (int i = 0; i < classifiers.length; i++) {\n\n            classifier = classifiers[i];\n            if (Model.getFacade().getName(classifier) != null\n                        && Model.getFacade().getName(classifier).equals(s)) {\n                return classifier;\n            }\n        }\n\n        return null;\n    }\n\n    /**\n     * Find all the model elements in the configured {@link Profile}s\n     * of the given meta type.\n     *\n     * @param metaType the meta type of the model elements to find\n     * @return a {@link Collection} containing the model elements that\n     *         are of the given meta type\n     */\n    @SuppressWarnings(\"unchecked\")\n    public Collection findByMetaType(Object metaType) {\n        Set elements = new HashSet();\n\n        Iterator it = getProfileModels().iterator();\n        while (it.hasNext()) {\n            Object model = it.next();\n            elements.addAll(Model.getModelManagementHelper()\n                    .getAllModelElementsOfKind(model, metaType));\n        }\n        return elements;\n    }\n\n    /**\n     * @param modelElement\n     *                ModelElement for which find possible stereotypes\n     * @return collection of stereotypes which are valid for the given model\n     *         element.\n     */\n    public Collection findAllStereotypesForModelElement(Object modelElement) {\n        return Model.getExtensionMechanismsHelper().getAllPossibleStereotypes(\n                getProfileModels(), modelElement);\n    }\n}\n", "human_rating": 3.267908673365, "metadata": {"project": "argoUML", "class": "org.argouml.kernel.ProfileConfiguration", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/kernel/ProfileConfiguration.java", "label_probabilities": {"readability": [0.269035, 0.729839, 0.00112576, 1.53365e-07], "understandability": [0.298312, 0.701045, 0.000641972, 1.26568e-06], "complexity": [0.000338845, 0.0395925, 0.738948, 0.221121], "modularization": [0.00304545, 0.455012, 0.541191, 0.000751069], "overall": [2.53546e-10, 0.83946, 0.16054, 9.78991e-11]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.AbstractUseCasesHelperDecorator", "source": "/* $Id: AbstractUseCasesHelperDecorator.java 17747 2010-01-10 21:16:51Z linus $\n *******************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *******************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.model;\n\nimport java.util.Collection;\n\n/**\n * An abstract Decorator for the {@link UseCasesHelper}.\n *\n * @author Bob Tarling\n */\npublic abstract class AbstractUseCasesHelperDecorator\n\timplements UseCasesHelper {\n\n    /**\n     * The component.\n     */\n    private UseCasesHelper impl;\n\n    /**\n     * @param component The component to decorate.\n     */\n    protected AbstractUseCasesHelperDecorator(UseCasesHelper component) {\n        impl = component;\n    }\n\n    /**\n     * The component we are decorating.\n     *\n     * @return Returns the component.\n     */\n    protected UseCasesHelper getComponent() {\n        return impl;\n    }\n\n    public Collection getExtensionPoints(Object useCase) {\n        return Model.getFacade().getExtensionPoints(useCase);\n    }\n\n    /*\n     * @see org.argouml.model.UseCasesHelper#getAllUseCases(java.lang.Object)\n     */\n    public Collection getAllUseCases(Object ns) {\n        return impl.getAllUseCases(ns);\n    }\n\n    public Collection getAllActors(Object ns) {\n        return impl.getAllActors(ns);\n    }\n\n    public Collection getExtendedUseCases(Object ausecase) {\n        return impl.getExtendedUseCases(ausecase);\n    }\n\n    public Object getExtends(Object abase, Object anextension) {\n        return impl.getExtends(abase, anextension);\n    }\n\n    public Collection getIncludedUseCases(Object ausecase) {\n        return impl.getIncludedUseCases(ausecase);\n    }\n\n    public Object getIncludes(Object abase, Object aninclusion) {\n        return impl.getIncludes(abase, aninclusion);\n    }\n\n    public Collection getSpecificationPath(Object ausecase) {\n        return impl.getSpecificationPath(ausecase);\n    }\n\n    public void setBase(Object extend, Object base) {\n        impl.setBase(extend, base);\n    }\n\n    public void removeExtend(Object elem, Object extend) {\n        impl.removeExtend(elem, extend);\n    }\n\n    public void removeExtensionPoint(Object elem, Object ep) {\n        impl.removeExtensionPoint(elem, ep);\n    }\n\n    public void removeInclude(Object usecase, Object include) {\n        impl.removeInclude(usecase, include);\n    }\n\n    public void addExtend(Object elem, Object extend) {\n        impl.addExtend(elem, extend);\n    }\n\n    public void addExtensionPoint(Object handle, Object extensionPoint) {\n        impl.addExtensionPoint(handle, extensionPoint);\n    }\n\n    public void addExtensionPoint(Object handle, int position, \n            Object extensionPoint) {\n        impl.addExtensionPoint(handle, position, extensionPoint);\n    }\n\n    public void addInclude(Object usecase, Object include) {\n        impl.addInclude(usecase, include);\n    }\n\n    public void setAddition(Object handle, Object useCase) {\n        impl.setAddition(handle, useCase);\n    }\n\n    public void setCondition(Object handle, Object booleanExpression) {\n        impl.setCondition(handle, booleanExpression);\n    }\n\n    public void setExtension(Object handle, Object ext) {\n        impl.setExtension(handle, ext);\n    }\n\n    public void setExtensionPoints(Object handle, Collection extensionPoints) {\n        impl.setExtensionPoints(handle, extensionPoints);\n    }\n\n    public void setIncludes(Object handle, Collection includes) {\n        impl.setIncludes(handle, includes);\n    }\n\n    public void setLocation(Object handle, String loc) {\n        impl.setLocation(handle, loc);\n    }\n\n    public void setUseCase(Object elem, Object usecase) {\n        impl.setUseCase(elem, usecase);\n    }\n\n}\n", "human_rating": 3.9305142124, "metadata": {"project": "argoUML", "class": "org.argouml.model.AbstractUseCasesHelperDecorator", "source_path": "argoUML/sourcefiles/src/argouml-core-model/src/org/argouml/model/AbstractUseCasesHelperDecorator.java", "label_probabilities": {"readability": [0.930529, 0.0694565, 1.43562e-05, 0.0], "understandability": [0.90414, 0.09586, 5.30072e-08, 0.0], "complexity": [0.0, 1.34765e-10, 0.0548876, 0.945112], "modularization": [0.0, 0.00129633, 0.071262, 0.927442], "overall": [0.985931, 0.0140686, 8.42778e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.euml.CollaborationsFactoryEUMLImpl", "source": "// $Id: CollaborationsFactoryEUMLImpl.java 19617 2011-07-23 09:04:49Z linus $\n/***************************************************************************\n * Copyright (c) 2007,2010 Tom Morris and other contributors\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Tom Morris - initial API and implementation\n ***************************************************************************/\npackage org.argouml.model.euml;\n\nimport org.argouml.model.AbstractModelFactory;\nimport org.argouml.model.CollaborationsFactory;\nimport org.eclipse.uml2.uml.Collaboration;\nimport org.eclipse.uml2.uml.ConnectableElement;\nimport org.eclipse.uml2.uml.Connector;\nimport org.eclipse.uml2.uml.ConnectorEnd;\nimport org.eclipse.uml2.uml.Element;\nimport org.eclipse.uml2.uml.Interaction;\nimport org.eclipse.uml2.uml.Lifeline;\nimport org.eclipse.uml2.uml.Message;\nimport org.eclipse.uml2.uml.MessageOccurrenceSpecification;\nimport org.eclipse.uml2.uml.UMLFactory;\n\n/**\n * Eclipse UML2 implementation of CollaborationsFactory.\n */\nclass CollaborationsFactoryEUMLImpl implements CollaborationsFactory,\n        AbstractModelFactory {\n\n    /**\n     * The model implementation.\n     */\n    private EUMLModelImplementation modelImpl;\n\n    /**\n     * Constructor.\n     *\n     * @param implementation The ModelImplementation.\n     */\n    public CollaborationsFactoryEUMLImpl(\n            EUMLModelImplementation implementation) {\n        modelImpl = implementation;\n    }\n\n    public Object buildActivator(Object owner, Object interaction) {\n        throw new NotYetImplementedException();\n    }\n\n    public ConnectorEnd buildAssociationEndRole(Object atype) {\n        Lifeline lifeline = (Lifeline) atype;\n        ConnectorEnd end = UMLFactory.eINSTANCE.createConnectorEnd();\n        ConnectableElement prop = lifeline.getRepresents();\n        if (prop == null) {\n            prop = UMLFactory.eINSTANCE.createProperty();\n            lifeline.setRepresents(prop);\n        }\n\n        end.setRole(prop);\n//        lifeline.setRepresents(prop);\n        return end;\n    }\n\n    public Connector buildAssociationRole(Object from, Object to) {\n        return buildAssociationRole((Lifeline) from, (Lifeline) to);\n    }\n    \n    /**\n     * Internal type-checked version of buildAssociationRole.\n     */\n    private Connector buildAssociationRole(Lifeline from,\n            Lifeline to) {\n        Connector connector = UMLFactory.eINSTANCE.createConnector();\n        from.getInteraction().getOwnedConnectors().add(connector);\n\n        connector.getEnds().add(buildAssociationEndRole(from));\n        connector.getEnds().add(buildAssociationEndRole(to));\n        return connector;\n    }\n\n    @Deprecated\n    public Object buildAssociationRole(Object from, Object agg1, Object to,\n            Object agg2, Boolean unidirectional) {\n        if (unidirectional == null) {\n            return buildAssociationRole(from, agg1, to, agg2, false);\n        } else {\n            return buildAssociationRole(from, agg1, to, agg2, \n                    unidirectional.booleanValue());\n        }\n    }\n\n    public Object buildAssociationRole(Object from, Object agg1, Object to,\n            Object agg2, boolean unidirectional) {\n        // TODO: Auto-generated method stub\n        return null;\n    }\n\n    public Object buildAssociationRole(Object link) {\n        // TODO: Auto-generated method stub\n        return null;\n    }\n\n    public Object buildClassifierRole(Object collaboration) {\n        throw new IllegalArgumentException(\n                \"No such thing as ClassifierRole in UML2\"); //$NON-NLS-1$\n    }\n    \n    public Object buildLifeline(Object interaction) {\n        Lifeline lifeline = createLifeline();\n        lifeline.setInteraction((Interaction) interaction);\n        return lifeline;\n    }\n    \n    // TODO: All build/create methods need Undo support - tfm\n\n    public Collaboration buildCollaboration(Object handle) {\n        Collaboration collab = createCollaboration();\n        ((Element) handle).getOwnedElements().add(collab);\n        return collab;\n    }\n\n    public Collaboration buildCollaboration(Object namespace, \n            Object representedElement) {\n        throw new IllegalArgumentException(\n                \"A collaboration is only attached to a namespace in UML2\");\n    }\n\n    public Object buildInteraction(Object collaboration) {\n        Interaction interaction = createInteraction();\n        Collaboration collab = (Collaboration) collaboration;\n        modelImpl.getCoreHelper().addOwnedElement(collab, interaction);\n        return interaction;\n    }\n\n    public Message buildMessage(Object from, Object to) {\n        \n        Lifeline l1 = (Lifeline) from;\n        Lifeline l2 = (Lifeline) to;\n\n        Message message = UMLFactory.eINSTANCE.createMessage();\n        \n        MessageOccurrenceSpecification receive = \n            UMLFactory.eINSTANCE.createMessageOccurrenceSpecification();\n        MessageOccurrenceSpecification send = \n            UMLFactory.eINSTANCE.createMessageOccurrenceSpecification();\n        \n        message.setReceiveEvent(receive);\n        message.setSendEvent(send);\n        \n        l1.getCoveredBys().add(send);\n        l2.getCoveredBys().add(receive);\n        return message;\n    }\n\n    public Object createAssociationEndRole() {\n        // TODO: Auto-generated method stub\n        return null;\n    }\n\n    public Object createAssociationRole() {\n        // TODO: Auto-generated method stub\n        return null;\n    }\n\n    public Object createClassifierRole() {\n        return UMLFactory.eINSTANCE.createLifeline();\n    }\n\n    public Collaboration createCollaboration() {\n        return UMLFactory.eINSTANCE.createCollaboration();\n    }\n\n    public Object createCollaborationInstanceSet() {\n        // TODO: Auto-generated method stub\n        return null;\n    }\n\n    public Interaction createInteraction() {\n        return UMLFactory.eINSTANCE.createInteraction();\n    }\n\n    public Object createInteractionInstanceSet() {\n        // TODO: Auto-generated method stub\n        return null;\n    }\n    \n    public Lifeline createLifeline() {\n        return UMLFactory.eINSTANCE.createLifeline();\n    }\n\n    public Message createMessage() {\n        return UMLFactory.eINSTANCE.createMessage();\n    }\n\n\n}\n", "human_rating": 3.9582949010401, "metadata": {"project": "argoUML", "class": "org.argouml.model.euml.CollaborationsFactoryEUMLImpl", "source_path": "argoUML/sourcefiles/src/argouml-core-model-euml/src/org/argouml/model/euml/CollaborationsFactoryEUMLImpl.java", "label_probabilities": {"readability": [0.958295, 0.0417043, 1.00052e-06, 9.98987e-14], "understandability": [0.00114495, 0.721657, 0.277165, 3.31079e-05], "complexity": [1.3372e-14, 6.33794e-05, 0.315255, 0.684682], "modularization": [0.0, 4.89703e-06, 0.155247, 0.844748], "overall": [0.0048363, 0.99515, 1.33174e-05, 1.2e-19]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.euml.DataTypesHelperEUMLImpl", "source": "// $Id: DataTypesHelperEUMLImpl.java 19617 2011-07-23 09:04:49Z linus $\n/***************************************************************************\n * Copyright (c) 2007,2010 Tom Morris and other contributors\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Tom Morris - initial implementation\n *    Thomas Neustupny\n *    Laurent Braud \n ***************************************************************************/\npackage org.argouml.model.euml;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.argouml.model.DataTypesHelper;\nimport org.eclipse.emf.common.util.EList;\nimport org.eclipse.uml2.uml.LiteralBoolean;\nimport org.eclipse.uml2.uml.LiteralInteger;\nimport org.eclipse.uml2.uml.LiteralNull;\nimport org.eclipse.uml2.uml.LiteralString;\nimport org.eclipse.uml2.uml.LiteralUnlimitedNatural;\nimport org.eclipse.uml2.uml.MultiplicityElement;\nimport org.eclipse.uml2.uml.OpaqueBehavior;\nimport org.eclipse.uml2.uml.OpaqueExpression;\nimport org.eclipse.uml2.uml.Property;\nimport org.eclipse.uml2.uml.PseudostateKind;\nimport org.eclipse.uml2.uml.UMLFactory;\nimport org.eclipse.uml2.uml.UMLPackage;\nimport org.eclipse.uml2.uml.ValueSpecification;\n\n/**\n * The implementation of the DataTypesHelper for EUML2.\n */\nclass DataTypesHelperEUMLImpl implements DataTypesHelper {\n\n    /**\n     * The model implementation.\n     */\n    private EUMLModelImplementation modelImpl;\n\n    /**\n     * Constructor.\n     *\n     * @param implementation The ModelImplementation.\n     */\n    public DataTypesHelperEUMLImpl(EUMLModelImplementation implementation) {\n        modelImpl = implementation;\n    }\n\n    public boolean equalsCHOICEKind(Object kind) {\n        return PseudostateKind.CHOICE_LITERAL.equals(kind);\n    }\n\n    public boolean equalsDeepHistoryKind(Object kind) {\n        return PseudostateKind.DEEP_HISTORY_LITERAL.equals(kind);\n    }\n\n    public boolean equalsFORKKind(Object kind) {\n        return PseudostateKind.FORK_LITERAL.equals(kind);\n    }\n\n    public boolean equalsINITIALKind(Object kind) {\n        return PseudostateKind.INITIAL_LITERAL.equals(kind);\n    }\n\n    public boolean equalsJOINKind(Object kind) {\n        return PseudostateKind.JOIN_LITERAL.equals(kind);\n    }\n\n    public boolean equalsJUNCTIONKind(Object kind) {\n        return PseudostateKind.JUNCTION_LITERAL.equals(kind);\n    }\n\n    public boolean equalsShallowHistoryKind(Object kind) {\n        return PseudostateKind.SHALLOW_HISTORY_LITERAL.equals(kind);\n    }\n\n    public String getBody(Object handle) {\n        EList<String> bodies = null;\n        if (handle instanceof OpaqueExpression) {\n            bodies = ((OpaqueExpression) handle).getBodies();\n        } else if (handle instanceof OpaqueBehavior) {\n            bodies = ((OpaqueBehavior) handle).getBodies();\n        } else {\n            throw new IllegalArgumentException(\n                    \"handle must be instance \"\n                    + \"of OpaqueExpression or OpaqueBehavior\"); //$NON-NLS-1$\n        }\n        return (bodies.size() < 1) ? null : bodies.get(0);\n    }\n\n    public String getLanguage(Object handle) {\n        EList<String> langs = null;\n        if (handle instanceof OpaqueExpression) {\n            langs = ((OpaqueExpression) handle).getLanguages();\n        } else if (handle instanceof OpaqueBehavior) {\n            langs = ((OpaqueBehavior) handle).getLanguages();\n        } else {\n            throw new IllegalArgumentException(\n                    \"handle must be instance of OpaqueExpression\" //$NON-NLS-1$\n                    + \" or OpaqueBehavior. We got \" + handle); //$NON-NLS-1$\n        }\n        return (langs.size() < 1) ? null : langs.get(0);\n    }\n\n    public String multiplicityToString(Object multiplicity) {\n        if (!(multiplicity instanceof MultiplicityElement)) {\n            throw new IllegalArgumentException(\n                    \"multiplicity must be instance \"\n                    + \"of MultiplicityElement\"); //$NON-NLS-1$\n        }\n        MultiplicityElement mult = (MultiplicityElement) multiplicity;\n        if (mult.getLower() == mult.getUpper()) {\n            return DataTypesFactoryEUMLImpl.boundToString(mult.getLower());\n        } else {\n            return DataTypesFactoryEUMLImpl.boundToString(\n                    mult.getLower())\n                    + \"..\" //$NON-NLS-1$\n                    + DataTypesFactoryEUMLImpl.boundToString(mult.getUpper());\n        }\n    }\n    \n    public Object setBody(Object handle, String body) {\n        List<String> bodies = null;\n        if (handle instanceof OpaqueExpression) {\n            bodies = ((OpaqueExpression) handle).getBodies();\n        } else if (handle instanceof OpaqueBehavior) {\n            bodies = ((OpaqueBehavior) handle).getBodies();\n        } else {\n            throw new IllegalArgumentException(\n                    \"handle must be instance \"\n                    + \"of OpaqueExpression or OpaqueBehavior\"); //$NON-NLS-1$\n        }\n        // TODO: Support more than one body/language\n        if (bodies.size() > 1) {\n            throw new IllegalStateException(\n                    \"Only one body/lang supported\"); //$NON-NLS-1$\n        }\n        bodies.clear();\n        bodies.add(body);\n        return handle;\n    }\n\n    public Object setLanguage(Object handle, String language) {\n        List<String> langs = null;\n        if (handle instanceof OpaqueExpression) {\n            langs = ((OpaqueExpression) handle).getLanguages();\n        } else if (handle instanceof OpaqueBehavior) {\n            langs = ((OpaqueBehavior) handle).getLanguages();\n        } else {\n            throw new IllegalArgumentException(\n                    \"handle must be instance \"\n                    + \"of OpaqueExpression or OpaqueBehavior\"); //$NON-NLS-1$\n        }\n        // TODO: Support more than one body/language\n        if (langs.size() > 1) {\n            throw new IllegalStateException(\n                    \"Only one body/lang supported\"); //$NON-NLS-1$\n        }\n        langs.clear(); \n        langs.add(language);\n        return handle;\n    }\n\n    /**\n     * @see org.argouml.model.DataTypesHelper#getValueSpecifications()\n     */\n    public ArrayList<String> getValueSpecifications() {\n        ArrayList<String> list = new ArrayList<String>(); \n        //\n        list.add(\"OpaqueExpression\");\n        //list.add(\"OpaqueExpression\");\n        \n        //LiteralSpecification\n        //list.add(\"LiteralNull\");//When other ok\n        list.add(\"LiteralString\");\n        //list.add(\"LiteralInteger\");//When other ok\n        list.add(\"LiteralBoolean\");\n        //list.add(\"LiteralUnlimitedNatural\");//When other ok\n        \n        //list.add(\"LiteralReal\");//UML 2.4\n        //End LiteralSpecification     \n        \n        //list.add(\"InstanceValue\");\n        \n        return list;\n    }\n    \n    /**\n     * @see org.argouml.model.DataTypesHelper#createValueValueSpecification(java.lang.String, java.lang.Object)\n     */\n    public Object createValueSpecification(Object handle,\n            String type) {\n        \n        ValueSpecification newValueSpecification = null;\n        if (handle instanceof Property) {\n            Property property = (Property) handle;\n            \n            Object[] tabValues = null;\n            if (type.equals(\"LiteralBoolean\")) {\n                newValueSpecification = \n                    (ValueSpecification) UMLFactory.eINSTANCE.create(\n                            UMLPackage.eINSTANCE.getLiteralBoolean());\n            } else if (type.equals(\"LiteralNull\")) {\n        \tnewValueSpecification = \n        \t    (ValueSpecification) UMLFactory.eINSTANCE.create(\n        \t            UMLPackage.eINSTANCE.getLiteralNull());\n            } else if (type.equals(\"LiteralString\")) {\n                newValueSpecification = \n                    (ValueSpecification) UMLFactory.eINSTANCE.create(\n                            UMLPackage.eINSTANCE.getLiteralString());\n                tabValues = new String[]{\"\"};\n            } else if (type.equals(\"LiteralUnlimitedNatural\")) {\n                newValueSpecification = \n                    (ValueSpecification) UMLFactory.eINSTANCE.create(\n                            UMLPackage.eINSTANCE.getLiteralUnlimitedNatural());\n                tabValues = new String[]{\"0\"};\n            } else if (type.equals(\"LiteralInteger\")) {\n                newValueSpecification = \n                    (ValueSpecification) UMLFactory.eINSTANCE.create(\n                            UMLPackage.eINSTANCE.getLiteralInteger());\n                tabValues = new String[]{\"0\"};\n            } else if (type.equals(\"OpaqueExpression\")) {\n                newValueSpecification =\n                    (ValueSpecification) UMLFactory.eINSTANCE.create(\n                            UMLPackage.eINSTANCE.getOpaqueExpression());\n                setLanguage(newValueSpecification, \"\");\n                setBody(newValueSpecification, \"\");\n            }\n            if (tabValues != null) {\n                modifyValueSpecification(newValueSpecification, tabValues);\n            }\n            \n            if (newValueSpecification != null) {\n                property.setDefaultValue(newValueSpecification);\n            }\n        } // TODO else => Exception !\n\n        return newValueSpecification;\n        \n    }\n    \n    /**\n     * @see org.argouml.model.DataTypesHelper#modifyValueSpecification(java.lang.Object, java.lang.Object[])\n     */\n    public void modifyValueSpecification(Object handle, Object[] tabValues) {\n        // LiteralSpecification  \n        if (handle instanceof LiteralBoolean) {\n            LiteralBoolean lb = (LiteralBoolean) handle;\n            if (tabValues != null && tabValues.length == 1) {\n                Boolean value = (Boolean) tabValues[0];\n                lb.setValue(value);\n            }\n        } else if (handle instanceof LiteralNull) {\n            // Can't be changed\n        } else if (handle instanceof LiteralString) {\n            LiteralString ls = (LiteralString) handle;\n            if (tabValues != null && tabValues.length == 1) {\n                String value = (String) tabValues[0];\n                ls.setValue(value);\n            }\n        } else if (handle instanceof LiteralUnlimitedNatural) {\n            LiteralUnlimitedNatural ls = (LiteralUnlimitedNatural) handle;\n            if (tabValues != null && tabValues.length == 1) {\n                Integer value = (Integer) tabValues[0];\n                ls.setValue(value);\n            }\n        } else if (handle instanceof LiteralInteger) {\n            LiteralInteger ls = (LiteralInteger) handle;\n            if (tabValues != null && tabValues.length == 1) {\n                Integer value = (Integer) tabValues[0];\n                ls.setValue(value);\n            }\n        } else if (handle instanceof OpaqueExpression) {\n            //rewrite it after change setExpression ?\n            OpaqueExpression oe = (OpaqueExpression) handle;\n            List<String> bodies = oe.getBodies();\n            List<String> langs = oe.getLanguages();\n            // as write in UML specification, we have size(bodies)==size(langs)\n            // we must have tabValues.length%2==0 \n            bodies.clear();\n            langs.clear();\n            for (int i = 0; i < tabValues.length; i += 2) {\n                bodies.add((String) tabValues[i]);\n                langs.add((String) tabValues[i + 1]);\n            }\n        }\n        // TODO Expression and InstanceValue (how)\n        // If anyone have an example.\n        \n    }\n    \n    /**\n     * @see org.argouml.model.DataTypesHelper#getValueSpecificationValues(java.lang.Object)\n     */\n    public Object[] getValueSpecificationValues(Object handle) {\n        Object[] tabValues = null;\n        // LiteralSpecification  \n        if (handle instanceof LiteralBoolean) {\n            LiteralBoolean lb = (LiteralBoolean) handle;\n            tabValues = new Boolean[]{lb.isValue()};\n            \n        } else if (handle instanceof LiteralNull) {\n            // Can't be set\n        } else if (handle instanceof LiteralString) {\n            LiteralString ls = (LiteralString) handle;\n            tabValues = new String[]{ls.getValue()};\n        } else if (handle instanceof LiteralUnlimitedNatural) {\n            LiteralUnlimitedNatural lun = (LiteralUnlimitedNatural) handle;\n            tabValues = new String[]{\"\" + lun.getValue()};\n        } else if (handle instanceof LiteralInteger) {\n            LiteralInteger li = (LiteralInteger) handle;\n            tabValues = new Integer[]{li.getValue()};\n        }\n        else if (handle instanceof OpaqueExpression) {\n            //rewrite it after change setExpression ?\n            OpaqueExpression oe = (OpaqueExpression) handle;\n            List<String> bodies = oe.getBodies();\n            List<String> langs = oe.getLanguages();\n            // as write in UML specification, we have size(bodies)==size(langs)\n            // we must have tabValues.length%2==0\n            if (bodies.size() > 0) {\n                tabValues = new String[bodies.size() * 2];\n                for (int i = 0; i < bodies.size(); i++) {\n                    tabValues[i * 2] = bodies.get(i);\n                    tabValues[i * 2 + 1] = langs.get(i);\n                }\n            }\n        }\n        // TODO Expression and InstanceValue (how)\n        // If anyone have an example.\n        \n        return tabValues;\n    }\n}\n", "human_rating": 2.9529509505614904, "metadata": {"project": "argoUML", "class": "org.argouml.model.euml.DataTypesHelperEUMLImpl", "source_path": "argoUML/sourcefiles/src/argouml-core-model-euml/src/org/argouml/model/euml/DataTypesHelperEUMLImpl.java", "label_probabilities": {"readability": [2.16371e-05, 0.952908, 0.0470702, 2.16149e-09], "understandability": [3.13396e-11, 0.0193747, 0.958787, 0.0218384], "complexity": [1.54605e-09, 0.727202, 0.272798, 1.98514e-10], "modularization": [5.38693e-08, 0.987707, 0.0122928, 1.782e-17], "overall": [1.02921e-15, 0.00696502, 0.918167, 0.0748678]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.euml.UMLUtil", "source": "// $Id: UMLUtil.java 19105 2011-03-05 01:04:10Z thn $\n/*******************************************************************************\n * Copyright (c) 2007,2010 Bogdan Pistol and other contributors\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Bogdan Pistol - initial API and implementation\n *******************************************************************************/\npackage org.argouml.model.euml;\n\nimport org.eclipse.emf.common.command.Command;\nimport org.eclipse.emf.common.command.StrictCompoundCommand;\nimport org.eclipse.emf.common.util.EList;\nimport org.eclipse.emf.common.util.URI;\nimport org.eclipse.emf.ecore.resource.Resource;\nimport org.eclipse.emf.edit.command.CopyToClipboardCommand;\nimport org.eclipse.emf.edit.command.PasteFromClipboardCommand;\nimport org.eclipse.uml2.uml.Association;\nimport org.eclipse.uml2.uml.AssociationClass;\nimport org.eclipse.uml2.uml.Element;\nimport org.eclipse.uml2.uml.NamedElement;\nimport org.eclipse.uml2.uml.Operation;\nimport org.eclipse.uml2.uml.Property;\nimport org.eclipse.uml2.uml.Type;\n\n/**\n * This class exposes protected methods from\n * {@link org.eclipse.uml2.uml.UMLUtil} and adds additional util methods\n * \n * @author Bogdan Pistol\n */\npublic class UMLUtil extends org.eclipse.uml2.uml.util.UMLUtil {\n\n    /**\n     * The default URI used for eUML\n     */\n    public static final URI DEFAULT_URI = \n        URI.createURI(\"http://argouml.tigris.org/euml/resource/default_uri.xmi\"); //$NON-NLS-1$\n        \n    /**\n     * Getter for the attributes of a Type\n     * \n     * @param type\n     *                The Type that owns the attributes\n     * @return the attributes or null\n     */\n    public static EList<Property> getOwnedAttributes(Type type) {\n        if (type instanceof AssociationClass) {\n            return ((AssociationClass) type).getOwnedAttributes();\n        } else if (type instanceof Association) {\n            return ((Association) type).getOwnedEnds();\n        } else {\n            return org.eclipse.uml2.uml.util.UMLUtil.getOwnedAttributes(type);\n        }\n    }\n\n    /**\n     * Getter for the operations of a Type\n     * \n     * @param type\n     *                The Type that owns the operations\n     * @return the operations or null\n     */\n    public static EList<Operation> getOwnedOperations(Type type) {\n        return org.eclipse.uml2.uml.util.UMLUtil.getOwnedOperations(type);\n    }\n\n    /**\n     * Copy a tree of UML elements into a destination location\n     * \n     * @param modelImplementation\n     *                the eUML model implementation\n     * @param source\n     *                the tree of UML elements to be copied\n     * @param destination\n     *                the destination container\n     * @return the root of the newly copied tree of UML elements or null\n     */\n    public static Element copy(EUMLModelImplementation modelImplementation,\n            Element source, Element destination) {\n        Command copyToClipboard = CopyToClipboardCommand.create(\n                modelImplementation.getEditingDomain(), source);\n        Command pasteFromClipboard = PasteFromClipboardCommand.create(\n                modelImplementation.getEditingDomain(), destination, null);\n        StrictCompoundCommand copyCommand = new StrictCompoundCommand() {\n            {\n                isPessimistic = true;\n            }\n        };\n        copyCommand.append(copyToClipboard);\n        copyCommand.append(pasteFromClipboard);\n        copyCommand.setLabel(\"Copy a tree of UML elements to a destination\"); //$NON-NLS-1$\n        if (copyCommand.canExecute()) {\n            modelImplementation.getModelEventPump().getRootContainer().setHoldEvents(\n                    true);\n            modelImplementation.getEditingDomain().getCommandStack().execute(\n                    copyCommand);\n            if (modelImplementation.getEditingDomain().getCommandStack().getMostRecentCommand().getAffectedObjects().size() == 1) {\n                modelImplementation.getModelEventPump().getRootContainer().setHoldEvents(\n                        false);\n                return (Element) modelImplementation.getEditingDomain().getCommandStack().getMostRecentCommand().getAffectedObjects().iterator().next();\n            } else {\n                modelImplementation.getEditingDomain().getCommandStack().undo();\n                modelImplementation.getModelEventPump().getRootContainer().clearHeldEvents();\n                modelImplementation.getModelEventPump().getRootContainer().setHoldEvents(\n                        false);\n            }\n        }\n        return null;\n    }\n    \n    /**\n     * Returns information about an Object.\n     * <p>\n     * If it's an Element it returns its metaclass name, and if it's a\n     * NamedElement it appends its name.\n     * \n     * @param o\n     *                The object\n     * @return the String description\n     */\n    public static String toString(Object o) {\n        if (o == null) {\n            return \"null\"; //$NON-NLS-1$\n        }\n        if (!(o instanceof Element)) {\n            return o.toString();\n        }\n        \n        StringBuilder sb = new StringBuilder(\"'\"); //$NON-NLS-1$\n        boolean named = false;\n        \n        if (o instanceof NamedElement && ((NamedElement) o).getName() != null\n                && !((NamedElement) o).getName().equals(\"\")) { //$NON-NLS-1$\n            named = true;\n            sb.append(((NamedElement) o).getName() + \" [\"); //$NON-NLS-1$\n        }\n        \n        sb.append(((Element) o).eClass().getName());\n        \n        if (named) {\n            sb.append(\"]\"); //$NON-NLS-1$\n        }\n        \n        sb.append(\"'\"); //$NON-NLS-1$\n        \n        return sb.toString();\n    }\n    \n    /**\n     * Returns the Resource associated with an URI or creates the resource if it\n     * does not exist\n     * \n     * @param modelImplementation\n     *                the eUML implementation\n     * @param uri\n     *                the URI which identifies the resource\n     * @return the retrieved or created resource\n     */\n    static Resource getResource(\n            EUMLModelImplementation modelImplementation, URI uri,\n            boolean readOnly) {\n        if (!\"xmi\".equals(uri.fileExtension()) //$NON-NLS-1$\n                && !\"uml\".equals(uri.fileExtension())) { //$NON-NLS-1$\n            // Make sure we have a recognized file extension\n            uri = uri.appendFileExtension(\"xmi\"); //$NON-NLS-1$\n        }\n        Resource r = modelImplementation.getEditingDomain().getResourceSet()\n                .getResource(uri, false);\n        if (r == null) {\n            r = modelImplementation.getEditingDomain().getResourceSet()\n                    .createResource(uri);\n        }\n        if (r == null) {\n            throw new NullPointerException(\"Failed to create resource for URI \"  //$NON-NLS-1$\n                    + uri);\n        }\n        modelImplementation.getReadOnlyMap().put(r, Boolean.valueOf(readOnly));\n        return r;\n    }\n\n\n    @SuppressWarnings(\"unchecked\")\n    static void checkArgs(Object[] args, Class[] types) {\n        if (args.length != types.length) {\n            throw new IllegalArgumentException(\n                    \"Mismatched array lengths for args and types\"); //$NON-NLS-1$\n        }\n        for (int i = 0; i < args.length; i++) {\n            if (!types[i].isAssignableFrom(args[i].getClass())) {\n                throw new IllegalArgumentException(\n                        \"Parameter \" + i + \" must be of type \" + types[i]);  //$NON-NLS-1$//$NON-NLS-2$\n            }\n        }\n    }\n}\n", "human_rating": 2.1686490000000003, "metadata": {"project": "argoUML", "class": "org.argouml.model.euml.UMLUtil", "source_path": "argoUML/sourcefiles/src/argouml-core-model-euml/src/org/argouml/model/euml/UMLUtil.java", "label_probabilities": {"readability": [1.1e-19, 0.168649, 0.831351, 6.2769e-16], "understandability": [5.2603e-09, 0.0130497, 0.98695, 7.24968e-09], "complexity": [8.0885e-06, 0.995863, 0.00412839, 0.0], "modularization": [0.000793313, 0.99536, 0.00384636, 1.29162e-14], "overall": [2.40483e-09, 0.923577, 0.0764227, 4.4119e-16]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.euml.XmiReaderEUMLImpl", "source": "// $Id: XmiReaderEUMLImpl.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n/*******************************************************************************\n * Copyright (c) 2007-2012 Tom Morris and other contributors\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Tom Morris - initial implementation\n *    Bogdan Pistol - undo support & UUID maps for diagrams\n *    thn\n *****************************************************************************/\n\npackage org.argouml.model.euml;\n\nimport java.io.BufferedInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\nimport java.net.MalformedURLException;\nimport java.net.URL;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.argouml.model.NotImplementedException;\nimport org.argouml.model.UmlException;\nimport org.argouml.model.XmiReader;\nimport org.eclipse.emf.common.util.URI;\nimport org.eclipse.emf.ecore.EObject;\nimport org.eclipse.emf.ecore.impl.EStructuralFeatureImpl.BasicFeatureMapEntry;\nimport org.eclipse.emf.ecore.impl.EStructuralFeatureImpl.SimpleFeatureMapEntry;\nimport org.eclipse.emf.ecore.resource.Resource;\nimport org.eclipse.emf.ecore.util.FeatureMap.Entry;\nimport org.eclipse.emf.ecore.xml.type.AnyType;\nimport org.eclipse.uml2.uml.Element;\nimport org.xml.sax.InputSource;\n\n/**\n * The implementation of the XmiReader for EUML2.\n */\nclass XmiReaderEUMLImpl implements XmiReader {\n\n    private static final Logger LOG =\n        Logger.getLogger(XmiReaderEUMLImpl.class.getName());\n\n    /**\n     * The model implementation.\n     */\n    private EUMLModelImplementation modelImpl;\n\n    private static Set<String> searchDirs = new HashSet<String>();\n\n    private Resource resource;\n\n    /**\n     * Constructor.\n     *\n     * @param implementation\n     *            The ModelImplementation.\n     */\n    public XmiReaderEUMLImpl(EUMLModelImplementation implementation) {\n        modelImpl = implementation;\n    }\n\n    public int getIgnoredElementCount() {\n        return 0;\n    }\n\n    public String[] getIgnoredElements() {\n        // Not needed currently for UML 2\n        return new String[0];\n    }\n\n    public Map<String, Object> getXMIUUIDToObjectMap() {\n        if (resource == null) {\n            throw new IllegalStateException();\n        }\n        Map<String, Object> map = new HashMap<String, Object>();\n        Iterator<EObject> it = resource.getAllContents();\n        while (it.hasNext()) {\n            EObject o  = it.next();\n            map.put(resource.getURIFragment(o), o);\n        }\n        return map;\n    }\n\n\n    public Collection parse(InputSource inputSource, boolean readOnly)\n        throws UmlException {\n\n        if (inputSource == null) {\n            throw new NullPointerException(\n                    \"The input source must be non-null.\"); //$NON-NLS-1$\n        }\n        InputStream is = null;\n        boolean needsClosing = false;\n        String name = inputSource.getSystemId();\n        if (name == null) {\n            name = inputSource.getPublicId();\n        }\n        if (name == null) {\n            name = inputSource.toString();\n        }\n        LOG.log(Level.FINE, \"Parsing {0}\", name); //$NON-NLS-1$\n\n        if (inputSource.getByteStream() != null) {\n            is = inputSource.getByteStream();\n        } else if (inputSource.getSystemId() != null) {\n            try {\n                URL url = new URL(inputSource.getSystemId());\n                if (url != null) {\n                    LOG.log(Level.FINE, \"Parsing URL {0}\", url); //$NON-NLS-1$\n                    is = url.openStream();\n                    if (is != null) {\n                        is = new BufferedInputStream(is);\n                        needsClosing = true;\n                    }\n                }\n            } catch (MalformedURLException e) {\n                // do nothing\n            } catch (IOException e) {\n                // do nothing\n            }\n\n        }\n        if (is == null) {\n            throw new UnsupportedOperationException();\n        }\n\n        // TODO: Review - priority of public ID vs system ID has been reversed\n        // from original implementation\n        String id = inputSource.getPublicId();\n        if (id == null) {\n            id = inputSource.getSystemId();\n            if (id != null) {\n                // we only take the filename, not the whole system path\n                int ix = id.lastIndexOf('/');\n                if (ix != -1) {\n                    id = id.substring(ix + 1);\n                }\n            }\n        }\n\n        Resource r = UMLUtil.getResource(modelImpl,\n                URI.createURI(id), readOnly);\n\n        try {\n            modelImpl.getModelEventPump().stopPumpingEvents();\n            r.unload();\n            r.load(is, null);\n            // TODO: Some import-only UML 2 profiles trigger this - Investigate.\n//            if (!isUML2(r)) {\n//                throw new UmlException(\"Attempted to load non-UML 2.x file\");\n//            }\n            if (isUML14(r)) {\n                throw new UmlException(\n                        \"Attempted to load UML 1.4 file\"); //$NON-NLS-1$\n            }\n        } catch (IOException e) {\n            throw new UmlException(e);\n        } finally {\n            modelImpl.getModelEventPump().startPumpingEvents();\n            if (needsClosing) {\n                try {\n                    is.close();\n                } catch (IOException e) {\n                    throw new RuntimeException(e);\n                }\n            }\n        }\n        resource = r;\n        LOG.log(Level.FINE,\n                \"Parsed resource \" + resource  //$NON-NLS-1$\n                + \" with \" + resource.getContents().size() //$NON-NLS-1$\n                + \" elements\"); //$NON-NLS-1$\n        return r.getContents();\n    }\n\n    /**\n     * Test whether this is a UML2 file. Returns as soon as the first UML2\n     * element is seen.\n     *\n     * @param r resource containing loaded UML model\n     * @return true if any of the contained objects are instances of UML2\n     *         Element.\n     */\n    private boolean isUML2(Resource r) {\n        for (EObject eobj : r.getContents()) {\n            if (eobj instanceof Element) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    /**\n     * Attempt to detect ArgoUML/NetBeans MDR style UML 1.4 XMI files. These can\n     * be loaded without complaint by EMF, but they won't do us any good.\n     *\n     * @param r resource containing the loaded file\n     * @return true if XMI.header/XMI.metamodel contains xmi.name=\"UML\" and\n     *         xmi.version=\"1.4\"\n     */\n    private boolean isUML14(Resource r) {\n        for (EObject eobj : r.getContents()) {\n            if (\"XMI.header\".equals(eobj.eClass().getName())) {\n                for (Entry e1 : ((AnyType) eobj).getMixed()) {\n                    if (e1 instanceof BasicFeatureMapEntry) {\n                        BasicFeatureMapEntry x1 = (BasicFeatureMapEntry) e1;\n                        String n1 = x1.getEStructuralFeature().getName();\n                        if (\"XMI.metamodel\".equals(n1)) {\n                            AnyType v = (AnyType) x1.getValue();\n                            for (Entry e2 : v.getAnyAttribute()) {\n                                if (e2 instanceof SimpleFeatureMapEntry) {\n                                    SimpleFeatureMapEntry x = (SimpleFeatureMapEntry) e2;\n                                    String n = x.getEStructuralFeature().getName();\n                                    if (\"xmi.name\".equals(n)) {\n                                        if (!(\"UML\".equals((String) x.getValue()))) {\n                                            LOG.log(Level.WARNING,\n                                                    \"Tried to parse XMI file with \"\n                                                     + \"XMI.header/XMI.metamodel/xmi.name = \"\n                                                     + (String) x.getValue());\n                                            return false;\n                                        }\n                                    } else if (\"xmi.version\".equals(n)) {\n                                        String version = (String) x.getValue();\n                                        if (version != null\n                                                && version.startsWith(\"1.4\")) {\n                                            LOG.log(Level.FINE,\n                                                    \"Tried to parse XMI file with \"\n                                                    + \"XMI.header/XMI.metamodel/xmi.version = \"\n                                                    + version);\n                                            return true;\n                                        }\n                                    }\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n        }\n        return false;\n    }\n\n    public boolean setIgnoredElements(String[] elementNames) {\n        if (elementNames == null) {\n            return true;\n        }\n        throw new NotImplementedException(\n                \"setIgnoredElements not implemented for UML 2.x\");\n        // TODO: Silently ignore instead?\n//        return false;\n    }\n\n    public String getTagName() {\n        if (resource == null) {\n            return \"uml:Model\"; //$NON-NLS-1$\n        }\n        List l = resource.getContents();\n        if (!l.isEmpty()) {\n            return \"uml:\" //$NON-NLS-1$\n                    + modelImpl.getMetaTypes().getName(l.get(0));\n        } else {\n            return null;\n        }\n    }\n\n    public void addSearchPath(String path) {\n        searchDirs.add(path);\n    }\n\n    public List<String> getSearchPath() {\n        return new ArrayList<String>(searchDirs);\n    }\n\n    public void removeSearchPath(String path) {\n        searchDirs.remove(path);\n    }\n\n    public String getHeader() {\n        // TODO: Auto-generated method stub\n        throw new NotYetImplementedException();\n    }\n\n}\n", "human_rating": 1.8966985811, "metadata": {"project": "argoUML", "class": "org.argouml.model.euml.XmiReaderEUMLImpl", "source_path": "argoUML/sourcefiles/src/argouml-core-model-euml/src/org/argouml/model/euml/XmiReaderEUMLImpl.java", "label_probabilities": {"readability": [0.0, 7.21937e-05, 0.896555, 0.103372], "understandability": [0.0, 2.29392e-05, 0.630307, 0.36967], "complexity": [0.357776, 0.642224, 0.0, 0.0], "modularization": [0.0, 1.0, 2.36173e-11, 0.0], "overall": [0.0, 0.0, 7.07932e-06, 0.999993]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.mdr.CollaborationsHelperMDRImpl", "source": "/* $Id: CollaborationsHelperMDRImpl.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.model.mdr;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.jmi.reflect.InvalidObjectException;\n\nimport org.argouml.model.CollaborationsHelper;\nimport org.argouml.model.CoreHelper;\nimport org.argouml.model.InvalidElementException;\nimport org.argouml.model.Model;\nimport org.argouml.model.ModelManagementHelper;\nimport org.omg.uml.behavioralelements.collaborations.AssociationEndRole;\nimport org.omg.uml.behavioralelements.collaborations.AssociationRole;\nimport org.omg.uml.behavioralelements.collaborations.ClassifierRole;\nimport org.omg.uml.behavioralelements.collaborations.Collaboration;\nimport org.omg.uml.behavioralelements.collaborations.Interaction;\nimport org.omg.uml.behavioralelements.collaborations.Message;\nimport org.omg.uml.behavioralelements.commonbehavior.Action;\nimport org.omg.uml.behavioralelements.commonbehavior.Instance;\nimport org.omg.uml.behavioralelements.commonbehavior.Stimulus;\nimport org.omg.uml.foundation.core.AssociationEnd;\nimport org.omg.uml.foundation.core.Classifier;\nimport org.omg.uml.foundation.core.Feature;\nimport org.omg.uml.foundation.core.ModelElement;\nimport org.omg.uml.foundation.core.Namespace;\nimport org.omg.uml.foundation.core.Operation;\nimport org.omg.uml.foundation.core.UmlAssociation;\nimport org.omg.uml.modelmanagement.UmlPackage;\n\n/**\n * Helper class for UML BehavioralElements::Collaborations Package.\n * <p>\n * @since ARGO0.19.5\n * @author Ludovic Ma&icirc;tre\n * @author Tom Morris\n * Derived from NSUML implementation by:\n * @author Thierry Lach\n */\nclass CollaborationsHelperMDRImpl implements CollaborationsHelper {\n\n    /**\n     * The model implementation.\n     */\n    private MDRModelImplementation modelImpl;\n\n    private static final Logger LOG =\n        Logger.getLogger(CollaborationsHelperMDRImpl.class.getName());\n\n    /**\n     * Constructor.\n     *\n     * @param implementation\n     *            To get other helpers and factories.\n     */\n    CollaborationsHelperMDRImpl(MDRModelImplementation implementation) {\n        modelImpl = implementation;\n    }\n\n\n    public Collection<ClassifierRole> getAllClassifierRoles(Object ns) {\n        if (!(ns instanceof Namespace)) {\n            throw new IllegalArgumentException();\n        }\n\n        try {\n            List<ClassifierRole> list = new ArrayList<ClassifierRole>();\n            for (Object o : ((Namespace) ns).getOwnedElement()) {\n                if (o instanceof Namespace) {\n                    list.addAll(getAllClassifierRoles(o));\n                }\n                if (o instanceof ClassifierRole) {\n                    list.add((ClassifierRole) o);\n                }\n            }\n            return list;\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n    }\n\n\n    public Collection getAllPossibleAssociationRoles(Object roleArg) {\n        if (!(roleArg instanceof ClassifierRole)) {\n            throw new IllegalArgumentException();\n        }\n\n        ClassifierRole role = (ClassifierRole) roleArg;\n\n        try {\n            if (role.getBase().isEmpty()) {\n                return Collections.emptyList();\n            }\n            Set associations = new HashSet();\n            for (Classifier base : role.getBase()) {\n                associations.addAll(\n                        modelImpl.getCoreHelper().getAssociations(base));\n            }\n            return associations;\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n    }\n\n\n    public Collection<Classifier> getClassifierRoles(Object role) {\n        if (role == null) {\n            return Collections.emptySet();\n        }\n\n        if (!(role instanceof ClassifierRole)) {\n            throw new IllegalArgumentException();\n        }\n\n        List<Classifier> roles = new ArrayList<Classifier>();\n        try {\n            Collection<AssociationEnd> associationEnds =\n                Model.getFacade().getAssociationEnds(role);\n            if (!associationEnds.isEmpty()) {\n                for (AssociationEnd end : associationEnds) {\n                    if (end instanceof AssociationEndRole) {\n                        UmlAssociation assoc = end.getAssociation();\n                        for (AssociationEnd end2 : assoc.getConnection()) {\n                            Classifier classifier = end2.getParticipant();\n                            if (classifier != role\n                                    && classifier instanceof ClassifierRole) {\n                                roles.add(classifier);\n                            }\n                        }\n                    }\n                }\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        return roles;\n    }\n\n\n    public Object getAssociationRole(Object afrom, Object ato) {\n        if (afrom == null || ato == null) {\n            throw new IllegalArgumentException();\n        }\n        ClassifierRole from = (ClassifierRole) afrom;\n        ClassifierRole to = (ClassifierRole) ato;\n\n        try {\n            Collection<AssociationEnd> ends =\n                Model.getFacade().getAssociationEnds(from);\n            for (AssociationEnd end : ends) {\n                if (end instanceof AssociationEndRole) {\n                    UmlAssociation assoc = end.getAssociation();\n                    for (AssociationEnd end2 : assoc.getConnection()) {\n                        Classifier classifier = end2.getParticipant();\n                        if (classifier == to) {\n                            return assoc;\n                        }\n                    }\n                }\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        return null;\n    }\n\n\n    public Collection<Message> getAllPossibleActivators(Object ames) {\n        Message mes = (Message) ames;\n        if (mes == null || mes.getInteraction() == null) {\n            return Collections.unmodifiableCollection(Collections.EMPTY_LIST);\n        }\n\n        try {\n            Interaction inter = mes.getInteraction();\n            Collection<Message> predecessors = mes.getPredecessor();\n            Collection<Message> allMessages = inter.getMessage();\n            List<Message> list = new ArrayList<Message>();\n            for (Message m : allMessages) {\n                if (!predecessors.contains(m) && mes != m\n                        && !hasAsActivator(m, mes)\n                        && !m.getPredecessor().contains(mes)) {\n                    list.add(m);\n                }\n            }\n            return list;\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n    }\n\n\n    public boolean hasAsActivator(Object message, Object activator) {\n        if (!(message instanceof Message)) {\n            throw new IllegalArgumentException();\n        }\n        if (!(activator instanceof Message)) {\n            throw new IllegalArgumentException();\n        }\n\n        try {\n            Message messActivator = ((Message) message).getActivator();\n            if (messActivator == null) {\n                return false;\n            }\n            if (messActivator == activator\n                    || messActivator.getPredecessor().contains(activator)) {\n                return true;\n            }\n            return hasAsActivator(messActivator, activator);\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n    }\n\n\n    public void setActivator(Object ames, Object anactivator) {\n        if (ames == null) {\n            throw new IllegalArgumentException(\"message is null\");\n        }\n        if (!(ames instanceof Message)) {\n            throw new IllegalArgumentException(\"message\");\n        }\n        if (anactivator != null && !(anactivator instanceof Message)) {\n            throw new IllegalArgumentException(\n                    \"An activator must be a message\");\n        }\n        Message mes = (Message) ames;\n        Message activator = (Message) anactivator;\n        if (mes == activator) {\n            throw new IllegalArgumentException(\"In setActivator: message may \"\n                    + \"not be equal to activator\");\n        }\n\n        if (activator != null) {\n            if (mes.getInteraction() != activator.getInteraction()) {\n                throw new IllegalArgumentException(\n                        \"In setActivator: interaction \"\n                                + \"of message should equal \"\n                                + \"interaction of activator\");\n            }\n            // we must find out if the activator itself does not have\n            // message as it's activator\n            if (hasAsActivator(activator, mes)) {\n                throw new IllegalArgumentException(\n                        \"In setActivator: message may \"\n                                + \"not be the activator for \"\n                                + \"the original activator\");\n            }\n            // An activator can't also be a predecessor of a message\n            if (mes.getPredecessor().contains(activator)) {\n                mes.getPredecessor().remove(activator);\n            }\n        }\n        List<Message> listToChange = new ArrayList<Message>();\n        Collection<Message> predecessors = mes.getPredecessor();\n        listToChange.addAll(predecessors);\n        listToChange.add(mes);\n        Interaction inter = mes.getInteraction();\n        for (Message mes2 : inter.getMessage()) {\n            if (mes2.getPredecessor().contains(mes)) {\n                listToChange.add(mes2);\n            }\n        }\n        // This causes problems. It can make multiple return messages\n        // refer to the same activator even if not returning to the same\n        // classifier role as the activator emenates from.\n        // I'm not sure that changing the activator of one message\n        // should amend any other messages but this is certainly changing\n        // too many - Bob.\n        for (Message mes2 : listToChange) {\n            mes2.setActivator(activator);\n        }\n\n    }\n\n\n    public Collection<Message> getAllPossiblePredecessors(Object amessage) {\n        Message message = (Message) amessage;\n        if (message == null) {\n            throw new IllegalArgumentException(\n                    \"In getAllPossiblePredecessors: \"\n                            + \"argument message is null\");\n        }\n\n        try {\n            Interaction inter = message.getInteraction();\n            List<Message> list = new ArrayList<Message>();\n            for (Message mes : inter.getMessage()) {\n                if (mes.getActivator() == message.getActivator()\n                        && message != mes\n                        && !mes.getPredecessor().contains(message)\n                        && !message.getPredecessor().contains(message)) {\n                    list.add(mes);\n                }\n            }\n            return list;\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n    }\n\n\n    public void addBase(Object arole, Object abase) {\n        ClassifierRole role = (ClassifierRole) arole;\n        Classifier base = (Classifier) abase;\n        if (role == null || base == null) {\n            throw new IllegalArgumentException(\"In addBase: either the role \"\n                    + \"or the base is null\");\n        }\n        role.getBase().add(base);\n        if (modelImpl.getFacade().getBases(role).size() == 1) {\n            role.getAvailableContents().clear();\n            role.getAvailableContents().addAll(base.getOwnedElement());\n            role.getAvailableFeature().clear();\n            role.getAvailableFeature().addAll(base.getFeature());\n        } else {\n            for (ModelElement elem : base.getOwnedElement()) {\n                if (!role.getAvailableContents().contains(elem)) {\n                    role.getAvailableContents().add(elem);\n                }\n            }\n            for (Feature feature : base.getFeature()) {\n                if (!role.getAvailableFeature().contains(feature)) {\n                    role.getAvailableFeature().add(feature);\n                }\n            }\n        }\n    }\n\n    public void setBases(Object role, Collection bases) {\n        if (role == null || bases == null) {\n            throw new IllegalArgumentException(\"In setBases: either the role \"\n                    + \"or the collection bases is \" + \"null\");\n        }\n        CollectionHelper.update(((ClassifierRole) role).getBase(), bases);\n    }\n\n\n    public Collection<Feature> allAvailableFeatures(Object arole) {\n        LOG.log(Level.INFO, \"allAvailableFeatures start\");\n\n        if (arole instanceof ClassifierRole) {\n            try {\n                List<Feature> returnList = new ArrayList<Feature>();\n                ClassifierRole role = (ClassifierRole) arole;\n                for (ModelElement genElem\n                        : CoreHelperMDRImpl.getAllParents(role)) {\n                    if (genElem instanceof ClassifierRole) {\n                        returnList.addAll(allAvailableFeatures(genElem));\n                    }\n                }\n                for (Classifier classifier : role.getBase()) {\n                    returnList.addAll(classifier.getFeature());\n                }\n                LOG.log(Level.INFO, \"allAvailableFeatures {0}\", returnList.size());\n                return returnList;\n            } catch (InvalidObjectException e) {\n                throw new InvalidElementException(e);\n            }\n        }\n        throw new IllegalArgumentException(\"Cannot get available features on \"\n                + arole);\n    }\n\n\n    public Collection allAvailableContents(Object arole) {\n        LOG.log(Level.INFO, \"allAvailableContents start\");\n        try {\n            if (arole instanceof ClassifierRole) {\n                List returnList = new ArrayList();\n                ClassifierRole role = (ClassifierRole) arole;\n                for (ModelElement genElem\n                        : CoreHelperMDRImpl.getAllParents(role)) {\n                    if (genElem instanceof ClassifierRole) {\n                        returnList.addAll(allAvailableContents(genElem));\n                    }\n                }\n                for (Classifier baseClassifier : role.getBase()) {\n                    returnList.addAll(baseClassifier.getOwnedElement());\n                }\n                LOG.log(Level.INFO, \"allAvailableFeatures {0}\", returnList.size());\n                return returnList;\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        throw new IllegalArgumentException(\"Cannot get available contents on \"\n                + arole);\n    }\n\n\n    public Collection getAllPossibleBases(Object role) {\n        try {\n            if (role instanceof ClassifierRole) {\n                return getAllPossibleBases((ClassifierRole) role);\n            } else if (role instanceof AssociationRole) {\n                return getAllPossibleBases((AssociationRole) role);\n            } else {\n                throw new IllegalArgumentException(\"Illegal type \" + role);\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n    }\n\n    /**\n     * Returns all possible bases for some AssociationRole taking into account\n     * the wellformednessrules as defined in section 2.10.3 of the UML 1.3 spec.\n     * <p>\n     * Beware: this function does not return the actual base!\n     * Which is by design; there are easier ways to retrieve the actual base.\n     *\n     * @param aRole\n     *            the given associationrole\n     * @return Collection all possible bases\n     */\n    private Collection getAllPossibleBases(AssociationRole aRole) {\n        Set<UmlAssociation> ret = new HashSet<UmlAssociation>();\n        if (aRole == null || aRole.getNamespace() == null) {\n            return ret;\n        }\n\n        // find the bases of the connected classifierroles so that we can see\n        // what associations are between them. If there are bases then the\n        // associations between those bases form the possible bases. Otherwise\n        // the bases are formed by all associations in the namespace of the\n        // collaboration\n        Set<Classifier> bases = new HashSet<Classifier>();\n        for (AssociationEnd end : aRole.getConnection()) {\n            assert end instanceof AssociationEndRole;\n            ClassifierRole type = (ClassifierRole) end.getParticipant();\n            if (type != null) {\n                bases.addAll(type.getBase());\n            }\n        }\n        if (bases.isEmpty()) {\n            ModelManagementHelper mmh = modelImpl.getModelManagementHelper();\n            Namespace ns =\n                ((Collaboration) aRole.getNamespace()).getNamespace();\n            ret.addAll(\n                    mmh.getAllModelElementsOfKind(ns, UmlAssociation.class));\n            ret.removeAll(mmh.getAllModelElementsOfKind(ns,\n                    AssociationRole.class));\n        } else {\n            CoreHelper ch = modelImpl.getCoreHelper();\n            /* This double 'for' loop may be optimised as follows:\n             * - Use arrays in stead of a Set for bases\n             * - Have the second loop start from the element after base1\n             * ... but I chose not to do this, since the gain is small,\n             * and this is only used for a lazily filled combo.\n             * BTW: This is also used by Notation.*/\n            for (Classifier base1 : bases)  {\n                for (Classifier base2 : bases) {\n                    // include associations to self - see issue 5602\n                    ret.addAll(ch.getAssociations(base1, base2));\n                }\n            }\n        }\n        // An Association can only have a single unnamed ClassifierRole, so\n        Collection<UmlAssociation> listToRemove = new ArrayList<UmlAssociation>();\n        for (UmlAssociation association : ret) {\n            Collection<AssociationRole> associationRoles =\n                ((org.omg.uml.UmlPackage) (association)\n                    .refOutermostPackage()).getCollaborations()\n                    .getABaseAssociationRole().getAssociationRole(association);\n            if (associationRoles.isEmpty()) {\n                continue;\n            }\n            // if we are unnamed eliminate all classifiers which are already\n            // the base of some role\n            if (aRole.getName() == null || aRole.getName().equals(\"\")) {\n                listToRemove.add(association);\n            } else {\n                // eliminate Classifiers which already have an unnamed role\n                for (AssociationRole ar : associationRoles) {\n                    if (ar.getName() == null || ar.getName().equals(\"\")) {\n                        listToRemove.add(association);\n                    }\n                }\n            }\n        }\n        ret.removeAll(listToRemove);\n\n        return ret;\n    }\n\n    /**\n     * Returns all possible bases for some classifierrole taking into account\n     * the wellformednessrules as defined in section 2.10.3 of the UML 1.4 spec.\n     * <p>\n     *\n     * @param role\n     *            the given classifierrole\n     * @return Collection all possible bases\n     */\n    private Collection getAllPossibleBases(ClassifierRole role) {\n        if (role == null || modelImpl.getFacade().getNamespace(role) == null) {\n            return Collections.EMPTY_SET;\n        }\n        Collaboration collaboration = (Collaboration) role.getNamespace();\n        Namespace ns = collaboration.getNamespace();\n        ModelManagementHelper mmh = modelImpl.getModelManagementHelper();\n        Collection<Classifier> returnList = mmh.getAllModelElementsOfKind(ns,\n                Classifier.class);\n        // WFR 2.10.3.3 #4\n        returnList.removeAll(mmh.getAllModelElementsOfKind(ns,\n                ClassifierRole.class));\n\n        // A Classifier can only have a single unnamed ClassifierRole, so\n        // TODO: This probably belongs in a critic instead of here\n        Collection<Classifier> listToRemove = new ArrayList<Classifier>();\n        for (Classifier classifier : returnList) {\n            Collection<ClassifierRole> classifierRoles =\n                ((org.omg.uml.UmlPackage) (classifier)\n                    .refOutermostPackage()).getCollaborations()\n                    .getAClassifierRoleBase().getClassifierRole(classifier);\n            if (classifierRoles.isEmpty()) {\n                continue;\n            }\n            // if we are unnamed eliminate all classifiers which are already\n            // the base of some role\n            if (role.getName() == null || role.getName().equals(\"\")) {\n                listToRemove.add(classifier);\n            } else {\n                // eliminate Classifiers which already have an unnamed role\n                for (ClassifierRole cr : classifierRoles) {\n                    if (cr.getName() == null || cr.getName().equals(\"\")) {\n                        listToRemove.add(classifier);\n                    }\n                }\n            }\n        }\n        returnList.removeAll(listToRemove);\n\n        /* We need to verify that ns is a Package,\n         * if not - find its parent package!\n         * Otherwise this causes an exception when creating\n         * a sequence diagram for a ClassifierRole.*/\n        if (!(ns instanceof UmlPackage)) {\n            while (ns != null) {\n                ns = ns.getNamespace();\n                if (ns instanceof UmlPackage) {\n                    break;\n                }\n            }\n        }\n        // now get all classifiers imported from other packages\n        // TODO: This should probably happen automatically in\n        // getAllModelElementsOfKind() - tfm\n        if (modelImpl.getFacade().isAPackage(ns)) {\n            returnList.addAll(getAllImportedClassifiers(ns));\n        }\n\n        return returnList;\n    }\n\n    /**\n     * Return a collection of classifiers that are imported from other packages\n     * into the given namespace.\n     *\n     * @param obj the given namespace\n     * @return a collection of classifiers\n     */\n    private Collection<Classifier> getAllImportedClassifiers(Object obj) {\n        Collection c = modelImpl.getModelManagementHelper()\n                        .getAllImportedElements(obj);\n        return filterClassifiers(c);\n    }\n\n    private Collection<Classifier> filterClassifiers(Collection in) {\n        Collection<Classifier> out = new ArrayList<Classifier>();\n        for (Object o : in) {\n            if (o instanceof Classifier && !(o instanceof ClassifierRole))\n                out.add((Classifier) o);\n        }\n        return out;\n    }\n\n\n    public void setBase(Object arole, Object abase) {\n        if (arole == null) {\n            throw new IllegalArgumentException(\"role is null\");\n        }\n        if (arole instanceof AssociationRole) {\n            AssociationRole role = (AssociationRole) arole;\n            UmlAssociation base = (UmlAssociation) abase;\n\n            // TODO: Must we calculate the whole list?\n            if (base != null && !getAllPossibleBases(role).contains(base)) {\n                throw new IllegalArgumentException(\"base is not allowed for \"\n                        + \"this role\");\n            }\n            role.setBase(base);\n            ClassifierRole sender = (ClassifierRole) modelImpl.getCoreHelper()\n                    .getSource(role);\n            ClassifierRole receiver = (ClassifierRole) modelImpl\n                    .getCoreHelper().getDestination(role);\n            Collection<Classifier> senderBases = sender.getBase();\n            Collection<Classifier> receiverBases = receiver.getBase();\n\n            AssociationEndRole senderRole = (AssociationEndRole) modelImpl.\n                getCoreHelper().getAssociationEnd(sender, role);\n            AssociationEndRole receiverRole = (AssociationEndRole) modelImpl.\n                getCoreHelper().getAssociationEnd(receiver, role);\n\n            if (base != null) {\n                for (AssociationEnd end : base.getConnection()) {\n                    if (senderBases.contains(end.getParticipant())) {\n                        senderRole.setBase(end);\n                    } else if (receiverBases.contains(end.getParticipant())) {\n                        receiverRole.setBase(end);\n                    }\n                }\n            }\n\n            return;\n        } else if (arole instanceof AssociationEndRole) {\n            AssociationEndRole role = (AssociationEndRole) arole;\n            AssociationEnd base = (AssociationEnd) abase;\n\n            role.setBase(base);\n\n            return;\n        }\n\n        throw new IllegalArgumentException(\"role\");\n    }\n\n\n    public boolean isAddingCollaborationAllowed(Object context) {\n        return (\n                context instanceof Classifier\n                || context instanceof Operation\n                //|| context instanceof Collaboration\n                //|| context instanceof Model\n                );\n    }\n\n\n    public void removeBase(Object handle, Object c) {\n        try {\n            if (handle instanceof ClassifierRole && c instanceof Classifier) {\n                ((ClassifierRole) handle).getBase().remove(c);\n\n                return;\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        throw new IllegalArgumentException(\n                \"There must be a ClassifierRole and a Classifier\");\n    }\n\n\n    public void removeConstrainingElement(Object handle, Object constraint) {\n        try {\n            if (handle instanceof Collaboration\n                    && constraint instanceof ModelElement) {\n                Collaboration collab = (Collaboration) handle;\n                collab.getConstrainingElement().remove(constraint);\n\n                return;\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle\n                + \" or constraint: \" + constraint);\n    }\n\n\n    public void removeMessage(Object handle, Object message) {\n        try {\n            if (handle instanceof Interaction && message instanceof Message) {\n                ((Interaction) handle).getMessage().remove(message);\n                return;\n            }\n            if (handle instanceof AssociationRole\n                    && message instanceof Message) {\n                ((AssociationRole) handle).getMessage().remove(message);\n                return;\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle\n                + \" or message: \" + message);\n    }\n\n\n    public void removeSuccessor(Object handle, Object mess) {\n        try {\n            if (handle instanceof Message && mess instanceof Message) {\n                ((org.omg.uml.UmlPackage) ((Message) handle)\n                        .refOutermostPackage()).getCollaborations()\n                        .getAPredecessorSuccessor().remove((Message) handle,\n                                (Message) mess);\n                return;\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        throw new IllegalArgumentException(\"predecessor: \" + handle\n                + \" or successor: \" + mess);\n    }\n\n\n    public void removePredecessor(Object handle, Object message) {\n        try {\n            if (handle instanceof Message && message instanceof Message) {\n                ((Message) handle).getPredecessor().remove(message);\n                return;\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle\n                + \" or message: \" + message);\n    }\n\n\n    public void addConstrainingElement(Object handle, Object constraint) {\n        if (handle instanceof Collaboration\n                && constraint instanceof ModelElement) {\n            ((Collaboration) handle).getConstrainingElement().add(\n                    (ModelElement) constraint);\n            return;\n        }\n\n        throw new IllegalArgumentException(\"handle: \" + handle\n                + \" or constraint: \" + constraint);\n    }\n\n\n    public void addInstance(Object classifierRole, Object instance) {\n        if (classifierRole instanceof ClassifierRole\n                && instance instanceof Instance) {\n            ((ClassifierRole) classifierRole).getConformingInstance().add(\n                    (Instance) instance);\n        }\n        throw new IllegalArgumentException(\"classifierRole: \" + classifierRole\n                + \" or instance: \" + instance);\n    }\n\n\n    public void addMessage(Object handle, Object elem) {\n        if (handle instanceof Interaction && elem instanceof Message) {\n            final Message message = (Message) elem;\n            final Interaction interaction = (Interaction) handle;\n            final Interaction oldInteraction = message.getInteraction();\n\n            if (oldInteraction != null) {\n                oldInteraction.getMessage().remove(message);\n            }\n            interaction.getMessage().add(message);\n            return;\n        }\n        if (handle instanceof AssociationRole && elem instanceof Message) {\n            ((AssociationRole) handle).getMessage().add((Message) elem);\n            return;\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle + \" or elem: \"\n                + elem);\n    }\n\n\n    public void addSuccessor(Object handle, Object mess) {\n        if (handle instanceof Message && mess instanceof Message) {\n            ((Message) mess).getPredecessor().add((Message) handle);\n            return;\n        }\n\n        throw new IllegalArgumentException(\"predecessor: \" + handle\n                + \" or successor: \" + mess);\n    }\n\n\n    public void addPredecessor(Object handle, Object predecessor) {\n        if (handle != null && handle instanceof Message && predecessor != null\n                && predecessor instanceof Message) {\n            ((Message) handle).getPredecessor().add((Message) predecessor);\n            return;\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle\n                + \" or predecessor: \" + predecessor);\n    }\n\n\n    public void setAction(Object handle, Object action) {\n        if (handle instanceof Message\n                && (action == null || action instanceof Action)) {\n            ((Message) handle).setAction((Action) action);\n            return;\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle + \" or action: \"\n                + action);\n    }\n\n\n    public void setContext(Object handle, Object col) {\n        if (handle instanceof Interaction\n                && (col instanceof Collaboration || col == null)) {\n            ((Interaction) handle).setContext((Collaboration) col);\n\n            return;\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle + \" or col: \"\n                + col);\n    }\n\n\n    public void setSuccessors(Object handle, Collection messages) {\n        if (handle instanceof Message) {\n            Collection currentMessages =\n                Model.getFacade().getSuccessors(handle);\n            if (!currentMessages.isEmpty()) {\n                Collection successors = new ArrayList(currentMessages);\n                for (Object msg : successors) {\n                    removeSuccessor(handle, msg);\n                }\n            }\n            for (Object msg : messages) {\n                addSuccessor(handle, msg);\n            }\n            return;\n        }\n\n        throw new IllegalArgumentException(\"predecessor: \" + handle\n                + \" or messages: \" + messages);\n    }\n\n    public void setMessageSort(Object message, Object messageSort) {\n        setAction(message, messageSort);\n    }\n\n    public void setPredecessors(Object handle, Collection predecessors) {\n        if (handle instanceof Message) {\n            CollectionHelper.update(\n                    ((Message) handle).getPredecessor(), predecessors);\n            return;\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle\n                + \" or predecessors: \" + predecessors);\n    }\n\n\n    public void setRepresentedClassifier(Object handle, Object classifier) {\n        if (handle instanceof Collaboration\n                && ((classifier == null) || classifier instanceof Classifier)) {\n            ((Collaboration) handle).\n                setRepresentedClassifier((Classifier) classifier);\n            return;\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle\n                + \" or classifier: \" + classifier);\n    }\n\n\n    public void setRepresentedOperation(Object handle, Object operation) {\n        if (handle instanceof Collaboration\n                && ((operation == null) || operation instanceof Operation)) {\n            ((Collaboration) handle).\n                setRepresentedOperation((Operation) operation);\n\n            return;\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle\n                + \" or operation: \" + operation);\n    }\n\n\n    public void setSender(Object handle, Object sender) {\n        if (handle instanceof Message\n                && (sender instanceof ClassifierRole || sender == null)) {\n            ((Message) handle).setSender((ClassifierRole) sender);\n            return;\n        }\n        if (handle instanceof Stimulus && sender instanceof Instance) {\n            ((Stimulus) handle).setSender((Instance) sender);\n            return;\n        }\n        throw new IllegalArgumentException(\"handle: \" + handle + \" or sender: \"\n                + sender);\n    }\n\n\n    public void removeInteraction(Object collab, Object interaction) {\n        try {\n            if (collab instanceof Collaboration\n                    && interaction instanceof Interaction) {\n                ((Collaboration) collab).getInteraction().remove(interaction);\n                return;\n            }\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        throw new IllegalArgumentException(\"collab: \" + collab\n                + \" or interaction: \" + interaction);\n    }\n}\n", "human_rating": 2.072277900005382, "metadata": {"project": "argoUML", "class": "org.argouml.model.mdr.CollaborationsHelperMDRImpl", "source_path": "argoUML/sourcefiles/src/argouml-core-model-mdr/src/org/argouml/model/mdr/CollaborationsHelperMDRImpl.java", "label_probabilities": {"readability": [1.92759e-13, 0.0722773, 0.927723, 4.61098e-12], "understandability": [9.89714e-11, 0.00647596, 0.992819, 0.000705395], "complexity": [0.0190783, 0.893088, 0.0878342, 6.50472e-11], "modularization": [0.0182244, 0.680318, 0.301457, 4.57405e-08], "overall": [0.0, 0.0434563, 0.956538, 6.02885e-06]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.mdr.CoreFactoryMDRImpl", "source": "/* $Id: CoreFactoryMDRImpl.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *    Thomas Neustupny\n *    Tom Morris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.model.mdr;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.jmi.reflect.InvalidObjectException;\nimport javax.jmi.reflect.RefObject;\n\nimport org.argouml.model.CoreFactory;\nimport org.argouml.model.Model;\nimport org.argouml.model.ModelCommand;\nimport org.argouml.model.ModelManagementHelper;\nimport org.argouml.model.NotImplementedException;\nimport org.omg.uml.behavioralelements.activitygraphs.ObjectFlowState;\nimport org.omg.uml.behavioralelements.commonbehavior.Reception;\nimport org.omg.uml.behavioralelements.commonbehavior.Signal;\nimport org.omg.uml.behavioralelements.statemachines.Event;\nimport org.omg.uml.foundation.core.Abstraction;\nimport org.omg.uml.foundation.core.Artifact;\nimport org.omg.uml.foundation.core.AssociationClass;\nimport org.omg.uml.foundation.core.AssociationEnd;\nimport org.omg.uml.foundation.core.Attribute;\nimport org.omg.uml.foundation.core.BehavioralFeature;\nimport org.omg.uml.foundation.core.Binding;\nimport org.omg.uml.foundation.core.Classifier;\nimport org.omg.uml.foundation.core.Comment;\nimport org.omg.uml.foundation.core.Component;\nimport org.omg.uml.foundation.core.Constraint;\nimport org.omg.uml.foundation.core.CorePackage;\nimport org.omg.uml.foundation.core.DataType;\nimport org.omg.uml.foundation.core.Dependency;\nimport org.omg.uml.foundation.core.Element;\nimport org.omg.uml.foundation.core.ElementResidence;\nimport org.omg.uml.foundation.core.Enumeration;\nimport org.omg.uml.foundation.core.EnumerationLiteral;\nimport org.omg.uml.foundation.core.Feature;\nimport org.omg.uml.foundation.core.Flow;\nimport org.omg.uml.foundation.core.GeneralizableElement;\nimport org.omg.uml.foundation.core.Generalization;\nimport org.omg.uml.foundation.core.Interface;\nimport org.omg.uml.foundation.core.Method;\nimport org.omg.uml.foundation.core.ModelElement;\nimport org.omg.uml.foundation.core.Namespace;\nimport org.omg.uml.foundation.core.Node;\nimport org.omg.uml.foundation.core.Operation;\nimport org.omg.uml.foundation.core.Parameter;\nimport org.omg.uml.foundation.core.Permission;\nimport org.omg.uml.foundation.core.PresentationElement;\nimport org.omg.uml.foundation.core.Primitive;\nimport org.omg.uml.foundation.core.ProgrammingLanguageDataType;\nimport org.omg.uml.foundation.core.Relationship;\nimport org.omg.uml.foundation.core.Stereotype;\nimport org.omg.uml.foundation.core.StructuralFeature;\nimport org.omg.uml.foundation.core.TemplateArgument;\nimport org.omg.uml.foundation.core.TemplateParameter;\nimport org.omg.uml.foundation.core.UmlAssociation;\nimport org.omg.uml.foundation.core.UmlClass;\nimport org.omg.uml.foundation.core.Usage;\nimport org.omg.uml.foundation.datatypes.AggregationKind;\nimport org.omg.uml.foundation.datatypes.AggregationKindEnum;\nimport org.omg.uml.foundation.datatypes.BooleanExpression;\nimport org.omg.uml.foundation.datatypes.CallConcurrencyKindEnum;\nimport org.omg.uml.foundation.datatypes.ChangeableKind;\nimport org.omg.uml.foundation.datatypes.ChangeableKindEnum;\nimport org.omg.uml.foundation.datatypes.Expression;\nimport org.omg.uml.foundation.datatypes.Multiplicity;\nimport org.omg.uml.foundation.datatypes.MultiplicityRange;\nimport org.omg.uml.foundation.datatypes.OrderingKind;\nimport org.omg.uml.foundation.datatypes.OrderingKindEnum;\nimport org.omg.uml.foundation.datatypes.ParameterDirectionKindEnum;\nimport org.omg.uml.foundation.datatypes.ProcedureExpression;\nimport org.omg.uml.foundation.datatypes.ScopeKind;\nimport org.omg.uml.foundation.datatypes.ScopeKindEnum;\nimport org.omg.uml.foundation.datatypes.VisibilityKind;\nimport org.omg.uml.foundation.datatypes.VisibilityKindEnum;\nimport org.omg.uml.modelmanagement.UmlPackage;\n\n/**\n * Factory to create UML classes for the UML Foundation::Core package.\n * <p>\n * Feature, StructuralFeature, and PresentationElement do not have a create\n * method since they are called an \"abstract metaclass\" in the UML\n * specifications.\n * <p>\n * @since ARGO0.19.5\n * @author Ludovic Ma&icirc;tre\n * @author Tom Morris\n * <p>\n * Derived from NSUML implementation by:\n * @author Thierry Lach\n * @author Jaap Branderhorst\n */\nclass CoreFactoryMDRImpl extends AbstractUmlModelFactoryMDR implements\n        CoreFactory {\n\n    private static final Logger LOG =\n        Logger.getLogger(CoreFactoryMDRImpl.class.getName());\n\n    /**\n     * The model implementation.\n     */\n    private MDRModelImplementation modelImpl;\n\n    /**\n     * Constructor.\n     *\n     * @param implementation\n     *            To get other helpers and factories.\n     */\n    CoreFactoryMDRImpl(MDRModelImplementation implementation) {\n        modelImpl = implementation;\n    }\n\n    private CorePackage getCorePackage() {\n        return modelImpl.getUmlPackage().getCore();\n    }\n\n    public Abstraction createAbstraction() {\n        Abstraction myAbstraction = getCorePackage().getAbstraction()\n                .createAbstraction();\n        super.initialize(myAbstraction);\n        return myAbstraction;\n    }\n\n\n    public Abstraction buildAbstraction(String name, Object supplier,\n            Object client) {\n        if (!(client instanceof Classifier)\n                || !(supplier instanceof Classifier)) {\n            throw new IllegalArgumentException(\n                    \"The supplier and client of an abstraction\"\n                            + \"should be classifiers\");\n        }\n        if (client.equals(supplier)) {\n            throw new IllegalArgumentException(\"The supplier and the client \"\n                    + \"must be different elements\");\n        }\n        Abstraction abstraction = createAbstraction();\n        abstraction.setName(name);\n        abstraction.getClient().add((Classifier) client);\n        abstraction.getSupplier().add((Classifier) supplier);\n        return abstraction;\n    }\n\n\n    public Artifact createArtifact() {\n        Artifact artifact = getCorePackage().getArtifact().createArtifact();\n        super.initialize(artifact);\n        return artifact;\n    }\n\n\n    @Deprecated\n    public UmlAssociation createAssociation() {\n        return createAssociation(modelImpl.getUmlPackage());\n    }\n\n\n    public UmlAssociation createAssociation(Object extent) {\n        UmlAssociation assoc = ((org.omg.uml.UmlPackage) extent).getCore()\n                .getUmlAssociation().createUmlAssociation();\n        super.initialize(assoc);\n        return assoc;\n    }\n\n    public AssociationClass createAssociationClass() {\n        AssociationClass assoc = getCorePackage().getAssociationClass()\n                .createAssociationClass();\n        super.initialize(assoc);\n        return assoc;\n    }\n\n\n    public AssociationEnd createAssociationEnd() {\n        AssociationEnd assocEnd = getCorePackage().getAssociationEnd()\n                .createAssociationEnd();\n        super.initialize(assocEnd);\n        return assocEnd;\n    }\n\n\n    public Attribute createAttribute() {\n        Attribute myAttribute = getCorePackage().getAttribute().createAttribute();\n        super.initialize(myAttribute);\n        return myAttribute;\n    }\n\n\n    public Binding createBinding() {\n        Binding myBinding = getCorePackage().getBinding().createBinding();\n        super.initialize(myBinding);\n        return myBinding;\n    }\n\n\n    public UmlClass createClass() {\n        return createClass(modelImpl.getUmlPackage());\n    }\n\n    public UmlClass createClass(org.omg.uml.UmlPackage extent) {\n        UmlClass myClass = extent.getCore().getUmlClass().createUmlClass();\n        super.initialize(myClass);\n        return myClass;\n    }\n\n    public Comment createComment() {\n        Comment myComment = getCorePackage().getComment().createComment();\n        super.initialize(myComment);\n        return myComment;\n    }\n\n\n    public Component createComponent() {\n        Component myComponent = getCorePackage().getComponent().createComponent();\n        super.initialize(myComponent);\n        return myComponent;\n    }\n\n\n    public Constraint createConstraint() {\n        Constraint myConstraint = getCorePackage().getConstraint()\n                .createConstraint();\n        super.initialize(myConstraint);\n        return myConstraint;\n    }\n\n\n    public DataType createDataType() {\n        DataType dataType = getCorePackage().getDataType().createDataType();\n        super.initialize(dataType);\n        return dataType;\n    }\n\n\n    public Dependency createDependency() {\n        Dependency myDependency = getCorePackage().getDependency()\n                .createDependency();\n        super.initialize(myDependency);\n        return myDependency;\n    }\n\n\n    public ElementResidence createElementResidence() {\n        ElementResidence myElementResidence = getCorePackage().\n                getElementResidence().createElementResidence();\n        super.initialize(myElementResidence);\n        return myElementResidence;\n    }\n\n\n    public ElementResidence buildElementResidence(Object me, Object component) {\n        ElementResidence myElementResidence =\n            ((org.omg.uml.UmlPackage) ((ModelElement) me)\n                .refOutermostPackage()).getCore().getElementResidence()\n                .createElementResidence();\n        super.initialize(myElementResidence);\n        myElementResidence.setContainer((Component) component);\n        myElementResidence.setResident((ModelElement) me);\n        return myElementResidence;\n    }\n\n\n    public Enumeration createEnumeration() {\n        Enumeration myEnumeration = getCorePackage().getEnumeration()\n                .createEnumeration();\n        super.initialize(myEnumeration);\n        return myEnumeration;\n    }\n\n\n    public EnumerationLiteral createEnumerationLiteral() {\n        EnumerationLiteral myEnumerationLiteral = getCorePackage()\n                .getEnumerationLiteral().createEnumerationLiteral();\n        super.initialize(myEnumerationLiteral);\n        return myEnumerationLiteral;\n    }\n\n\n    public EnumerationLiteral buildEnumerationLiteral(String name,\n            Object enumeration) {\n        EnumerationLiteral el = createEnumerationLiteral();\n        el.setName(name);\n        el.setEnumeration((Enumeration) enumeration);\n        return el;\n    }\n\n\n    public Flow createFlow() {\n        Flow myFlow = getCorePackage().getFlow().createFlow();\n        super.initialize(myFlow);\n        return myFlow;\n    }\n\n    @Deprecated\n    public Generalization createGeneralization() {\n        return createGeneralization(modelImpl.getUmlPackage());\n    }\n\n    public Generalization createGeneralization(Object extent) {\n        Generalization myGeneralization = ((org.omg.uml.UmlPackage) extent)\n                .getCore().getGeneralization().createGeneralization();\n        super.initialize(myGeneralization);\n        return myGeneralization;\n    }\n\n    public Interface createInterface() {\n        Interface myInterface = getCorePackage()\n                .getInterface().createInterface();\n        super.initialize(myInterface);\n        return myInterface;\n    }\n\n\n    public Method createMethod() {\n        Method myMethod = getCorePackage().getMethod()\n                .createMethod();\n        super.initialize(myMethod);\n        return myMethod;\n    }\n\n\n    public Node createNode() {\n        Node myNode = getCorePackage().getNode().createNode();\n        super.initialize(myNode);\n        return myNode;\n    }\n\n\n    public Operation createOperation() {\n        Operation myOperation = getCorePackage()\n                .getOperation().createOperation();\n        super.initialize(myOperation);\n        return myOperation;\n    }\n\n\n    public Parameter createParameter() {\n        Parameter myParameter = getCorePackage()\n                .getParameter().createParameter();\n        super.initialize(myParameter);\n        return myParameter;\n    }\n\n\n    @Deprecated\n    public Permission createPermission() {\n        return createPackageImport();\n    }\n\n    public Permission createPackageImport() {\n        Permission myPermission = getCorePackage()\n                .getPermission().createPermission();\n        super.initialize(myPermission);\n        return myPermission;\n    }\n\n    public Primitive createPrimitiveType() {\n        Primitive obj = getCorePackage().getPrimitive().createPrimitive();\n        super.initialize(obj);\n        return obj;\n    }\n\n\n    public TemplateArgument createTemplateArgument() {\n        return createTemplateArgument(modelImpl.getUmlPackage());\n    }\n\n      private  TemplateArgument createTemplateArgument(\n              org.omg.uml.UmlPackage extent) {\n        TemplateArgument obj = extent.getCore().getTemplateArgument()\n                .createTemplateArgument();\n        super.initialize(obj);\n        return obj;\n    }\n\n\n    public TemplateParameter createTemplateParameter() {\n        return createTemplateParameter(modelImpl.getUmlPackage());\n    }\n\n    private TemplateParameter createTemplateParameter(\n            org.omg.uml.UmlPackage extent) {\n        TemplateParameter myTemplateParameter = extent.getCore()\n                .getTemplateParameter().createTemplateParameter();\n        super.initialize(myTemplateParameter);\n        return myTemplateParameter;\n    }\n\n\n    public Usage createUsage() {\n        Usage myUsage = getCorePackage().getUsage().createUsage();\n        super.initialize(myUsage);\n        return myUsage;\n    }\n\n    /**\n     * Builds a default binary association with two default association ends.\n     *\n     * @param c1\n     *            The first classifier to connect to\n     * @param nav1\n     *            The navigability of the Associaton end\n     * @param agg1\n     *            The aggregation type of the second Associaton end\n     * @param c2\n     *            The second classifier to connect to\n     * @param nav2\n     *            The navigability of the second Associaton end\n     * @param agg2\n     *            The aggregation type of the second Associaton end\n     * @return a newly created Association\n     * @throws IllegalArgumentException\n     *             if either Classifier is null\n     */\n    private UmlAssociation buildAssociation(Classifier c1, boolean nav1,\n            AggregationKind agg1, Classifier c2, boolean nav2,\n            AggregationKind agg2) {\n        if (c1 == null || c2 == null) {\n            throw new IllegalArgumentException(\"one of \"\n                    + \"the classifiers to be \" + \"connected is null\");\n        }\n        Namespace ns1 = c1.getNamespace();\n        Namespace ns2 = c2.getNamespace();\n        if (ns1 == null || ns2 == null) {\n            throw new IllegalArgumentException(\"one of \"\n                    + \"the classifiers does not \" + \"belong to a namespace\");\n        }\n\n        // We'll put the association in the namespace of whichever end\n        // is not navigable and is writeable.  If they both are, we'll use the\n        // namepace of c1.\n        Namespace ns = null;\n        if (nav2 && !modelImpl.getModelManagementHelper().isReadOnly(ns1)) {\n            ns = ns1;\n        } else if (nav1\n                && !modelImpl.getModelManagementHelper().isReadOnly(ns2)) {\n            ns = ns2;\n        } else {\n            throw new IllegalArgumentException(\n                    \"At least one end must be navigable\");\n        }\n        UmlAssociation assoc = createAssociation(ns.refOutermostPackage());\n        assoc.setName(\"\");\n        assoc.setNamespace(ns);\n        buildAssociationEnd(assoc, null, c1, null, null,\n                nav1, null, agg1, null, null, null);\n        buildAssociationEnd(assoc, null, c2, null, null,\n                nav2, null, agg2, null, null, null);\n        return assoc;\n    }\n\n    @Deprecated\n    public UmlAssociation buildAssociation(Object fromClassifier,\n            Object aggregationKind1, Object toClassifier,\n            Object aggregationKind2, Boolean unidirectional) {\n\n        if (unidirectional == null) {\n            return buildAssociation(fromClassifier, aggregationKind1,\n                    toClassifier, aggregationKind2, false);\n        } else {\n            return buildAssociation(fromClassifier, aggregationKind1,\n                    toClassifier, aggregationKind2, unidirectional\n                            .booleanValue());\n        }\n    }\n\n    public UmlAssociation buildAssociation(Object fromClassifier,\n            Object aggregationKind1, Object toClassifier,\n            Object aggregationKind2, boolean unidirectional) {\n        if (fromClassifier == null || toClassifier == null) {\n            throw new IllegalArgumentException(\"one of \"\n                    + \"the classifiers to be \" + \"connected is null\");\n        }\n        Classifier from = (Classifier) fromClassifier;\n        Classifier to = (Classifier) toClassifier;\n        AggregationKind agg1 = (AggregationKind) aggregationKind1;\n        AggregationKind agg2 = (AggregationKind) aggregationKind2;\n\n        Namespace ns = from.getNamespace();\n        if (ns == null || modelImpl.getModelManagementHelper().isReadOnly(ns)) {\n            ns = to.getNamespace();\n            if (ns == null\n                    || modelImpl.getModelManagementHelper().isReadOnly(ns)) {\n                throw new IllegalArgumentException(\n                        \"At least one namespace must be non-null and writeable\");\n            }\n        }\n\n        UmlAssociation assoc = createAssociation(ns.refOutermostPackage());\n        assoc.setName(\"\");\n        assoc.setNamespace(ns);\n\n        final boolean nav1 = !unidirectional;\n        final boolean nav2 = true;\n\n        buildAssociationEnd(assoc, null, from, null, null, nav1, null, agg1,\n                null, null, null);\n        buildAssociationEnd(assoc, null, to, null, null, nav2, null, agg2,\n                null, null, null);\n        return assoc;\n    }\n\n\n    public UmlAssociation buildAssociation(Object classifier1,\n            Object classifier2) {\n        Classifier c1 = (Classifier) classifier1;\n        Classifier c2 = (Classifier) classifier2;\n        return buildAssociation(c1, true, AggregationKindEnum.AK_NONE, c2,\n                true, AggregationKindEnum.AK_NONE);\n    }\n\n\n    public UmlAssociation buildAssociation(Object c1, boolean nav1, Object c2,\n            boolean nav2, String name) {\n        UmlAssociation assoc = buildAssociation((Classifier) c1, nav1,\n                AggregationKindEnum.AK_NONE, (Classifier) c2, nav2,\n                AggregationKindEnum.AK_NONE);\n        if (assoc != null) {\n            assoc.setName(name);\n        }\n        return assoc;\n    }\n\n\n    public AssociationClass buildAssociationClass(Object end1, Object end2) {\n        if (end1 == null || end2 == null || !(end1 instanceof Classifier)\n                || !(end2 instanceof Classifier)) {\n            throw new IllegalArgumentException(\n                    \"either one of the arguments was null\");\n        }\n        final Classifier classifier1 = (Classifier) end1;\n        final Classifier classifier2 = (Classifier) end2;\n        AssociationClass assocClass = createAssociationClass();\n\n        assocClass.setNamespace(classifier1.getNamespace());\n        assocClass.setName(\"\");\n        assocClass.setAbstract(false);\n        assocClass.setActive(false);\n        assocClass.setRoot(false);\n        assocClass.setLeaf(false);\n        assocClass.setSpecification(false);\n        assocClass.setVisibility(VisibilityKindEnum.VK_PUBLIC);\n\n        buildAssociationEnd(\n                assocClass, null, classifier1, null, null, true, null, null,\n                null, null, null);\n        buildAssociationEnd(\n                assocClass, null, classifier2, null, null, true, null, null,\n                null, null, null);\n        return assocClass;\n    }\n\n\n    public AssociationEnd buildAssociationEnd(Object assoc, String name,\n            Object type, Integer[] multiplicity, Object stereo, boolean navigable,\n            Object order, Object aggregation, Object scope, Object changeable,\n            Object visibility) {\n        if (aggregation != null\n                && aggregation.equals(AggregationKindEnum.AK_COMPOSITE)\n                && multiplicity != null\n                && (multiplicity[1] > 1 || multiplicity[1] == -1) ) {\n            throw new IllegalArgumentException(\"aggregation is composite \"\n                    + \"and multiplicity > 1\");\n        }\n        AssociationEnd ae = buildAssociationEndInternal(assoc, name, type,\n                stereo, navigable, order, aggregation, scope, changeable,\n                visibility);\n        if (multiplicity != null) {\n            Multiplicity m = modelImpl.getDataTypesFactoryInternal()\n                    .createMultiplicityInternal(multiplicity[0],\n                            multiplicity[1]);\n            ae.setMultiplicity(m);\n        }\n        return ae;\n    }\n\n    @Deprecated\n    public AssociationEnd buildAssociationEnd(Object assoc, String name,\n            Object type, Object multi, Object stereo, boolean navigable,\n            Object order, Object aggregation, Object scope, Object changeable,\n            Object visibility) {\n        if (multi != null && !(multi instanceof Multiplicity)) {\n            throw new IllegalArgumentException(\"Multiplicity\");\n        }\n        if (aggregation != null\n                && aggregation.equals(AggregationKindEnum.AK_COMPOSITE)\n                && multi != null\n                && compareMultiplicity(getMaxUpper((Multiplicity) multi), 1)\n                    > 0) {\n            throw new IllegalArgumentException(\"aggregation is composite \"\n                    + \"and multiplicity > 1\");\n        }\n        AssociationEnd ae = buildAssociationEndInternal(assoc, name, type,\n                stereo, navigable, order, aggregation, scope, changeable,\n                visibility);\n        if (multi == null) {\n            ae.setMultiplicity(getMultiplicity11());\n        } else if (multi instanceof Multiplicity) {\n            ae.setMultiplicity((Multiplicity) multi);\n        } else if (multi instanceof String) {\n            Multiplicity m = modelImpl.getDataTypesFactoryInternal()\n                    .createMultiplicityInternal((String) multi);\n            ae.setMultiplicity(m);\n        }\n        return ae;\n    }\n\n    private AssociationEnd buildAssociationEndInternal (Object assoc, String name,\n            Object type, Object stereo, boolean navigable,\n            Object order, Object aggregation, Object scope, Object changeable,\n            Object visibility) {\n        // wellformednessrules and preconditions\n        if (assoc == null || !(assoc instanceof UmlAssociation) || type == null\n                || !(type instanceof Classifier)) {\n            throw new IllegalArgumentException(\"either type or association \"\n                    + \"are null\");\n        }\n        if (stereo != null && !(stereo instanceof Stereotype)) {\n            throw new IllegalArgumentException(\"Stereotype\");\n        }\n        if (order != null && !(order instanceof OrderingKind)) {\n            throw new IllegalArgumentException(\"OrderingKind\");\n        }\n        if (aggregation != null && !(aggregation instanceof AggregationKind)) {\n            throw new IllegalArgumentException(\"AggregationKind\");\n        }\n        if (scope != null && !(scope instanceof ScopeKind)) {\n            throw new IllegalArgumentException(\"ScopeKind\");\n        }\n        if (changeable != null && !(changeable instanceof ChangeableKind)) {\n            throw new IllegalArgumentException(\"ChangeableKind\");\n        }\n        if (visibility != null && !(visibility instanceof VisibilityKind)) {\n            throw new IllegalArgumentException(\"VisibilityKind\");\n        }\n\n        AssociationEnd end = createAssociationEnd();\n        end.setAssociation((UmlAssociation) assoc);\n        end.setParticipant((Classifier) type);\n        end.setName(name);\n        // UML 1.4 WFR 2.5.3.1 #3 - no aggregation for N-ary associations\n        List<AssociationEnd> ends = ((UmlAssociation) assoc).getConnection();\n        if (ends.size() >= 3) {\n            for (AssociationEnd e : ends) {\n                e.setAggregation(AggregationKindEnum.AK_NONE);\n            }\n        }\n        if (stereo != null) {\n            end.getStereotype().clear();\n            end.getStereotype().add((Stereotype) stereo);\n        }\n        end.setNavigable(navigable);\n        if (order != null) {\n            end.setOrdering((OrderingKind) order);\n        } else {\n            end.setOrdering(OrderingKindEnum.OK_UNORDERED);\n        }\n        if (aggregation != null) {\n            end.setAggregation((AggregationKind) aggregation);\n        } else {\n            end.setAggregation(AggregationKindEnum.AK_NONE);\n        }\n        if (scope != null) {\n            end.setTargetScope((ScopeKind) scope);\n        } else {\n            end.setTargetScope(ScopeKindEnum.SK_INSTANCE);\n        }\n        if (changeable != null) {\n            end.setChangeability((ChangeableKind) changeable);\n        } else {\n            end.setChangeability(ChangeableKindEnum.CK_CHANGEABLE);\n        }\n        if (visibility != null) {\n            end.setVisibility((VisibilityKind) visibility);\n        } else {\n            end.setVisibility(VisibilityKindEnum.VK_PUBLIC);\n        }\n        return end;\n    }\n\n    private static final int MULT_UNLIMITED = -1;\n\n    /**\n     * Get the maximum value of a multiplicity\n     *\n     * @param m\n     *            the Multiplicity\n     * @return upper range\n     */\n    private int getMaxUpper(Multiplicity m) {\n        int max = 0;\n        for (MultiplicityRange mr : m.getRange()) {\n            int value = mr.getUpper();\n            if (value == MULT_UNLIMITED) {\n                max = value;\n            } else if (max != MULT_UNLIMITED && value > max) {\n                max = value;\n            }\n        }\n        return max;\n    }\n\n    /**\n     * Compare two multiplicities taking care of the value 'unlimited' (-1).\n     *\n     * @param mult1 first multiplicity\n     * @param mult2 second multiplicity\n     * @return 0 if equal, a positive integer (not necessarily 1) if mult1 is\n     *         greater than mult2 and a negative integer if mult2 is greater..\n     */\n    private static int compareMultiplicity(int mult1, int mult2) {\n        if (mult1 == MULT_UNLIMITED) {\n            if (mult2 == MULT_UNLIMITED) {\n                return 0; // equal\n            }\n            return 1; // greater\n        } else if (mult2 == MULT_UNLIMITED) {\n            return -1; // less than\n        }\n        return mult1 - mult2;\n    }\n\n    /**\n     * Get a 1..1 multiplicity\n     */\n    private Multiplicity getMultiplicity11() {\n        return modelImpl.getDataTypesFactoryInternal()\n                .createMultiplicityInternal(1, 1);\n    }\n\n\n    public AssociationEnd buildAssociationEnd(Object type, Object assoc) {\n        if (type == null || !(type instanceof Classifier) || assoc == null\n                || !(assoc instanceof UmlAssociation)) {\n            throw new IllegalArgumentException(\"one of the arguments is null\");\n        }\n        return buildAssociationEnd(assoc, \"\", type, null, null, true, null,\n                null, null, null, VisibilityKindEnum.VK_PUBLIC);\n    }\n\n    public Attribute buildAttribute(Object model, Object theType) {\n        return buildAttribute2(theType);\n    }\n\n    public Attribute buildAttribute2(Object theType) {\n        Attribute attr = buildAttribute();\n        attr.setType((Classifier) theType);\n        return attr;\n    }\n\n    /**\n     * Build a new attribute with no type\n     * @return the new attribute\n     */\n    Attribute buildAttribute() {\n        Attribute attr = createAttribute();\n        attr.setMultiplicity(getMultiplicity11());\n        attr.setVisibility(VisibilityKindEnum.VK_PUBLIC);\n        attr.setOwnerScope(ScopeKindEnum.SK_INSTANCE);\n        attr.setChangeability(ChangeableKindEnum.CK_CHANGEABLE);\n        attr.setTargetScope(ScopeKindEnum.SK_INSTANCE);\n        return attr;\n    }\n\n\n    public Attribute buildAttribute2(Object handle, Object type) {\n        Attribute attr = buildAttribute2(type);\n        if (handle instanceof Classifier) {\n            Classifier cls = (Classifier) handle;\n            cls.getFeature().add(attr);\n        } else if (handle instanceof AssociationEnd) {\n            AssociationEnd assend = (AssociationEnd) handle;\n            assend.getQualifier().add(attr);\n        } else {\n            throw new IllegalArgumentException();\n        }\n        return attr;\n    }\n\n\n    public UmlClass buildClass() {\n        return buildClass((Object) null);\n    }\n\n\n    private static void initClass(UmlClass cl) {\n        cl.setName(\"\");\n        cl.setAbstract(false);\n        cl.setActive(false);\n        cl.setRoot(false);\n        cl.setLeaf(false);\n        cl.setSpecification(false);\n        cl.setVisibility(VisibilityKindEnum.VK_PUBLIC);\n    }\n\n    public UmlClass buildClass(final Object owner) {\n        ModelCommand command = new ModelCommand() {\n            private UmlClass cl;\n            public UmlClass execute() {\n                if (owner == null) {\n                    cl = createClass();\n                } else {\n                    cl = createClass(getExtent(owner));\n                }\n                initClass(cl);\n                return cl;\n            }\n\n            public void undo() {\n                try {\n                    cl.refDelete();\n                } catch (InvalidObjectException e) {\n                    LOG.log(Level.WARNING, \"Object already deleted \" + cl);\n                }\n            }\n\n            public boolean isUndoable() {\n                return true;\n            }\n\n            public boolean isRedoable() {\n                return false;\n            }\n        };\n        UmlClass clazz = (UmlClass) org.argouml.model.Model.execute(command);\n        if (owner instanceof Namespace) {\n            modelImpl.getCoreHelper().setNamespace(clazz, owner);\n        }\n        return clazz;\n    }\n\n\n    private org.omg.uml.UmlPackage getExtent(Object element) {\n        return (org.omg.uml.UmlPackage) ((RefObject) element)\n                .refOutermostPackage();\n    }\n\n    public UmlClass buildClass(String name) {\n        UmlClass clazz = buildClass();\n        clazz.setName(name);\n        return clazz;\n    }\n\n\n    public UmlClass buildClass(String name, Object owner) {\n        UmlClass clazz = buildClass();\n        clazz.setName(name);\n        if (owner instanceof Namespace) {\n            modelImpl.getCoreHelper().setNamespace(clazz, owner);\n        }\n        return clazz;\n    }\n\n\n    public Interface buildInterface() {\n        Interface cl = createInterface();\n        cl.setName(\"\");\n        cl.setAbstract(false);\n        cl.setRoot(false);\n        cl.setLeaf(false);\n        cl.setSpecification(false);\n        cl.setVisibility(VisibilityKindEnum.VK_PUBLIC);\n        return cl;\n    }\n\n\n    public Interface buildInterface(Object owner) {\n        Interface cl = buildInterface();\n        if (owner instanceof Namespace) {\n            cl.setNamespace((Namespace) owner);\n        }\n        return cl;\n    }\n\n\n    public Interface buildInterface(String name) {\n        Interface cl = buildInterface();\n        cl.setName(name);\n        return cl;\n    }\n\n\n    public Interface buildInterface(String name, Object owner) {\n        Interface cl = buildInterface();\n        cl.setName(name);\n        if (owner instanceof Namespace) {\n            cl.setNamespace((Namespace) owner);\n        }\n        return cl;\n    }\n\n\n    public DataType buildDataType(String name, Object owner) {\n        DataType dt = createDataType();\n        dt.setName(name);\n        if (owner instanceof Namespace) {\n            dt.setNamespace((Namespace) owner);\n        }\n        return dt;\n    }\n\n\n    public Enumeration buildEnumeration(String name, Object owner) {\n        Enumeration e = createEnumeration();\n        e.setName(name);\n        if (owner instanceof Namespace) {\n            e.setNamespace((Namespace) owner);\n        }\n        return e;\n    }\n\n\n    public Dependency buildDependency(Object clientObj, Object supplierObj) {\n\n        ModelElement client = (ModelElement) clientObj;\n        ModelElement supplier = (ModelElement) supplierObj;\n        if (client == null || supplier == null) {\n            throw new IllegalArgumentException(\"client or supplier is null \"\n                    + \"client = \" + client + \" supplier = \" + supplier);\n        }\n        Dependency dep = createDependency();\n        dep.getSupplier().add(supplier);\n        dep.getClient().add(client);\n        if (client instanceof Namespace) {\n            dep.setNamespace((Namespace) client);\n        } else if (client.getNamespace() != null) {\n            dep.setNamespace(client.getNamespace());\n        }\n        return dep;\n    }\n\n\n    public Permission buildPackageImport(Object client, Object supplier) {\n        if (!(client instanceof Namespace)\n                || !(supplier instanceof UmlPackage)) {\n            throw new IllegalArgumentException(\"client is not a Namespace\"\n                    + \" or supplier is not a Package\");\n        }\n        Permission per = buildPermissionInternal((ModelElement) client,\n                (UmlPackage) supplier);\n\n        // TODO: This should fetch the stereotype from our profile\n        modelImpl.getExtensionMechanismsFactory().buildStereotype(per,\n                ModelManagementHelper.IMPORT_STEREOTYPE,\n                per.getNamespace());\n        return per;\n    }\n\n\n    private Permission buildPermissionInternal(ModelElement client,\n            ModelElement supplier) {\n        Permission permission = createPackageImport();\n        permission.getSupplier().add(supplier);\n        permission.getClient().add(client);\n        if (client instanceof Namespace) {\n            permission.setNamespace((Namespace) client);\n        } else if (client.getNamespace() != null) {\n            permission.setNamespace(client.getNamespace());\n        }\n        return permission;\n    }\n\n\n    public Permission buildPackageAccess(Object client, Object supplier) {\n        if (!(client instanceof Namespace)\n                || !(supplier instanceof UmlPackage)) {\n            throw new IllegalArgumentException(\"client or \"\n                    + \"supplier is not a Namespace\");\n        }\n        Permission per = buildPermissionInternal((ModelElement) client,\n                (UmlPackage) supplier);\n\n        // TODO: This should fetch the stereotype from our profile\n        modelImpl.getExtensionMechanismsFactory().buildStereotype(per,\n                ModelManagementHelper.ACCESS_STEREOTYPE,\n                per.getNamespace());\n        return per;\n    }\n\n\n    public Generalization buildGeneralization(Object child1, Object parent1) {\n        // TODO: This is a part implementation of well-formedness rule\n        // UML1.4.2 - 4.5.3.20 [3] Circular inheritance is not allowed.\n        // not self.allParents->includes(self)\n        if (!(child1 instanceof GeneralizableElement\n                && parent1 instanceof GeneralizableElement\n                && child1 != parent1)) {\n            throw new IllegalArgumentException(\n                    \"Both items must be different generalizable elements\");\n        }\n\n        GeneralizableElement child = (GeneralizableElement) child1;\n        GeneralizableElement parent = (GeneralizableElement) parent1;\n\n        // Check that the two elements aren't already linked the opposite way\n        // TODO: This is a part implementation of well-formedness rule\n        // UML1.4.2 - 4.5.3.20 [3] Circular inheritance is not allowed.\n        // not self.allParents->includes(self)\n        for (Generalization gen : parent.getGeneralization()) {\n            if (gen.getParent().equals(child)) {\n                throw new IllegalArgumentException(\"Generalization exists\"\n                        + \" in opposite direction\");\n            }\n        }\n\n        // TODO: This is well-formedness rule from UML1.4.2\n        // 4.5.3.20 [2] No GeneralizableElement can have a parent\n        // Generalization to an element that is a leaf.\n        // self.parent->forAll(s | not s.isLeaf)\n        if (parent.isLeaf()) {\n            throw new IllegalArgumentException(\"parent is leaf\");\n        }\n\n        // TODO: This is well-formedness rule from UML1.4.2\n        // 4.5.3.20 [1] A root cannot have any Generalizations.\n        // self.isRoot implies self.generalization->isEmpty\n        if (child.isRoot()) {\n            throw new IllegalArgumentException(\"child is root\");\n        }\n\n        Namespace ns = child.getNamespace();\n        if ((ns == null || modelImpl.getModelManagementHelper().isReadOnly(ns))\n                && child instanceof Namespace) {\n            ns = (Namespace) child;\n        }\n        if (ns == null || modelImpl.getModelManagementHelper().isReadOnly(ns)) {\n            throw new IllegalArgumentException(\"No valid writeable namespace\");\n        }\n        Generalization gen = createGeneralization(ns.refOutermostPackage());\n        gen.setParent(parent);\n        gen.setChild(child);\n        gen.setNamespace(ns);\n        return gen;\n    }\n\n    public Object buildManifestation(Object utilizedElement) {\n        throw new NotImplementedException( \"UML 1.4 has no manifestations\");\n    }\n\n    public Method buildMethod(String name) {\n        Method method = createMethod();\n        if (method != null) {\n            method.setName(name);\n        }\n        return method;\n    }\n\n\n    public Operation buildOperation(Object classifier, Object returnType) {\n        if (!(classifier instanceof Classifier)) {\n            throw new IllegalArgumentException(\"Handle is not a classifier\");\n        }\n        Classifier cls = (Classifier) classifier;\n        Operation oper = createOperation();\n        oper.setOwner(cls);\n        oper.setVisibility(VisibilityKindEnum.VK_PUBLIC);\n        oper.setAbstract(false);\n        oper.setLeaf(false);\n        oper.setRoot(false);\n        oper.setQuery(false);\n        oper.setOwnerScope(ScopeKindEnum.SK_INSTANCE);\n        oper.setConcurrency(CallConcurrencyKindEnum.CCK_SEQUENTIAL);\n\n        Parameter returnParameter = buildParameter(oper, returnType);\n        returnParameter.setKind(ParameterDirectionKindEnum.PDK_RETURN);\n        returnParameter.setName(\"return\");\n        return oper;\n    }\n\n\n    public Operation buildOperation2(Object cls, Object returnType,\n            String name) {\n        Operation oper = buildOperation(cls, returnType);\n        if (oper != null) {\n            oper.setName(name);\n        }\n        return oper;\n    }\n\n    /**\n     * Constructs a default parameter.\n     *\n     * @return The newly created parameter.\n     */\n    private Parameter buildParameter(Classifier type,\n            javax.jmi.reflect.RefObject ref) {\n        Parameter param = ((org.omg.uml.UmlPackage) ref.refOutermostPackage())\n                .getCore().getParameter().createParameter();\n        param.setType(type);\n        return param;\n    }\n\n\n    public Parameter buildParameter(Object o, Object type) {\n        if (o instanceof Event) {\n            Event event = (Event) o;\n            Parameter res = buildParameter((Classifier) type, event);\n            res.setKind(ParameterDirectionKindEnum.PDK_IN);\n            event.getParameter().add(res);\n            res.setName(\"arg\" + event.getParameter().size());\n            return res;\n        } else if (o instanceof ObjectFlowState) {\n            ObjectFlowState ofs = (ObjectFlowState) o;\n            Parameter res = buildParameter((Classifier) type, ofs);\n            res.setKind(ParameterDirectionKindEnum.PDK_IN);\n            ofs.getParameter().add(res);\n            res.setName(\"arg\" + ofs.getParameter().size());\n            return res;\n        } else if (o instanceof BehavioralFeature) {\n            BehavioralFeature oper = (BehavioralFeature) o;\n            Parameter res = buildParameter((Classifier) type, oper);\n            res.setKind(ParameterDirectionKindEnum.PDK_IN);\n            oper.getParameter().add(res);\n            res.setName(\"arg\" + oper.getParameter().size());\n            return res;\n        } else if (o == null) {\n            throw new IllegalArgumentException(\n                    \"A containing element must be supplied for the parameter\");\n        } else {\n            throw new IllegalArgumentException(\n                    \"Unsupported contining element for parameter \"\n                    + o.getClass().getName());\n        }\n    }\n\n\n    public Abstraction buildRealization(Object clnt, Object spplr,\n            Object model) {\n        ModelElement client = (ModelElement) clnt;\n        ModelElement supplier = (ModelElement) spplr;\n        if (client == null || supplier == null || client.getNamespace() == null\n                || supplier.getNamespace() == null || client.equals(supplier)) {\n            throw new IllegalArgumentException(\"faulty arguments.\");\n        }\n        Abstraction realization = createAbstraction();\n        Namespace nsc = client.getNamespace();\n        Namespace nss = supplier.getNamespace();\n        Namespace ns = null;\n        if (nsc.equals(nss)) {\n            ns = nsc;\n        } else {\n            ns = (Namespace) model;\n        }\n        realization.setNamespace(nsc);\n        modelImpl.getExtensionMechanismsFactory().buildStereotype(realization,\n                CoreFactory.REALIZE_STEREOTYPE, ns);\n        realization.getClient().add(client);\n        realization.getSupplier().add(supplier);\n        return realization;\n    }\n\n\n    public TemplateArgument buildTemplateArgument(Object element) {\n        TemplateArgument ta = createTemplateArgument();\n        ta.setModelElement((ModelElement) element);\n        return ta;\n    }\n\n    public TemplateArgument buildTemplateArgument(Object binding,\n            Object element) {\n        if (!(binding instanceof Binding && element instanceof ModelElement)) {\n            throw new IllegalArgumentException();\n        }\n        TemplateArgument ta = createTemplateArgument(getExtent(binding));\n        ta.setModelElement((ModelElement) element);\n        ta.setBinding((Binding) binding);\n        return ta;\n    }\n\n    public Object buildTemplateParameter(Object template, Object parameter,\n            Object defaultElement) {\n        if (!(template instanceof ModelElement)) {\n            throw new IllegalArgumentException(\n                    \"Template must be a model element\");\n        }\n        if (!(parameter instanceof ModelElement)) {\n            if (parameter == null) {\n                parameter = createClass(getExtent(template));\n            } else {\n            throw new IllegalArgumentException(\n                    \"Parameter must be a model element\");\n            }\n        }\n        if (defaultElement != null\n                && !(defaultElement instanceof ModelElement)) {\n            throw new IllegalArgumentException(\n                    \"Default element must be a model element\");\n        }\n\n        TemplateParameter templateParam =\n            createTemplateParameter(getExtent(template));\n        templateParam.setParameter((ModelElement) parameter);\n        if (defaultElement != null) {\n            templateParam.setDefaultElement((ModelElement) defaultElement);\n        }\n        templateParam.setTemplate((ModelElement) template);\n        return templateParam;\n    }\n\n\n    public Usage buildUsage(Object client, Object supplier) {\n        if (client == null || supplier == null) {\n            throw new IllegalArgumentException(\"In buildUsage null arguments.\");\n        }\n        if (!(client instanceof ModelElement)) {\n            throw new IllegalArgumentException(\"client ModelElement\");\n        }\n        if (!(supplier instanceof ModelElement)) {\n            throw new IllegalArgumentException(\"supplier ModelElement\");\n        }\n        // TODO: UML 1.4 spec requires both client and supplier to be\n        // in the same model - tfm\n        Usage usage = createUsage();\n        usage.getSupplier().add((ModelElement) supplier);\n        usage.getClient().add((ModelElement) client);\n        if (((ModelElement) supplier).getNamespace() != null) {\n            usage.setNamespace(((ModelElement) supplier).getNamespace());\n        } else if (((ModelElement) client).getNamespace() != null) {\n            usage.setNamespace(((ModelElement) client).getNamespace());\n        }\n        // TODO: Add standard stereotype?  Set is open ended, but\n        // predefined names include: call, create, instantiate, send\n        return usage;\n    }\n\n\n    public Comment buildComment(Object element, Object model) {\n        if (model == null) {\n            throw new IllegalArgumentException(\"A namespace must be supplied.\");\n        }\n        ModelElement elementToAnnotate = (ModelElement) element;\n        Comment comment = createComment();\n\n        Namespace commentsModel = null;\n        if (elementToAnnotate != null) {\n            comment.getAnnotatedElement().add(elementToAnnotate);\n            commentsModel = elementToAnnotate.getNamespace();\n        } else {\n            commentsModel = (Namespace) model;\n        }\n\n        comment.setNamespace(commentsModel);\n        return comment;\n    }\n\n\n    public Constraint buildConstraint(Object constrElement) {\n        ModelElement constrainedElement = (ModelElement) constrElement;\n        if (constrainedElement == null) {\n            throw new IllegalArgumentException(\"the constrained element is \"\n                    + \"mandatory and may not be \" + \"null.\");\n        }\n        Constraint con = createConstraint();\n        con.getConstrainedElement().add(constrainedElement);\n        con.setNamespace(constrainedElement.getNamespace());\n        return con;\n    }\n\n\n    public Constraint buildConstraint(String name, Object bexpr) {\n        if (bexpr == null || !(bexpr instanceof BooleanExpression)) {\n            throw new IllegalArgumentException(\"invalid boolean expression.\");\n        }\n        Constraint con = createConstraint();\n        if (name != null) {\n            con.setName(name);\n        }\n        con.setBody((BooleanExpression) bexpr);\n        return con;\n    }\n\n\n    public Binding buildBinding(Object client, Object supplier,\n            List arguments) {\n        Collection<Dependency> clientDeps = ((ModelElement) client)\n                .getClientDependency();\n        for (Dependency dep : clientDeps) {\n            if (dep instanceof Binding) {\n                throw new IllegalArgumentException(\n                        \"client is already client of another Binding\");\n            }\n        }\n\n        // Check arguments against parameters for type and number\n        // TODO: Perhaps move this to a critic instead? - tfm - 20070326\n        if (arguments != null) {\n            List<TemplateParameter> params =\n                ((ModelElement) supplier).getTemplateParameter();\n            if (params.size() != arguments.size()) {\n                throw new IllegalArgumentException(\n                        \"number of arguments doesn't match number of params\");\n            }\n            Iterator<TemplateArgument> ita = arguments.iterator();\n            for (TemplateParameter param : params) {\n                TemplateArgument ta = ita.next();\n                // TODO: Before allowing this, we should really check that\n                // TemplateParameter.defaultElement is defined\n                if (ta == null || ta.getModelElement() == null) {\n                    continue;\n                }\n                if (!(param.getParameter().getClass().equals(\n                        ta.getModelElement().getClass()))) {\n                    throw new IllegalArgumentException(\n                            \"type of argument doesn't match type of parameter\");\n                }\n            }\n        }\n\n        Binding binding = createBinding();\n        binding.getClient().add((ModelElement) client);\n        binding.getSupplier().add((ModelElement) supplier);\n        if (arguments != null) {\n            binding.getArgument().addAll(arguments);\n        }\n\n        return binding;\n    }\n\n\n    /**\n     * @param elem\n     *            the abstraction to be deleted\n     */\n    void deleteAbstraction(Object elem) {\n        if (!(elem instanceof Abstraction)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the artifact to be deleted\n     */\n    void deleteArtifact(Object elem) {\n        if (!(elem instanceof Artifact)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the association to be deleted\n     */\n    void deleteAssociation(Object elem) {\n        if (!(elem instanceof UmlAssociation)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the a. to be deleted\n     */\n    void deleteAssociationClass(Object elem) {\n        if (!(elem instanceof AssociationClass)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * Does a 'cascading delete' to all modelelements that are associated with\n     * this element that would be in an illegal state after deletion of the\n     * element. This method should not be called directly.\n     * <p>\n     *\n     * In the case of an AssociationEnd these are the following elements:\n     * <ul>\n     * <li>Binary Associations that lose one of the AssociationEnds by this\n     * deletion.\n     * <li>LinkEnds associated with this AssociationEnd.\n     * </ul>\n     *\n     *\n     * @param elem\n     * @see UmlFactoryMDRImpl#delete(Object)\n     */\n    void deleteAssociationEnd(Object elem) {\n        if (!(elem instanceof AssociationEnd)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n        AssociationEnd ae = (AssociationEnd) elem;\n        UmlAssociation assoc = ae.getAssociation();\n        if (assoc != null && assoc.getConnection() != null\n                && assoc.getConnection().size() == 2) { // binary association\n            modelImpl.getUmlFactory().delete(assoc);\n        }\n        // delete LinkEnds which have this as their associationEnd\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) ae.refOutermostPackage())\n                        .getCommonBehavior().getAAssociationEndLinkEnd()\n                        .getLinkEnd(ae));\n    }\n\n    /**\n     * @param elem\n     *            the attribute to be deleted\n     */\n    void deleteAttribute(Object elem) {\n        if (!(elem instanceof Attribute)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n        // delete AttributeLinks where this is the Attribute\n        Attribute attr = (Attribute) elem;\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) attr.refOutermostPackage())\n                        .getCommonBehavior().getAAttributeLinkAttribute()\n                        .getAttributeLink(attr));\n    }\n\n    /**\n     * @param elem the element to be deleted\n     */\n    void deleteBehavioralFeature(Object elem) {\n        if (!(elem instanceof BehavioralFeature)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteBinding(Object elem) {\n        if (!(elem instanceof Binding)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n        Binding binding = (Binding) elem;\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) binding.refOutermostPackage())\n                        .getCore().getABindingArgument().getArgument(binding));\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteClass(Object elem) {\n        if (!(elem instanceof UmlClass)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * Does a 'cascading delete' to all modelelements that are associated with\n     * this element that would be in an illegal state after deletion of the\n     * element. Does not do an cascading delete for elements that are deleted by\n     * the MDR method remove. This method should not be called directly.\n     * <p>\n     *\n     * In the case of a classifier these are the following elements:\n     * <ul>\n     * <li>AssociationEnds that have this classifier as type\n     * </ul>\n     *\n     * @param elem\n     * @see UmlFactoryMDRImpl#delete(Object)\n     */\n    void deleteClassifier(Object elem) {\n        if (!(elem instanceof Classifier)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n        modelImpl.getUmlHelper().deleteCollection(\n                modelImpl.getFacade().getAssociationEnds(elem));\n        Classifier cls = (Classifier) elem;\n        // delete CreateActions which have this as their instantiation\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) cls.refOutermostPackage())\n                        .getCommonBehavior().getACreateActionInstantiation()\n                        .getCreateAction(cls));\n        // TODO: ?delete Instances which have this as their classifier?\n        // or should we leave them since they contain so much state that the\n        // user would have to recreate??\n//        nsmodel.getUmlHelper().deleteCollection(\n//                nsmodel.getUmlPackage().getCommonBehavior()\n//                        .getAInstanceClassifier().getInstance(cls));\n        // TODO: ?delete ObjectFlowStates which have this as their type?\n//        nsmodel.getUmlHelper().deleteCollection(\n//                nsmodel.getUmlPackage().getActivityGraphs()\n//                        .getATypeObjectFlowState().getObjectFlowState(cls));\n        // TODO: ?delete ClassifierInStates which have this as their type?\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) cls.refOutermostPackage())\n                        .getActivityGraphs().getATypeClassifierInState()\n                        .getClassifierInState(cls));\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteComment(Object elem) {\n        if (!(elem instanceof Comment)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteComponent(Object elem) {\n        if (!(elem instanceof Component)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteConstraint(Object elem) {\n        if (!(elem instanceof Constraint)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteDataType(Object elem) {\n        if (!(elem instanceof DataType)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteDependency(Object elem) {\n        if (!(elem instanceof Dependency)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteElement(Object elem) {\n        if (!(elem instanceof Element)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteElementResidence(Object elem) {\n        if (!(elem instanceof ElementResidence)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteFeature(Object elem) {\n        if (!(elem instanceof Feature)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteFlow(Object elem) {\n        if (!(elem instanceof Flow)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteGeneralizableElement(Object elem) {\n        if (!(elem instanceof GeneralizableElement)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n        GeneralizableElement ge = (GeneralizableElement) elem;\n        modelImpl.getUmlHelper().deleteCollection(ge.getGeneralization());\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) ge.refOutermostPackage()).getCore()\n                        .getAParentSpecialization().getSpecialization(ge));\n\n    }\n\n    /**\n     * @param elem the element to be deleted\n     */\n    void deleteGeneralization(Object elem) {\n        if (!(elem instanceof Generalization)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteInterface(Object elem) {\n        if (!(elem instanceof Interface)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteMethod(Object elem) {\n        if (!(elem instanceof Method)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * Does a 'cascading delete' to all modelelements that are associated with\n     * this element that would be in an illegal state after deletion of the\n     * element. Does not do an cascading delete for elements that are deleted by\n     * MDR automatically. This method should not be called directly.\n     * <p>\n     *\n     * In the case of a modelelement these are the following elements:\n     * <ul>\n     * <li>Dependencies that have the modelelement as supplier or as a client\n     * and are binary. (that is, they only have one supplier and one client)\n     * <li>Behaviors, TemplateArguments, and ElementImports which require\n     * this ModelElement\n     * </ul>\n     *\n     * @param elem\n     * @see UmlFactoryMDRImpl#delete(Object)\n     */\n    void deleteModelElement(Object elem) {\n        if (!(elem instanceof ModelElement)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n        // Delete dependencies where this is the only client\n        Collection<Dependency> deps = org.argouml.model.Model.getFacade()\n                .getClientDependencies(elem);\n        for (Dependency dep : deps) {\n            if (dep.getClient().size() < 2\n                    && dep.getClient().contains(elem)) {\n                modelImpl.getUmlFactory().delete(dep);\n            }\n        }\n\n        // Delete dependencies where this is the only supplier\n        deps = org.argouml.model.Model.getFacade()\n                .getSupplierDependencies(elem);\n        for (Dependency dep : deps) {\n            if (dep.getSupplier().size() < 2\n                    && dep.getSupplier().contains(elem)) {\n                modelImpl.getUmlFactory().delete(dep);\n            }\n        }\n\n        /* Do not delete behaviors here!\n         * The behavior-context relation in the UML model\n         * is an aggregate, not composition. See issue 4281. */\n\n        ModelElement me = (ModelElement) elem;\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) me.refOutermostPackage()).getCore()\n                        .getAModelElementTemplateArgument()\n                        .getTemplateArgument(me));\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) me.refOutermostPackage())\n                        .getModelManagement()\n                        .getAImportedElementElementImport()\n                        .getElementImport(me));\n\n\n    }\n\n    /**\n     * A namespace deletes its owned elements.\n     *\n     * @param elem\n     *            is the namespace.\n     */\n    void deleteNamespace(Object elem) {\n        LOG.log(Level.FINE, \"Deleting namespace {0}\", elem);\n\n        if (!(elem instanceof Namespace)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n        List<ModelElement> ownedElements = new ArrayList<ModelElement>();\n        // TODO: This is a composite association, so these will get deleted\n        // automatically.  The only thing we need to do is check for any\n        // additional elements that need to be deleted as a result.\n        ownedElements.addAll(((Namespace) elem).getOwnedElement());\n        for (ModelElement element : ownedElements) {\n\n            LOG.log(Level.FINE, \"Deleting ownedElement {0}\", element);\n\n            modelImpl.getUmlFactory().delete(element);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteNode(Object elem) {\n        if (!(elem instanceof Node)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteOperation(Object elem) {\n        if (!(elem instanceof Operation)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n        Operation oper = (Operation) elem;\n        // delete CallActions which have this as their operation\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) oper.refOutermostPackage())\n                        .getCommonBehavior().getACallActionOperation()\n                        .getCallAction(oper));\n        // delete CallEvents which have this as their operation\n        modelImpl.getUmlHelper().deleteCollection(\n                ((org.omg.uml.UmlPackage) oper.refOutermostPackage())\n                        .getStateMachines().getAOccurrenceOperation()\n                        .getOccurrence(oper));\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteParameter(Object elem) {\n        if (!(elem instanceof Parameter)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deletePermission(Object elem) {\n        if (!(elem instanceof Permission)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deletePresentationElement(Object elem) {\n        if (!(elem instanceof PresentationElement)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteRelationship(Object elem) {\n        if (!(elem instanceof Relationship)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteStructuralFeature(Object elem) {\n        if (!(elem instanceof StructuralFeature)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteTemplateArgument(Object elem) {\n        if (!(elem instanceof TemplateArgument)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteTemplateParameter(Object elem) {\n        if (!(elem instanceof TemplateParameter)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * @param elem\n     *            the element to be deleted\n     */\n    void deleteUsage(Object elem) {\n        if (!(elem instanceof Usage)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * Delete an Enumeration.\n     * @param elem\n     *            the element to be deleted\n     * @since UML 1.4\n     */\n    void deleteEnumeration(Object elem) {\n        if (!(elem instanceof Enumeration)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n        // EnumerationLiterals should get deleted implicitly\n        // since they are associated by composition\n    }\n\n    /**\n     * Delete EnumerationLiteral.\n     * @param elem\n     *            the element to be deleted\n     * @since UML 1.4\n     */\n    void deleteEnumerationLiteral(Object elem) {\n        if (!(elem instanceof EnumerationLiteral)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * Delete the given UML Primitive.\n     *\n     * @param elem the element to be deleted\n     * @since UML 1.4\n     */\n    void deletePrimitive(Object elem) {\n        if (!(elem instanceof Primitive)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n    /**\n     * Delete the given ProgrammingLanguageDataType.\n     *\n     * @param elem the element to be deleted\n     * @since UML 1.4\n     */\n    void deleteProgrammingLanguageDataType(Object elem) {\n        if (!(elem instanceof ProgrammingLanguageDataType)) {\n            throw new IllegalArgumentException(\"elem: \" + elem);\n        }\n    }\n\n\n\n    /**\n     * Copies a class, and it's features. This may also require other\n     * classifiers to be copied.\n     *\n     * @param source\n     *            is the class to copy.\n     * @param ns\n     *            is the namespace to put the copy in.\n     * @return a newly created class.\n     */\n    public UmlClass copyClass(Object source, Object ns) {\n        if (!(source instanceof UmlClass && ns instanceof Namespace)) {\n            throw new IllegalArgumentException(\"source: \" + source + \",ns: \"\n                    + ns);\n        }\n\n        UmlClass c = createClass();\n        ((Namespace) ns).getOwnedElement().add(c);\n        doCopyClass(source, c);\n        return c;\n    }\n\n    /**\n     * Copies a feature from one classifier to another.\n     *\n     * @param source is the feature to copy.\n     * @param classifier is the classifier to put the copy in.\n     * @return a newly created feature.\n     */\n    public Feature copyFeature(Object source, Object classifier) {\n        if (!(source instanceof Feature && classifier instanceof Classifier)) {\n            throw new IllegalArgumentException(\"source: \" + source\n                    + \",classifier: \" + classifier);\n        }\n\n        Feature f = null;\n        if (source instanceof Attribute) {\n            Attribute attr = createAttribute();\n            doCopyAttribute((Attribute) source, attr);\n            f = attr;\n        } else if (source instanceof Operation) {\n            Operation oper = createOperation();\n            doCopyOperation((Operation) source, oper);\n            // TODO: build a return parameter\n            f = oper;\n        } else if (source instanceof Method) {\n            Method method = createMethod();\n            doCopyMethod((Method) source, method);\n            f = method;\n        } else if (source instanceof Reception) {\n            Reception reception = (Reception)\n                modelImpl.getCommonBehaviorFactory().createReception();\n            doCopyReception((Reception) source, reception);\n            f = reception;\n        } else {\n            throw new IllegalArgumentException(\"source: \" + source);\n        }\n\n        f.setOwner((Classifier) classifier);\n        ((Classifier) classifier).getFeature().add(f);\n        return f;\n    }\n\n    /**\n     * Copies a datatype, and it's features. This may also require other\n     * classifiers to be copied.\n     *\n     * @param source\n     *            is the datatype to copy.\n     * @param ns\n     *            is the namespace to put the copy in.\n     * @return a newly created data type.\n     */\n    public DataType copyDataType(Object source, Object ns) {\n        if (!(source instanceof DataType)) {\n            throw new IllegalArgumentException();\n        }\n\n        if (!(ns instanceof Namespace)) {\n            throw new IllegalArgumentException();\n        }\n\n        DataType i = createDataType();\n        ((Namespace) ns).getOwnedElement().add(i);\n        doCopyDataType(source, i);\n        return i;\n    }\n\n    /**\n     * Copies an interface, and it's features. This may also require other\n     * classifiers to be copied.\n     *\n     * @param source\n     *            is the interface to copy.\n     * @param ns\n     *            is the namespace to put the copy in.\n     * @return a newly created interface.\n     */\n    public Interface copyInterface(Object source, Object ns) {\n        if (!(source instanceof Interface)) {\n            throw new IllegalArgumentException();\n        }\n\n        if (!(ns instanceof Namespace)) {\n            throw new IllegalArgumentException();\n        }\n\n        Interface i = createInterface();\n        ((Namespace) ns).getOwnedElement().add(i);\n        doCopyInterface(source, i);\n        return i;\n    }\n\n    /**\n     *\n     * @param from\n     *            The object which own the enumeration to copy\n     * @param to\n     *            The object to which copy the enumeration\n     */\n    public void copyEnumeration(Object from, Object to) {\n        doCopyModelElement(from, to);\n        List listFrom = ((Enumeration) from).getLiteral();\n        List listTo = ((Enumeration) to).getLiteral();\n        Object literalFrom;\n        Object literalTo;\n        for (int i = 0; i < listFrom.size(); i++) {\n            literalFrom = listFrom.get(i);\n            if (listTo.size() > i) {\n                literalTo = listTo.get(i);\n            } else {\n                literalTo = createEnumerationLiteral();\n                listTo.add(literalTo);\n            }\n            doCopyModelElement(literalFrom, literalTo);\n            ((EnumerationLiteral) literalTo).setEnumeration((Enumeration) to);\n        }\n    }\n\n    /**\n     * Used by the copy functions. Do not call this function directly.\n     */\n    private void doCopyElement(Object source, Object target) {\n        // Nothing more to do.\n    }\n\n    /**\n     * Used by the copy functions. Do not call this function directly.\n     *\n     * @param source\n     *            the source class\n     * @param target\n     *            the target class\n     */\n    public void doCopyClass(Object source, Object target) {\n        if (!(source instanceof UmlClass)) {\n            throw new IllegalArgumentException();\n        }\n\n        if (!(target instanceof UmlClass)) {\n            throw new IllegalArgumentException();\n        }\n\n        doCopyClassifier(source, target);\n\n        ((UmlClass) target).setActive(((UmlClass) source).isActive());\n    }\n\n    /*\n     * TODO: All the ToDos in the doCopyFoo methods below are inherited from the\n     * NSUML implementation and do not reflect new issues. One additional thing\n     * which does need to be dealt with is the copying of any attributes which\n     * have been added since this code was implemented for UML 1.3.\n     */\n    /**\n     * Used by the copy functions. Do not call this function directly.\n     * TODO: actions? instances? collaborations etc?\n     *\n     * @param source\n     *            the source classifier\n     * @param target\n     *            the target classifier\n     */\n    public void doCopyClassifier(Object source, Object target) {\n        if (!(source instanceof Classifier)) {\n            throw new IllegalArgumentException();\n        }\n\n        if (!(target instanceof Classifier)) {\n            throw new IllegalArgumentException();\n        }\n\n        // TODO: how to merge multiple inheritance? Necessary?\n        // This currently copies the common ancestors multiple times\n        doCopyNamespace(source, target);\n        doCopyGeneralizableElement(source, target);\n\n        // Copy all the Features\n        for (Feature f : ((Classifier) source).getFeature()) {\n            copyFeature(f, target);\n        }\n    }\n\n    /**\n     * Used by the copy functions. Do not call this function directly.\n     *\n     * @param source\n     *            the source datatype\n     * @param target\n     *            the target datatype\n     */\n    public void doCopyDataType(Object source, Object target) {\n        if (!(source instanceof DataType)) {\n            throw new IllegalArgumentException();\n        }\n\n        if (!(target instanceof DataType)) {\n            throw new IllegalArgumentException();\n        }\n\n        doCopyClassifier(source, target);\n    }\n\n    /**\n     * Used by the copy functions. Do not call this function directly.\n     * TODO: generalizations, specializations?\n     *\n     * @param source\n     *            the source generalizable element\n     * @param target\n     *            the target generalizable element\n     */\n    public void doCopyGeneralizableElement(Object source, Object target) {\n        if (!(source instanceof GeneralizableElement\n                && target instanceof GeneralizableElement)) {\n            throw new IllegalArgumentException(\"source: \" + source\n                    + \",target: \" + target);\n        }\n\n        doCopyModelElement(source, target);\n\n        GeneralizableElement targetGE = ((GeneralizableElement) target);\n        GeneralizableElement sourceGE = ((GeneralizableElement) source);\n        targetGE.setAbstract(sourceGE.isAbstract());\n        targetGE.setLeaf(sourceGE.isLeaf());\n        targetGE.setRoot(sourceGE.isRoot());\n    }\n\n    /**\n     * Used by the copy functions. Do not call this function directly.\n     *\n     * @param source\n     *            the source interface\n     * @param target\n     *            the target interface\n     */\n    public void doCopyInterface(Object source, Object target) {\n        if (!(source instanceof Interface)) {\n            throw new IllegalArgumentException();\n        }\n\n        if (!(target instanceof Interface)) {\n            throw new IllegalArgumentException();\n        }\n\n        doCopyClassifier(source, target);\n    }\n\n    /**\n     * Used by the copy functions. Do not call this function directly.\n     * TODO: template parameters, default type\n     * TODO: constraining elements\n     * TODO: flows, dependencies, comments, bindings, contexts ???\n     * TODO: contents, residences ???\n     *\n     * @param source\n     *            the source me\n     * @param target\n     *            the target me\n     */\n    public void doCopyModelElement(Object source, Object target) {\n        if (!(source instanceof ModelElement)) {\n            throw new IllegalArgumentException();\n        }\n\n        if (!(target instanceof ModelElement)) {\n            throw new IllegalArgumentException();\n        }\n\n        // Set the name so that superclasses can find the newly\n        // created element in the model, if necessary.\n        ModelElement targetME = ((ModelElement) target);\n        ModelElement sourceME = ((ModelElement) source);\n        targetME.setName(sourceME.getName());\n        doCopyElement(source, target);\n\n        targetME.setSpecification(sourceME.isSpecification());\n        targetME.setVisibility(sourceME.getVisibility());\n        modelImpl.getExtensionMechanismsFactory()\n                .copyTaggedValues(source, target);\n\n        if (!sourceME.getStereotype().isEmpty()) {\n            // Note that if we're copying this element then we\n            // must also be allowed to copy other necessary\n            // objects.\n            for (Stereotype s : sourceME.getStereotype()) {\n                targetME.getStereotype().add(s);\n            }\n        }\n    }\n\n    /**\n     * Used by the copy functions. Do not call this function directly.\n     *\n     * @param source\n     *            the source namespace\n     * @param target\n     *            the target namespace\n     */\n    public void doCopyNamespace(Object source, Object target) {\n        if (!(source instanceof Namespace)) {\n            throw new IllegalArgumentException();\n        }\n\n        if (!(target instanceof Namespace)) {\n            throw new IllegalArgumentException();\n        }\n\n        doCopyModelElement(source, target);\n        // Nothing more to do, don't copy owned elements.\n    }\n\n    /**\n     * Copy the meta-attributes of an Attribute to another.\n     *\n     * @param source the source attribute\n     * @param target the new attribute to be adapted\n     */\n    void doCopyAttribute(Attribute source, Attribute target) {\n        // TODO: Delete old multiplicity? Why is \"copy\" using hard coded value? - tfm\n        target.setMultiplicity(getMultiplicity11());\n        target.setChangeability(source.getChangeability());\n        target.setTargetScope(source.getTargetScope());\n        target.setType(source.getType());\n\n        doCopyFeature(source, target);\n    }\n\n    /**\n     * Copy the attributes of an Operation to another.\n     *\n     * @param source the source operation\n     * @param target the new operation to be modified\n     */\n    void doCopyOperation(Operation source, Operation target) {\n        target.setAbstract(source.isAbstract());\n        target.setLeaf(source.isLeaf());\n        target.setRoot(source.isRoot());\n        target.setConcurrency(source.getConcurrency());\n        target.setSpecification(source.getSpecification());\n\n        doCopyBehavioralFeature(source, target);\n    }\n\n    /**\n     * Copy the attributes of one Method to another.\n     *\n     * @param source the method to copy attributes from\n     * @param target the method to be adapted\n     */\n    void doCopyMethod(Method source, Method target) {\n        ProcedureExpression pe = source.getBody();\n        ProcedureExpression oldPe = target.getBody();\n        if (!equal(oldPe,pe)) {\n            target.setBody((ProcedureExpression)\n                    modelImpl.getDataTypesFactory().createProcedureExpression(\n                            pe.getLanguage(), pe.getBody()));\n            if (oldPe != null) {\n                Model.getUmlFactory().delete(oldPe);\n            }\n        }\n\n        doCopyBehavioralFeature(source, target);\n    }\n\n\n    private boolean equal(Expression expr1, Expression expr2) {\n        if (expr1 == null) {\n            if (expr2 == null) {\n                return true;\n            } else {\n                return false;\n            }\n        } else {\n            return expr1.equals(expr2);\n        }\n    }\n\n    /**\n     * Copy the attributes of one Reception to another.\n     *\n     * @param source the reception to copy attributes from\n     * @param target the reception to be adapted\n     */\n    void doCopyReception(Reception source, Reception target) {\n        target.setAbstract(source.isAbstract());\n        target.setLeaf(source.isLeaf());\n        target.setRoot(source.isRoot());\n        target.setSpecification(source.getSpecification());\n        target.setSignal(source.getSignal());\n\n        doCopyBehavioralFeature(source, target);\n    }\n\n\n    /**\n     * Copy the attributes of one BehavioralFeature to another.\n     *\n     * @param source the BehavioralFeature to copy from\n     * @param target the BehavioralFeature to b adapted\n     */\n    void doCopyBehavioralFeature(BehavioralFeature source,\n            BehavioralFeature target) {\n        target.setQuery(source.isQuery());\n        // copy raised signals:\n        Collection<Signal> raisedSignals = ((org.omg.uml.UmlPackage) source\n                .refOutermostPackage()).getCommonBehavior()\n                .getAContextRaisedSignal().getRaisedSignal(source);\n        for (Signal signal : raisedSignals) {\n            ((org.omg.uml.UmlPackage) source.refOutermostPackage())\n                    .getCommonBehavior().getAContextRaisedSignal().add(target,\n                            signal);\n        }\n\n        doCopyFeature(source, target);\n    }\n\n    /**\n     * Copy the attributes of one Feature to another.\n     *\n     * @param source the Feature to copy from\n     * @param target the Feature to copy to\n     */\n    void doCopyFeature(Feature source, Feature target) {\n        target.setVisibility(source.getVisibility());\n        target.setOwnerScope(source.getOwnerScope());\n\n        doCopyModelElement(source, target);\n    }\n\n}\n", "human_rating": 1.985835035, "metadata": {"project": "argoUML", "class": "org.argouml.model.mdr.CoreFactoryMDRImpl", "source_path": "argoUML/sourcefiles/src/argouml-core-model-mdr/src/org/argouml/model/mdr/CoreFactoryMDRImpl.java", "label_probabilities": {"readability": [0.0, 0.000136645, 0.985562, 0.0143011], "understandability": [0.0, 0.0, 0.000346783, 0.999653], "complexity": [0.814834, 0.185166, 0.0, 0.0], "modularization": [0.0723511, 0.927649, 0.0, 0.0], "overall": [0.0, 0.0, 2.88425e-14, 1.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.mdr.ModelEventPumpMDRImpl", "source": "/* $Id: ModelEventPumpMDRImpl.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2005-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Tom Morris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2005-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.model.mdr;\n\nimport java.beans.PropertyChangeListener;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.jmi.model.Association;\nimport javax.jmi.model.AssociationEnd;\nimport javax.jmi.model.Attribute;\nimport javax.jmi.model.GeneralizableElement;\nimport javax.jmi.model.ModelElement;\nimport javax.jmi.model.ModelPackage;\nimport javax.jmi.model.MofClass;\nimport javax.jmi.model.NameNotFoundException;\nimport javax.jmi.model.Reference;\nimport javax.jmi.reflect.InvalidObjectException;\nimport javax.jmi.reflect.RefAssociation;\nimport javax.jmi.reflect.RefBaseObject;\nimport javax.jmi.reflect.RefObject;\n\nimport org.argouml.model.AbstractModelEventPump;\nimport org.argouml.model.AddAssociationEvent;\nimport org.argouml.model.AttributeChangeEvent;\nimport org.argouml.model.DeleteInstanceEvent;\nimport org.argouml.model.InvalidElementException;\nimport org.argouml.model.Model;\nimport org.argouml.model.NotImplementedException;\nimport org.argouml.model.RemoveAssociationEvent;\nimport org.argouml.model.UmlChangeEvent;\nimport org.argouml.model.UmlChangeListener;\nimport org.netbeans.api.mdr.MDRManager;\nimport org.netbeans.api.mdr.MDRepository;\nimport org.netbeans.api.mdr.events.AssociationEvent;\nimport org.netbeans.api.mdr.events.AttributeEvent;\nimport org.netbeans.api.mdr.events.InstanceEvent;\nimport org.netbeans.api.mdr.events.MDRChangeEvent;\nimport org.netbeans.api.mdr.events.MDRPreChangeListener;\nimport org.netbeans.api.mdr.events.TransactionEvent;\nimport org.netbeans.api.mdr.events.VetoChangeException;\n\n/**\n * The ModelEventPump for the MDR implementation.<p>\n *\n * This implements three different event dispatching interfaces\n * which support a variety of different types of listener registration.\n * We keep a single event listener registered with the repository\n * for all events and then re-dispatch events to those listeners\n * who have requested them.<p>\n *\n * @since ARGO0.19.5\n * @author Ludovic Ma&icirc;tre\n * @author Tom Morris\n */\nclass ModelEventPumpMDRImpl extends AbstractModelEventPump implements\n        MDRPreChangeListener {\n\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(ModelEventPumpMDRImpl.class.getName());\n\n    private static final boolean VETO_READONLY_CHANGES = true;\n\n    private MDRModelImplementation modelImpl;\n\n    private Object registrationMutex = new Byte[0];\n\n    private MDRepository repository;\n\n    private Boolean eventCountMutex = new Boolean(false);\n    private int pendingEvents = 0;\n\n    private Thread eventThread;\n\n    /**\n     * Map of Element/attribute tuples and the listeners they have registered.\n     */\n    private Registry<PropertyChangeListener> elements =\n        new Registry<PropertyChangeListener>();\n\n    /**\n     * Map of Class/attribute tuples and the listeners they have registered.\n     */\n    private Registry<PropertyChangeListener> listenedClasses =\n        new Registry<PropertyChangeListener>();\n\n    /**\n     * Map of subtypes for all types in our metamodel.\n     */\n    private Map<String, Collection<String>> subtypeMap;\n\n    /**\n     * Map of all valid property names (association end names & attribute names)\n     * for each class.\n     */\n    private Map<String, Collection<String>> propertyNameMap;\n\n    /**\n     * Constructor.\n     *\n     * @param implementation The implementation.\n     */\n    public ModelEventPumpMDRImpl(MDRModelImplementation implementation) {\n        this(implementation, MDRManager.getDefault().getDefaultRepository());\n    }\n\n    /**\n     * Constructor.\n     *\n     * @param implementation The implementation.\n     * @param repo The repository.\n     */\n    public ModelEventPumpMDRImpl(MDRModelImplementation implementation,\n            MDRepository repo) {\n        super();\n        modelImpl = implementation;\n        repository = repo;\n        subtypeMap = buildTypeMap(modelImpl.getModelPackage());\n        propertyNameMap = buildPropertyNameMap(modelImpl.getModelPackage());\n    }\n\n    /*\n     * @see org.argouml.model.AbstractModelEventPump#addModelEventListener(java.beans.PropertyChangeListener,\n     *      java.lang.Object, java.lang.String[])\n     */\n    public void addModelEventListener(PropertyChangeListener listener,\n            Object modelElement, String[] propertyNames) {\n        if (listener == null) {\n            throw new IllegalArgumentException(\"A listener must be supplied\");\n        }\n\n        if (modelElement == null) {\n            throw new IllegalArgumentException(\n                    \"A model element must be supplied\");\n        }\n\n        registerModelEvent(listener, modelElement, propertyNames);\n    }\n\n    /*\n     * @see org.argouml.model.AbstractModelEventPump#addModelEventListener(java.beans.PropertyChangeListener,\n     *      java.lang.Object, java.lang.String[])\n     */\n    public void addModelEventListener(UmlChangeListener listener,\n            Object modelElement, String[] propertyNames) {\n        throw new NotImplementedException();\n    }\n\n    /*\n     * @see org.argouml.model.AbstractModelEventPump#addModelEventListener(java.beans.PropertyChangeListener,\n     *      java.lang.Object)\n     */\n    public void addModelEventListener(PropertyChangeListener listener,\n            Object modelElement) {\n        if (listener == null) {\n            throw new IllegalArgumentException(\"A listener must be supplied\");\n        }\n\n        if (modelElement == null) {\n            throw new IllegalArgumentException(\n                    \"A model element must be supplied\");\n        }\n\n        registerModelEvent(listener, modelElement, null);\n    }\n\n    /*\n     * @see org.argouml.model.AbstractModelEventPump#removeModelEventListener(java.beans.PropertyChangeListener,\n     *      java.lang.Object, java.lang.String[])\n     */\n    public void removeModelEventListener(PropertyChangeListener listener,\n            Object modelelement, String[] propertyNames) {\n        unregisterModelEvent(listener, modelelement, propertyNames);\n    }\n\n    /*\n     * @see org.argouml.model.AbstractModelEventPump#removeModelEventListener(java.beans.PropertyChangeListener,\n     *      java.lang.Object, java.lang.String[])\n     */\n    public void removeModelEventListener(UmlChangeListener listener,\n            Object modelelement, String[] propertyNames) {\n        throw new NotImplementedException();\n    }\n\n    /*\n     * @see org.argouml.model.AbstractModelEventPump#removeModelEventListener(java.beans.PropertyChangeListener,\n     *      java.lang.Object)\n     */\n    public void removeModelEventListener(PropertyChangeListener listener,\n            Object modelelement) {\n        unregisterModelEvent(listener, modelelement, null);\n    }\n\n    /*\n     * @see org.argouml.model.AbstractModelEventPump#addClassModelEventListener(java.beans.PropertyChangeListener,\n     *      java.lang.Object, java.lang.String[])\n     */\n    public void addClassModelEventListener(PropertyChangeListener listener,\n            Object modelClass, String[] propertyNames) {\n        registerClassEvent(listener, modelClass, propertyNames);\n    }\n\n    /*\n     * @see org.argouml.model.AbstractModelEventPump#removeClassModelEventListener(java.beans.PropertyChangeListener,\n     *      java.lang.Object, java.lang.String[])\n     */\n    public void removeClassModelEventListener(PropertyChangeListener listener,\n            Object modelClass, String[] propertyNames) {\n        unregisterClassEvent(listener, modelClass, propertyNames);\n    }\n\n    /**\n     * Detect a change event in MDR and convert this to a change event from the\n     * model interface.  We also keep track of the number of pending changes so\n     * that we can implement a simple flush interface.<p>\n     *\n     * The conversions are according to this table.\n     * <pre>\n     * MDR Event         MDR Event Type            Propogated Event\n     *\n     * InstanceEvent     EVENT_INSTANCE_DELETE     DeleteInstanceEvent\n     * AttributeEvent    EVENT_ATTRIBUTE_SET       AttributeChangeEvent\n     * AssociationEvent  EVENT_ASSOCIATION_ADD     AddAssociationEvent\n     * AssociationEvent  EVENT_ASSOCIATION_REMOVE  RemoveAssociationEvent\n     * </pre>\n     * Any other events are ignored and not propogated beyond the model\n     * subsystem.\n     *\n     * @param mdrEvent Change event from MDR\n     * @see org.netbeans.api.mdr.events.MDRChangeListener#change\n     */\n    public void change(MDRChangeEvent mdrEvent) {\n\n        if (eventThread == null) {\n            eventThread = Thread.currentThread();\n        }\n\n        // TODO: This should be done after all events are delivered, but leave\n        // it here for now to avoid last minute synchronization problems\n        decrementEvents();\n\n        // Quick exit if it's a transaction event\n        // (we get a lot of them and they are all ignored)\n        if (mdrEvent instanceof TransactionEvent) {\n            return;\n        }\n\n        List<UmlChangeEvent> events = new ArrayList<UmlChangeEvent>();\n\n        if (mdrEvent instanceof AttributeEvent) {\n            AttributeEvent ae = (AttributeEvent) mdrEvent;\n            events.add(new AttributeChangeEvent(ae.getSource(),\n                    ae.getAttributeName(), ae.getOldElement(),\n                    ae.getNewElement(), mdrEvent));\n        } else if (mdrEvent instanceof InstanceEvent\n                && mdrEvent.isOfType(InstanceEvent.EVENT_INSTANCE_DELETE)) {\n            InstanceEvent ie = (InstanceEvent) mdrEvent;\n            events.add(new DeleteInstanceEvent(ie.getSource(),\n                    \"remove\", null, null, mdrEvent));\n            // Clean up index entries\n            String mofid = ((InstanceEvent)mdrEvent).getInstance().refMofId();\n            modelImpl.removeElement(mofid);\n        } else if (mdrEvent instanceof AssociationEvent) {\n            AssociationEvent ae = (AssociationEvent) mdrEvent;\n            if (ae.isOfType(AssociationEvent.EVENT_ASSOCIATION_ADD)) {\n                events.add(new AddAssociationEvent(\n                        ae.getNewElement(),\n                        mapPropertyName(ae.getEndName()),\n                        ae.getOldElement(), // will always be null\n                        ae.getFixedElement(),\n                        ae.getFixedElement(),\n                        mdrEvent));\n                // Create a change event for the corresponding property\n                events.add(new AttributeChangeEvent(\n                        ae.getNewElement(),\n                        mapPropertyName(ae.getEndName()),\n                        ae.getOldElement(), // will always be null\n                        ae.getFixedElement(),\n                        mdrEvent));\n                // Create an event for the other end of the association\n                events.add(new AddAssociationEvent(\n                        ae.getFixedElement(),\n                        otherAssocEnd(ae),\n                        ae.getOldElement(), // will always be null\n                        ae.getNewElement(),\n                        ae.getNewElement(),\n                        mdrEvent));\n                // and a change event for that end\n                events.add(new AttributeChangeEvent(\n                        ae.getFixedElement(),\n                        otherAssocEnd(ae),\n                        ae.getOldElement(), // will always be null\n                        ae.getNewElement(),\n                        mdrEvent));\n            } else if (ae.isOfType(AssociationEvent.EVENT_ASSOCIATION_REMOVE)) {\n                events.add(new RemoveAssociationEvent(\n                        ae.getOldElement(),\n                        mapPropertyName(ae.getEndName()),\n                        ae.getFixedElement(),\n                        ae.getNewElement(), // will always be null\n                        ae.getFixedElement(),\n                        mdrEvent));\n                // Create a change event for the associated property\n                events.add(new AttributeChangeEvent(\n                        ae.getOldElement(),\n                        mapPropertyName(ae.getEndName()),\n                        ae.getFixedElement(),\n                        ae.getNewElement(), // will always be null\n                        mdrEvent));\n                // Create an event for the other end of the association\n                events.add(new RemoveAssociationEvent(\n                        ae.getFixedElement(),\n                        otherAssocEnd(ae),\n                        ae.getOldElement(),\n                        ae.getNewElement(), // will always be null\n                        ae.getOldElement(),\n                        mdrEvent));\n                // Create a change event for the associated property\n                events.add(new AttributeChangeEvent(\n                        ae.getFixedElement(),\n                        otherAssocEnd(ae),\n                        ae.getOldElement(),\n                        ae.getNewElement(), // will always be null\n                        mdrEvent));\n            } else if (ae.isOfType(AssociationEvent.EVENT_ASSOCIATION_SET)) {\n                LOG.log(Level.SEVERE, \"Unexpected EVENT_ASSOCIATION_SET received\");\n            } else {\n                LOG.log(Level.SEVERE, \"Unknown association event type \" + ae.getType());\n            }\n        } else {\n            String name = mdrEvent.getClass().getName();\n            // Cut down on debugging noise\n            if (!name.endsWith(\"CreateInstanceEvent\")) {\n                LOG.log(Level.FINE, \"Ignoring MDR event \" + mdrEvent);\n            }\n        }\n\n        for (UmlChangeEvent event : events) {\n            fire(event);\n            // Unregister deleted instances after all events have been delivered\n            if (event instanceof DeleteInstanceEvent) {\n                elements.unregister(null, ((RefBaseObject) event.getSource())\n                        .refMofId(), null);\n            }\n        }\n    }\n\n    private boolean isReadOnly(RefBaseObject object) {\n        return modelImpl.isReadOnly(object.refOutermostPackage());\n    }\n\n    /**\n     * @param e Event from MDR indicating a planned change.\n     * @see org.netbeans.api.mdr.events.MDRPreChangeListener#plannedChange\n     */\n    public void plannedChange(MDRChangeEvent e) {\n\n        if (VETO_READONLY_CHANGES) {\n            if (e instanceof InstanceEvent) {\n                if (e.isOfType(InstanceEvent.EVENT_INSTANCE_CREATE)) {\n                    RefBaseObject element = (RefBaseObject) ((InstanceEvent) e)\n                            .getSource();\n                    if (isReadOnly(element)) {\n                        throw new VetoChangeException(e.getSource(), null);\n                    }\n                } else {\n                    RefObject element = ((InstanceEvent) e).getInstance();\n                    if (isReadOnly(element)) {\n                        throw new VetoChangeException(e.getSource(), element);\n                    }\n                }\n            } else if (e instanceof AssociationEvent) {\n                // TODO: association changes are too hard to check easily\n                // we don't know which end of the association is significant\n                // without checking the metamodel for navigability of the ends\n//                RefObject element = ((AssociationEvent) e).getFixedElement();\n//                if (isReadOnly(element)) {\n//                    throw new VetoChangeException(element, element);\n//                }\n            } else if (e instanceof AttributeEvent) {\n                RefObject element = (RefObject) ((AttributeEvent) e)\n                        .getSource();\n                if (isReadOnly(element)) {\n                    throw new VetoChangeException(element, element);\n                }\n            }\n        }\n\n        synchronized (eventCountMutex) {\n            pendingEvents++;\n        }\n\n        // Prototypical logging code that can be enabled and modified to\n        // discover who's creating certain types of events\n//        if (/* LOG.isDebugEnabled() && */ e instanceof AssociationEvent) {\n//            AssociationEvent ae = (AssociationEvent) e;\n//            if (ae.isOfType(AssociationEvent.EVENT_ASSOCIATION_REMOVE)\n//                    && \"namespace\".equals(ae.getEndName())\n//                    /* && ae.getFixedElement() instanceof UmlPackage */) {\n//                LOG.log(Level.FINE, \"Removing element \" + ae.getOldElement()\n//                        + \" from package \" + ae.getFixedElement());\n//            }\n//        }\n    }\n\n    /**\n     * @param e\n     *            MDR event which was announced to plannedChange then\n     *            subsequently cancelled.\n     * @see org.netbeans.api.mdr.events.MDRPreChangeListener#changeCancelled\n     */\n    public void changeCancelled(MDRChangeEvent e) {\n        decrementEvents();\n    }\n\n    /**\n     * Decrement count of outstanding events and wake\n     * any waiters when it becomes zero.\n     */\n    private void decrementEvents() {\n\n        synchronized (eventCountMutex) {\n            pendingEvents--;\n            if (pendingEvents <= 0) {\n                eventCountMutex.notifyAll();\n            }\n        }\n    }\n\n    /**\n     * Fire an event to any registered listeners.\n     */\n    private void fire(UmlChangeEvent event) {\n        String mofId = ((RefBaseObject) event.getSource()).refMofId();\n        String className  = getClassName(event.getSource());\n\n        // Any given listener is only called once even if it is\n        // registered for multiple relevant matches\n        Set<PropertyChangeListener> listeners =\n                new HashSet<PropertyChangeListener>();\n        synchronized (registrationMutex) {\n            listeners.addAll(elements.getMatches(mofId, event\n                    .getPropertyName()));\n\n            // This will include all subtypes registered\n            listeners.addAll(listenedClasses.getMatches(className, event\n                    .getPropertyName()));\n        }\n\n        if (LOG.isLoggable(Level.FINE)) {\n            LOG.log(Level.FINE, \"Firing \"\n                    + modelImpl.getMetaTypes().getName(event)\n                    + \" source \"\n                    + modelImpl.getMetaTypes().getName(\n                            event.getSource())\n                    + \" [\" + ((RefBaseObject) event.getSource()).refMofId()\n                    + \"].\"  + event.getPropertyName()\n                    + \",\" + formatElement(event.getOldValue())\n                    + \"->\" + formatElement(event.getNewValue()));\n        }\n\n        if (!listeners.isEmpty()) {\n            for (PropertyChangeListener pcl : listeners) {\n                if (false /*(LOG.isDebugEnabled()*/) {\n                    LOG.log(Level.FINE, \"Firing event on \" + pcl.getClass().getName()\n                            + \"[\" + pcl + \"]\");\n                }\n                pcl.propertyChange(event);\n            }\n        } else {\n            // For debugging you probably want either this\n            // OR the logging for every event which is fired - not both\n            if (false/*LOG.isDebugEnabled()*/) {\n                LOG.log(Level.FINE, \"No listener for \"\n                        + modelImpl.getMetaTypes().getName(event)\n                        + \" source \"\n                        + modelImpl.getMetaTypes().getName(\n                                event.getSource())\n                        + \" [\"\n                        + ((RefBaseObject) event.getSource()).refMofId() + \"].\"\n                        + event.getPropertyName() + \",\" + event.getOldValue()\n                        + \"->\" + event.getNewValue());\n            }\n        }\n    }\n\n\n    /**\n     * Register a listener for a Model Event.  The ModelElement's\n     * MofID is used as the string to match against.\n     */\n    private void registerModelEvent(PropertyChangeListener listener,\n            Object modelElement, String[] propertyNames) {\n        if (listener == null || modelElement == null) {\n            throw new IllegalArgumentException(\"Neither listener (\" + listener\n                    + \") or modelElement (\" + modelElement\n                    + \") can be null! [Property names: \" + propertyNames + \"]\");\n        }\n\n        // Fetch the key before going in synchronized mode\n        String mofId = ((RefBaseObject) modelElement).refMofId();\n        try {\n            verifyAttributeNames(((RefBaseObject) modelElement).refMetaObject(),\n                    propertyNames);\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n        if (LOG.isLoggable(Level.FINE)) {\n            LOG.log(Level.FINE, \"Register [\"\n                    + \" element:\" + formatElement(modelElement)\n                    + \", properties:\" + formatArray(propertyNames)\n                    + \", listener:\" + listener\n                    + \"]\");\n        }\n        synchronized (registrationMutex) {\n            elements.register(listener, mofId, propertyNames);\n        }\n    }\n\n    /**\n     * Unregister a listener for a Model Event.\n     */\n    private void unregisterModelEvent(PropertyChangeListener listener,\n            Object modelElement, String[] propertyNames) {\n        if (listener == null || modelElement == null) {\n            LOG.log(Level.SEVERE, \"Attempt to unregister null listener(\" + listener\n                    + \") or modelElement (\" + modelElement\n                    + \")! [Property names: \" + propertyNames + \"]\");\n            return;\n        }\n        if (!(modelElement instanceof RefBaseObject)) {\n            LOG.log(Level.SEVERE, \"Ignoring non-RefBaseObject received by \"\n                    + \"unregisterModelEvent - \" + modelElement);\n            return;\n        }\n        String mofId = ((RefBaseObject) modelElement).refMofId();\n        if (LOG.isLoggable(Level.FINE)) {\n            LOG.log(Level.FINE, \"Unregister [\"\n                    + \" element:\" + formatElement(modelElement)\n                    + \", properties:\" + formatArray(propertyNames)\n                    + \", listener:\" + listener\n                    + \"]\");\n        }\n        synchronized (registrationMutex) {\n            elements.unregister(listener, mofId, propertyNames);\n        }\n    }\n\n    /**\n     * Register a listener for metamodel Class (and all its\n     * subclasses), optionally qualified by a list of\n     * property names.\n     *\n     * TODO: verify that property/event names are legal for\n     * this class in the metamodel\n     */\n    private void registerClassEvent(PropertyChangeListener listener,\n            Object modelClass, String[] propertyNames) {\n\n        if (modelClass instanceof Class) {\n            String className = getClassName(modelClass);\n            if (LOG.isLoggable(Level.FINE)) {\n                LOG.log(Level.FINE, \"Register class [\"\n                        + modelImpl.getMetaTypes().getName(modelClass)\n                        + \"properties:\" + formatArray(propertyNames)\n                        + \", listener:\" + listener + \"]\");\n            }\n            Collection<String> subtypes = subtypeMap.get(className);\n            verifyAttributeNames(className, propertyNames);\n            synchronized (registrationMutex) {\n                listenedClasses.register(listener, className, propertyNames);\n                for (String subtype : subtypes) {\n                    listenedClasses.register(listener, subtype, propertyNames);\n                }\n            }\n            return;\n        }\n        throw new IllegalArgumentException(\n                \"Don't know how to register class event for object \"\n                        + modelClass);\n    }\n\n\n    /**\n     * Unregister a listener for a class and its subclasses.\n     */\n    private void unregisterClassEvent(PropertyChangeListener listener,\n            Object modelClass, String[] propertyNames) {\n        if (modelClass instanceof Class) {\n            String className = getClassName(modelClass);\n            if (LOG.isLoggable(Level.FINE)) {\n                LOG.log(Level.FINE,\n                        \"Unregister class [\" + className\n                        + \", properties:\" + formatArray(propertyNames)\n                        + \", listener:\" + listener + \"]\");\n            }\n            Collection<String> subtypes = subtypeMap.get(className);\n            synchronized (registrationMutex) {\n                listenedClasses.unregister(listener, className, propertyNames);\n                for (String subtype : subtypes) {\n                    listenedClasses.unregister(listener, subtype,\n                            propertyNames);\n                }\n            }\n            return;\n        }\n        throw new IllegalArgumentException(\n                \"Don't know how to unregister class event for object \"\n                        + modelClass);\n    }\n\n    private String getClassName(Object elementOrClass) {\n        return modelImpl.getMetaTypes().getName(elementOrClass);\n    }\n\n    /*\n     * @see org.argouml.model.ModelEventPump#startPumpingEvents()\n     */\n    public void startPumpingEvents() {\n        LOG.log(Level.FINE, \"Start pumping events\");\n        repository.addListener(this);\n    }\n\n    /*\n     * @see org.argouml.model.ModelEventPump#stopPumpingEvents()\n     */\n    public void stopPumpingEvents() {\n        LOG.log(Level.FINE, \"Stop pumping events\");\n        repository.removeListener(this);\n    }\n\n    /*\n     * @see org.argouml.model.ModelEventPump#flushModelEvents()\n     */\n    public void flushModelEvents() {\n        while (true) {\n            synchronized (eventCountMutex) {\n                if (pendingEvents <= 0\n                        // Don't wait on ourselves, we'll deadlock!\n                        // TODO: We might want to throw an exception here\n                        || Thread.currentThread().equals(eventThread)) {\n                    return;\n                }\n                try {\n                    eventCountMutex.wait();\n                } catch (InterruptedException e) {\n                    LOG.log(Level.SEVERE, \"Interrupted while waiting in flushModelEvents\");\n                }\n            }\n        }\n\n    }\n\n    /**\n     * Get name of opposite end of association using\n     * reflection on metamodel.\n     */\n    private String otherAssocEnd(AssociationEvent ae) {\n        RefAssociation ra = (RefAssociation) ae.getSource();\n        Association a = (Association) ra.refMetaObject();\n        AssociationEnd aend = null;\n        try {\n            aend = (AssociationEnd) a.lookupElementExtended(ae.getEndName());\n        } catch (NameNotFoundException e) {\n            LOG.log(Level.SEVERE, \"Failed to find other end of association : \"\n                    + ae.getSource() + \" -> \" + ae.getEndName());\n            return null;\n        }\n        return aend.otherEnd().getName();\n    }\n\n\n    /**\n     * Map from UML 1.4 names to UML 1.3 names\n     * expected by ArgoUML.<p>\n     *\n     * Note: It would have less performance impact to do the\n     * mapping during listener registration, but ArgoUML\n     * depends on the value in the event.\n     */\n    private static String mapPropertyName(String name) {\n\n        // TODO: We don't want to do this once we have dropped UML1.3\n        // Map UML 1.4 names to UML 1.3 equivalents\n        if (\"typedParameter\".equals(name)) {\n            return \"parameter\";\n        }\n        if (\"typedFeature\".equals(name)) {\n            return \"feature\";\n        }\n        return name;\n    }\n\n    /**\n     * Formatters for debug output.\n     */\n    private String formatArray(String[] array) {\n        if (array == null) {\n            return null;\n        }\n        String result = \"[\";\n        for (int i = 0; i < array.length; i++) {\n            result = result + array[i] + \", \";\n        }\n        return result.substring(0, result.length() - 2) + \"]\";\n    }\n\n    private String formatElement(Object element) {\n        try {\n            if (element instanceof RefBaseObject) {\n                return modelImpl.getMetaTypes().getName(element)\n                        + \"<\" + ((RefBaseObject) element).refMofId() + \">\";\n            } else if (element != null) {\n                return element.toString();\n            }\n        } catch (InvalidObjectException e) {\n            return modelImpl.getMetaTypes().getName(element)\n                    + \"<deleted>\";\n        }\n        return null;\n    }\n\n\n    /**\n     * Traverse metamodel and build list of subtypes for every metatype.\n     */\n    private Map<String, Collection<String>> buildTypeMap(ModelPackage extent) {\n        Map<String, Collection<String>> names =\n            new HashMap<String, Collection<String>>();\n        for (Object metaclass : extent.getMofClass().refAllOfClass()) {\n            ModelElement element = (ModelElement) metaclass;\n            String name = element.getName();\n            if (names.containsKey(name)) {\n                LOG.log(Level.SEVERE,\n                        \"Found duplicate class '\" + name + \"' in metamodel\");\n            } else {\n                names.put(name, getSubtypes(extent, element));\n                // LOG.log(Level.FINE, \" Class \" + name + \" has subtypes : \"\n                // + names.get(name));\n            }\n        }\n        return names;\n    }\n\n    /**\n     * Recursive method to get all subtypes.\n     *\n     * TODO: Does this have a scalability problem?\n     */\n    private Collection<String> getSubtypes(ModelPackage extent,\n            ModelElement me) {\n        Collection<String> allSubtypes = new HashSet<String>();\n        if (me instanceof GeneralizableElement) {\n            GeneralizableElement ge = (GeneralizableElement) me;\n            Collection<ModelElement> subtypes = extent.getGeneralizes()\n                    .getSubtype(ge);\n            for (ModelElement st : subtypes) {\n                allSubtypes.add(st.getName());\n                allSubtypes.addAll(getSubtypes(extent, st));\n            }\n        }\n        return allSubtypes;\n    }\n\n    /**\n     * Traverse metamodel and build list of names for all attributes and\n     * reference ends.\n     */\n    private Map<String, Collection<String>> buildPropertyNameMap(\n            ModelPackage extent) {\n        Map<String, Collection<String>> names =\n                new HashMap<String, Collection<String>>();\n        for (Reference reference : (Collection<Reference>) extent\n                .getReference().refAllOfClass()) {\n            mapAssociationEnd(names, reference.getExposedEnd());\n            mapAssociationEnd(names, reference.getReferencedEnd());\n        }\n        for (Attribute attribute : (Collection<Attribute>) extent\n                .getAttribute().refAllOfClass()) {\n            mapPropertyName(names, attribute.getContainer(),\n                    attribute.getName());\n        }\n        return names;\n    }\n\n    private void mapAssociationEnd(Map<String, Collection<String>> names,\n            AssociationEnd end) {\n        ModelElement type = end.otherEnd().getType();\n        mapPropertyName(names, type, end.getName());\n    }\n\n    private boolean mapPropertyName(Map<String, Collection<String>> names,\n            ModelElement type, String propertyName) {\n        String typeName = type.getName();\n        boolean added = mapPropertyName(names, typeName, propertyName);\n\n        Collection<String> subtypes = subtypeMap.get(typeName);\n        if (subtypes != null) {\n            for (String subtype : subtypes) {\n                added &= mapPropertyName(names, subtype, propertyName);\n            }\n        }\n\n        return added;\n    }\n\n    private boolean mapPropertyName(Map<String, Collection<String>> names,\n            String typeName, String propertyName) {\n        if (!names.containsKey(typeName)) {\n            names.put(typeName, new HashSet<String>());\n        }\n        boolean added = names.get(typeName).add(propertyName);\n        if (!added) {\n            // Because we map both ends of an association we'll see many\n            // names twice\n//                LOG.log(Level.FINE, \"Duplicate property name found - {0}:{1}\", new Object[]{typeName, propertyName});\n        } else {\n            LOG.log(Level.FINE, \"Added property name - {0}:{1}\", new Object[]{typeName, propertyName});\n        }\n        return added;\n    }\n\n    /**\n     * Check whether given attribute names exist for this\n     * metatype in the metamodel.  Throw exception if not found.\n     */\n    private void verifyAttributeNames(String className, String[] attributes) {\n        // convert classname to RefObject\n        RefObject ro = null;\n        verifyAttributeNames(ro, attributes);\n    }\n\n    /**\n     * Check whether given attribute names exist for this\n     * metatype in the metamodel.  Throw exception if not found.\n     */\n    private void verifyAttributeNames(RefObject metaobject,\n            String[] attributes) {\n        // Only do verification if debug level logging is on\n        // TODO: Should we leave this on always? - tfm\n        if (LOG.isLoggable(Level.FINE)) {\n            if (metaobject == null || attributes == null) {\n                return;\n            }\n            // If we don't have a MofClass, see if we can get one from the\n            // instance\n            if (!(metaobject instanceof MofClass)) {\n                metaobject = metaobject.refMetaObject();\n            }\n\n            // If we still don't have a MofClass, something's wrong\n            if (!(metaobject instanceof MofClass)) {\n                throw new IllegalArgumentException(\n                        \"Argument must be MofClass or instance of MofClass\");\n            }\n\n            MofClass metaclass = (MofClass) metaobject;\n            Collection<String> names = propertyNameMap.get(metaclass.getName());\n            if (names == null) {\n                names = Collections.emptySet();\n            }\n\n            for (String attribute : attributes) {\n                if (!names.contains(attribute)\n                        && !\"remove\".equals(attribute)) {\n\n                    // TODO: We also have code registering for the names of\n                    // a tagged value like \"derived\"\n                    LOG.log(Level.SEVERE,\n                            \"Property '\" + attribute\n                             + \"' for class '\"\n                             + metaclass.getName()\n                             + \"' doesn't exist in metamodel\");\n//                    throw new IllegalArgumentException(\"Property '\"\n//                            + attribute + \"' doesn't exist in metamodel\");\n                }\n            }\n        }\n    }\n\n\n    @SuppressWarnings(\"unchecked\")\n    public List getDebugInfo() {\n        List info = new ArrayList();\n        info.add(\"Event Listeners\");\n        for (Iterator it = elements.registry.entrySet().iterator();\n                it.hasNext(); ) {\n            Map.Entry entry = (Map.Entry) it.next();\n            String item = entry.getKey().toString();\n            List modelElementNode = newDebugNode(getDebugDescription(item));\n            info.add(modelElementNode);\n            Map propertyMap = (Map) entry.getValue();\n            for (Iterator propertyIterator = propertyMap.entrySet().iterator();\n                    propertyIterator.hasNext();) {\n                Map.Entry propertyEntry = (Map.Entry) propertyIterator.next();\n                List propertyNode =\n                    newDebugNode(propertyEntry.getKey().toString());\n                modelElementNode.add(propertyNode);\n\n                List listenerList = (List) propertyEntry.getValue();\n                for (Iterator listIt = listenerList.iterator();\n                        listIt.hasNext(); ) {\n                    Object listener = listIt.next();\n                    List listenerNode =\n                        newDebugNode(\n                                listener.getClass().getName());\n                    propertyNode.add(listenerNode);\n                }\n            }\n        }\n\n        return info;\n    }\n\n    private List<String> newDebugNode(String name) {\n        List<String> list = new ArrayList<String>();\n        list.add(name);\n        return list;\n    }\n\n    private String getDebugDescription(String mofId) {\n        Object modelElement = repository.getByMofId(mofId);\n        String name = Model.getFacade().getName(modelElement);\n        if (name != null && name.trim().length() != 0) {\n            return \"\\\"\" + name + \"\\\" - \" + modelElement.toString();\n        } else {\n            return modelElement.toString();\n        }\n    }\n\n}\n\n\n/**\n * A simple typed registry which supports two levels of string keys.\n *\n * @param <T> type of object to be registered\n * @author Tom Morris\n */\nclass Registry<T> {\n\n    private static final Logger LOG = Logger.getLogger(Registry.class.getName());\n\n    Map<String, Map<String, List<T>>> registry;\n\n    /**\n     * Construct a new registry for the given type of object.\n     */\n    Registry() {\n        registry = Collections\n                .synchronizedMap(new HashMap<String, Map<String, List<T>>>());\n    }\n\n    /**\n     * Register an object with given keys(s) in the registry. The object is\n     * registered in multiple locations for quick lookup. During matching an\n     * object registered without subkeys will match any subkey. Multiple calls\n     * with the same item and key pair will only result in a single registration\n     * being made.\n     *\n     * @param item object to be registered\n     * @param key primary key for registration\n     * @param subkeys array of subkeys. If null, register under primary key\n     *                only. The special value of the empty string (\"\") must not\n     *                be used as a subkey by the caller.\n     */\n    void register(T item, String key,\n            String[] subkeys) {\n\n        // Lookup primary key, creating new entry if needed\n        Map<String, List<T>> entry = registry.get(key);\n        if (entry == null) {\n            entry = new HashMap<String, List<T>>();\n            registry.put(key, entry);\n        }\n\n        // If there are no subkeys, register using our special value\n        // to indicate that this is a primary key only registration\n        if (subkeys == null || subkeys.length < 1) {\n            subkeys =\n                new String[] {\n                    \"\",\n                };\n        }\n\n        for (int i = 0; i < subkeys.length; i++) {\n            List<T> list = entry.get(subkeys[i]);\n            if (list == null) {\n                list = new ArrayList<T>();\n                entry.put(subkeys[i], list);\n            }\n            if (!list.contains(item)) {\n                list.add(item);\n            } else {\n                LOG.log(Level.FINE, \"Duplicate registration attempt for {0}: {1} Listener: {2}\",\n                        new Object[]{key,subkeys,item});\n            }\n        }\n    }\n\n    /**\n     * Unregister an item or all items which match key set.\n     *\n     * @param item object to be unregistered.  If null, unregister all\n     * matching objects.\n     * @param key primary key for registration\n     * @param subkeys array of subkeys.  If null, unregister under primary\n     * key only.\n     */\n    void unregister(T item, String key, String[] subkeys) {\n        Map<String, List<T>> entry = registry.get(key);\n        if (entry == null) {\n            return;\n        }\n\n        if (subkeys != null && subkeys.length > 0) {\n            for (int i = 0; i < subkeys.length; i++) {\n                lookupRemoveItem(entry, subkeys[i], item);\n            }\n        } else {\n            if (item == null) {\n                registry.remove(key);\n            } else {\n                lookupRemoveItem(entry, \"\", item);\n            }\n        }\n    }\n\n    private void lookupRemoveItem(Map<String, List<T>> map, String key,\n            T item) {\n        List<T> list = map.get(key);\n        if (list == null) {\n            return;\n        }\n        if (item == null) {\n            map.remove(key);\n            return;\n        }\n        if (LOG.isLoggable(Level.FINE)) {\n            if (!list.contains(item)) {\n                LOG.log(Level.FINE,\n                        \"Attempt to unregister non-existant registration {0} Listener: {1}\",\n                        new Object[]{key, item});\n            }\n        }\n        while (list.contains(item)) {\n            list.remove(item);\n        }\n        if (list.isEmpty()) {\n            map.remove(key);\n        }\n    }\n\n    /**\n     * Return a list of items which have been registered for given key(s).\n     * Returns items registered both for the key/subkey pair as well as\n     * those registered just for the primary key.\n     * @param key\n     * @param subkey\n     * @return collection of items previously registered.\n     */\n    Collection<T> getMatches(String key, String subkey) {\n        List<T> results = new ArrayList<T>();\n        Map<String, List<T>> entry = registry.get(key);\n        if (entry != null) {\n            if (entry.containsKey(subkey)) {\n                results.addAll(entry.get(subkey));\n            }\n            if (entry.containsKey(\"\")) {\n                results.addAll(entry.get(\"\"));\n            }\n        }\n        return results;\n    }\n\n}\n", "human_rating": 3.7844084600000136, "metadata": {"project": "argoUML", "class": "org.argouml.model.mdr.ModelEventPumpMDRImpl", "source_path": "argoUML/sourcefiles/src/argouml-core-model-mdr/src/org/argouml/model/mdr/ModelEventPumpMDRImpl.java", "label_probabilities": {"readability": [0.78475, 0.214908, 0.00034223, 1.36792e-14], "understandability": [2.02793e-11, 0.0508673, 0.940417, 0.0087159], "complexity": [1.24696e-09, 0.0933002, 0.9067, 8.77088e-09], "modularization": [0.967674, 0.0323213, 4.41241e-06, 1.77e-18], "overall": [8.859e-17, 0.00121692, 0.896359, 0.102424]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.model.mdr.UmlFactoryMDRImpl", "source": "/* $Id: UmlFactoryMDRImpl.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Bob Tarling\n *    Luis Sergio Oliveira (euluis)\n *    Thomas Neustupny\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.model.mdr;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.jmi.reflect.InvalidObjectException;\nimport javax.jmi.reflect.RefObject;\n\nimport org.argouml.model.Defaults;\nimport org.argouml.model.DummyModelCommand;\nimport org.argouml.model.IllegalModelElementConnectionException;\nimport org.argouml.model.InvalidElementException;\nimport org.argouml.model.MetaTypes;\nimport org.argouml.model.Model;\nimport org.argouml.model.UmlFactory;\nimport org.omg.uml.behavioralelements.activitygraphs.ActionState;\nimport org.omg.uml.behavioralelements.activitygraphs.ActivityGraph;\nimport org.omg.uml.behavioralelements.activitygraphs.CallState;\nimport org.omg.uml.behavioralelements.activitygraphs.ClassifierInState;\nimport org.omg.uml.behavioralelements.activitygraphs.ObjectFlowState;\nimport org.omg.uml.behavioralelements.activitygraphs.Partition;\nimport org.omg.uml.behavioralelements.activitygraphs.SubactivityState;\nimport org.omg.uml.behavioralelements.collaborations.AssociationEndRole;\nimport org.omg.uml.behavioralelements.collaborations.AssociationRole;\nimport org.omg.uml.behavioralelements.collaborations.ClassifierRole;\nimport org.omg.uml.behavioralelements.collaborations.Collaboration;\nimport org.omg.uml.behavioralelements.collaborations.CollaborationInstanceSet;\nimport org.omg.uml.behavioralelements.collaborations.Interaction;\nimport org.omg.uml.behavioralelements.collaborations.InteractionInstanceSet;\nimport org.omg.uml.behavioralelements.collaborations.Message;\nimport org.omg.uml.behavioralelements.commonbehavior.Action;\nimport org.omg.uml.behavioralelements.commonbehavior.ActionSequence;\nimport org.omg.uml.behavioralelements.commonbehavior.Argument;\nimport org.omg.uml.behavioralelements.commonbehavior.AttributeLink;\nimport org.omg.uml.behavioralelements.commonbehavior.CallAction;\nimport org.omg.uml.behavioralelements.commonbehavior.ComponentInstance;\nimport org.omg.uml.behavioralelements.commonbehavior.CreateAction;\nimport org.omg.uml.behavioralelements.commonbehavior.DataValue;\nimport org.omg.uml.behavioralelements.commonbehavior.DestroyAction;\nimport org.omg.uml.behavioralelements.commonbehavior.Instance;\nimport org.omg.uml.behavioralelements.commonbehavior.Link;\nimport org.omg.uml.behavioralelements.commonbehavior.LinkEnd;\nimport org.omg.uml.behavioralelements.commonbehavior.LinkObject;\nimport org.omg.uml.behavioralelements.commonbehavior.NodeInstance;\nimport org.omg.uml.behavioralelements.commonbehavior.Reception;\nimport org.omg.uml.behavioralelements.commonbehavior.ReturnAction;\nimport org.omg.uml.behavioralelements.commonbehavior.SendAction;\nimport org.omg.uml.behavioralelements.commonbehavior.Signal;\nimport org.omg.uml.behavioralelements.commonbehavior.Stimulus;\nimport org.omg.uml.behavioralelements.commonbehavior.SubsystemInstance;\nimport org.omg.uml.behavioralelements.commonbehavior.TerminateAction;\nimport org.omg.uml.behavioralelements.commonbehavior.UmlException;\nimport org.omg.uml.behavioralelements.commonbehavior.UninterpretedAction;\nimport org.omg.uml.behavioralelements.statemachines.CallEvent;\nimport org.omg.uml.behavioralelements.statemachines.ChangeEvent;\nimport org.omg.uml.behavioralelements.statemachines.CompositeState;\nimport org.omg.uml.behavioralelements.statemachines.Event;\nimport org.omg.uml.behavioralelements.statemachines.FinalState;\nimport org.omg.uml.behavioralelements.statemachines.Guard;\nimport org.omg.uml.behavioralelements.statemachines.Pseudostate;\nimport org.omg.uml.behavioralelements.statemachines.SignalEvent;\nimport org.omg.uml.behavioralelements.statemachines.SimpleState;\nimport org.omg.uml.behavioralelements.statemachines.State;\nimport org.omg.uml.behavioralelements.statemachines.StateMachine;\nimport org.omg.uml.behavioralelements.statemachines.StateVertex;\nimport org.omg.uml.behavioralelements.statemachines.StubState;\nimport org.omg.uml.behavioralelements.statemachines.SubmachineState;\nimport org.omg.uml.behavioralelements.statemachines.SynchState;\nimport org.omg.uml.behavioralelements.statemachines.TimeEvent;\nimport org.omg.uml.behavioralelements.statemachines.Transition;\nimport org.omg.uml.behavioralelements.usecases.Actor;\nimport org.omg.uml.behavioralelements.usecases.Extend;\nimport org.omg.uml.behavioralelements.usecases.ExtensionPoint;\nimport org.omg.uml.behavioralelements.usecases.Include;\nimport org.omg.uml.behavioralelements.usecases.UseCase;\nimport org.omg.uml.behavioralelements.usecases.UseCaseInstance;\nimport org.omg.uml.foundation.core.Abstraction;\nimport org.omg.uml.foundation.core.Artifact;\nimport org.omg.uml.foundation.core.AssociationClass;\nimport org.omg.uml.foundation.core.AssociationEnd;\nimport org.omg.uml.foundation.core.Attribute;\nimport org.omg.uml.foundation.core.BehavioralFeature;\nimport org.omg.uml.foundation.core.Binding;\nimport org.omg.uml.foundation.core.Classifier;\nimport org.omg.uml.foundation.core.Comment;\nimport org.omg.uml.foundation.core.Component;\nimport org.omg.uml.foundation.core.Constraint;\nimport org.omg.uml.foundation.core.DataType;\nimport org.omg.uml.foundation.core.Dependency;\nimport org.omg.uml.foundation.core.Element;\nimport org.omg.uml.foundation.core.ElementResidence;\nimport org.omg.uml.foundation.core.Enumeration;\nimport org.omg.uml.foundation.core.EnumerationLiteral;\nimport org.omg.uml.foundation.core.Feature;\nimport org.omg.uml.foundation.core.Flow;\nimport org.omg.uml.foundation.core.GeneralizableElement;\nimport org.omg.uml.foundation.core.Generalization;\nimport org.omg.uml.foundation.core.Interface;\nimport org.omg.uml.foundation.core.Method;\nimport org.omg.uml.foundation.core.ModelElement;\nimport org.omg.uml.foundation.core.Namespace;\nimport org.omg.uml.foundation.core.Node;\nimport org.omg.uml.foundation.core.Operation;\nimport org.omg.uml.foundation.core.Parameter;\nimport org.omg.uml.foundation.core.Permission;\nimport org.omg.uml.foundation.core.PresentationElement;\nimport org.omg.uml.foundation.core.Primitive;\nimport org.omg.uml.foundation.core.ProgrammingLanguageDataType;\nimport org.omg.uml.foundation.core.Relationship;\nimport org.omg.uml.foundation.core.Stereotype;\nimport org.omg.uml.foundation.core.StructuralFeature;\nimport org.omg.uml.foundation.core.TagDefinition;\nimport org.omg.uml.foundation.core.TaggedValue;\nimport org.omg.uml.foundation.core.TemplateArgument;\nimport org.omg.uml.foundation.core.TemplateParameter;\nimport org.omg.uml.foundation.core.UmlAssociation;\nimport org.omg.uml.foundation.core.UmlClass;\nimport org.omg.uml.foundation.core.Usage;\nimport org.omg.uml.modelmanagement.ElementImport;\nimport org.omg.uml.modelmanagement.Subsystem;\nimport org.omg.uml.modelmanagement.UmlPackage;\n\n/**\n * Root factory for UML model element instance creation.<p>\n *\n * @since ARGO0.19.5\n * @author Ludovic Ma&icirc;tre\n * based on NSUML implementation by:\n * @author Thierry Lach\n */\nclass UmlFactoryMDRImpl extends AbstractUmlModelFactoryMDR implements\n        UmlFactory {\n\n    /**\n     * The logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(UmlFactoryMDRImpl.class.getName());\n\n    /**\n     * The model implementation.\n     */\n    private MDRModelImplementation modelImpl;\n\n    /**\n     * The meta types factory.\n     */\n    private MetaTypes metaTypes;\n\n    /**\n     * A map of valid connections keyed by the connection type. The constructor\n     * builds this from the data in the VALID_CONNECTIONS array\n     */\n    private Map<Class<?>, List<Class<?>[]>> validConnectionMap =\n        new HashMap<Class<?>, List<Class<?>[]>>();\n\n    /**\n     * A map of the valid model elements that are valid to be contained\n     * by other model elements.\n     */\n    private HashMap<Class<?>, Class<?>[]> validContainmentMap =\n        new HashMap<Class<?>, Class<?>[]>();\n\n    /**\n     * The instance that we are deleting.\n     */\n    private Set<RefObject> elementsToBeDeleted = new HashSet<RefObject>();\n\n    /**\n     * Ordered list of elements to be deleted.\n     */\n    private List<RefObject> elementsInDeletionOrder =\n        new ArrayList<RefObject>();\n\n    /**\n     * The top object is the first object given to the UmlFactory when calling\n     * the delete method.\n     */\n    private Object top;\n\n    /**\n     * The mutex for this class.\n     */\n    private Object lock = new Byte[0];\n\n    /**\n     * An array of valid connections, the combination of connecting class and\n     * node classes must exist as a row in this list to be considered valid.\n     * <ul>\n     * <li>The 1st column is the connecting element.\n     * <li>The 2nd column is the \"from\" element type.\n     * <li>The 3rd column is the \"to\" element type.\n     * The 3rd column is optional, if not given then it is assumed to be\n     * the same as the \"from\" element.\n     * <li>The existence of a 4th column indicates that the connection is valid\n     * in one direction only.\n     * </ul>\n     * TODO: This encodes not only what is legal in UML, but also what ArgoUML\n     * knows how to create, so not all legal connections are included. Probably\n     * should be split into two pieces: 1) legal UML (here) and 2) supported (in\n     * ArgoUML application someplace) - tfm - 20060325<p>\n     * See also issue 3863.<p>\n     *\n     * Most of these are subtypes of Relationship which includes Association,\n     * Dependency, Flow, Generalization, Extend, and Include. Dependency\n     * includes Binding, Abstraction, Usage, and Permission. AssociationRole and\n     * AssociationClass are Associations. The remaining items (Link, Transition,\n     * AssociationEnd, Message) are non-Relationship types which ArgoUML treats\n     * as connections/edges.\n     */\n    // TODO: This should be built by reflection from the metamodel - tfm\n    //       Update for UML 1.4 metamodel if not replaced by reflection\n    private static final Class<?>[][] VALID_CONNECTIONS = {\n        {Generalization.class,   GeneralizableElement.class, },\n        {Dependency.class,       ModelElement.class, },\n        // Although Usage & Permission are Dependencies, they need to\n        // be include separately because of the way lookup works\n        {Usage.class,            ModelElement.class, },\n        {Permission.class,       ModelElement.class, },\n        // The following is specifically for Realizations\n        {Abstraction.class, UmlClass.class, Interface.class, null, },\n        // The next 3 restrictions for Abstraction seem to be Argo specific\n        // not something the UML spec requires - tfm - 20070215\n        {Abstraction.class, UmlClass.class, UmlClass.class, null, },\n        {Abstraction.class, UmlPackage.class, UmlPackage.class, null, },\n        {Abstraction.class, Component.class, Interface.class, null, },\n        {UmlAssociation.class,     Classifier.class, },\n        {AssociationRole.class,  ClassifierRole.class, },\n        {Extend.class,           UseCase.class, },\n        {Include.class,          UseCase.class, },\n        {Link.class, Instance.class, },\n        {Transition.class,       StateVertex.class, },\n        {AssociationClass.class, UmlClass.class, },\n        {AssociationEnd.class, Classifier.class, UmlAssociation.class, },\n        {Message.class, ClassifierRole.class },\n    };\n\n    /**\n     * Package-private constructor.\n     *\n     * @param implementation\n     *            To get other helpers and factories.\n     */\n    UmlFactoryMDRImpl(MDRModelImplementation implementation) {\n        modelImpl = implementation;\n        metaTypes = modelImpl.getMetaTypes();\n\n        buildValidConnectionMap();\n\n        buildValidContainmentMap();\n    }\n\n    private void buildValidConnectionMap() {\n        // A list of valid connections between elements, the\n        // connection type first and then the elements to be connected\n\n        for (int i = 0; i < VALID_CONNECTIONS.length; ++i) {\n            final Class<?> connection = VALID_CONNECTIONS[i][0];\n            List<Class<?>[]> validItems = validConnectionMap.get(connection);\n            if (validItems == null) {\n                validItems = new ArrayList<Class<?>[]>();\n                validConnectionMap.put(connection, validItems);\n            }\n            if (VALID_CONNECTIONS[i].length < 3) {\n                // If there isn't a 3rd column then this represents a connection\n                // of elements of the same type.\n                Class<?>[] modeElementPair = new Class[2];\n                modeElementPair[0] = VALID_CONNECTIONS[i][1];\n                modeElementPair[1] = VALID_CONNECTIONS[i][1];\n                validItems.add(modeElementPair);\n            } else {\n                // If there is a 3rd column then this represents a connection\n                // of between 2 different types of element.\n                Class<?>[] modeElementPair = new Class[2];\n                modeElementPair[0] = VALID_CONNECTIONS[i][1];\n                modeElementPair[1] = VALID_CONNECTIONS[i][2];\n                validItems.add(modeElementPair);\n                // If the array hasn't been flagged to indicate otherwise\n                // swap elements the elements and add again.\n                if (VALID_CONNECTIONS[i].length < 4) {\n                    Class<?>[] reversedModeElementPair = new Class[2];\n                    reversedModeElementPair[0] = VALID_CONNECTIONS[i][2];\n                    reversedModeElementPair[1] = VALID_CONNECTIONS[i][1];\n                    validItems.add(reversedModeElementPair);\n                }\n            }\n        }\n    }\n\n    /**\n     * Initializes the validContainmentMap based on the rules for\n     * valid containment of elements.\n     *\n     * @author Scott Roberts\n     */\n    private void buildValidContainmentMap() {\n\n        validContainmentMap.clear();\n\n        validContainmentMap.put(ModelElement.class,\n                new Class<?>[] {\n                    TemplateParameter.class\n                });\n\n        // specifies valid elements for a Model to contain\n        validContainmentMap.put(org.omg.uml.modelmanagement.Model.class,\n            new Class<?>[] {\n                TemplateParameter.class,\n                ComponentInstance.class, NodeInstance.class\n            });\n\n        // specifies valid elements for a Model to contain\n        validContainmentMap.put(AssociationEnd.class,\n            new Class<?>[] {\n                Attribute.class\n            });\n\n        // specifies valid elements for a Package to contain\n        validContainmentMap.put(UmlPackage.class,\n            new Class<?>[] {\n                TemplateParameter.class,\n                UmlPackage.class, Actor.class,\n                UseCase.class, UmlClass.class,\n                Interface.class, Component.class,\n                Node.class, Stereotype.class,\n                Enumeration.class, DataType.class,\n                UmlException.class, Signal.class\n            });\n\n        // specifies valid elements for a class to contain\n        validContainmentMap.put(UmlClass.class,\n            new Class<?>[] {\n                TemplateParameter.class,\n                Attribute.class, Operation.class,\n                UmlClass.class, Reception.class\n            });\n\n        // specifies valid elements for a classifier to contain\n        validContainmentMap.put(Classifier.class,\n            new Class<?>[] {\n                TemplateParameter.class\n            });\n\n        // specifies valid elements for an Interface to contain\n        validContainmentMap.put(Interface.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Operation.class, Reception.class\n                });\n\n        // specifies valid elements for a Signal to contain\n        validContainmentMap.put(Signal.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Operation.class, Attribute.class\n                });\n\n        // specifies valid elements for an Actor to contain\n        validContainmentMap.put(Actor.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Operation.class,\n                    Reception.class\n                });\n\n        // specifies valid elements for a Use Case to contain\n        validContainmentMap.put(UseCase.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    ExtensionPoint.class, Attribute.class,\n                    Operation.class, Reception.class\n                });\n\n        // specifies valid elements for a Use Case to contain\n        validContainmentMap.put(Extend.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    ExtensionPoint.class\n                });\n\n        // specifies valid elements for a Component to contain\n        validContainmentMap.put(Component.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Reception.class,\n                    Operation.class\n                });\n\n        // specifies valid elements for a Node to contain\n        validContainmentMap.put(Node.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Operation.class,\n                    Reception.class\n                });\n\n        // specifies valid elements for a Enumeration to contain\n        validContainmentMap.put(Enumeration.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    EnumerationLiteral.class, Operation.class\n                });\n\n        // specifies valid elements for a DataType to contain\n        validContainmentMap.put(DataType.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Operation.class,\n                    Reception.class\n                });\n\n        // specifies valid elements for a Operation to contain\n        validContainmentMap.put(Operation.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Parameter.class,\n                    Signal.class,\n                    Method.class\n                });\n\n        // specifies valid elements for an Event to contain\n        validContainmentMap.put(Event.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Parameter.class\n                });\n\n        // specifies valid elements for an ObjectFlowState to contain\n        validContainmentMap.put(ObjectFlowState.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Parameter.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(AssociationRole.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Message.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(CallAction.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Argument.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(UninterpretedAction.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Argument.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(ReturnAction.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Argument.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(DestroyAction.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Argument.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(SendAction.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Argument.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(TerminateAction.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Argument.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(ActionSequence.class,\n                new Class<?>[] {\n                    TemplateParameter.class, Argument.class,\n                    CallAction.class, ReturnAction.class, CreateAction.class,\n                    DestroyAction.class, SendAction.class,\n                    TerminateAction.class, UninterpretedAction.class,\n                    ActionSequence.class,\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(Transition.class,\n                new Class<?>[] {\n                    TemplateParameter.class,\n                    Guard.class,\n                    CallAction.class, ReturnAction.class,\n                    CreateAction.class, DestroyAction.class, SendAction.class, TerminateAction.class, UninterpretedAction.class, ActionSequence.class,\n                    CallEvent.class, ChangeEvent.class, SignalEvent.class, TimeEvent.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(SignalEvent.class,\n                new Class<?>[] {\n                    Signal.class\n                });\n\n        // specifies valid elements for an AssociationRole to contain\n        validContainmentMap.put(Reception.class,\n                new Class<?>[] {\n                    Parameter.class,\n                    TemplateParameter.class\n                });\n\n        // specifies valid elements for an State to contain\n        validContainmentMap.put(State.class,\n                new Class<?>[] {\n                    CallEvent.class, ChangeEvent.class, SignalEvent.class,\n                    TimeEvent.class\n                });\n\n        // specifies valid elements for an CallState to contain\n        validContainmentMap.put(CallState.class,\n                new Class<?>[] {\n                    CallAction.class,\n                    CallEvent.class, ChangeEvent.class, SignalEvent.class,\n                    TimeEvent.class\n                });\n\n        // specifies valid elements for an SimpleState to contain\n        validContainmentMap.put(SimpleState.class,\n                new Class<?>[] {\n                    Transition.class,\n                    CallAction.class, CreateAction.class, DestroyAction.class,\n                    ReturnAction.class, SendAction.class,\n                    TerminateAction.class,\n                    UninterpretedAction.class, ActionSequence.class,\n                    CallEvent.class, ChangeEvent.class, SignalEvent.class,\n                    TimeEvent.class\n                });\n\n        // specifies valid elements for an SimpleState to contain\n        validContainmentMap.put(FinalState.class,\n                new Class<?>[] {\n                    Transition.class,\n                    CallAction.class, CreateAction.class, DestroyAction.class,\n                    ReturnAction.class, SendAction.class, TerminateAction.class,\n                    UninterpretedAction.class, ActionSequence.class\n                });\n\n        // specifies valid elements for an SubactivityState to contain\n        validContainmentMap.put(SubactivityState.class,\n                new Class<?>[] {\n                    Transition.class,\n                    CallAction.class, CreateAction.class, DestroyAction.class,\n                    ReturnAction.class, SendAction.class, TerminateAction.class,\n                    UninterpretedAction.class, ActionSequence.class,\n                    CallEvent.class, ChangeEvent.class, SignalEvent.class,\n                    TimeEvent.class\n                });\n\n        // specifies valid elements for an ActionState to contain\n        validContainmentMap.put(ActionState.class,\n                new Class<?>[] {\n                    CallAction.class, CreateAction.class, DestroyAction.class,\n                    ReturnAction.class, SendAction.class, TerminateAction.class,\n                    UninterpretedAction.class, ActionSequence.class,\n                    CallEvent.class, ChangeEvent.class, SignalEvent.class,\n                    TimeEvent.class\n                });\n\n        // specifies valid elements for an ActionState to contain\n        validContainmentMap.put(CompositeState.class,\n                new Class<?>[] {\n                    Transition.class,\n                    Pseudostate.class, SynchState.class, StubState.class,\n                    CompositeState.class, SimpleState.class,\n                    FinalState.class,\n                    SubmachineState.class,\n                    CallAction.class, CreateAction.class, DestroyAction.class,\n                    ReturnAction.class, SendAction.class,\n                    TerminateAction.class,\n                    UninterpretedAction.class, ActionSequence.class\n                });\n\n    }\n\n    public Object buildConnection(Object elementType, Object fromElement,\n            Object fromStyle, Object toElement, Object toStyle,\n            Object unidirectional, Object namespace)\n        throws IllegalModelElementConnectionException {\n\n        if (!isConnectionValid(elementType, fromElement, toElement, true)) {\n            throw new IllegalModelElementConnectionException(\"Cannot make a \"\n                    + elementType.getClass().getName() + \" between a \"\n                    + fromElement.getClass().getName() + \" and a \"\n                    + toElement.getClass().getName());\n        }\n\n        Object connection = null;\n        boolean uni = (unidirectional instanceof Boolean)\n            ? ((Boolean) unidirectional).booleanValue() : false;\n        if (elementType == metaTypes.getAssociation()) {\n            connection =\n                getCore().buildAssociation(fromElement,\n                    fromStyle, toElement,\n                    toStyle, uni);\n        } else if (elementType == metaTypes.getAssociationEnd()) {\n            if (fromElement instanceof UmlAssociation) {\n                connection =\n                    getCore().buildAssociationEnd(toElement, fromElement);\n            } else if (fromElement instanceof Classifier) {\n                connection =\n                    getCore().buildAssociationEnd(fromElement, toElement);\n            }\n        } else if (elementType\n                == metaTypes.getAssociationClass()) {\n            connection =\n                getCore().buildAssociationClass(fromElement, toElement);\n        } else if (elementType == metaTypes.getAssociationRole()) {\n            connection =\n                getCollaborations().buildAssociationRole(fromElement,\n                    fromStyle, toElement, toStyle,\n                    ((Boolean) unidirectional).booleanValue());\n        } else if (elementType == metaTypes.getGeneralization()) {\n            connection = getCore().buildGeneralization(fromElement, toElement);\n        } else if (elementType == metaTypes.getPackageImport()) {\n            connection = getCore().buildPackageImport(fromElement, toElement);\n        } else if (elementType == metaTypes.getUsage()) {\n            connection = getCore().buildUsage(fromElement, toElement);\n        } else if (elementType == metaTypes.getGeneralization()) {\n            connection = getCore().buildGeneralization(fromElement, toElement);\n        } else if (elementType == metaTypes.getDependency()) {\n            connection = getCore().buildDependency(fromElement, toElement);\n        } else if (elementType == metaTypes.getAbstraction()) {\n            connection =\n                getCore().buildRealization(fromElement, toElement, namespace);\n        } else if (elementType == metaTypes.getLink()) {\n            connection = getCommonBehavior().buildLink(fromElement, toElement);\n        } else if (elementType == metaTypes.getExtend()) {\n            // Extend, but only between two use cases. Remember we draw from the\n            // extension port to the base port.\n            connection = getUseCases().buildExtend(toElement, fromElement);\n        } else if (elementType == metaTypes.getInclude()) {\n            connection = getUseCases().buildInclude(fromElement, toElement);\n        } else if (elementType == metaTypes.getTransition()) {\n            connection =\n                getStateMachines().buildTransition(fromElement, toElement);\n        }\n\n        if (connection == null) {\n            throw new IllegalModelElementConnectionException(\"Cannot make a \"\n                    + elementType.getClass().getName() + \" between a \"\n                    + fromElement.getClass().getName() + \" and a \"\n                    + toElement.getClass().getName());\n        }\n\n        return connection;\n    }\n\n\n    public Object buildNode(Object elementType) {\n        if (elementType == metaTypes.getActor()) {\n            return getUseCases().createActor();\n        } else if (elementType == metaTypes.getUseCase()) {\n            return getUseCases().createUseCase();\n        } else if (elementType == metaTypes.getUMLClass()) {\n            return getCore().buildClass();\n        } else if (elementType == metaTypes.getInterface()) {\n            return getCore().buildInterface();\n        } else if (elementType == metaTypes.getDataType()) {\n            return getCore().createDataType();\n        } else if (elementType == metaTypes.getPackage()) {\n            return getModelManagement().createPackage();\n        } else if (elementType == metaTypes.getModel()) {\n            return getModelManagement().createModel();\n        } else if (elementType == metaTypes.getInstance()) {\n            throw new IllegalArgumentException(\n                    \"Attempt to instantiate abstract type\");\n        } else if (elementType == metaTypes.getSubsystem()) {\n            return getModelManagement().createSubsystem();\n        } else if (elementType == metaTypes.getCallState()) {\n            return getActivityGraphs().createCallState();\n        } else if (elementType == metaTypes.getSimpleState()) {\n            return getStateMachines().createSimpleState();\n        } else if (elementType == metaTypes.getFinalState()) {\n            return getStateMachines().createFinalState();\n        } else if (elementType == metaTypes.getPseudostate()) {\n            return getStateMachines().createPseudostate();\n        } else if (elementType == metaTypes.getObjectFlowState()) {\n            return getActivityGraphs().createObjectFlowState();\n        } else if (elementType == metaTypes.getActionState()) {\n            return getActivityGraphs().createActionState();\n        } else if (elementType == metaTypes.getSubactivityState()) {\n            return getActivityGraphs().createSubactivityState();\n        } else if (elementType == metaTypes.getPartition()) {\n            return getActivityGraphs().createPartition();\n        } else if (elementType == metaTypes.getStubState()) {\n            return getStateMachines().createStubState();\n        } else if (elementType == metaTypes.getSubmachineState()) {\n            return getStateMachines().createSubmachineState();\n        } else if (elementType == metaTypes.getCompositeState()) {\n            return getStateMachines().createCompositeState();\n        } else if (elementType == metaTypes.getSynchState()) {\n            return getStateMachines().createSynchState();\n        } else if (elementType == metaTypes.getState()) {\n            throw new IllegalArgumentException(\n                    \"Attempt to instantiate abstract type\");\n        } else if (elementType == modelImpl.getMetaTypes().getSimpleState()) {\n            return getStateMachines().createSimpleState();\n        } else if (elementType == metaTypes.getClassifierRole()) {\n            return getCollaborations().createClassifierRole();\n        } else if (elementType == metaTypes.getComponent()) {\n            return getCore().createComponent();\n        } else if (elementType == metaTypes.getComponentInstance()) {\n            return getCommonBehavior().createComponentInstance();\n        } else if (elementType == metaTypes.getNode()) {\n            return getCore().createNode();\n        } else if (elementType == metaTypes.getNodeInstance()) {\n            return getCommonBehavior().createNodeInstance();\n        } else if (elementType == metaTypes.getObject()) {\n            return getCommonBehavior().createObject();\n        } else if (elementType == metaTypes.getComment()) {\n            return getCore().createComment();\n        } else if (elementType == metaTypes.getNamespace()) {\n            throw new IllegalArgumentException(\n                    \"Attempt to instantiate abstract type\");\n        } else if (elementType == metaTypes.getOperation()) {\n            return getCore().createOperation();\n        } else if (elementType == metaTypes.getEnumeration()) {\n            return getCore().createEnumeration();\n        } else if (elementType == metaTypes.getStereotype()) {\n            return getExtensionMechanisms().createStereotype();\n        } else if (elementType == metaTypes.getAttribute()) {\n            return getCore().buildAttribute();\n        } else if (elementType == metaTypes.getSignal()) {\n            return getCommonBehavior().createSignal();\n        } else if (elementType == metaTypes.getException()) {\n            return getCommonBehavior().createException();\n        } else if (elementType == metaTypes.getTransition()) {\n            return getStateMachines().createTransition();\n        } else if (elementType == metaTypes.getTransition()) {\n            return getStateMachines().createTransition();\n        }\n\n        throw new IllegalArgumentException(\n                \"Attempted to create unsupported model element type: \"\n                + elementType);\n    }\n\n    public Object buildNode(Object elementType, Object container, String property, Defaults defaults) {\n        Object element = buildNode(elementType, container, property);\n        if (defaults != null) {\n            final Object type = defaults.getDefaultType(elementType);\n            final String name = defaults.getDefaultName(elementType);\n            if (type != null) {\n                modelImpl.getCoreHelper().setType(element, type);\n            }\n            if (name != null) {\n                modelImpl.getCoreHelper().setName(element, name);\n            } else {\n                modelImpl.getCoreHelper().setName(element, \"\");\n            }\n        }\n        return element;\n    }\n\n\n    public Object buildNode(Object elementType, Object container, String properyName) {\n\n        Object element = null;\n\n        // if this is a feature get the owner of that feature\n        // TODO: Does anything actually make use of this? It can\n        // cause unexpected behaviour.\n        if (this.modelImpl.getFacade().isAFeature(container)\n                && elementType != metaTypes.getParameter()\n                && elementType != metaTypes.getMethod()\n                && elementType != metaTypes.getSignal()) {\n            container = this.modelImpl.getFacade().getOwner(container);\n        }\n\n        // supports implementation of some special elements not\n        // supported by buildNode\n        if (elementType == this.metaTypes.getAttribute()) {\n            element = getCore().buildAttribute2(container, null);\n        } else if (elementType == this.metaTypes.getOperation()) {\n            element = getCore().buildOperation(container, null);\n        } else if (elementType == this.metaTypes.getReception()) {\n            element = this.modelImpl.getCommonBehaviorFactory().buildReception(container);\n        } else if (elementType == this.metaTypes.getEnumerationLiteral()) {\n            element = getCore().buildEnumerationLiteral(null, container);\n        } else if (elementType == this.metaTypes.getExtensionPoint()) {\n            element = this.modelImpl.getUseCasesFactory().\n                buildExtensionPoint(container);\n        } else if (elementType == this.metaTypes.getTemplateParameter()) {\n            // TODO: the type of the model element used in a type parameter\n            // (ie the formal) needs to match the actual parameter that it\n            // gets replaced with later.  This code is going to restrict that\n            // to always being a Parameter which doesn't seem right, but I\n            // don't have time to debug it right now. - tfm - 20090608\n            Parameter param = getCore().createParameter();\n            param.setName(\"T\"); // default parameter name\n            element =\n                modelImpl.getCoreFactory().buildTemplateParameter(container,\n                        param, null);\n        } else if (elementType == metaTypes.getParameter()) {\n            element = getCore().buildParameter(container, null);\n        } else if (elementType == metaTypes.getSignal()) {\n            element = modelImpl.getCommonBehaviorFactory().buildSignal(container);\n        } else if (elementType == metaTypes.getMethod()) {\n            final Operation op = (Operation) container;\n            element = getCore().buildMethod(op.getName());\n            modelImpl.getCoreHelper().addMethod(op, element);\n            modelImpl.getCoreHelper().addFeature(\n                    modelImpl.getFacade().getOwner(op), element);\n        } else if (elementType == metaTypes.getMessage()) {\n            Object collaboration = Model.getFacade().getNamespace(container);\n            element =\n                Model.getCollaborationsFactory()\n                    .buildMessage(collaboration, container);\n        } else if (elementType == metaTypes.getArgument()) {\n            element = Model.getCommonBehaviorFactory().createArgument();\n            Model.getCommonBehaviorHelper().addActualArgument(container, element);\n        } else if (elementType == metaTypes.getGuard()) {\n            element = Model.getStateMachinesFactory().buildGuard(container);\n        } else if (elementType == metaTypes.getCreateAction()) {\n            element = Model.getCommonBehaviorFactory().createCreateAction();\n            setNewAction(container, (Action) element, properyName);\n        } else if (elementType == metaTypes.getCallAction()) {\n            element = Model.getCommonBehaviorFactory().createCallAction();\n            setNewAction(container, (Action) element, properyName);\n        } else if (elementType == metaTypes.getReturnAction()) {\n            element = Model.getCommonBehaviorFactory().createReturnAction();\n            setNewAction(container, (Action) element, properyName);\n        } else if (elementType == metaTypes.getDestroyAction()) {\n            element = Model.getCommonBehaviorFactory().createDestroyAction();\n            setNewAction(container, (Action) element, properyName);\n        } else if (elementType == metaTypes.getSendAction()) {\n            element = Model.getCommonBehaviorFactory().createSendAction();\n            setNewAction(container, (Action) element, properyName);\n        } else if (elementType == metaTypes.getTerminateAction()) {\n            element = Model.getCommonBehaviorFactory().createTerminateAction();\n            setNewAction(container, (Action) element, properyName);\n        } else if (elementType == metaTypes.getUninterpretedAction()) {\n            element = Model.getCommonBehaviorFactory().createUninterpretedAction();\n            setNewAction(container, (Action) element, properyName);\n        } else if (elementType == metaTypes.getActionSequence()) {\n            element = Model.getCommonBehaviorFactory().createActionSequence();\n            setNewAction(container, (Action) element, properyName);\n        } else if (elementType == metaTypes.getCallEvent()) {\n            element = Model.getStateMachinesFactory().createCallEvent();\n            if (container instanceof Transition) {\n                setNewTrigger((Transition) container, (Event) element);\n            } else if (container instanceof State) {\n                setNewDeferrableEvent((State) container, (Event) element);\n            }\n        } else if (elementType == metaTypes.getChangeEvent()) {\n            element = Model.getStateMachinesFactory().createChangeEvent();\n            if (container instanceof Transition) {\n                setNewTrigger((Transition) container, (Event) element);\n            } else if (container instanceof State) {\n                setNewDeferrableEvent((State) container, (Event) element);\n            }\n        } else if (elementType == metaTypes.getSignalEvent()) {\n            element = Model.getStateMachinesFactory().createSignalEvent();\n            if (container instanceof Transition) {\n                setNewTrigger((Transition) container, (Event) element);\n            } else if (container instanceof State) {\n                setNewDeferrableEvent((State) container, (Event) element);\n            }\n        } else if (elementType == metaTypes.getTimeEvent()) {\n            element = Model.getStateMachinesFactory().createTimeEvent();\n            if (container instanceof Transition) {\n                setNewTrigger((Transition) container, (Event) element);\n            } else if (container instanceof State) {\n                setNewDeferrableEvent((State) container, (Event) element);\n            }\n        } else if (elementType == metaTypes.getSignal()) {\n            element = Model.getStateMachinesFactory().buildSignalEvent(container);\n        } else if (elementType == metaTypes.getPseudostate() && container instanceof CompositeState) {\n            element = Model.getStateMachinesFactory().buildPseudoState(container);\n        } else if (elementType == metaTypes.getSynchState() && container instanceof CompositeState) {\n            element = Model.getStateMachinesFactory().buildSynchState(container);\n        } else if (elementType == metaTypes.getStubState() && container instanceof CompositeState) {\n            element = Model.getStateMachinesFactory().buildStubState(container);\n        } else if (elementType == metaTypes.getCompositeState() && container instanceof CompositeState) {\n            element = Model.getStateMachinesFactory().buildCompositeState(container);\n        } else if (elementType == metaTypes.getSimpleState() && container instanceof CompositeState) {\n            element = Model.getStateMachinesFactory().buildSimpleState(container);\n        } else if (elementType == metaTypes.getFinalState() && container instanceof CompositeState) {\n            element = Model.getStateMachinesFactory().buildFinalState(container);\n        } else if (elementType == metaTypes.getSubmachineState() && container instanceof CompositeState) {\n            element = Model.getStateMachinesFactory().buildSubmachineState(container);\n        } else if (elementType == metaTypes.getTransition() && container instanceof State) {\n            element = Model.getStateMachinesFactory().buildInternalTransition(container);\n        } else if (elementType == metaTypes.getActivity()) {\n            element = Model.getActivityGraphsFactory().buildActivityGraph(container);\n        } else {\n            // build all other elements using existing buildNode\n            element = buildNode(elementType);\n\n            if (container instanceof Namespace\n                    && element instanceof Namespace) {\n                ((Namespace) element).setNamespace(\n                        ((Namespace) container).getNamespace());\n            }\n\n            this.modelImpl.getCoreHelper().addOwnedElement(container, element);\n        }\n\n        modelImpl.getCoreHelper().setName(element, \"\");\n        return element;\n    }\n\n    private void setNewAction(Object container, Action action, String propertyName) {\n        if (container instanceof Transition) {\n            ((Transition) container).setEffect(action);\n        } else if (container instanceof State) {\n            if (\"exit\".equals(propertyName)) {\n                ((State) container).setExit(action);\n            } else if (\"doActivity\".equals(propertyName)) {\n                ((State) container).setDoActivity(action);\n            } else {\n                ((State) container).setEntry(action);\n            }\n        } else if (container instanceof ActionSequence) {\n            ((ActionSequence) container).getAction().add(action);\n        } else {\n            throw new IllegalArgumentException(\"Did not expect a \" + container);\n        }\n    }\n\n    public Object buildNode(Object elementType, Object container) {\n        return buildNode(elementType, container, (String) null);\n    }\n\n\n    /**\n     * Add a newly created event to a trigger\n     * @param transition\n     * @param event\n     */\n    private void setNewTrigger(Transition transition, Event event) {\n        transition.setTrigger(event);\n        event.setName(\"\");\n        final StateMachine statemachine = transition.getStateMachine();\n        final Namespace namespace = statemachine.getNamespace();\n        event.setNamespace(namespace);\n    }\n\n    /**\n     * Add a newly created event to a trigger\n     * @param transition\n     * @param event\n     */\n    private void setNewDeferrableEvent(final State state, final Event event) {\n        ((State) state).getDeferrableEvent().add((Event) event);\n        event.setName(\"\");\n        Object parent = state;\n        do {\n            parent = ((RefObject) parent).refImmediateComposite();\n        } while (!(parent instanceof Namespace));\n\n        event.setNamespace((Namespace) parent);\n    }\n\n    public boolean isConnectionType(Object connectionType) {\n        // If our map has any entries for this type, it's a connection type\n        return (validConnectionMap.get(connectionType) != null);\n    }\n\n\n    public boolean isConnectionValid(Object connectionType, Object fromElement,\n            Object toElement, boolean checkWFR) {\n        if (Model.getModelManagementHelper().isReadOnly(fromElement)) {\n            // Don't allow connections to be created from a read only\n            // model element to any other\n            // TODO: This should be considered a workaround.  It only works\n            // because, by default, we place newly created relationships in\n            // the namespace of the fromElement.  The correct behavior in\n            // the presence of read-only elements really depends on the type of\n            // connection as well as the writeability of both ends.\n            return false;\n        }\n        // Get the list of valid model item pairs for the given connection type\n        List<Class<?>[]> validItems = validConnectionMap.get(connectionType);\n        if (validItems == null) {\n            return false;\n        }\n        // See if there's a pair in this list that match the given\n        // model elements\n        for (Class<?>[] modeElementPair : validItems) {\n            if (modeElementPair[0].isInstance(fromElement)\n                    && modeElementPair[1].isInstance(toElement)) {\n                if (checkWFR) {\n                    return isConnectionWellformed(\n                            (Class<?>) connectionType,\n                            (ModelElement) fromElement,\n                            (ModelElement) toElement);\n                } else {\n                    return true;\n                }\n            }\n        }\n        return false;\n    }\n\n    public boolean isContainmentValid(Object metaType, Object container) {\n\n        // find the passed in container in validContainmentMap\n        for (Class<?> containerType : validContainmentMap.keySet()) {\n\n            if (containerType.isInstance(container)) {\n                // determine if metaType is a valid element for container\n                Class<?>[] validElements =\n                    validContainmentMap.get(containerType);\n\n                for (int eIter = 0; eIter < validElements.length; ++eIter) {\n\n                    if (metaType == validElements[eIter]) {\n                        return true;\n                    }\n                }\n            }\n        }\n\n        return false;\n    }\n\n    /**\n     * Run through any well formedness rules we wish to enforce for a\n     * connection.\n     * @param connectionType\n     * @param fromElement\n     * @param toElement\n     * @return true if the connection satisfies the wellformedness rules\n     */\n    private boolean isConnectionWellformed(\n            Class<?> connectionType,\n            ModelElement fromElement,\n            ModelElement toElement) {\n\n        if (fromElement == null || toElement == null) {\n            return false;\n        }\n\n        if (connectionType == Generalization.class) {\n            /*\n             * UML 1.4.2 Spec section 4.5.3.20 [5]\n             * A GeneralizableElement may only be a child of\n             * GeneralizableElement of the same kind.\n             */\n            if (fromElement.getClass() != toElement.getClass()) {\n                return false;\n            }\n        }\n\n        return true;\n    }\n\n    /**\n     * Returns the package factory for the UML package\n     * Foundation::ExtensionMechanisms.\n     *\n     * @return the ExtensionMechanisms factory instance.\n     */\n    private ExtensionMechanismsFactoryMDRImpl getExtensionMechanisms() {\n        return (ExtensionMechanismsFactoryMDRImpl) modelImpl.\n                getExtensionMechanismsFactory();\n    }\n\n    /**\n     * Returns the package factory for the UML package Foundation::Core.\n     *\n     * @return the Core factory instance.\n     */\n    private CoreFactoryMDRImpl getCore() {\n        return (CoreFactoryMDRImpl) modelImpl.getCoreFactory();\n    }\n\n    /**\n     * Returns the package factory for the UML package\n     * BehavioralElements::CommonBehavior.\n     *\n     * @return the CommonBehavior factory instance.\n     */\n    private CommonBehaviorFactoryMDRImpl getCommonBehavior() {\n        return (CommonBehaviorFactoryMDRImpl) modelImpl.\n                getCommonBehaviorFactory();\n    }\n\n    /**\n     * Returns the package factory for the UML package\n     * BehavioralElements::UseCases.\n     *\n     * @return the UseCases factory instance.\n     */\n    private UseCasesFactoryMDRImpl getUseCases() {\n        return (UseCasesFactoryMDRImpl) modelImpl.getUseCasesFactory();\n    }\n\n    /**\n     * Returns the package factory for the UML package\n     * BehavioralElements::StateMachines.\n     *\n     * @return the StateMachines factory instance.\n     */\n    private StateMachinesFactoryMDRImpl getStateMachines() {\n        return (StateMachinesFactoryMDRImpl) modelImpl\n                .getStateMachinesFactory();\n    }\n\n    /**\n     * Returns the package factory for the UML package\n     * BehavioralElements::Collaborations.\n     *\n     * @return the Collaborations factory instance.\n     */\n    private CollaborationsFactoryMDRImpl getCollaborations() {\n        return (CollaborationsFactoryMDRImpl) modelImpl.\n                getCollaborationsFactory();\n    }\n\n    /**\n     * Returns the package factory for the UML package\n     * BehavioralElements::ActivityGraphs.\n     *\n     * @return the ActivityGraphs factory instance.\n     */\n    private ActivityGraphsFactoryMDRImpl getActivityGraphs() {\n        return (ActivityGraphsFactoryMDRImpl) modelImpl.\n                getActivityGraphsFactory();\n    }\n\n    /**\n     * Returns the package factory for the UML package ModelManagement.\n     *\n     * @return the ModelManagement factory instance.\n     */\n    private ModelManagementFactoryMDRImpl getModelManagement() {\n        return (ModelManagementFactoryMDRImpl) modelImpl.\n                getModelManagementFactory();\n    }\n\n    /*\n     * Delete a model element.  Implements 'cascading delete' to make sure\n     * model is still valid after element has been deleted.<p>\n     *\n     * The actual deletion is delegated to delete methods in the rest of the\n     * factories. For example: a method deleteClass exists on CoreHelper. Delete\n     * methods as deleteClass should only do those extra actions that are\n     * necessary for the deletion of the modelelement itself. I.e. deleteClass\n     * should only take care of things specific to UmlClass.<p>\n     *\n     * The delete methods in the UML Factories should not be called directly\n     * throughout the code! Calls should always refer to this method and never\n     * call the deleteXXX method on XXXFactory directly. The reason that it is\n     * possible to call the deleteXXX methods directly is a pure implementation\n     * detail.<p>\n     *\n     * The implementation of this method uses a quite complicated if/then/else\n     * tree. This is done to provide optimal performance and full compliance to\n     * the UML 1.4 metamodel. The last remark refers to the fact that the\n     * UML 1.4 model uses multiple inheritance in several places.\n     * This has to be taken into account.<p>\n     *\n     * TODO: The requirements of the metamodel could probably be better\n     * determined by reflection on the metamodel.  Then each association\n     * that a deleted element participates in could be reviewed to make sure\n     * that it meets the requirements and, if not, be deleted. - tfm<p>\n     *\n     * Extensions and its children are not taken into account here. They do not\n     * require extra cleanup actions. Not in the form of a call to the remove\n     * method as is normal for all children of MBase and not in the form of\n     * other behaviour we want to implement via this operation.\n     *\n     * @param elem\n     *            The element to be deleted\n     *\n     * @see org.argouml.model.UmlFactory#delete(java.lang.Object)\n     */\n    public void delete(Object elem) {\n        if (elem == null) {\n            throw new IllegalArgumentException(\"Element may not be null \"\n                    + \"in delete\");\n        }\n\n        // TODO: Hold lock for entire recursive traversal?\n        synchronized (lock) {\n            if (elementsToBeDeleted.contains(elem)) {\n                return;\n            }\n            if (top == null) {\n                top = elem;\n            }\n            elementsToBeDeleted.add((RefObject) elem);\n        }\n\n        if (top == elem) {\n            LOG.log(Level.FINE, \"Set top for cascade delete to {0}\", elem);\n        }\n        LOG.log(Level.FINE, \"Deleting {0}\", elem);\n\n        // Begin a transaction - we'll do a bunch of reads first\n        // to collect a set of elements to delete - then delete them all\n        modelImpl.getRepository().beginTrans(false);\n        try {\n            // TODO: Encountering a deleted object during\n            // any part of this traversal will\n            // abort the rest of the traversal.\n            // We probably should do the whole traversal\n            // in a single MDR transaction.\n            if (elem instanceof Element) {\n                getCore().deleteElement(elem);\n                if (elem instanceof ModelElement) {\n                    getCore().deleteModelElement(elem);\n                    // no else here to make sure Classifier with\n                    // its double inheritance goes ok\n\n                    if (elem instanceof GeneralizableElement) {\n                        GeneralizableElement ge = (GeneralizableElement) elem;\n                        getCore().deleteGeneralizableElement(ge);\n                        if (elem instanceof Stereotype) {\n                            Stereotype s = (Stereotype) elem;\n                            getExtensionMechanisms().deleteStereotype(s);\n                        }\n                    } // no else here to make sure AssociationClass goes ok\n\n                    if (elem instanceof Parameter) {\n                        getCore().deleteParameter(elem);\n                    } else if (elem instanceof Constraint) {\n                        getCore().deleteConstraint(elem);\n                    } else if (elem instanceof Relationship) {\n                        deleteRelationship((Relationship) elem);\n                    } else if (elem instanceof AssociationEnd) {\n                        getCore().deleteAssociationEnd(elem);\n                        if (elem instanceof AssociationEndRole) {\n                            getCollaborations().deleteAssociationEndRole(elem);\n                        }\n                    } else if (elem instanceof Comment) {\n                        getCore().deleteComment(elem);\n                    } else if (elem instanceof Action) {\n                        deleteAction(elem);\n                    } else if (elem instanceof AttributeLink) {\n                        getCommonBehavior().deleteAttributeLink(elem);\n                    } else if (elem instanceof Instance) {\n                        deleteInstance((Instance) elem);\n                    } else if (elem instanceof Stimulus) {\n                        getCommonBehavior().deleteStimulus(elem);\n                    } // no else to handle multiple inheritance of linkobject\n\n                    if (elem instanceof Link) {\n                        getCommonBehavior().deleteLink(elem);\n                    } else if (elem instanceof LinkEnd) {\n                        getCommonBehavior().deleteLinkEnd(elem);\n                    } else if (elem instanceof Interaction) {\n                        getCollaborations().deleteInteraction(elem);\n                    } else if (elem instanceof InteractionInstanceSet) {\n                        getCollaborations().deleteInteractionInstanceSet(elem);\n                    } else if (elem instanceof CollaborationInstanceSet) {\n                        getCollaborations()\n                                .deleteCollaborationInstanceSet(elem);\n                    } else if (elem instanceof Message) {\n                        getCollaborations().deleteMessage(elem);\n                    } else if (elem instanceof ExtensionPoint) {\n                        getUseCases().deleteExtensionPoint(elem);\n                    } else if (elem instanceof StateVertex) {\n                        deleteStateVertex((StateVertex) elem);\n                    }\n\n                    if (elem instanceof StateMachine) {\n                        getStateMachines().deleteStateMachine(elem);\n                        if (elem instanceof ActivityGraph) {\n                            getActivityGraphs().deleteActivityGraph(elem);\n                        }\n                    } else if (elem instanceof Transition) {\n                        getStateMachines().deleteTransition(elem);\n                    } else if (elem instanceof Guard) {\n                        getStateMachines().deleteGuard(elem);\n                    } else if (elem instanceof TaggedValue) {\n                        getExtensionMechanisms().deleteTaggedValue(elem);\n                    } else if (elem instanceof TagDefinition) {\n                        getExtensionMechanisms().deleteTagDefinition(elem);\n                    }\n                    // else if (elem instanceof MEvent) {\n                    //\n                    // }\n                } else if (elem instanceof PresentationElement) {\n                    getCore().deletePresentationElement(elem);\n                }\n            } else if (elem instanceof TemplateParameter) {\n                getCore().deleteTemplateParameter(elem);\n            } else if (elem instanceof TemplateArgument) {\n                getCore().deleteTemplateArgument(elem);\n            } else if (elem instanceof ElementImport) {\n                getModelManagement().deleteElementImport(elem);\n            } else if (elem instanceof ElementResidence) {\n                getCore().deleteElementResidence(elem);\n            }\n\n            if (elem instanceof Partition) {\n                getActivityGraphs().deletePartition(elem);\n            }\n\n            if (elem instanceof Feature) {\n                deleteFeature((Feature) elem);\n            } else if (elem instanceof Namespace) {\n                deleteNamespace((Namespace) elem);\n            }\n        } catch (InvalidObjectException e) {\n            // If we get this with the repository locked, it means our root\n            // model element was already deleted.  Nothing to do...\n            LOG.log(Level.SEVERE, \"Encountered deleted object during delete of \" + elem);\n        } catch (InvalidElementException e) {\n            // Our wrapped version of the same error\n            LOG.log(Level.SEVERE, \"Encountered deleted object during delete of \" + elem);\n        } finally {\n            // end our transaction\n            modelImpl.getRepository().endTrans();\n        }\n\n        synchronized (lock) {\n            // Elements which will be deleted when their container is deleted\n            // don't get added to the list of elements to be deleted\n            // (but we still want to traverse them looking for other elements\n            //  to be deleted)\n            try {\n                Object container = ((RefObject) elem).refImmediateComposite();\n                if (container == null\n                        || !elementsToBeDeleted.contains(container)\n                        // There is a bug in the version of MDR (20050711) that\n                        // we use  that causes it to fail to delete aggregate\n                        // elements which are single valued and where the\n                        // aggregate end is listed second in the association\n                        // defined in the metamodel. For the UML 1.4 metamodel,\n                        // this affects a StateMachine's top StateVertex and\n                        // a Transition's Guard.  See issue 4948 & 5227 - tfm\n                        // 20080713\n                        || (container instanceof StateMachine\n                                && elem instanceof StateVertex)\n                        || (container instanceof Transition\n                                && elem instanceof Guard)) {\n                    elementsInDeletionOrder.add((RefObject) elem);\n                }\n            } catch (InvalidObjectException e) {\n                LOG.log(Level.FINE, \"Object already deleted {0}\", elem);\n            }\n\n            if (elem == top) {\n                for (RefObject o : elementsInDeletionOrder) {\n                    // TODO: This doesn't belong here, but it's not a good time\n                    // to move it.  Find someplace less obtrusive than this\n                    // inner loop. - tfm\n                    if (o instanceof CompositeState) {\n                        // This enforces the following well-formedness rule.\n                        // <p>Well formedness rule 4.12.3.1 CompositeState\n                        // [4] There have to be at least two composite\n                        // substates in a concurrent composite state.<p>\n                        // If this is broken by deletion of substate then we\n                        // change the parent composite substate to be not\n                        // concurrent.\n                        CompositeState deletedCompositeState =\n                            (CompositeState) o;\n                        try {\n                            CompositeState containingCompositeState =\n                                deletedCompositeState.getContainer();\n                            if (containingCompositeState != null\n                                    && containingCompositeState.\n                                    isConcurrent()\n                                    && containingCompositeState.getSubvertex().\n                                        size() == 1) {\n                                containingCompositeState.setConcurrent(false);\n                            }\n                        } catch (InvalidObjectException e) {\n                            LOG.log(Level.FINE, \"Object already deleted {0}\", o);\n                        }\n                    }\n                    try {\n                        o.refDelete();\n                    } catch (InvalidObjectException e) {\n                        LOG.log(Level.FINE, \"Object already deleted {0}\", o);\n                    }\n                    elementsToBeDeleted.remove(o);\n                }\n                top = null;\n                elementsInDeletionOrder.clear();\n                if (!elementsToBeDeleted.isEmpty()) {\n                    LOG.log(Level.FINE, \"**Skipped deleting {0} elements (probably in a deleted container\", elementsToBeDeleted.size());\n                    elementsToBeDeleted.clear();\n                }\n            }\n        }\n\n        Model.execute(new DummyModelCommand());\n    }\n\n\n    public boolean isRemoved(Object o) {\n        if (!(o instanceof RefObject)) {\n            throw new IllegalArgumentException(\n                    \"Expected JMI RefObject, received \" + o);\n        }\n        try {\n            // We don't care about the value - just want to see if it throws\n            ((RefObject) o).refImmediateComposite();\n            return false;\n        } catch (InvalidObjectException e) {\n            return true;\n        }\n    }\n\n    /**\n     * Delete a Feature.\n     *\n     * @param elem feature to be deleted\n     */\n    private void deleteFeature(Feature elem) {\n        getCore().deleteFeature(elem);\n        if (elem instanceof BehavioralFeature) {\n            getCore().deleteBehavioralFeature(elem);\n            if (elem instanceof Operation) {\n                getCore().deleteOperation(elem);\n            } else if (elem instanceof Method) {\n                getCore().deleteMethod(elem);\n            } else if (elem instanceof Reception) {\n                getCommonBehavior().deleteReception(elem);\n            }\n        } else if (elem instanceof StructuralFeature) {\n            getCore().deleteStructuralFeature(elem);\n            if (elem instanceof Attribute) {\n                getCore().deleteAttribute(elem);\n            }\n        }\n    }\n\n    /**\n     * Delete a Namespace.\n     *\n     * @param elem namespace to be deleted\n     */\n    private void deleteNamespace(Namespace elem) {\n        getCore().deleteNamespace(elem);\n        if (elem instanceof Classifier) {\n            getCore().deleteClassifier(elem);\n            if (elem instanceof UmlClass) {\n                getCore().deleteClass(elem);\n                if (elem instanceof AssociationClass) {\n                    getCore().deleteAssociationClass(elem);\n                }\n            } else if (elem instanceof Interface) {\n                getCore().deleteInterface(elem);\n            } else if (elem instanceof DataType) {\n                getCore().deleteDataType(elem);\n                if (elem instanceof Primitive) {\n                    getCore().deletePrimitive(elem);\n                } else if (elem instanceof Enumeration) {\n                    // TODO: Add EnumerationLiteral someplace\n                    getCore().deleteEnumeration(elem);\n                } else if (elem instanceof ProgrammingLanguageDataType) {\n                    getCore().deleteProgrammingLanguageDataType(elem);\n                }\n            } else if (elem instanceof Node) {\n                getCore().deleteNode(elem);\n            } else if (elem instanceof Component) {\n                getCore().deleteComponent(elem);\n            } else if (elem instanceof Artifact) {\n                getCore().deleteArtifact(elem);\n            } else if (elem instanceof Signal) {\n                getCommonBehavior().deleteSignal(elem);\n                if (elem instanceof Exception) {\n                    getCommonBehavior().deleteException(elem);\n                }\n            } else if (elem instanceof ClassifierRole) {\n                getCollaborations().deleteClassifierRole(elem);\n            } else if (elem instanceof UseCase) {\n                getUseCases().deleteUseCase(elem);\n            } else if (elem instanceof Actor) {\n                getUseCases().deleteActor(elem);\n            } else if (elem instanceof ClassifierInState) {\n                getActivityGraphs().deleteClassifierInState(elem);\n            }\n        } else if (elem instanceof Collaboration) {\n            getCollaborations().deleteCollaboration(elem);\n        } else if (elem instanceof UmlPackage) {\n            getModelManagement().deletePackage(elem);\n            if (elem instanceof org.omg.uml.modelmanagement.Model) {\n                getModelManagement().deleteModel(elem);\n            } else if (elem instanceof Subsystem) {\n                getModelManagement().deleteSubsystem(elem);\n            }\n        }\n    }\n\n    /**\n     * Delete a Relationship.\n     *\n     * @param elem Relationship to be deleted\n     */\n    private void deleteRelationship(Relationship elem) {\n        getCore().deleteRelationship(elem);\n        if (elem instanceof Flow) {\n            getCore().deleteFlow(elem);\n        } else if (elem instanceof Generalization) {\n            getCore().deleteGeneralization(elem);\n        } else if (elem instanceof UmlAssociation) {\n            getCore().deleteAssociation(elem);\n            if (elem instanceof AssociationRole) {\n                getCollaborations().deleteAssociationRole(elem);\n            }\n        } else if (elem instanceof Dependency) {\n            getCore().deleteDependency(elem);\n            if (elem instanceof Abstraction) {\n                getCore().deleteAbstraction(elem);\n            } else if (elem instanceof Binding) {\n                getCore().deleteBinding(elem);\n            } else if (elem instanceof Usage) {\n                getCore().deleteUsage(elem);\n            } else if (elem instanceof Permission) {\n                getCore().deletePermission(elem);\n            }\n        } else if (elem instanceof Include) {\n            getUseCases().deleteInclude(elem);\n        } else if (elem instanceof Extend) {\n            getUseCases().deleteExtend(elem);\n        }\n    }\n\n    /**\n     * Delete an Action.\n     *\n     * @param elem the Action to be deleted\n     */\n    private void deleteAction(Object elem) {\n        getCommonBehavior().deleteAction(elem);\n        if (elem instanceof ActionSequence) {\n            getCommonBehavior().deleteActionSequence(elem);\n        } else if (elem instanceof CreateAction) {\n            getCommonBehavior().deleteCreateAction(elem);\n        } else if (elem instanceof CallAction) {\n            getCommonBehavior().deleteCallAction(elem);\n        } else if (elem instanceof ReturnAction) {\n            getCommonBehavior().deleteReturnAction(elem);\n        } else if (elem instanceof SendAction) {\n            getCommonBehavior().deleteSendAction(elem);\n        } else if (elem instanceof TerminateAction) {\n            getCommonBehavior().deleteTerminateAction(elem);\n        } else if (elem instanceof UninterpretedAction) {\n            getCommonBehavior().deleteUninterpretedAction(elem);\n        } else if (elem instanceof DestroyAction) {\n            getCommonBehavior().deleteDestroyAction(elem);\n        }\n    }\n\n    /**\n     * Delete an Instance.\n     *\n     * @param elem the Instance to be deleted.\n     */\n    private void deleteInstance(Instance elem) {\n        getCommonBehavior().deleteInstance(elem);\n        if (elem instanceof DataValue) {\n            getCommonBehavior().deleteDataValue(elem);\n        } else if (elem instanceof ComponentInstance) {\n            getCommonBehavior().deleteComponentInstance(elem);\n        } else if (elem instanceof NodeInstance) {\n            getCommonBehavior().deleteNodeInstance(elem);\n        } else if (elem\n                instanceof\n                org.omg.uml.behavioralelements.commonbehavior.Object) {\n            getCommonBehavior().deleteObject(elem);\n            if (elem instanceof LinkObject) {\n                getCommonBehavior().deleteLinkObject(elem);\n            }\n        } else if (elem instanceof SubsystemInstance) {\n            getCommonBehavior().deleteSubsystemInstance(elem);\n        }\n        if (elem instanceof UseCaseInstance) {\n            getUseCases().deleteUseCaseInstance(elem);\n        }\n    }\n\n    /**\n     * Delete a StateVertex.\n     *\n     * @param elem the StateVertex to be deleted\n     */\n    private void deleteStateVertex(StateVertex elem) {\n        getStateMachines().deleteStateVertex(elem);\n        if (elem instanceof Pseudostate) {\n            getStateMachines().deletePseudostate(elem);\n        } else if (elem instanceof SynchState) {\n            getStateMachines().deleteSynchState(elem);\n        } else if (elem instanceof StubState) {\n            getStateMachines().deleteStubState(elem);\n        } else if (elem instanceof State) {\n            getStateMachines().deleteState(elem);\n            if (elem instanceof CompositeState) {\n                getStateMachines().deleteCompositeState(elem);\n                if (elem instanceof SubmachineState) {\n                    getStateMachines().deleteSubmachineState(elem);\n                    if (elem instanceof SubactivityState) {\n                        getActivityGraphs().deleteSubactivityState(elem);\n                    }\n                }\n            } else if (elem instanceof SimpleState) {\n                getStateMachines().deleteSimpleState(elem);\n                if (elem instanceof ActionState) {\n                    getActivityGraphs().deleteActionState(elem);\n                    if (elem instanceof CallState) {\n                        getActivityGraphs().deleteCallState(elem);\n                    }\n                } else if (elem instanceof ObjectFlowState) {\n                    getActivityGraphs().deleteObjectFlowState(elem);\n                }\n            } else if (elem instanceof FinalState) {\n                getStateMachines().deleteFinalState(elem);\n            }\n        }\n    }\n\n    public void deleteExtent(Object element) {\n        try {\n            org.omg.uml.UmlPackage extent =\n                (org.omg.uml.UmlPackage) ((RefObject) element)\n                    .refOutermostPackage();\n\n            LOG.log(Level.FINE, \"Removing extent {0}\", extent);\n\n            modelImpl.deleteExtent(extent);\n        } catch (InvalidObjectException e) {\n            throw new InvalidElementException(e);\n        }\n    }\n\n    public Collection getExtentElements(String name) {\n        return getExtentPackages(name);\n    }\n\n    public Collection getExtentPackages(String name) {\n        org.omg.uml.UmlPackage pkg = modelImpl.getExtent(name);\n        if (pkg == null) {\n            return null;\n        }\n        Collection<Object> packages = pkg.getModelManagement().getUmlPackage().\n            refAllOfType();\n        Collection<Object> topLevelPackages = new ArrayList<Object>();\n        for (Object pack : packages) {\n            if (Model.getFacade().getNamespace(pack) == null) {\n                topLevelPackages.add(pack);\n            }\n        }\n        return topLevelPackages;\n    }\n\n}\n", "human_rating": 2.00484241571904, "metadata": {"project": "argoUML", "class": "org.argouml.model.mdr.UmlFactoryMDRImpl", "source_path": "argoUML/sourcefiles/src/argouml-core-model-mdr/src/org/argouml/model/mdr/UmlFactoryMDRImpl.java", "label_probabilities": {"readability": [0.0, 0.00484147, 0.995159, 5.71904e-09], "understandability": [7.79898e-13, 7.86981e-05, 0.93223, 0.0676915], "complexity": [0.723761, 0.276172, 6.7397e-05, 0.0], "modularization": [0.997663, 0.00233626, 2.19295e-07, 0.0], "overall": [0.0, 8.52015e-05, 0.297496, 0.702419]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.notation.providers.ActionStateNotation", "source": "/* $Id: ActionStateNotation.java 18852 2010-11-20 19:27:11Z mvw $\n *****************************************************************************\n * Copyright (c) 2009-2010 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Michiel van der Wulp\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2005-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.notation.providers;\n\nimport java.util.Collection;\nimport java.util.Iterator;\n\nimport org.argouml.model.Model;\nimport org.argouml.notation.NotationProvider;\n\n/**\n * This abstract class forms the basis of all Notation providers\n * for the text shown in the Fig that represents the ActionState.\n * Subclass this for all languages.\n *\n * @author Michiel van der Wulp\n */\npublic abstract class ActionStateNotation extends NotationProvider {\n\n    /**\n     * The constructor.\n     *\n     * @param actionState the uml element\n     */\n    public ActionStateNotation(Object actionState) {\n        if (!Model.getFacade().isAActionState(actionState)) {\n            throw new IllegalArgumentException(\"This is not an ActionState.\");\n        }\n    }\n\n    @Override\n    public void initialiseListener(Object modelElement) {\n        addElementListener(modelElement, \n                new String[] {\"entry\", \"remove\", \"stereotype\"} );\n        Object entry = Model.getFacade().getEntry(modelElement);\n        if (entry != null) {\n            addElementListener(entry, \"script\");\n        }\n        Collection c = Model.getFacade().getStereotypes(modelElement);\n        Iterator i = c.iterator();\n        while (i.hasNext()) {\n            Object st = i.next();\n            addElementListener(st, \"name\");\n        }\n    }\n\n}\n", "human_rating": 3.584558923200005, "metadata": {"project": "argoUML", "class": "org.argouml.notation.providers.ActionStateNotation", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/notation/providers/ActionStateNotation.java", "label_probabilities": {"readability": [0.584582, 0.415395, 2.29616e-05, 4.60988e-15], "understandability": [0.179774, 0.819112, 0.00111319, 1.47414e-14], "complexity": [9e-20, 1.1399e-07, 0.0242425, 0.975757], "modularization": [0.0, 4.28517e-11, 0.0203369, 0.979663], "overall": [0.996843, 0.00315683, 6.82826e-14, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.notation.providers.java.AssociationEndNameNotationJava", "source": "/* $Id: AssociationEndNameNotationJava.java 18615 2010-08-03 08:23:26Z mvw $\n *****************************************************************************\n * Copyright (c) 2009-2010 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2006-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.notation.providers.java;\n\nimport org.argouml.application.events.ArgoEventPump;\nimport org.argouml.application.events.ArgoEventTypes;\nimport org.argouml.application.events.ArgoHelpEvent;\nimport org.argouml.model.Model;\nimport org.argouml.notation.NotationSettings;\nimport org.argouml.notation.providers.AssociationEndNameNotation;\nimport org.argouml.notation.providers.uml.NotationUtilityUml;\n\n/**\n * The Java notation for an associationEnd name (i.e. the  role).\n * \n * @author michiel\n */\npublic class AssociationEndNameNotationJava extends AssociationEndNameNotation {\n\n    /**\n     * The constructor.\n     * \n     * @param associationEnd the UML element\n     */\n    public AssociationEndNameNotationJava(Object associationEnd) {\n        super(associationEnd);\n    }\n\n    /*\n     * @see org.argouml.notation.providers.NotationProvider#getParsingHelp()\n     */\n    public String getParsingHelp() {\n//        return \"parsing.help.fig-association-end-name\";\n        return \"Parsing in Java not yet supported\";\n    }\n\n    /*\n     * @see org.argouml.notation.providers.NotationProvider#parse(java.lang.Object, java.lang.String)\n     */\n    public void parse(Object modelElement, String text) {\n        ArgoEventPump.fireEvent(new ArgoHelpEvent(\n                ArgoEventTypes.HELP_CHANGED, this,\n            \"Parsing in Java not yet supported\"));\n    }\n\n    private String toString(Object modelElement, boolean useGuillemets) {\n        String name = Model.getFacade().getName(modelElement);\n        if (name == null) {\n            name = \"\";\n        }\n\n        Object visi = Model.getFacade().getVisibility(modelElement);\n        String visibility = \"\";\n        if (visi != null) {\n            visibility = NotationUtilityJava.generateVisibility(visi);\n        }\n        if (name.length() < 1) {\n            visibility = \"\";\n            //this is the temporary solution for issue 1011\n        }\n\n        String stereoString = \n            NotationUtilityUml.generateStereotype(modelElement, useGuillemets);\n\n        return stereoString + visibility + name;\n    }\n\n    @Override\n    public String toString(Object modelElement, NotationSettings settings) {\n        return toString(modelElement, settings.isUseGuillemets());\n    }\n    \n}\n", "human_rating": 3.90988374897, "metadata": {"project": "argoUML", "class": "org.argouml.notation.providers.java.AssociationEndNameNotationJava", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/notation/providers/java/AssociationEndNameNotationJava.java", "label_probabilities": {"readability": [0.909891, 0.090104, 3.24958e-06, 1.24981e-06], "understandability": [0.576995, 0.42189, 0.00111496, 1.03004e-10], "complexity": [1.705e-12, 2.96941e-05, 0.90928, 0.0906898], "modularization": [0.0, 3.02134e-11, 0.0140928, 0.985907], "overall": [0.993417, 0.00658346, 7.92256e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.notation.providers.uml.ClassifierRoleNotationUml", "source": "/* $Id: ClassifierRoleNotationUml.java 18852 2010-11-20 19:27:11Z mvw $\n *****************************************************************************\n * Copyright (c) 2009-2010 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Michiel van der Wulp\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2006-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.notation.providers.uml;\n\nimport java.text.ParseException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.NoSuchElementException;\n\nimport org.argouml.application.events.ArgoEventPump;\nimport org.argouml.application.events.ArgoEventTypes;\nimport org.argouml.application.events.ArgoHelpEvent;\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.Model;\nimport org.argouml.notation.NotationSettings;\nimport org.argouml.notation.providers.ClassifierRoleNotation;\nimport org.argouml.util.MyTokenizer;\n\n/**\n * The UML notation for a ClassifierRole. <p>\n * \n * The following is supported: <p>\n * \n * <pre>\n * baselist := [base] [, base]*\n * classifierRole := [name] [/ role] [: baselist]\n * </pre>\n *\n * The <code>role </code> and <code>baselist</code> can be given in\n * any order.<p>\n * \n * The <code>name</code> is the Instance name, not used for a ClassifierRole.<p>\n *\n * This syntax is compatible with the UML 1.3 and 1.4 specification.\n * \n * @author Michiel van der Wulp\n */\npublic class ClassifierRoleNotationUml extends ClassifierRoleNotation {\n\n\n    /**\n     * The Constructor.\n     * \n     * @param classifierRole the UML ClassifierRole\n     */\n    public ClassifierRoleNotationUml(Object classifierRole) {\n        super(classifierRole);\n    }\n\n    /*\n     * @see org.argouml.notation.providers.NotationProvider#getParsingHelp()\n     */\n    public String getParsingHelp() {\n        return \"parsing.help.fig-classifierrole\";\n    }\n\n    /*\n     * @see org.argouml.notation.providers.NotationProvider#parse(java.lang.Object, java.lang.String)\n     */\n    public void parse(Object modelElement, String text) {\n        try {\n            parseClassifierRole(modelElement, text);\n        } catch (ParseException pe) {\n            String msg = \"statusmsg.bar.error.parsing.classifierrole\";\n            Object[] args = {pe.getLocalizedMessage(),\n                             Integer.valueOf(pe.getErrorOffset()), };\n            ArgoEventPump.fireEvent(new ArgoHelpEvent(\n                    ArgoEventTypes.HELP_CHANGED, this,\n                    Translator.messageFormat(msg, args)));\n        }\n    }\n    \n    /**\n     * Parses a ClassifierRole represented by the following line of the format:\n     *\n     * <pre>\n     * baselist := [base] [, base]*\n     * classifierRole := [name] [/ role] [: baselist]\n     * </pre>\n     *\n     * <code>role </code> and <code>baselist</code> can be given in\n     * any order.<p>\n     *\n     * This syntax is compatible with the UML 1.3 specification.\n     *\n     * (formerly: \"name: base\" )\n     *\n     * @param cls the classifier role to apply any changes to\n     * @param s the String to parse\n     * @return the classifier role with the applied changes\n     * @throws ParseException when it detects an error in the attribute string. \n     *                  See also ParseError.getErrorOffset().\n     */\n    protected Object parseClassifierRole(Object cls, String s)\n        throws ParseException {\n        \n        String name = null;\n        String token;\n        String role = null;\n        String base = null;\n        List<String> bases = null;\n        boolean hasColon = false;\n        boolean hasSlash = false;\n\n        try {\n            MyTokenizer st = new MyTokenizer(s, \" ,\\t,/,:,\\\\,\");\n\n            while (st.hasMoreTokens()) {\n                token = st.nextToken();\n                if (\" \".equals(token) || \"\\t\".equals(token)) {\n                    /* Do nothing. */\n                } else if (\"/\".equals(token)) {\n                    hasSlash = true;\n                    hasColon = false;\n\n                    if (base != null) {\n                        if (bases == null) {\n                            bases = new ArrayList<String>();\n                        }\n                        bases.add(base);\n                    }\n                    base = null;\n                } else if (\":\".equals(token)) {\n                    hasColon = true;\n                    hasSlash = false;\n\n                    if (bases == null) {\n                        bases = new ArrayList<String>();\n                    }\n                    if (base != null) {\n                        bases.add(base);\n                    }\n                    base = null;\n                } else if (\",\".equals(token)) {\n                    if (base != null) {\n                        if (bases == null) {\n                            bases = new ArrayList<String>();\n                        }\n                        bases.add(base);\n                    }\n                    base = null;\n                } else if (hasColon) {\n                    if (base != null) {\n                    \tString msg = \"parsing.error.classifier.extra-test\";\n                        throw new ParseException(\n                                Translator.localize(msg), \n                                st.getTokenIndex());\n                    }\n\n                    base = token;\n                } else if (hasSlash) {\n                    if (role != null) {\n                    \tString msg = \"parsing.error.classifier.extra-test\";\n                        throw new ParseException(\n                                Translator.localize(msg), \n                                st.getTokenIndex());\n                    }\n\n                    role = token;\n                } else {\n                    if (name != null) {\n                    \tString msg = \"parsing.error.classifier.extra-test\";\n                        throw new ParseException(\n                                Translator.localize(msg), \n                                st.getTokenIndex());\n                    }\n\n                    name = token;\n                }\n            }\n        } catch (NoSuchElementException nsee) {\n            String msg = \"parsing.error.classifier.unexpected-end-attribute\";\n            throw new ParseException(Translator.localize(msg), s.length());\n        }\n\n        if (base != null) {\n            if (bases == null) {\n                bases = new ArrayList<String>();\n            }\n            bases.add(base);\n        }\n\n        // TODO: What to do about object name???\n        //    if (name != null)\n        //      ;\n\n        if (role != null) {\n            Model.getCoreHelper().setName(cls, role.trim());\n        }\n\n        if (bases != null) {\n            // Remove bases that aren't there anymore\n\n            // copy - can't iterate modify live collection while iterating it\n            Collection b = new ArrayList(Model.getFacade().getBases(cls));\n            Iterator it = b.iterator();\n            Object c;\n            Object ns = Model.getFacade().getNamespace(cls);\n            if (ns != null && Model.getFacade().getNamespace(ns) != null) {\n                ns = Model.getFacade().getNamespace(ns);\n            } else {\n                ns = Model.getFacade().getRoot(cls);\n            }\n\n            while (it.hasNext()) {\n                c = it.next();\n                if (!bases.contains(Model.getFacade().getName(c))) {\n                    Model.getCollaborationsHelper().removeBase(cls, c);\n                }\n            }\n\n            it = bases.iterator();\n        addBases:\n            while (it.hasNext()) {\n                String d = ((String) it.next()).trim();\n\n                Iterator it2 = b.iterator();\n                while (it2.hasNext()) {\n                    c = it2.next();\n                    if (d.equals(Model.getFacade().getName(c))) {\n                        continue addBases;\n                    }\n                }\n                c = NotationUtilityUml.getType(d, ns);\n                if (Model.getFacade().isACollaboration(\n                        Model.getFacade().getNamespace(c))) {\n                    Model.getCoreHelper().setNamespace(c, ns);\n                }\n                Model.getCollaborationsHelper().addBase(cls, c);\n            }\n        }\n        \n        return cls;\n    }\n\n    private String toString(Object modelElement) {\n        String nameString = Model.getFacade().getName(modelElement);\n        if (nameString == null) { \n            nameString = \"\";\n        }\n        nameString = nameString.trim();\n        // Loop through all base classes, building a comma separated list\n        StringBuilder baseString = NotationUtilityUml.formatNameList(\n                Model.getFacade().getBases(modelElement));\n        baseString = new StringBuilder(baseString.toString().trim());       \n        // Build the final string\n        if (nameString.length() != 0) {\n            nameString = \"/\" + nameString;\n        }\n        if (baseString.length() != 0) {\n            baseString = baseString.insert(0, \":\");\n        }\n        return nameString + baseString.toString();\n    }\n\n    @Override\n    public String toString(Object modelElement, NotationSettings settings) {\n        return toString(modelElement);\n    }\n\n}\n", "human_rating": 2.00519310325, "metadata": {"project": "argoUML", "class": "org.argouml.notation.providers.uml.ClassifierRoleNotationUml", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/notation/providers/uml/ClassifierRoleNotationUml.java", "label_probabilities": {"readability": [1e-20, 0.00519981, 0.994794, 5.67325e-06], "understandability": [2.49917e-07, 0.00130213, 0.998621, 7.63328e-05], "complexity": [0.907919, 0.0920788, 1.87185e-06, 0.0], "modularization": [0.413004, 0.586895, 0.000100999, 0.0], "overall": [0.0, 7.52369e-07, 0.149396, 0.850603]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.persistence.AbstractFilePersister", "source": "/* $Id: AbstractFilePersister.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *    Michiel van der Wulp\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.persistence;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.event.EventListenerList;\nimport javax.swing.filechooser.FileFilter;\n\nimport org.argouml.configuration.Configuration;\nimport org.argouml.kernel.ProfileConfiguration;\nimport org.argouml.kernel.Project;\nimport org.argouml.kernel.ProjectMember;\nimport org.argouml.taskmgmt.ProgressEvent;\nimport org.argouml.taskmgmt.ProgressListener;\nimport org.argouml.uml.ProjectMemberModel;\nimport org.argouml.uml.cognitive.ProjectMemberTodoList;\nimport org.argouml.uml.diagram.ProjectMemberDiagram;\nimport org.argouml.util.ThreadUtils;\n\n/**\n * To persist to and from zargo (zipped file) storage.\n *\n * @author Bob Tarling\n */\npublic abstract class AbstractFilePersister extends FileFilter\n        implements ProjectFilePersister {\n\n    private static final Logger LOG =\n        Logger.getLogger(AbstractFilePersister.class.getName());\n\n    /**\n     * Map of persisters by target class.\n     */\n    private static Map<Class, Class<? extends MemberFilePersister>>\n    persistersByClass =\n        new HashMap<Class, Class<? extends MemberFilePersister>>();\n\n    /**\n     * Map of persisters by tag / file extension.\n     */\n    private static Map<String, Class<? extends MemberFilePersister>>\n    persistersByTag =\n        new HashMap<String, Class<? extends MemberFilePersister>>();\n\n    static {\n        registerPersister(ProjectMemberDiagram.class, \"pgml\",\n                DiagramMemberFilePersister.class);\n        registerPersister(ProfileConfiguration.class, \"profile\",\n                ProfileConfigurationFilePersister.class);\n        registerPersister(ProjectMemberTodoList.class, \"todo\",\n                TodoListMemberFilePersister.class);\n        registerPersister(ProjectMemberModel.class, \"xmi\",\n                ModelMemberFilePersister.class);\n    }\n\n    private EventListenerList listenerList = new EventListenerList();\n\n    // This can be made public to allow others to extend their own persisters\n    private static boolean registerPersister(Class target, String tag,\n            Class<? extends MemberFilePersister> persister) {\n        persistersByClass.put(target, persister);\n        persistersByTag.put(tag, persister);\n        return true;\n    }\n\n    /**\n     * Create a temporary copy of the existing file.\n     *\n     * @param file the file to copy.\n     * @return the temp file or null if none copied.\n     * @throws FileNotFoundException if file not found\n     * @throws IOException if error reading or writing\n     */\n    protected File createTempFile(File file)\n        throws FileNotFoundException, IOException {\n        File tempFile = new File(file.getAbsolutePath() + \"#\");\n\n        if (tempFile.exists()) {\n            tempFile.delete();\n        }\n\n        if (file.exists()) {\n            copyFile(file, tempFile);\n        }\n\n        return tempFile;\n    }\n\n    /**\n     * Saving in a safe way means: Retain the previous project\n     * file even when the save operation causes an\n     * exception in the middle.\n     * Also create a backup file after saving.\n     *\n     * See issue 6012 - our method of saving in a safe way does not\n     * work on a SharePoint drive.\n     * Hence we can configure ArgoUML to save unsafe, too...\n     *\n     * @return true if we should be careful\n     */\n    protected boolean useSafeSaves() {\n        boolean result = Configuration.getBoolean(\n                        PersistenceManager.USE_SAFE_SAVES, true);\n\n        /* make sure this setting exists in the configuration file\n         * to facilitate changing: */\n        Configuration.setBoolean(PersistenceManager.USE_SAFE_SAVES, result);\n\n        return result;\n    }\n\n    /**\n     * Copies one file src to another, raising file exceptions\n     * if there are some problems.\n     *\n     * @param dest The destination file.\n     * @param src The source file.\n     * @return The destination file after successful copying.\n     * @throws IOException if there is some problems with the files.\n     * @throws FileNotFoundException if any of the files cannot be found.\n     */\n    protected File copyFile(File src, File dest)\n        throws FileNotFoundException, IOException {\n\n        FileInputStream fis  = new FileInputStream(src);\n        FileOutputStream fos = new FileOutputStream(dest);\n        byte[] buf = new byte[1024];\n        int i = 0;\n        while ((i = fis.read(buf)) != -1) {\n            fos.write(buf, 0, i);\n        }\n        fis.close();\n        fos.close();\n\n        dest.setLastModified(src.lastModified());\n\n        return dest;\n    }\n\n\n\n    ////////////////////////////////////////////////////////////////\n    // FileFilter API\n\n    /*\n     * @see javax.swing.filechooser.FileFilter#accept(java.io.File)\n     */\n    public boolean accept(File f) {\n        if (f == null) {\n\t    return false;\n\t}\n        if (f.isDirectory()) {\n\t    return true;\n\t}\n        String s = getExtension(f);\n        if (s != null) {\n\t    // this check for files without extension...\n            if (s.equalsIgnoreCase(getExtension())) {\n\t\treturn true;\n\t    }\n\t}\n        return false;\n    }\n\n    /**\n     * The extension valid for this type of file.\n     * (Just the chars, not the dot: e.g. \"zargo\".)\n     *\n     * @return the extension valid for this type of file\n     */\n    public abstract String getExtension();\n\n    /**\n     * Just the description, not the extension between \"()\".\n     *\n     * @return the description valid for this type of file\n     */\n    protected abstract String getDesc();\n\n    private static String getExtension(File f) {\n        if (f == null) {\n\t    return null;\n\t}\n        return getExtension(f.getName());\n    }\n\n    private static String getExtension(String filename) {\n        int i = filename.lastIndexOf('.');\n        if (i > 0 && i < filename.length() - 1) {\n            return filename.substring(i + 1).toLowerCase();\n        }\n        return null;\n    }\n\n    /**\n     * Given the full filename this returns true if that filename contains the\n     * expected extension for the is persister.\n     *\n     * @param filename The filename to test.\n     * @return true if the filename is valid for this persister\n     */\n    public boolean isFileExtensionApplicable(String filename) {\n        return filename.toLowerCase().endsWith(\".\" + getExtension());\n    }\n\n    /*\n     * @see javax.swing.filechooser.FileFilter#getDescription()\n     */\n    public String getDescription() {\n        return getDesc() + \" (*.\" + getExtension() + \")\";\n    }\n\n    /**\n     * Save a project to file.<p>\n     * This first archives the existing file, then calls\n     * doSave(...) to do the actual saving.<p>\n     * Should doSave(...) throw an exception then it is\n     * caught here and any rollback handled before rethrowing\n     * the exception.\n     *\n     * @param project The project being saved.\n     * @param file The file to which the save is taking place.\n     * @throws SaveException when anything goes wrong\n     * @throws InterruptedException     if the thread is interrupted\n     *\n     * @see org.argouml.persistence.ProjectFilePersister#save(\n     * org.argouml.kernel.Project, java.io.File)\n     */\n    public final void save(Project project, File file) throws SaveException,\n    InterruptedException {\n        preSave(project, file);\n        doSave(project, file);\n        postSave(project, file);\n    }\n\n    /**\n     * Handle archiving of previous file or any other common\n     * requirements before saving a model to a file.\n     *\n     * @param project The project being saved.\n     * @param file The file to which the save is taking place.\n     * @throws SaveException when anything goes wrong\n     */\n    private void preSave(Project project, File file) throws SaveException {\n        if (project == null && file == null) {\n            throw new SaveException(\"No project nor file given\");\n        }\n    }\n\n    /**\n     * Handle archiving on completion of a save such as renaming\n     * the temporary save file to the real filename.\n     *\n     * @param project The project being saved.\n     * @param file The file to which the save is taking place.\n     * @throws SaveException when anything goes wrong\n     */\n    private void postSave(Project project, File file) throws SaveException {\n        if (project == null && file == null) {\n            throw new SaveException(\"No project nor file given\");\n        }\n    }\n\n    /**\n     * Implement in your concrete class to save a project to a\n     * file.<p>\n     * There is no need to worry about archiving or restoring\n     * archive on failure, that is handled by the rest of the\n     * framework.<p>\n     *\n     * @param project the project to save\n     * @param file The file to write.\n     * @throws SaveException when anything goes wrong\n     * @throws InterruptedException     if the thread is interrupted\n     *\n     * @see org.argouml.persistence.AbstractFilePersister#save(\n     * org.argouml.kernel.Project, java.io.File)\n     */\n    protected abstract void doSave(Project project, File file)\n        throws SaveException, InterruptedException;\n\n    /**\n     * Some persisters only provide load functionality for discontinued formats\n     * but no save.\n     * This method returns true by default. Those Peristers that do not provide\n     * save must override this.\n     * @return true if this persister is able to save\n     */\n    public boolean isSaveEnabled() {\n        return true;\n    }\n\n    /**\n     * Some persisters only provide save functionality for deprecated formats.\n     * Other persisters with the same extension will manage loading.\n     * This method returns true by default. Those Peristers that do not provide\n     * load must override this.\n     * @return true if this persister is able to load\n     */\n    public boolean isLoadEnabled() {\n        return true;\n    }\n\n    /*\n     * @see org.argouml.persistence.ProjectFilePersister#doLoad(java.io.File)\n     */\n    public abstract Project doLoad(File file)\n    \tthrows OpenException, InterruptedException;\n\n\n\n    /**\n     * Add any object interested in listening to persistence progress.\n     *\n     * @param listener the interested listener.\n     */\n    public void addProgressListener(ProgressListener listener) {\n        listenerList.add(ProgressListener.class, listener);\n    }\n\n    /**\n     * Remove any object no longer interested in listening to persistence\n     * progress.\n     *\n     * @param listener the listener to remove.\n     */\n    public void removeProgressListener(ProgressListener listener) {\n        listenerList.remove(ProgressListener.class, listener);\n    }\n\n    /**\n     * Returns true if a FileChooser should visualize an icon for the\n     * persister.\n     *\n     * @return true if the persister is associated to an icon\n     */\n    public abstract boolean hasAnIcon();\n\n\n    /**\n     * Get a MemberFilePersister based on a given ProjectMember.\n     *\n     * @param pm the project member\n     * @return the persister\n     */\n    protected MemberFilePersister getMemberFilePersister(ProjectMember pm) {\n        Class<? extends MemberFilePersister> persister = null;\n        if (persistersByClass.containsKey(pm)) {\n            persister = persistersByClass.get(pm);\n        } else {\n            /*\n             * TODO: Not sure we need to do this, but just to be safe for now.\n             */\n            for (Class clazz : persistersByClass.keySet()) {\n                if (clazz.isAssignableFrom(pm.getClass())) {\n                    persister = persistersByClass.get(clazz);\n                    break;\n                }\n            }\n        }\n        if (persister != null) {\n            return newPersister(persister);\n        }\n        return null;\n    }\n\n\n    /**\n     * Get a MemberFilePersister based on a given tag.\n     *\n     * @param tag The tag.\n     * @return the persister\n     */\n    protected MemberFilePersister getMemberFilePersister(String tag) {\n        Class<? extends MemberFilePersister> persister =\n            persistersByTag.get(tag);\n        if (persister != null) {\n            return newPersister(persister);\n        }\n        return null;\n    }\n\n    private static MemberFilePersister newPersister(\n            Class<? extends MemberFilePersister> clazz) {\n        try {\n            return clazz.newInstance();\n        } catch (InstantiationException e) {\n            LOG.log(Level.SEVERE, \"Exception instantiating file persister \" + clazz, e);\n            return null;\n        } catch (IllegalAccessException e) {\n            LOG.log(Level.SEVERE, \"Exception instantiating file persister \" + clazz, e);\n            return null;\n        }\n    }\n\n    // TODO: Document\n    class ProgressMgr implements ProgressListener {\n\n        /**\n         * The percentage completeness of phases complete.\n         * Does not include part-completed phases.\n         */\n        private int percentPhasesComplete;\n\n        /**\n         * The sections complete of a load or save.\n         */\n        private int phasesCompleted;\n\n        /**\n         * The number of equals phases the progress will measure.\n         * It is assumed each phase will be of equal time.\n         * There is one phase for each upgrade from a previous\n         * version and one pahse for the final load.\n         */\n        private int numberOfPhases;\n\n        public void setPercentPhasesComplete(int aPercentPhasesComplete) {\n            this.percentPhasesComplete = aPercentPhasesComplete;\n        }\n\n        public void setPhasesCompleted(int aPhasesCompleted) {\n            this.phasesCompleted = aPhasesCompleted;\n        }\n\n        public void setNumberOfPhases(int aNumberOfPhases) {\n            this.numberOfPhases = aNumberOfPhases;\n        }\n\n        public int getNumberOfPhases() {\n            return this.numberOfPhases;\n        }\n\n        protected void nextPhase() throws InterruptedException {\n            ThreadUtils.checkIfInterrupted();\n            ++phasesCompleted;\n            percentPhasesComplete =\n                (phasesCompleted * 100) / numberOfPhases;\n            fireProgressEvent(percentPhasesComplete);\n        }\n\n        /**\n         * Called when a ProgressEvent is fired.\n         *\n         * @see org.argouml.taskmgmt.ProgressListener#progress(org.argouml.taskmgmt.ProgressEvent)\n         * @throws InterruptedException     if thread is interrupted\n         */\n        public void progress(ProgressEvent event) throws InterruptedException {\n            ThreadUtils.checkIfInterrupted();\n            int percentPhasesLeft = 100 - percentPhasesComplete;\n            long position = event.getPosition();\n            long length = event.getLength();\n            long proportion = (position * percentPhasesLeft) / length;\n            fireProgressEvent(percentPhasesComplete + proportion);\n        }\n\n        /**\n         * Inform listeners of any progress notifications.\n         * @param percent the current percentage progress.\n         * @throws InterruptedException     if thread is interrupted\n         */\n        protected void fireProgressEvent(long percent)\n            throws InterruptedException {\n            ProgressEvent event = null;\n            // Guaranteed to return a non-null array\n            Object[] listeners = listenerList.getListenerList();\n            // Process the listeners last to first, notifying\n            // those that are interested in this event\n            for (int i = listeners.length - 2; i >= 0; i -= 2) {\n                if (listeners[i] == ProgressListener.class) {\n                    // Lazily create the event:\n                    if (event == null) {\n                        event = new ProgressEvent(this, percent, 100);\n                    }\n                    ((ProgressListener) listeners[i + 1]).progress(event);\n                }\n            }\n        }\n    }\n}\n", "human_rating": 3.9971810100000003, "metadata": {"project": "argoUML", "class": "org.argouml.persistence.AbstractFilePersister", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/persistence/AbstractFilePersister.java", "label_probabilities": {"readability": [0.997182, 0.00281767, 0.0, 0.0], "understandability": [0.660073, 0.339927, 0.0, 0.0], "complexity": [0.0, 0.0147697, 0.98523, 0.0], "modularization": [0.0, 0.0, 1.0, 1.7e-19], "overall": [0.0135493, 0.986451, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.sequence2.diagram.FigMessage", "source": "/* $Id: FigMessage.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *    Michiel van der Wulp\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2007-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.sequence2.diagram;\n\nimport java.awt.Color;\nimport java.awt.Point;\nimport java.awt.event.MouseEvent;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.Set;\nimport java.util.Vector;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.JSeparator;\n\nimport org.argouml.model.Model;\nimport org.argouml.model.UmlChangeEvent;\nimport org.argouml.notation.Notation;\nimport org.argouml.notation.NotationProvider;\nimport org.argouml.notation.NotationProviderFactory2;\nimport org.argouml.notation.SDNotationSettings;\nimport org.argouml.ui.ArgoJMenu;\nimport org.argouml.uml.diagram.DiagramSettings;\nimport org.argouml.uml.diagram.ui.FigEdgeModelElement;\nimport org.argouml.uml.diagram.ui.FigTextGroup;\nimport org.argouml.uml.diagram.ui.PathItemPlacement;\nimport org.tigris.gef.base.Selection;\nimport org.tigris.gef.presentation.ArrowHead;\nimport org.tigris.gef.presentation.ArrowHeadGreater;\nimport org.tigris.gef.presentation.ArrowHeadTriangle;\nimport org.tigris.gef.presentation.Fig;\nimport org.tigris.gef.presentation.FigNode;\nimport org.tigris.gef.presentation.FigPoly;\nimport org.tigris.gef.presentation.FigText;\n\n/**\n * The Fig that represents a message between classifier roles.\n * @author penyaskito\n */\npublic class FigMessage extends FigEdgeModelElement {\n\n    private static final long serialVersionUID = -2961220746360335159L;\n\n    private static final Logger LOG =\n        Logger.getLogger(FigEdgeModelElement.class.getName());\n\n    private FigTextGroup textGroup;\n\n    /**\n     * The action owned by the message\n     */\n    private Object action = null;\n\n    private SDNotationSettings notationSettings;\n    private boolean t[] = {\n        false,\n        false,\n        false,\n        false,\n        false,\n        false,\n        false,\n        false\n    };\n\n    /**\n     * Construct a fig owned by the given UML element with the provided render\n     * settings.\n     * @param edge owning UML element\n     * @param settings rendering settings\n     */\n    public FigMessage(Object edge, DiagramSettings settings) {\n        super(edge, settings);\n        textGroup = new FigTextGroup(edge, settings);\n        initialize();\n        action = Model.getFacade().getAction(getOwner());\n        updateArrow();\n        if (action != null) {\n            addElementListener(action, \"isAsynchronous\");\n        }\n        t[1] = Model.getFacade().isASynchCallMessage(getOwner());\n        t[2] = Model.getFacade().isAASynchCallMessage(getOwner());\n        t[3] = Model.getFacade().isACreateMessage(getOwner());\n        t[4] = Model.getFacade().isADeleteMessage(getOwner());\n        t[5] = Model.getFacade().isAReplyMessage(getOwner());\n        t[6] = Model.getFacade().isAASynchSignalMessage(getOwner());\n    }\n\n    private void initialize() {\n        textGroup.addFig(getNameFig());\n        textGroup.addFig(getStereotypeFig());\n        addPathItem(textGroup, new PathItemPlacement(this, textGroup, 50, 10));\n        notationSettings = new SDNotationSettings();\n    }\n\n    @Override\n    protected int getNotationProviderType() {\n        /* Use a different notation as Messages on a collaboration diagram: */\n        return NotationProviderFactory2.TYPE_SD_MESSAGE;\n    }\n\n    /* This next argument may be used to switch off\n     * the generation of sequence numbers - this is\n     * still to be implemented.\n     * They are less desired in sequence diagrams,\n     * since they do not add any information.\n     * In collaboration diagrams they are needed,\n     * and they are still optional in sequence diagrams. */\n    @Override\n    protected void initNotationProviders(Object own) {\n        super.initNotationProviders(own);\n        notationSettings.setShowSequenceNumbers(false);\n    }\n\n    @Override\n    protected void textEditStarted(FigText ft) {\n        /* This is a temporary hack until the notation provider\n         * for a SD Message will be able to parse successfully when the sequence\n         * number is missing.\n         * Remove this method completely then.*/\n        notationSettings.setShowSequenceNumbers(true);\n        super.textEditStarted(ft);\n        notationSettings.setShowSequenceNumbers(false);\n    }\n\n    protected SDNotationSettings getNotationSettings() {\n        return notationSettings;\n    }\n\n    boolean isSynchCallMessage() {\n    \treturn t[1];\n    }\n\n    boolean isASynchCallMessage() {\n        return t[2];\n    }\n\n    boolean isCreateMessage() {\n    \treturn t[3];\n    }\n\n    boolean isDeleteMessage() {\n    \treturn t[4];\n    }\n\n    boolean isReplyMessage() {\n    \treturn t[5];\n    }\n\n    boolean isASynchSignalMessage() {\n        return t[6];\n    }\n\n    /**\n     * Updates the arrow head and the arrow line according\n     * to the action type..\n     */\n    private void updateArrow() {\n        if (getOwner() == null) {\n            return;\n        }\n        getFig().setDashed(isReplyMessage());\n        final Object act = getAction();\n        final ArrowHead arrowHead;\n        if (act != null && Model.getFacade().isAsynchronous(getAction())) {\n            arrowHead = new ArrowHeadGreater();\n        } else {\n            arrowHead = new ArrowHeadTriangle();\n            getFig().setFillColor(getLineColor());\n        }\n        setDestArrowHead(arrowHead);\n    }\n\n    /**\n     * Gets the action attached to the message.\n     * @return the action\n     */\n    private Object getAction() {\n        return action;\n    }\n\n    /**\n     * @param me the MouseEvent that triggered the popup menu request\n     * @return a Vector containing a combination of these 4 types: Action,\n     *         JMenu, JMenuItem, JSeparator.\n     */\n    @Override\n    public Vector getPopUpActions(MouseEvent me) {\n        Vector popUpActions = super.getPopUpActions(me);\n\n        // Operations ...\n        if (Model.getFacade().isACallAction(getAction())) {\n            ArgoJMenu opMenu = buildOperationMenu();\n            int index = popUpActions.size() - getPopupAddOffset() - 1;\n            if (index < 0) {\n                index = 0;\n            }\n            popUpActions.add(index, new JSeparator());\n            popUpActions.add(index, opMenu);\n        }\n\n        return popUpActions;\n    }\n\n    protected ArgoJMenu buildOperationMenu() {\n        ArgoJMenu opMenu = new ArgoJMenu(\"Operation\");\n        Iterator<Object> iter = getReceiverOperations().iterator();\n        opMenu.setEnabled(iter.hasNext());\n        while (iter.hasNext()) {\n            Object op = iter.next();\n            NotationProvider np = null;\n            try {\n                String s = getNotationSettings().getNotationLanguage();\n                np = NotationProviderFactory2.getInstance()\n                    .getNotationProvider(\n                        NotationProviderFactory2.TYPE_OPERATION,\n                        op,\n                        Notation.findNotation(s));\n            } catch (Exception e) {\n                //TODO: add logging, but this will never happen and is handled\n                np = null;\n            }\n            String label = (np != null)\n                ? np.toString(op, getNotationSettings())\n                : Model.getFacade().getName(op);\n            opMenu.add(new ActionSetOperation(getAction(), op, label));\n        }\n        return opMenu;\n    }\n\n    @Override\n    public Selection makeSelection() {\n        return new SelectionMessage(this);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.FigEdge#setFig(org.tigris.gef.presentation.Fig)\n     */\n    public void setFig(Fig f) {\n        super.setFig(f);\n        updateArrow();\n    }\n\n    int getFinalY() {\n\tint finalY = 0;\n        Point[] points = getFig().getPoints();\n        if (points.length > 0) {\n            finalY = points[points.length - 1].y;\n        }\n        return finalY;\n    }\n\n    int getStartY() {\n\tint finalY = 0;\n        Point[] points = getFig().getPoints();\n        if (points.length > 0) {\n            finalY = points[0].y;\n        }\n        return finalY;\n    }\n\n\n    /**\n     * Checks if the message source and dest are the same.\n     * @return true if they are the same, otherwise false.\n     */\n    boolean isSelfMessage() {\n        // If possible we determine this by checking the destination\n        // and source Figs are the same. If this is not possible\n        // because the edge is not yet connected then we check the\n        // model.\n        if (getDestPortFig() == null || getSourcePortFig() == null) {\n            return getDestination().equals(getSource());\n        } else {\n            return (getDestPortFig().equals(getSourcePortFig()));\n        }\n    }\n\n    /**\n     * Converts the message into a spline.\n     * This is needed for self-referencing messages.\n     */\n    public void convertToArc() {\n        if (getPoints().length > 0) {\n            FigMessageSpline spline = new FigMessageSpline(getPoint(0));\n            spline.setDashed(isReplyMessage());\n            super.setFig(spline);\n            computeRoute();\n        }\n    }\n\n    @Override\n    public void computeRouteImpl() {\n\tsuper.computeRouteImpl();\n\tupdateActivations();\n    }\n\n    public void calcBounds() {\n        final FigPoly fp = (FigPoly) getFig();\n        final FigNode node = getSourceFigNode();\n        if (node != null && isSelfMessage() && fp.isComplete()) {\n            // TODO: calcBounds is called by SelectionManager when the Fig is\n            // dragged. This code is needed to reposition any self message\n            // as they are become detached from their classifier role\n            // (see issue 5562). The cause of the detachment is not yet\n            // understood.\n            // Unfortunately calcBounds is called from several other places\n            // so the code here is not optimal but is the best workaround until\n            // ArgoUML can provide its own replacement SelectionManager for\n            // sequence diagram requirements\n            // See - http://gef.tigris.org/issues/show_bug.cgi?id=344\n            final int x =\n                node.getX()\n                + (node.getWidth() + FigActivation.DEFAULT_WIDTH) / 2;\n            final Point startPoint = new Point(x, getYs()[0]);\n            final FigMessageSpline spline = new FigMessageSpline(startPoint);\n            spline.setComplete(true);\n            spline.setDashed(isReplyMessage());\n            super.setFig(spline);\n        }\n        super.calcBounds();\n    }\n\n    private synchronized void updateActivations() {\n\t// we update the activations...\n\tFigClassifierRole source = (FigClassifierRole) getSourceFigNode();\n\tif (source != null) {\n\t    source.createActivations();\n\t}\n\n\t// for performance, we check if this is a selfmessage\n\t// if it is, we have just updated the activations\n\tif (!isSelfMessage()) {\n\t    FigClassifierRole dest = (FigClassifierRole) getDestFigNode();\n\t    if (dest != null) {\n\t\tdest.createActivations();\n\t    }\n\t}\n    }\n\n    @Override\n    public void setLineColor(Color c) {\n    \tsuper.setLineColor(c);\n    \tgetDestArrowHead().setFillColor(c);\n    }\n\n    @Override\n    public void deleteFromModel() {\n    \t((FigClassifierRole) getSourceFigNode()).createActivations();\n    \tif (!isSelfMessage()) {\n    \t    ((FigClassifierRole) getDestFigNode()).createActivations();\n    \t}\n    \tsuper.deleteFromModel();\n    }\n\n    /**\n     * The default behaviour from FigEdgeModelElement is not correct\n     * here. See issue 5005. TODO: We must determine what to do here but for\n     * now doing nothing is better. I'm not sure why the super method would\n     * not work as I would expect that to do nothing if the ends are already\n     * correct.\n     * @return true at all times for now\n     */\n    @Override\n    protected boolean determineFigNodes() {\n        return true;\n    }\n\n    @Override\n    public void translate(int dx, int dy) {\n        if (isSelfMessage()) {\n            ((FigMessageSpline) getFig()).translateFig(dx, dy);\n        }\n        super.translate(dx, dy);\n    }\n\n    /**\n     * {@inheritDoc}\n     * @see org.argouml.uml.diagram.ui.FigEdgeModelElement#updateLayout(org.argouml.model.UmlChangeEvent)\n     */\n    @Override\n    public void updateLayout(UmlChangeEvent event) {\n        if (\"isAsynchronous\".equals(event.getPropertyName())) {\n            updateArrow();\n        }\n        super.updateLayout(event);\n    }\n\n    /*\n     * Overridden purely to keep our superclass from removing the listener\n     * that we just added.\n     *\n     * @see org.argouml.uml.diagram.ui.FigEdgeModelElement#updateListeners(java.lang.Object, java.lang.Object)\n     */\n    @Override\n    protected void updateListeners(Object oldOwner, Object newOwner ) {\n        action = Model.getFacade().getAction(newOwner);\n        Set<Object[]> listeners = new HashSet<Object[]>();\n        Object action = getAction();\n        listeners.add(new Object[] {getOwner(), \"remove\"});\n        if (action != null) {\n            listeners.add(new Object[] {action, \"isAsynchronous\"});\n        }\n        try {\n            updateElementListeners(listeners);\n        } catch (Exception e) {\n            // This call seems not very robust. Yet to determine cause.\n            LOG.log(Level.SEVERE, \"Exception caught\", e);\n        }\n    }\n\n    private Collection<Object> getReceiverOperations() {\n        ArrayList<Object> opList = new ArrayList<Object>();\n        Object action = getAction();\n\t    Object receiver = Model.getFacade().getReceiver(getOwner());\n        if (action != null && receiver != null) {\n            //TODO: What can we do with other kind of actions?\n            if (Model.getFacade().isACallAction(action)) {\n                Iterator bases =\n                    Model.getFacade().getBases(receiver).iterator();\n                while (bases.hasNext()) {\n                    Object base = bases.next();\n                    opList.addAll(Model.getFacade().getOperations(base));\n                }\n            }\n        }\n        return opList;\n    }\n    /**\n     * Determines the activator of this message based on the message position\n     * in relation to other messages.\n     * <p>Currently this only manages return messages. Any other message type\n     * returns with no action taking place.\n     * <p>The activator is set to the first call or create message found above\n     * this message.\n     * @return the activator that has been applied to the message.\n     */\n    public Object determineActivator() {\n        final FigClassifierRole fcr = (FigClassifierRole) getSourceFigNode();\n        final List<FigMessage> messageFigs = fcr.getFigMessages();\n        final Iterator<FigMessage> it = messageFigs.iterator();\n        Object activator = null;\n        while (it.hasNext()) {\n            FigMessage messageFig = it.next();\n            if ((messageFig.isCreateMessage() || messageFig.isSynchCallMessage())\n                    && messageFig.getDestFigNode() == fcr) {\n                activator = messageFig.getOwner();\n            } else if (messageFig == this) {\n                Model.getCollaborationsHelper().setActivator(\n                        getOwner(), activator);\n                return activator;\n            } else if (messageFig.isReplyMessage()) {\n                activator = null;\n            }\n        }\n        return null;\n    }\n}\n", "human_rating": 2.724764736, "metadata": {"project": "argoUML", "class": "org.argouml.sequence2.diagram.FigMessage", "source_path": "argoUML/sourcefiles/src/argouml-core-diagrams-sequence2/src/org/argouml/sequence2/diagram/FigMessage.java", "label_probabilities": {"readability": [0.000477674, 0.727781, 0.26777, 0.00397104], "understandability": [4.6932e-08, 0.991684, 0.00831642, 3.35336e-12], "complexity": [0.313478, 0.424887, 0.261635, 7e-20], "modularization": [2.65368e-08, 0.210027, 0.789973, 1.42825e-08], "overall": [4.595e-16, 5.73583e-06, 0.611055, 0.388939]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.ui.cmd.ShortcutField", "source": "/* $Id: ShortcutField.java 17842 2010-01-12 19:21:22Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2006-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.ui.cmd;\n\nimport java.awt.KeyboardFocusManager;\nimport java.awt.event.KeyEvent;\nimport java.awt.event.KeyListener;\nimport java.util.Collections;\n\nimport javax.swing.JTextField;\nimport javax.swing.KeyStroke;\nimport javax.swing.event.EventListenerList;\n\nimport org.argouml.util.KeyEventUtils;\n\n/**\n * A special JTextField that records key strokes\n *\n * @author nirux\n */\npublic class ShortcutField extends JTextField {\n\n    /**\n     * The UID\n     */\n    private static final long serialVersionUID = -62483698420802557L;\n\n    private EventListenerList listenerList = new EventListenerList();\n\n    /**\n     * Main constructor for ShortcutField\n     * \n     * @param text      the initial text of the field\n     * @param columns   the number of columns\n     */\n    public ShortcutField(String text, int columns) {\n        super(null, text, columns);\n        \n        // trap focus traversal keys also \n        this.setFocusTraversalKeys(\n                KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, \n                Collections.EMPTY_SET); \n        this.setFocusTraversalKeys(\n                KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, \n                Collections.EMPTY_SET); \n \n        // let's add the key printing logic\n        this.addKeyListener(new KeyListener() { \n            private int currentKeyCode = 0; \n            public void keyPressed(KeyEvent ke) { \n                ke.consume(); \n                JTextField tf = (JTextField) ke.getSource(); \n                tf.setText(toString(ke)); \n            } \n \n            public void keyReleased(KeyEvent ke) { \n                ke.consume(); \n                JTextField tf = (JTextField) ke.getSource(); \n                switch(currentKeyCode) { \n                case KeyEvent.VK_ALT: \n                case KeyEvent.VK_ALT_GRAPH: \n                case KeyEvent.VK_CONTROL: \n                case KeyEvent.VK_SHIFT: \n                    tf.setText(\"\"); \n                    return; \n                } \n            } \n \n            public void keyTyped(KeyEvent ke) { \n                ke.consume(); \n            } \n            \n            private String toString(KeyEvent ke) { \n                currentKeyCode = ke.getKeyCode(); \n                int keyCode = currentKeyCode; \n                String modifText = \n                    KeyEventUtils.getModifiersText(ke.getModifiers());\n                \n                if (\"\".equals(modifText)) {\n                    // no modifiers - let's check if the key is valid\n                    if (KeyEventUtils.isActionEvent(ke)) {\n                        return KeyEventUtils.getKeyText(keyCode);\n                    } else {\n                        return \"\";\n                    }\n                } else {\n                    switch(keyCode) { \n                    case KeyEvent.VK_ALT: \n                    case KeyEvent.VK_ALT_GRAPH: \n                    case KeyEvent.VK_CONTROL: \n                    case KeyEvent.VK_SHIFT: \n                        return modifText; // middle of shortcut \n                    default: \n                        modifText += KeyEventUtils.getKeyText(ke.getKeyCode());\n                        fireShortcutChangedEvent(modifText);\n                        return modifText;\n                    }\n                } \n            } \n        });\n    }\n\n    /**\n     * Adds a ShortcutChangedListener to the listener list\n     *  \n     * @param listener          the ShortcutChangedListener to be added\n     */\n    public void addShortcutChangedListener(ShortcutChangedListener listener) {\n        listenerList.add(ShortcutChangedListener.class, listener);\n    }\n\n    /**\n     * Inform listeners of any shortcut notifications.\n     * \n     * @param text      the text of the field\n     */\n    protected void fireShortcutChangedEvent(String text) {\n        ShortcutChangedEvent event = null;\n        // Guaranteed to return a non-null array\n        Object[] listeners = listenerList.getListenerList();\n\n        KeyStroke keyStroke = ShortcutMgr.decodeKeyStroke(text);\n\n        // Process the listeners last to first, notifying\n        // those that are interested in this event\n        for (int i = listeners.length - 2; i >= 0; i -= 2) {\n            if (listeners[i] == ShortcutChangedListener.class) {\n                // Lazily create the event:\n                if (event == null) {\n                    event = new ShortcutChangedEvent(this, keyStroke);\n                }\n                ((ShortcutChangedListener) listeners[i + 1])\n                        .shortcutChange(event);\n            }\n        }\n    }\n}\n", "human_rating": 3.999871517, "metadata": {"project": "argoUML", "class": "org.argouml.ui.cmd.ShortcutField", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/ui/cmd/ShortcutField.java", "label_probabilities": {"readability": [0.999872, 0.000127839, 3e-20, 0.0], "understandability": [0.00105809, 0.998935, 6.4894e-06, 1e-20], "complexity": [1.38117e-07, 0.895009, 0.104991, 4.90838e-08], "modularization": [0.0, 7.21282e-15, 0.999675, 0.000325138], "overall": [7.80593e-05, 0.990595, 0.0093268, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.ui.explorer.ExplorerTreeModel", "source": "/* $Id: ExplorerTreeModel.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.ui.explorer;\n\nimport java.awt.EventQueue;\nimport java.awt.event.ItemEvent;\nimport java.awt.event.ItemListener;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.Comparator;\nimport java.util.Enumeration;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.tree.DefaultMutableTreeNode;\nimport javax.swing.tree.DefaultTreeModel;\nimport javax.swing.tree.MutableTreeNode;\nimport javax.swing.tree.TreeNode;\nimport javax.swing.tree.TreePath;\n\nimport org.argouml.kernel.Project;\nimport org.argouml.kernel.ProjectManager;\nimport org.argouml.model.InvalidElementException;\nimport org.argouml.ui.explorer.rules.PerspectiveRule;\n\n/**\n * The model for the Explorer tree view of the uml model.\n *\n * provides:\n *  - receives events from the uml model and updates itself and the tree ui.\n *  - responds to changes in perspective and ordering.\n *\n * @author  alexb\n * @since 0.15.2\n */\npublic class ExplorerTreeModel extends DefaultTreeModel\n\t\timplements TreeModelUMLEventListener, ItemListener {\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(ExplorerTreeModel.class.getName());\n\n    /**\n     * an array of\n     * {@link org.argouml.ui.explorer.rules.PerspectiveRule PerspectiveRules},\n     * that determine the tree view.\n     */\n    private List<PerspectiveRule> rules;\n\n    /**\n     * a map used to resolve model elements to tree nodes when determining\n     * what effect a model event will have on the tree.\n     */\n    private Map<Object, Set<ExplorerTreeNode>> modelElementMap;\n\n    /**\n     * the global order for siblings in the tree.\n     */\n    private Comparator order;\n\n    /**\n     * The children currently being updated.\n     */\n    private List<ExplorerTreeNode> updatingChildren =\n            new ArrayList<ExplorerTreeNode>();\n\n    /**\n     * A Runnable object that when executed does update some\n     * currently pending nodes.\n     */\n    private ExplorerUpdater nodeUpdater = new ExplorerUpdater();\n\n    private ExplorerTree tree;\n\n    /**\n     * Help class to semi-lazily update nodes in the tree.\n     * This class is thread safe.\n     */\n    class ExplorerUpdater implements Runnable {\n\t/**\n\t * The set of nodes pending being updated.\n\t */\n\tprivate LinkedList<ExplorerTreeNode> pendingUpdates =\n\t    new LinkedList<ExplorerTreeNode>();\n\n\t/**\n\t * Is this object currently waiting to be run.\n\t */\n\tprivate boolean hot;\n\n\t/**\n         * The maximum number of nodes to update in one chunk.\n         */\n\tpublic static final int MAX_UPDATES_PER_RUN = 100;\n\n\t/**\n\t * Schedule this object to run on AWT-EventQueue-0 at some later time.\n\t */\n\tprivate synchronized void schedule() {\n\t    if (hot) {\n                return;\n            }\n\t    hot = true;\n\t    EventQueue.invokeLater(this);\n\t}\n\n\t/**\n\t * Schedule updateChildren to be called on node at some later time.\n\t * Does nothing if there already is a pending update of node.\n\t *\n\t * @param node The ExplorerTreeNode to be updated.\n\t * @throws NullPointerException If node is null.\n\t */\n\tpublic synchronized void schedule(ExplorerTreeNode node) {\n\t    if (node.getPending()) {\n                return;\n            }\n\n\t    pendingUpdates.add(node);\n\t    node.setPending(true);\n\t    schedule();\n\t}\n\n\t/**\n\t * Call updateChildren for some pending nodes. Will call at most\n\t * MAX_UPDATES_PER_RUN each time. Should there still be pending\n\t * updates after that then it will reschedule itself.<p>\n\t *\n\t * This method should not be called explicitly, instead schedule\n\t * should be called and this method will be called automatically.\n\t */\n\tpublic void run() {\n\t    boolean done = false;\n\n\t    for (int i = 0; i < MAX_UPDATES_PER_RUN; i++) {\n\t\tExplorerTreeNode node = null;\n\t\tsynchronized (this) {\n\t\t    if (!pendingUpdates.isEmpty()) {\n\t\t\tnode = pendingUpdates.removeFirst();\n\t\t\tnode.setPending(false);\n\t\t    } else {\n\t\t\tdone = true;\n\t\t\thot = false;\n\t\t\tbreak;\n\t\t    }\n\t\t}\n\n\t\tupdateChildren(new TreePath(getPathToRoot(node)));\n\t    }\n\n\t    if (!done) {\n\t\tschedule();\n            } else {\n                // TODO: This seems like a brute force workaround (and a very\n                // indirect one at that).  It appears to be needed though until\n                // we fix the problem properly. - tfm 20070904\n                /* This solves issue 2287. */\n                tree.refreshSelection();\n            }\n\t}\n    }\n\n    /**\n     * The constructor of ExplorerTreeModel.\n     *\n     * @param root an object to place at the root\n     * @param myTree the tree\n     */\n    public ExplorerTreeModel(Object root, ExplorerTree myTree) {\n\tsuper(new DefaultMutableTreeNode());\n\n        tree = myTree;\n\tsetRoot(new ExplorerTreeNode(root, this));\n\tsetAsksAllowsChildren(false);\n\tmodelElementMap = new HashMap<Object, Set<ExplorerTreeNode>>();\n\n\tExplorerEventAdaptor.getInstance()\n\t    .setTreeModelUMLEventListener(this);\n\n\torder = new TypeThenNameOrder();\n    }\n\n    /*\n     * @see org.argouml.ui.explorer.TreeModelUMLEventListener#modelElementChanged(java.lang.Object)\n     */\n    public void modelElementChanged(Object node) {\n        traverseModified((TreeNode) getRoot(), node);\n    }\n\n    /*\n     * @see org.argouml.ui.explorer.TreeModelUMLEventListener#modelElementAdded(java.lang.Object)\n     */\n    public void modelElementAdded(Object node) {\n        traverseModified((TreeNode) getRoot(), node);\n    }\n\n    /**\n     * Traverses the children, finds those affected by the given node,\n     * and notifies them that they are modified.\n     *\n     * @param start the node to start from\n     * @param node the given node\n     */\n    private void traverseModified(TreeNode start, Object node) {\n\tEnumeration children = start.children();\n\twhile (children.hasMoreElements()) {\n\t    TreeNode child = (TreeNode) children.nextElement();\n\t    traverseModified(child, node);\n\t}\n\n\tif (start instanceof ExplorerTreeNode) {\n\t    ((ExplorerTreeNode) start).nodeModified(node);\n\t}\n    }\n\n    /*\n     * @see org.argouml.ui.explorer.TreeModelUMLEventListener#modelElementRemoved(java.lang.Object)\n     */\n    public void modelElementRemoved(Object node) {\n        for (ExplorerTreeNode changeNode\n                : new ArrayList<ExplorerTreeNode>(findNodes(node))) {\n            if (changeNode.getParent() != null) {\n                removeNodeFromParent(changeNode);\n            }\n        }\n\n        traverseModified((TreeNode) getRoot(), node);\n    }\n\n    /*\n     * the model structure has changed significantly, eg a new project.\n     * @see org.argouml.ui.explorer.TreeModelUMLEventListener#structureChanged()\n     */\n    public void structureChanged() {\n\t// remove references for gc\n\tif (getRoot() instanceof ExplorerTreeNode) {\n            ((ExplorerTreeNode) getRoot()).remove();\n        }\n\n\t// This should only be helpful for old garbage collectors.\n\tfor (Collection nodes : modelElementMap.values()) {\n\t    nodes.clear();\n\t}\n\tmodelElementMap.clear();\n\n\t// This is somewhat inconsistent with the design of the constructor\n\t// that receives the root object by argument. If this is okay\n\t// then there may be no need for a constructor with that argument.\n\tmodelElementMap = new HashMap<Object, Set<ExplorerTreeNode>>();\n\tProject proj = ProjectManager.getManager().getCurrentProject();\n\tExplorerTreeNode rootNode = new ExplorerTreeNode(proj, this);\n\n\taddToMap(proj, rootNode);\n\tsetRoot(rootNode);\n    }\n\n    /**\n     * updates next level of the explorer tree for a given tree path.\n     *\n     * @param path the path to the node whose children to update.\n     * @throws IllegalArgumentException if node has a child that is not a\n     *         (descendant of) DefaultMutableTreeNode.\n     */\n    public void updateChildren(TreePath path) {\n\tExplorerTreeNode node = (ExplorerTreeNode) path.getLastPathComponent();\n        Object modelElement = node.getUserObject();\n\n\t// Avoid doing this too early in the initialization process\n\tif (rules == null) {\n\t    return;\n\t}\n\n\t// Avoid recursively updating the same child\n\tif (updatingChildren.contains(node)) {\n\t    return;\n\t}\n\tupdatingChildren.add(node);\n\n\tList children = reorderChildren(node);\n\n\tList newChildren = new ArrayList();\n\tSet deps = new HashSet();\n\tcollectChildren(modelElement, newChildren, deps);\n\n\tnode.setModifySet(deps);\n\n\tmergeChildren(node, children, newChildren);\n\n\tupdatingChildren.remove(node);\n    }\n\n    /**\n     * Sorts the child nodes of node using the current ordering.<p>\n     *\n     * Note: UserObject is only available from descendants of\n     * DefaultMutableTreeNode, so any other children couldn't be sorted.\n     * Thus these are currently forbidden. But currently no such node is\n     * ever inserted into the tree.\n     *\n     * @param node the node whose children to sort\n     * @return the UserObjects of the children, in the same order as the\n     *         children.\n     * @throws IllegalArgumentException if node has a child that is not a\n     *         (descendant of) DefaultMutableTreeNode.\n     */\n    private List<Object> reorderChildren(ExplorerTreeNode node) {\n\tList<Object> childUserObjects = new ArrayList<Object>();\n\tList<ExplorerTreeNode> reordered = new ArrayList<ExplorerTreeNode>();\n\n\t// Enumerate the current children of node to find out which now sorts\n\t// in different order, since these must be moved\n\tEnumeration enChld = node.children();\n\tObject lastObj = null;\n\twhile (enChld.hasMoreElements()) {\n\t    Object child = enChld.nextElement();\n\t    if (child instanceof ExplorerTreeNode) {\n\t\tObject obj = ((ExplorerTreeNode) child).getUserObject();\n\t\tif (lastObj != null && order.compare(lastObj, obj) > 0) {\n\t\t    /*\n\t\t     * If a node to be moved is currently selected,\n\t\t     * move its predecessors instead so don't lose selection.\n\t\t     * This fixes issue 3249.\n\t\t     * NOTE: this does not deal with the case where\n                     * multiple nodes are selected and they are out\n                     * of order with respect to each other, but I\n                     * don't think more than one node is ever reordered\n\t\t     * at a time - tfm\n\t\t     */\n\t\t    if (!tree.isPathSelected(new TreePath(\n                            getPathToRoot((ExplorerTreeNode) child)))) {\n\t\t\treordered.add((ExplorerTreeNode) child);\n\t\t    } else {\n\t\t        ExplorerTreeNode prev =\n\t\t            (ExplorerTreeNode) ((ExplorerTreeNode) child)\n                                .getPreviousSibling();\n\t\t\twhile (prev != null\n                                && (order.compare(prev.getUserObject(), obj)\n                                        >= 0)) {\n\t\t\t    reordered.add(prev);\n\t\t\t    childUserObjects.remove(childUserObjects.size() - 1);\n\t\t\t    prev = (ExplorerTreeNode) prev.getPreviousSibling();\n\t\t\t}\n\t\t\tchildUserObjects.add(obj);\n\t\t\tlastObj = obj;\n\t\t    }\n\t\t} else {\n\t\t    childUserObjects.add(obj);\n\t\t    lastObj = obj;\n\t\t}\n\t    } else {\n\t\tthrow new IllegalArgumentException(\n\t\t\t\"Incomprehencible child node \" + child.toString());\n\t    }\n\t}\n\n\tfor (ExplorerTreeNode child : reordered) {\n\t    // Avoid our deinitialization here\n\t    // The node will be added back to the tree again\n\t    super.removeNodeFromParent(child);\n\t}\n\n\t// For each reordered node, find it's new position among the current\n\t// children and move it there\n        for (ExplorerTreeNode child : reordered) {\n\t    Object obj = child.getUserObject();\n\t    int ip = Collections.binarySearch(childUserObjects, obj, order);\n\n\t    if (ip < 0) {\n\t\tip = -(ip + 1);\n\t    }\n\n\t    // Avoid our initialization here\n\t    super.insertNodeInto(child, node, ip);\n\t    childUserObjects.add(ip, obj);\n\t}\n\n\treturn childUserObjects;\n    }\n\n    /**\n     * Collects the set of children modelElement should have at this point in\n     * time. The children are added to newChildren.<p>\n     *\n     * Note: Both newChildren and deps are modified by this function, it\n     * is in fact it's primary purpose to modify these collections. It is your\n     * responsibility to make sure that they are empty when it is called, or\n     * to know what you are doing if they are not.\n     *\n     * @param modelElement the element to collect children for.\n     * @param newChildren the new children of modelElement.\n     * @param deps the set of objects that should be monitored for changes\n     *        since these could affect this list.\n     * @throws UnsupportedOperationException if add is not supported by\n     *         newChildren or addAll isn't supported by deps.\n     * @throws NullPointerException if newChildren or deps is null.\n     * @throws ClassCastException if newChildren or deps rejects some element.\n     * @throws IllegalArgumentException if newChildren or deps rejects some\n     *         element.\n     */\n    private void collectChildren(Object modelElement, List newChildren,\n\t\t\t\t Set deps) {\n\tif (modelElement == null) {\n\t    return;\n\t}\n\n\t// Collect the current set of objects that should be children to\n\t// this node\n        for (PerspectiveRule rule : rules) {\n\n            // TODO: A better implementation would be to batch events into\n            // logical groups and update the tree one time for the entire\n            // group, synchronizing access to the model repository so that\n            // it stays consistent during the query.  This would likely\n            // require doing the updates in a different thread than the\n            // event delivery thread to prevent deadlocks, so for right now\n            // we protect ourselves with try/catch blocks.\n            Collection children = Collections.emptySet();\n            try {\n                children = rule.getChildren(modelElement);\n            } catch (InvalidElementException e) {\n                LOG.log(Level.FINE, \"InvalidElementException in ExplorerTree : \", e );\n            }\n\n            for (Object child : children) {\n                if (child == null) {\n                    LOG.log(Level.WARNING, \"PerspectiveRule \" + rule + \" wanted to \"\n                            + \"add null to the explorer tree!\");\n                } else if (!newChildren.contains(child)) {\n                    newChildren.add(child);\n                }\n            }\n\n\n            try {\n                Set dependencies = rule.getDependencies(modelElement);\n                deps.addAll(dependencies);\n            } catch (InvalidElementException e) {\n                LOG.log(Level.FINE, \"InvalidElementException in ExplorerTree : \", e );\n            }\n\n        }\n\n\t// Order the new children, the dependencies cannot and\n\t// need not be ordered\n\tCollections.sort(newChildren, order);\n\tdeps.addAll(newChildren);\n    }\n\n    /**\n     * Returns a Set of current children to remove and modifies newChildren\n     * to only contain the children not already in children and not subsumed\n     * by any WeakExplorerNode in children.<p>\n     *\n     * Note: newChildren will be modified by this call.<p>\n     *\n     * Note: It is expected that a WeakExplorerNode will not be reused and\n     * thus they will always initially be slated for removal, and only those\n     * nodes are in fact used to check subsumption of new nodes. New nodes\n     * are not checked among themselves for subsumtion.\n     *\n     * @param children is the list of current children.\n     * @param newChildren is the list of expected children.\n     * @return the Set of current children to remove.\n     * @throws UnsupportedOperationException if newChildren doesn't support\n     *         remove or removeAll.\n     * @throws NullPointerException if either argument is null.\n     */\n    private Set prepareAddRemoveSets(List children, List newChildren) {\n\tSet removeSet = new HashSet();\n\tSet commonObjects = new HashSet();\n\tif (children.size() < newChildren.size()) {\n\t    commonObjects.addAll(children);\n\t    commonObjects.retainAll(newChildren);\n\t} else {\n\t    commonObjects.addAll(newChildren);\n\t    commonObjects.retainAll(children);\n\t}\n\tnewChildren.removeAll(commonObjects);\n\tremoveSet.addAll(children);\n\tremoveSet.removeAll(commonObjects);\n\n\t// Handle WeakExplorerNodes\n\tIterator it = removeSet.iterator();\n\tList weakNodes = null;\n\twhile (it.hasNext()) {\n\t    Object obj = it.next();\n\t    if (!(obj instanceof WeakExplorerNode)) {\n\t\tcontinue;\n\t    }\n\t    WeakExplorerNode node = (WeakExplorerNode) obj;\n\n\t    if (weakNodes == null) {\n\t\tweakNodes = new LinkedList();\n\t\tIterator it2 = newChildren.iterator();\n\t\twhile (it2.hasNext()) {\n\t\t    Object obj2 = it2.next();\n\t\t    if (obj2 instanceof WeakExplorerNode) {\n\t\t\tweakNodes.add(obj2);\n\t\t    }\n\t\t}\n\t    }\n\n\t    Iterator it3 = weakNodes.iterator();\n\t    while (it3.hasNext()) {\n\t\tObject obj3 = it3.next();\n\t\tif (node.subsumes(obj3)) {\n\t\t    // Remove the node from removeSet\n\t\t    it.remove();\n\t\t    // Remove obj3 from weakNodes and newChildren\n\t\t    newChildren.remove(obj3);\n\t\t    it3.remove();\n\t\t    break;\n\t\t}\n\t    }\n\t}\n\n\treturn removeSet;\n    }\n\n    /**\n     * Merges the current children with the new children removing children no\n     * longer present and adding new children in the right place.\n     *\n     * @param node the TreeNode were merging lists for.\n     * @param children the current child UserObjects, in order.\n     * @param newChildren the expected child UserObjects, in order.\n     * @throws UnsupportedOperationException if the Iterator returned by\n     *         newChildren doesn't support the remove operation, or if\n     *         newChildren itself doesn't support remove or removeAll.\n     * @throws NullPointerException if node, children or newChildren are null.\n     */\n    private void mergeChildren(ExplorerTreeNode node, List children,\n\t\t\t       List newChildren) {\n\tSet removeObjects = prepareAddRemoveSets(children, newChildren);\n\t// Remember that children are not TreeNodes but UserObjects\n\tList<ExplorerTreeNode> actualNodes = new ArrayList<ExplorerTreeNode>();\n\tEnumeration childrenEnum = node.children();\n\twhile (childrenEnum.hasMoreElements()) {\n\t    actualNodes.add((ExplorerTreeNode) childrenEnum.nextElement());\n\t}\n\n\tint position = 0;\n\tIterator childNodes = actualNodes.iterator();\n\tIterator newNodes = newChildren.iterator();\n\tObject firstNew = newNodes.hasNext() ? newNodes.next() : null;\n\twhile (childNodes.hasNext()) {\n\t    Object childObj = childNodes.next();\n\t    if (!(childObj instanceof ExplorerTreeNode)) {\n\t\tcontinue;\n\t    }\n\n\t    ExplorerTreeNode child = (ExplorerTreeNode) childObj;\n\t    Object userObject = child.getUserObject();\n\n\t    if (removeObjects.contains(userObject)) {\n\t\tremoveNodeFromParent(child);\n\t    } else {\n\t\twhile (firstNew != null\n\t\t       && order.compare(firstNew, userObject) < 0) {\n\t\t    insertNodeInto(new ExplorerTreeNode(firstNew, this),\n\t\t\t\t   node,\n\t\t\t\t   position);\n\t\t    position++;\n\t\t    firstNew = newNodes.hasNext() ? newNodes.next() : null;\n\t\t}\n\t\tposition++;\n\t    }\n\t}\n\n\t// Add any remaining nodes\n\twhile (firstNew != null) {\n\t    insertNodeInto(new ExplorerTreeNode(firstNew, this),\n\t\t\t   node,\n\t\t\t   position);\n\t    position++;\n\t    firstNew = newNodes.hasNext() ? newNodes.next() : null;\n\t}\n    }\n\n    /*\n     * @see javax.swing.tree.DefaultTreeModel#insertNodeInto(javax.swing.tree.MutableTreeNode, javax.swing.tree.MutableTreeNode, int)\n     */\n    @Override\n    public void insertNodeInto(MutableTreeNode newChild,\n\t\t\t       MutableTreeNode parent, int index) {\n\tsuper.insertNodeInto(newChild, parent, index);\n        if (newChild instanceof ExplorerTreeNode) {\n            addNodesToMap((ExplorerTreeNode) newChild);\n        }\n    }\n\n    /*\n     * @see javax.swing.tree.DefaultTreeModel#removeNodeFromParent(javax.swing.tree.MutableTreeNode)\n     */\n    @Override\n    public void removeNodeFromParent(MutableTreeNode node) {\n\tif (node instanceof ExplorerTreeNode) {\n\t    removeNodesFromMap((ExplorerTreeNode) node);\n\t    ((ExplorerTreeNode) node).remove();\n\t}\n\tsuper.removeNodeFromParent(node);\n    }\n\n    /**\n     * Map all nodes in the subtree rooted at node.\n     *\n     * @param node the node to be added\n     */\n    private void addNodesToMap(ExplorerTreeNode node) {\n\tEnumeration children = node.children();\n\twhile (children.hasMoreElements()) {\n\t    ExplorerTreeNode child = (ExplorerTreeNode) children.nextElement();\n\t    addNodesToMap(child);\n\t}\n\taddToMap(node.getUserObject(), node);\n    }\n\n    /**\n     * Unmap all nodes in the subtree rooted at the given node.\n     *\n     * @param node the given node\n     */\n    private void removeNodesFromMap(ExplorerTreeNode node) {\n\tEnumeration children = node.children();\n\twhile (children.hasMoreElements()) {\n\t    ExplorerTreeNode child = (ExplorerTreeNode) children.nextElement();\n\t    removeNodesFromMap(child);\n\t}\n\tremoveFromMap(node.getUserObject(), node);\n    }\n\n    /**\n     * Adds a new tree node and model element to the map.\n     * nodes are removed from the map when a {@link #modelElementRemoved(Object)\n     * modelElementRemoved} event is received.\n     *\n     * @param modelElement the modelelement to be added\n     * @param node the node to be added\n     */\n    private void addToMap(Object modelElement, ExplorerTreeNode node) {\n\tSet<ExplorerTreeNode> nodes = modelElementMap.get(modelElement);\n\n\tif (nodes != null) {\n\t    nodes.add(node);\n\t} else {\n\t    nodes = new HashSet<ExplorerTreeNode>();\n\t    nodes.add(node);\n\t    modelElementMap.put(modelElement, nodes);\n\t}\n    }\n\n    /**\n     * removes a new tree node and model element from the map.\n     *\n     * @param modelElement the modelelement to be removed\n     * @param node the node to be removed\n     */\n    private void removeFromMap(Object modelElement, ExplorerTreeNode node) {\n\tCollection<ExplorerTreeNode> nodes = modelElementMap.get(modelElement);\n\tif (nodes != null) {\n\t    nodes.remove(node);\n\t    if (nodes.isEmpty()) {\n                modelElementMap.remove(modelElement);\n            }\n\t}\n    }\n\n    /**\n     * Node lookup for a given model element.\n     *\n     * @param modelElement the given modelelement\n     * @return the nodes sought\n     */\n    private Collection<ExplorerTreeNode> findNodes(Object modelElement) {\n\tCollection<ExplorerTreeNode> nodes = modelElementMap.get(modelElement);\n\n\tif (nodes == null) {\n\t    return Collections.EMPTY_LIST;\n\t}\n        return nodes;\n    }\n\n    /**\n     * Updates the explorer for new perspectives / orderings.\n     *\n     * {@inheritDoc}\n     */\n    public void itemStateChanged(ItemEvent e) {\n\tif (e.getSource() instanceof PerspectiveComboBox) {\n            rules = ((ExplorerPerspective) e.getItem()).getList();\n\t} else { // it is the combo for \"order\"\n\t    order = (Comparator) e.getItem();\n\t}\n\tstructureChanged();\n\t// TODO: temporary - let tree expand implicitly - tfm\n\ttree.expandPath(tree.getPathForRow(1));\n    }\n\n    /**\n     * @return Returns the nodeUpdater.\n     */\n    ExplorerUpdater getNodeUpdater() {\n        return nodeUpdater;\n    }\n\n    /**\n     * The UID.\n     */\n    private static final long serialVersionUID = 3132732494386565870L;\n}\n", "human_rating": 3.29718220231265, "metadata": {"project": "argoUML", "class": "org.argouml.ui.explorer.ExplorerTreeModel", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/ui/explorer/ExplorerTreeModel.java", "label_probabilities": {"readability": [0.310328, 0.676527, 0.0131446, 2.31265e-09], "understandability": [0.0, 0.875816, 0.12408, 0.00010383], "complexity": [0.0343718, 0.816161, 0.149467, 0.0], "modularization": [0.000265336, 0.881963, 0.117772, 0.0], "overall": [2.827e-07, 0.236097, 0.70733, 0.0565721]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.ui.explorer.rules.AbstractPerspectiveRule", "source": "/* $Id: AbstractPerspectiveRule.java 17844 2010-01-12 19:35:07Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.ui.explorer.rules;\n\nimport java.util.Collection;\n\n/**\n *\n * @author  alexb\n */\npublic abstract class AbstractPerspectiveRule implements PerspectiveRule {\n\n    /*\n     * @see org.argouml.ui.explorer.rules.PerspectiveRule#getRuleName()\n     */\n    public abstract String getRuleName();\n\n    /*\n     * @see org.argouml.ui.explorer.rules.PerspectiveRule#getChildren(java.lang.Object)\n     */\n    public abstract Collection getChildren(Object parent);\n\n    /*\n     * @see java.lang.Object#toString()\n     */\n    public String toString() {\n        return getRuleName();\n    }\n\n}\n", "human_rating": 3.9998458279999998, "metadata": {"project": "argoUML", "class": "org.argouml.ui.explorer.rules.AbstractPerspectiveRule", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/ui/explorer/rules/AbstractPerspectiveRule.java", "label_probabilities": {"readability": [0.999845, 0.000155276, 1.6e-19, 0.0], "understandability": [0.989843, 0.0101574, 4.54508e-10, 0.0], "complexity": [0.0, 0.0, 1.21932e-07, 1.0], "modularization": [0.0, 2.13674e-13, 0.00696887, 0.993031], "overall": [0.997367, 0.0026326, 2.961e-17, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.ui.explorer.rules.GoStateToDoActivity", "source": "/* $Id: GoStateToDoActivity.java 17844 2010-01-12 19:35:07Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\n\npackage org.argouml.ui.explorer.rules;\n\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.Model;\n\n/**\n * Go rule to navigate from a state to it's do-activity. Used in the package\n * perspective.\n *\n * @author jaap.branderhorst@xs4all.nl\n * @since Dec 25, 2002\n */\npublic class GoStateToDoActivity extends AbstractPerspectiveRule {\n\n    /*\n     * @see org.argouml.ui.explorer.rules.PerspectiveRule#getChildren(java.lang.Object)\n     */\n    public Collection getChildren(Object parent) {\n        if (Model.getFacade().isAState(parent)\n                && Model.getFacade().getDoActivity(parent) != null) {\n            Collection children = new ArrayList();\n\n            children.add(Model.getFacade().getDoActivity(parent));\n            return children;\n        }\n        return Collections.EMPTY_SET;\n    }\n\n    /*\n     * @see org.argouml.ui.explorer.rules.PerspectiveRule#getDependencies(java.lang.Object)\n     */\n    public Set getDependencies(Object parent) {\n        if (Model.getFacade().isAState(parent)) {\n\t    Set set = new HashSet();\n\t    set.add(parent);\n\t    return set;\n\t}\n\treturn Collections.EMPTY_SET;\n    }\n\n    /*\n     * @see org.argouml.ui.explorer.rules.PerspectiveRule#getRuleName()\n     */\n    public String getRuleName() {\n        return Translator.localize(\"misc.state.do-activity\");\n    }\n\n}\n", "human_rating": 3.624805872000078, "metadata": {"project": "argoUML", "class": "org.argouml.ui.explorer.rules.GoStateToDoActivity", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/ui/explorer/rules/GoStateToDoActivity.java", "label_probabilities": {"readability": [0.62559, 0.373625, 0.000785436, 7.84167e-14], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.ui.SettingsTabLayout", "source": "/* $Id: SettingsTabLayout.java 17841 2010-01-12 19:17:52Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.ui;\n\nimport java.awt.BorderLayout;\n\nimport javax.swing.BorderFactory;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.SwingConstants;\n\nimport org.argouml.application.api.GUISettingsTabInterface;\nimport org.argouml.configuration.Configuration;\nimport org.argouml.configuration.ConfigurationKey;\nimport org.argouml.i18n.Translator;\nimport org.tigris.swidgets.Property;\n\n/**\n * Settings dialog tab panel for layout options.<p>\n *\n * TODO: This class contains a lot of references to org.argouml.uml.ui.\n * It would probably be better to move it there.\n * \n * TODO: This class breaks too many dependency limitations. \n * And it is not used anywhere. So I (MVW) disabled its functionality. \n *\n * @author Linus Tolke\n */\nclass SettingsTabLayout extends JPanel\n    implements GUISettingsTabInterface {\n\n//    private Property\tprpTodo;\n//    private Property\tprpProperties;\n//    private Property\tprpDocumentation;\n//    private Property\tprpStyle;\n//    private Property\tprpSource;\n//    private Property\tprpConstraints;\n//    private Property\tprpTaggedValues;\n\n    /**\n     * The constructor.\n     *\n     */\n    SettingsTabLayout() {\n        super();\n        setLayout(new BorderLayout());\n\n        // TODO: Localize these\n        final String[] positions = {\"North\", \"South\", \"East\"};\n        final String paneColumnHeader = \"Pane\";\n        final String positionColumnHeader = \"Position\";\n\n        JPanel top = new JPanel(new BorderLayout());\n\n//        prpTodo = createProperty(\"label.todo-pane\", positions, TabToDo.class);\n//        prpProperties =\n//            createProperty(\"label.properties-pane\",\n//                    positions, TabProps.class);\n//        prpDocumentation =\n//            createProperty(\"label.documentation-pane\",\n//                    positions, TabDocumentation.class);\n//        prpStyle =\n//            createProperty(\"label.style-pane\",\n//                    positions, TabStyle.class);\n//        prpSource =\n//            createProperty(\"label.source-pane\",\n//                    positions, TabSrc.class);\n//        prpConstraints =\n//            createProperty(\"label.constraints-pane\",\n//                    positions, TabConstraints.class);\n//        prpTaggedValues =\n//            createProperty(\"label.tagged-values-pane\",\n//                    positions, TabTaggedValues.class);\n//\n//        Property[] propertyList = new Property[] {\n//            prpTodo, prpProperties, prpDocumentation, prpStyle,\n//\t    prpSource, prpConstraints, prpTaggedValues,\n//        };\n//        Arrays.sort(propertyList);\n//\n//        top.add(new JScrollPane(new PropertyTable(\n//\t\t\t\t\t\t  propertyList,\n//\t\t\t\t\t\t  paneColumnHeader,\n//\t\t\t\t\t\t  positionColumnHeader)),\n//\t\tBorderLayout.CENTER);\n\n        top.setBorder(BorderFactory.createEmptyBorder(10, 10, 0, 10));\n        add(top, BorderLayout.CENTER);\n\n        JLabel restart =\n            new JLabel(Translator.localize(\"label.restart-application\"));\n        restart.setHorizontalAlignment(SwingConstants.CENTER);\n        restart.setVerticalAlignment(SwingConstants.CENTER);\n        restart.setBorder(BorderFactory.createEmptyBorder(10, 2, 10, 2));\n        add(restart, BorderLayout.SOUTH);\n    }\n\n    /**\n     * Create a Property for the position of the given tab pane, selecting\n     * the current display value from the user properties file.\n     */\n    private Property createProperty(String text, String[] positions,\n\t\t\t\t    Class tab) {\n        ConfigurationKey key = makeKey(tab);\n        String currentValue = Configuration.getString(key, \"South\");\n        return new Property(Translator.localize(text), String.class,\n\t\t\t    currentValue, positions);\n    }\n\n    private void loadPosition(Property position, Class tab) {\n        ConfigurationKey key = makeKey(tab);\n        position.setCurrentValue(Configuration.getString(key, \"South\"));\n    }\n\n    private void savePosition(Property position, Class tab) {\n        ConfigurationKey key = makeKey(tab);\n        Configuration.setString(key, position.getCurrentValue().toString());\n    }\n\n    private ConfigurationKey makeKey(Class tab) {\n        String className = tab.getName();\n        String shortClassName =\n\t    className.substring(className.lastIndexOf('.') + 1).toLowerCase();\n        ConfigurationKey key = Configuration.makeKey(\"layout\", shortClassName);\n        return key;\n    }\n\n    /**\n     * When the setting values should be reloaded.\n     */\n    public void handleSettingsTabRefresh() {\n//        loadPosition(prpTodo, TabToDo.class);\n//        loadPosition(prpProperties, TabProps.class);\n//        loadPosition(prpDocumentation, TabDocumentation.class);\n//        loadPosition(prpStyle, TabStyle.class);\n//        loadPosition(prpSource, TabSrc.class);\n//        loadPosition(prpConstraints, TabConstraints.class);\n//        loadPosition(prpTaggedValues, TabTaggedValues.class);\n    }\n\n    /**\n     * When the ok or apply button is pressed.\n     */\n    public void handleSettingsTabSave() {\n//        savePosition(prpTodo, TabToDo.class);\n//        savePosition(prpProperties, TabProps.class);\n//        savePosition(prpDocumentation, TabDocumentation.class);\n//        savePosition(prpStyle, TabStyle.class);\n//        savePosition(prpSource, TabSrc.class);\n//        savePosition(prpConstraints, TabConstraints.class);\n//        savePosition(prpTaggedValues, TabTaggedValues.class);\n    }\n\n    /*\n     * @see GUISettingsTabInterface#handleSettingsTabCancel()\n     */\n    public void handleSettingsTabCancel() { }\n\n    /*\n     * @see org.argouml.ui.GUISettingsTabInterface#handleResetToDefault()\n     */\n    public void handleResetToDefault() {\n        // Do nothing - these buttons are not shown.\n    }\n\n    /*\n     * @see GUISettingsTabInterface#getTabKey()\n     */\n    public String getTabKey() { return \"tab.layout\"; }\n\n    /*\n     * @see GUISettingsTabInterface#getTabPanel()\n     */\n    public JPanel getTabPanel() { return this; }\n\n    /**\n     * The UID.\n     */\n    private static final long serialVersionUID = 739259705815092510L;\n}\n", "human_rating": 3.005248807, "metadata": {"project": "argoUML", "class": "org.argouml.ui.SettingsTabLayout", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/ui/SettingsTabLayout.java", "label_probabilities": {"readability": [0.00625837, 0.992837, 0.000800063, 0.000104201], "understandability": [0.0148572, 0.974543, 0.00945726, 0.00114267], "complexity": [1.25621e-15, 2.72772e-05, 0.165537, 0.834436], "modularization": [0.0, 0.00040178, 0.997402, 0.00219637], "overall": [0.0, 0.779858, 0.220142, 9.08e-18]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.ui.ZoomSliderButton", "source": "/* $Id: ZoomSliderButton.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2003-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.ui;\n\nimport java.awt.BorderLayout;\nimport java.awt.Component;\nimport java.awt.Dimension;\nimport java.awt.FlowLayout;\nimport java.awt.Font;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.FocusAdapter;\nimport java.awt.event.FocusEvent;\nimport java.awt.event.MouseEvent;\nimport java.util.Enumeration;\n\nimport javax.swing.AbstractAction;\nimport javax.swing.Icon;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JPopupMenu;\nimport javax.swing.JSlider;\nimport javax.swing.JTextField;\nimport javax.swing.event.ChangeEvent;\nimport javax.swing.event.ChangeListener;\nimport javax.swing.event.MouseInputAdapter;\nimport javax.swing.event.PopupMenuEvent;\nimport javax.swing.event.PopupMenuListener;\n\nimport org.argouml.application.helpers.ResourceLoaderWrapper;\nimport org.argouml.i18n.Translator;\nimport org.tigris.gef.base.Editor;\nimport org.tigris.gef.base.Globals;\nimport org.tigris.swidgets.PopupButton;\n\n/**\n * A button that can be used to change the zoom magnification of the current\n * diagram. When the user presses the button, a popup is displayed which\n * contains a vertical slider representing the range of zoom magnifications.\n * Dragging the slider changes the zoom magnification for the current diagram.\n *\n * @author Jeremy Jones\n */\npublic class ZoomSliderButton extends PopupButton {\n\n    /**\n     * Used for loading the zoom icon from the Zoom Reset action.\n     */\n    private static final String RESOURCE_NAME = \"Zoom Reset\";\n\n    /**\n     * Font used for the slider tick labels and for the current magnification\n     * value label.\n     */\n    private static final Font LABEL_FONT = new Font(\"Dialog\", Font.PLAIN, 10);\n\n    /**\n     * The minimum zoom slider value (as percentage).\n     */\n    public static final int MINIMUM_ZOOM = 25;\n\n    /**\n     * The maximum zoom slider value (as percentage).\n     */\n    public static final int MAXIMUM_ZOOM = 300;\n\n    /**\n     * The preferred height of the slider component.\n     */\n    private static final int SLIDER_HEIGHT = 250;\n\n    /**\n     * The slider component.\n     */\n    private JSlider slider = null;\n\n    /**\n     * The text field which shows the current zoom magnification value.\n     */\n    private JTextField currentValue = null;\n\n    /**\n     * Used to enable/disable the popup button.\n     */\n    private boolean popupButtonIsActive = true;\n\n    /**\n     * Indicates whether the popupmenu is showing or not.\n     */\n    private boolean popupMenuIsShowing = false;\n\n    /**\n     * Indicates whether the mouse is over the popup button or not.\n     */\n    private boolean mouseIsOverPopupButton = false;\n\n    /**\n     * Constructs a new ZoomSliderButton.\n     */\n    public ZoomSliderButton() {\n        super();\n        setAction(new AbstractAction() {\n            public void actionPerformed(ActionEvent e) {\n                /* If action comes in with *no* modifiers, it is a pure\n                 * keyboard event (e.g. spacebar), so do it.  Anything else\n                 * is probably a mouse event, so ignore it. Mouse events are\n                 * dealt with by mousePressed() instead (see bottom of page).\n                 */ \n                if (e.getModifiers() == 0) {\n                    showPopup();\n                }\n            }\n        });\n\n        Icon icon = ResourceLoaderWrapper.lookupIcon(RESOURCE_NAME);\n\n        MyMouseListener myMouseListener = new MyMouseListener();\n        addMouseMotionListener(myMouseListener);\n        addMouseListener(myMouseListener);\n\n        setIcon(icon);\n        setToolTipText(Translator.localize(\"button.zoom\"));\n    }\n\n    /**\n     * Creates the slider popup component.\n     */\n    private void createPopupComponent() {\n        slider =\n            new JSlider(\n                    JSlider.VERTICAL,\n                    MINIMUM_ZOOM,\n                    MAXIMUM_ZOOM,\n                    MINIMUM_ZOOM);\n        slider.setInverted(true);\n        slider.setMajorTickSpacing(25);\n        slider.setMinorTickSpacing(5);\n        slider.setPaintTicks(true);\n        slider.setPaintTrack(true);\n        int sliderBaseWidth = slider.getPreferredSize().width;\n        slider.setPaintLabels(true);\n\n        for (Enumeration components = slider.getLabelTable().elements();\n             components.hasMoreElements();) {\n            ((Component) components.nextElement()).setFont(LABEL_FONT);\n        }\n\n        slider.setToolTipText(Translator.localize(\n                \"button.zoom.slider-tooltip\"));\n\n        slider.addChangeListener(new ChangeListener() {\n            public void stateChanged(ChangeEvent e) {\n                handleSliderValueChange();\n            }\n        });\n\n        int labelWidth =\n            slider.getFontMetrics(LABEL_FONT).stringWidth(\n                    String.valueOf(MAXIMUM_ZOOM)) + 6;\n\n        slider.setPreferredSize(new Dimension(\n            sliderBaseWidth + labelWidth, SLIDER_HEIGHT));\n\n        currentValue = new JTextField(5);\n        currentValue.setHorizontalAlignment(JLabel.CENTER);\n        currentValue.setFont(LABEL_FONT);\n        currentValue.setToolTipText(Translator.localize(\n            \"button.zoom.current-zoom-magnification\"));\n        updateCurrentValueLabel();\n        currentValue.addActionListener(new ActionListener() {\n            public void actionPerformed(ActionEvent e) {\n                handleTextEntry();\n            }\n        });\n        currentValue.addFocusListener(new FocusAdapter() {\n            @Override\n            public void focusLost(FocusEvent e) {\n                handleTextEntry();\n            }\n        });\n\n        JPanel currentValuePanel =\n            new JPanel(new FlowLayout(\n                    FlowLayout.CENTER, 0, 0));\n        currentValuePanel.add(currentValue);\n\n        JPanel zoomPanel = new JPanel(new BorderLayout(0, 0));\n        zoomPanel.add(slider, BorderLayout.CENTER);\n        zoomPanel.add(currentValuePanel, BorderLayout.NORTH);\n\n        setPopupComponent(zoomPanel);\n    }\n\n    /**\n     * Update the slider value every time the popup is shown.\n     */\n    @Override\n    protected void showPopup() {\n        if (slider == null) {\n            createPopupComponent();\n        }\n\n        Editor ed = Globals.curEditor();\n        if (ed != null) {\n            slider.setValue((int) (ed.getScale() * 100d));\n        }\n\n        if ( popupButtonIsActive ) {\n            super.showPopup();\n            JPopupMenu pm = (JPopupMenu) this.getPopupComponent().getParent();\n            PopupMenuListener pml = new MyPopupMenuListener();\n            pm.addPopupMenuListener(pml);\n            popupMenuIsShowing = true;\n        }\n        slider.requestFocus();\n    }\n\n    /**\n     * Called when the slider value changes.\n     */\n    private void handleSliderValueChange() {\n        updateCurrentValueLabel();\n\n        //if (!source.getValueIsAdjusting()) {\n        double zoomPercentage = slider.getValue() / 100d;\n\n        Editor ed = Globals.curEditor();\n        if (ed == null || zoomPercentage <= 0.0) {\n            return;\n        }\n\n        if (zoomPercentage != ed.getScale()) {\n            ed.setScale(zoomPercentage);\n            ed.damageAll();\n        }\n        //}\n    }\n\n    /**\n     * Called when the text field value changes.\n     */\n    private void handleTextEntry() {\n        String value = currentValue.getText();\n        if (value.endsWith(\"%\")) {\n            value = value.substring(0, value.length() - 1);\n        }\n        try {\n            int newZoom = Integer.parseInt(value);\n            if (newZoom < MINIMUM_ZOOM || newZoom > MAXIMUM_ZOOM) {\n                throw new NumberFormatException();\n            }\n            slider.setValue(newZoom);\n        } catch (NumberFormatException ex) {\n            updateCurrentValueLabel();\n        }\n    }\n\n    /**\n     * Sets the current value label's text to the current slider value.\n     */\n    private void updateCurrentValueLabel() {\n        currentValue.setText(String.valueOf(slider.getValue()) + '%');\n    }\n    \n    private class MyPopupMenuListener extends AbstractAction implements\n        PopupMenuListener {\n\n\t/**\n         * Empty method to satisfy interface.\n         */\n\tpublic void actionPerformed(ActionEvent e) {\n        }\n\n        /**\n         * Method gets fired when the popup dies.\n         * Conditionally re-enable the button depending on where the pointer \n         * is.\n         */\n        public void popupMenuCanceled(PopupMenuEvent e) {\n            if (mouseIsOverPopupButton) {\n                popupButtonIsActive = false;\n            } else {\n                popupButtonIsActive = true;\n            }\n            popupMenuIsShowing = false;\n        }\n\n        public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {\n        }\n\n        public void popupMenuWillBecomeVisible(PopupMenuEvent e) {\n        }\n\n    }\n\n    private class MyMouseListener extends MouseInputAdapter {\n\n        /**\n         * Keeps track of mouseover status. \n         */\n        @Override\n        public void mouseEntered(MouseEvent me) {\n            mouseIsOverPopupButton = true;\n        }\n        \n        /**\n         * Keeps track of mouseover status, and renables button if necessary.\n         */\n        @Override\n        public void mouseExited(MouseEvent me) {\n            mouseIsOverPopupButton = false;\n            if (!popupButtonIsActive && !popupMenuIsShowing)\n            {\n                popupButtonIsActive = true;\n            }\n        }\n\n        /**\n         * Catch the down stroke of mouse click to make the popup appear a tiny\n         * bit earlier.\n         */\n        @Override\n        public void mousePressed(MouseEvent me) {\n            if (popupButtonIsActive) {\n                showPopup();\n            }\n            else if ( !popupMenuIsShowing )\n            {\n                popupButtonIsActive = true;\n            }\n        }\n    }\n}\n", "human_rating": 3.0136185023000004, "metadata": {"project": "argoUML", "class": "org.argouml.ui.ZoomSliderButton", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/ui/ZoomSliderButton.java", "label_probabilities": {"readability": [0.029332, 0.954998, 0.0156261, 4.43023e-05], "understandability": [0.000188948, 0.276109, 0.707136, 0.0165661], "complexity": [0.0077364, 0.392712, 0.599551, 6.74932e-08], "modularization": [5.54443e-07, 0.168712, 0.829111, 0.00217636], "overall": [0.0011249, 0.721043, 0.277832, 3.41147e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.cognitive.checklist.Init", "source": "/* $Id: Init.java 19444 2011-05-17 07:23:39Z bobtarling $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.cognitive.checklist;\n\nimport org.argouml.cognitive.checklist.CheckItem;\nimport org.argouml.cognitive.checklist.CheckManager;\nimport org.argouml.cognitive.checklist.Checklist;\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.Model;\n\n\n/**\n * Registers Checklists for different kinds of model elements. If you\n * add a new checklist, a line must be added here.\n *\n * @see org.argouml.cognitive.checklist.CheckManager\n */\npublic class Init {\n    /**\n     * static initializer, register all appropriate critics.\n     */\n    public static void init() {\n\tcreateChecklists();\n    }\n\n\n    /**\n     * Creat a check item (an UMLCheckItem) corresponding to the given key.\n     * and add it to the given checklist.\n     *\n     * @param category to add the item to.\n     * @param key to get the localized string.\n     * @param checklist to add the item to.\n     */\n    private static void newCheckItem(String category, String key,\n\t\t\t\t     Checklist checklist) {\n\tCheckItem checkitem =\n\t    new UMLCheckItem(category, Translator.localize(key));\n\tchecklist.add(checkitem);\n    }\n\n    /**\n     * Create all check lists.<p>\n     *\n     * This is the new implementation and a change from the old implementation\n     * in that the source code (i.e. this function) contains knowledge on\n     * what to check.<p>\n     *\n     * The purpose of this is to allow the ArgoUML project to jointly develop\n     * the knowledge database and let the internationalizations be just\n     * internationalizations.<p>\n     *\n     * When adding a new check list or an item to an existing check list you\n     * will have to:<ol>\n     * <li>Add the lines in this function.\n     * <li>Add the tags for the new items to the i18n property file\n     *     (checklist.properties).\n     * <li>Notify the localization teams.\n     * </ol>\n     */\n    private static void createChecklists() {\n\t//\n\t// This function will, by design, contain long lists of i18n keys.\n\t// It might be tempting to shorten these by constructing them from\n\t// the parts but please then consider that we might loose the\n\t// possibility to build tools to statically check the property files\n\t// against this file.\n\t//\n\tChecklist cl;\n\tString cat;\n\n\t// Class\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.class.naming\");\n\tnewCheckItem(cat, \"checklist.class.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.class.naming.is-noun\", cl);\n\tnewCheckItem(cat, \"checklist.class.naming.misinterpret\", cl);\n\n\tcat = Translator.localize(\"checklist.class.encoding\");\n\tnewCheckItem(cat, \"checklist.class.encoding.convert-to-attribute\", cl);\n\tnewCheckItem(cat, \"checklist.class.encoding.do-just-one-thing\", cl);\n\tnewCheckItem(cat, \"checklist.class.encoding.break-into-parts\", cl);\n\n\tcat = Translator.localize(\"checklist.class.value\");\n\tnewCheckItem(cat, \"checklist.class.value.start-with-meaningful-values\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.class.value.convert-to-invariant\", cl);\n\tnewCheckItem(cat,\n\t\t \"checklist.class.value.establish-invariant-in-constructors\",\n\t\t cl);\n\tnewCheckItem(cat, \"checklist.class.value.maintain-invariant\", cl);\n\n\tcat = Translator.localize(\"checklist.class.location\");\n\tnewCheckItem(cat, \"checklist.class.location.move-somewhere\", cl);\n\tnewCheckItem(cat, \"checklist.class.location.planned-subclasses\", cl);\n\tnewCheckItem(cat, \"checklist.class.location.eliminate-from-model\", cl);\n\tnewCheckItem(cat,\n\t        \"checklist.class.location.eliminates-or-affects-something-else\",\n\t\tcl);\n\n\tcat = Translator.localize(\"checklist.class.updates\");\n        newCheckItem(cat, \"checklist.class.updates.reasons-for-update\", cl);\n\tnewCheckItem(cat, \"checklist.class.updates.affects-something-else\", cl);\n\n\tCheckManager.register(Model.getMetaTypes().getUMLClass(), cl);\n\n\n\t// Attribute\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.attribute.naming\");\n\tnewCheckItem(cat, \"checklist.attribute.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.attribute.naming.is-noun\", cl);\n\tnewCheckItem(cat, \"checklist.attribute.naming.misinterpret\", cl);\n\n\tcat = Translator.localize(\"checklist.attribute.encoding\");\n\tnewCheckItem(cat, \"checklist.attribute.encoding.is-too-restrictive\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t\t     \"checklist.attribute.encoding.allow-impossible-values\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.attribute.encoding.combine-with-other\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.attribute.encoding.break-into-parts\", cl);\n\tnewCheckItem(cat, \"checklist.attribute.encoding.is-computable\", cl);\n\n\tcat = Translator.localize(\"checklist.attribute.value\");\n\tnewCheckItem(cat, \"checklist.attribute.value.default-value\", cl);\n\tnewCheckItem(cat, \"checklist.attribute.value.correct-default-value\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.attribute.value.is-correctness-checkable\",\n\t\t     cl);\n\n\tcat = Translator.localize(\"checklist.attribute.location\");\n\tnewCheckItem(cat, \"checklist.attribute.location.move-somewhere\", cl);\n\tnewCheckItem(cat, \"checklist.attribute.location.move-up-hierarchy\", cl);\n\tnewCheckItem(cat, \"checklist.attribute.location.include-all\", cl);\n\tnewCheckItem(cat, \"checklist.attribute.location.could-be-eliminated\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.attribute.location.eliminates-or-affects-something-else\",\n\t    cl);\n\n\tcat = Translator.localize(\"checklist.attribute.updates\");\n        newCheckItem(cat, \"checklist.attribute.updates.reasons-for-update\", cl);\n\tnewCheckItem(cat, \"checklist.attribute.updates.affects-something-else\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t\t     \"checklist.attribute.updates.exists-method-for-update\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.attribute.updates.exists-method-for-specific-value\",\n\t    cl);\n\n\tCheckManager.register(Model.getMetaTypes().getAttribute(), cl);\n\n\n\t// Operation\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.operation.naming\");\n\tnewCheckItem(cat, \"checklist.operation.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.operation.naming.is-verb\", cl);\n\tnewCheckItem(cat, \"checklist.operation.naming.misinterpret\", cl);\n\tnewCheckItem(cat, \"checklist.operation.naming.do-just-one-thing\", cl);\n\n\tcat = Translator.localize(\"checklist.operation.encoding\");\n\tnewCheckItem(cat,\n\t    \"checklist.operation.encoding.is-returntype-too-restrictive\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.operation.encoding.does-returntype-allow-impossible-\"\n            + \"values\", cl);\n\tnewCheckItem(cat,\n            \"checklist.operation.encoding.combine-with-other\", cl);\n\tnewCheckItem(cat, \"checklist.operation.encoding.break-into-parts\", cl);\n\tnewCheckItem(cat, \"checklist.operation.encoding.break-into-series\", cl);\n\tnewCheckItem(cat, \"checklist.operation.encoding.reduce-number-of-calls\",\n\t\t     cl);\n\n\tcat = Translator.localize(\"checklist.operation.value\");\n\tnewCheckItem(cat, \"checklist.operation.value.handle-all-inputs\", cl);\n\tnewCheckItem(cat, \"checklist.operation.value.are-special-cases\", cl);\n\tnewCheckItem(cat, \"checklist.operation.value.is-correctness-checkable\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t\t     \"checklist.operation.value.express-preconditions-possible\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.operation.value.express-postconditions-possible\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.operation.value.how-behave-preconditions-violated\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.operation.value.how-behave-postconditions-not-achieved\",\n\t    cl);\n\n\tcat = Translator.localize(\"checklist.operation.location\");\n\tnewCheckItem(cat, \"checklist.operation.location.move-somewhere\", cl);\n\tnewCheckItem(cat, \"checklist.operation.location.move-up-hierarchy\", cl);\n\tnewCheckItem(cat, \"checklist.operation.location.include-all\", cl);\n\tnewCheckItem(cat, \"checklist.operation.location.could-be-eliminated\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.operation.location.eliminates-or-affects-something-else\",\n\t    cl);\n\n\tCheckManager.register(Model.getMetaTypes().getOperation(), cl);\n\n\n\n\t// Association\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.association.naming\");\n\tnewCheckItem(cat, \"checklist.association.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.association.naming.is-noun\", cl);\n\tnewCheckItem(cat, \"checklist.association.naming.misinterpret\", cl);\n\n\tcat = Translator.localize(\"checklist.association.encoding\");\n\tnewCheckItem(cat, \"checklist.association.encoding.convert-to-attribute\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.association.encoding.do-just-one-thing\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.association.encoding.break-into-parts\",\n\t\t     cl);\n\n\tcat = Translator.localize(\"checklist.association.value\");\n\tnewCheckItem(cat,\n\t\t     \"checklist.association.value.start-with-meaningful-values\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.association.value.convert-to-invariant\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.association.value.establish-invariant-in-constructors\",\n\t    cl);\n\tnewCheckItem(cat, \"checklist.association.value.maintain-invariant\", cl);\n\n\tcat = Translator.localize(\"checklist.association.location\");\n\tnewCheckItem(cat, \"checklist.association.location.move-somewhere\", cl);\n\tnewCheckItem(cat, \"checklist.association.location.planned-subclasses\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.association.location.eliminate-from-model\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.association.location.eliminates-or-affects-\"\n            + \"something-else\", cl);\n\n\tcat = Translator.localize(\"checklist.association.updates\");\n\tnewCheckItem(cat, \"checklist.association.updates.reasons-for-update\",\n\t\t     cl);\n\tnewCheckItem(cat,\n            \"checklist.association.updates.affects-something-else\",\n\t    cl);\n\n\tCheckManager.register(Model.getMetaTypes().getAssociation(), cl);\n\n\n\t// Interface\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.interface.naming\");\n\tnewCheckItem(cat, \"checklist.interface.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.interface.naming.is-noun\", cl);\n\tnewCheckItem(cat, \"checklist.interface.naming.misinterpret\", cl);\n\n\tcat = Translator.localize(\"checklist.interface.encoding\");\n\tnewCheckItem(cat, \"checklist.interface.encoding.convert-to-attribute\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.interface.encoding.do-just-one-thing\", cl);\n\tnewCheckItem(cat, \"checklist.interface.encoding.break-into-parts\", cl);\n\n\tcat = Translator.localize(\"checklist.interface.value\");\n\tnewCheckItem(cat,\n\t\t     \"checklist.interface.value.start-with-meaningful-values\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.interface.value.convert-to-invariant\", cl);\n\tnewCheckItem(cat,\n\t    \"checklist.interface.value.establish-invariant-in-constructors\",\n\t    cl);\n\tnewCheckItem(cat, \"checklist.interface.value.maintain-invariant\", cl);\n\n\tcat = Translator.localize(\"checklist.interface.location\");\n\tnewCheckItem(cat, \"checklist.interface.location.move-somewhere\", cl);\n\tnewCheckItem(cat, \"checklist.interface.location.planned-subclasses\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.interface.location.eliminate-from-model\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.interface.location.eliminates-or-affects-something-else\",\n\t    cl);\n\n\tcat = Translator.localize(\"checklist.interface.updates\");\n\tnewCheckItem(cat, \"checklist.interface.updates.reasons-for-update\", cl);\n\tnewCheckItem(cat, \"checklist.interface.updates.affects-something-else\",\n\t\t     cl);\n\n\tCheckManager.register(Model.getMetaTypes().getInterface(), cl);\n\n\n\t// Instance\n\tif (Model.getFacade().getUmlVersion().startsWith(\"1\")) {\n            cl = new Checklist();\n    \n            cat = Translator.localize(\"checklist.instance.general\");\n            newCheckItem(cat, \"checklist.instance.general.describe-clearly\", cl);\n    \n            cat = Translator.localize(\"checklist.instance.naming\");\n            newCheckItem(cat, \"checklist.instance.naming.describe-clearly\", cl);\n            newCheckItem(cat, \"checklist.instance.naming.denotes-state\", cl);\n            newCheckItem(cat, \"checklist.instance.naming.misinterpret\", cl);\n    \n            cat = Translator.localize(\"checklist.instance.structure\");\n            newCheckItem(cat, \"checklist.instance.structure.merged-with-other\", cl);\n            newCheckItem(cat, \"checklist.instance.structure.do-just-one-thing\", cl);\n            newCheckItem(cat, \"checklist.instance.structure.break-into-parts\", cl);\n            newCheckItem(cat,\n                \"checklist.instance.structure.can-write-characteristic-equation\",\n                cl);\n            newCheckItem(cat, \"checklist.instance.structure.belong\", cl);\n            newCheckItem(cat, \"checklist.instance.structure.make-internal\", cl);\n            newCheckItem(cat,\n                \"checklist.instance.structure.is-state-in-another-machine-\"\n                + \"exclusive\", cl);\n    \n            cat = Translator.localize(\"checklist.instance.actions\");\n            newCheckItem(cat, \"checklist.instance.actions.list-entry-actions\", cl);\n            newCheckItem(cat,\n                \"checklist.instance.actions.update-attribute-on-entry\",\n                cl);\n            newCheckItem(cat, \"checklist.instance.actions.list-exit-action\", cl);\n            newCheckItem(cat, \"checklist.instance.actions.update-attribute-on-exit\",\n                cl);\n            newCheckItem(cat, \"checklist.instance.actions.list-do-action\", cl);\n            newCheckItem(cat, \"checklist.instance.actions.maintained-state\", cl);\n            cat = Translator.localize(\"checklist.instance.transitions\");\n            newCheckItem(cat,\n                \"checklist.instance.transitions.need-another-transition-into\",\n                cl);\n            newCheckItem(cat,\n                \"checklist.instance.transitions.use-all-transitions-into\",\n                cl);\n            newCheckItem(cat,\n                \"checklist.instance.transitions.combine-with-other-incoming\",\n                cl);\n            newCheckItem(cat,\n                \"checklist.instance.transitions.need-another-transition-out-of\",\n                cl);\n            newCheckItem(cat,\n                \"checklist.instance.transitions.use-all-transitions-out-of\",\n                cl);\n            newCheckItem(cat,\n                \"checklist.instance.transitions.are-transitions-out-of-exclusive\",\n                cl);\n            newCheckItem(cat,\n                \"checklist.instance.transitions.combine-with-other-outgoing\",\n                cl);\n            CheckManager.register(Model.getMetaTypes().getInstance(), cl);\n\t}\n\n\t// Link\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.link.naming\");\n\tnewCheckItem(cat, \"checklist.link.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.link.naming.is-noun\", cl);\n\tnewCheckItem(cat, \"checklist.link.naming.misinterpret\", cl);\n\n\tcat = Translator.localize(\"checklist.link.encoding\");\n\tnewCheckItem(cat, \"checklist.link.encoding.convert-to-attribute\", cl);\n\tnewCheckItem(cat, \"checklist.link.encoding.do-just-one-thing\", cl);\n\tnewCheckItem(cat, \"checklist.link.encoding.break-into-parts\", cl);\n\n\tcat = Translator.localize(\"checklist.link.value\");\n\tnewCheckItem(cat, \"checklist.link.value.start-with-meaningful-values\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.link.value.convert-to-invariant\", cl);\n\tnewCheckItem(cat,\n\t\t     \"checklist.link.value.establish-invariant-in-constructors\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.link.value.maintain-invariant\", cl);\n\n\tcat = Translator.localize(\"checklist.link.location\");\n\tnewCheckItem(cat, \"checklist.link.location.move-somewhere\", cl);\n\tnewCheckItem(cat, \"checklist.link.location.planned-subclasses\", cl);\n\tnewCheckItem(cat, \"checklist.link.location.eliminate-from-model\", cl);\n\tnewCheckItem(cat,\n\t    \"checklist.link.location.eliminates-or-affects-something-else\",\n\t    cl);\n\n\tcat = Translator.localize(\"checklist.link.updates\");\n\tnewCheckItem(cat, \"checklist.link.updates.reasons-for-update\", cl);\n\tnewCheckItem(cat, \"checklist.link.updates.affects-something-else\", cl);\n\n\tCheckManager.register(Model.getMetaTypes().getLink(), cl);\n\n\n\t// State\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.state.naming\");\n\tnewCheckItem(cat, \"checklist.state.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.state.naming.denotes-state\", cl);\n\tnewCheckItem(cat, \"checklist.state.naming.misinterpret\", cl);\n\n\tcat = Translator.localize(\"checklist.state.structure\");\n\tnewCheckItem(cat, \"checklist.state.structure.merged-with-other\", cl);\n\tnewCheckItem(cat, \"checklist.state.structure.do-just-one-thing\", cl);\n\tnewCheckItem(cat, \"checklist.state.structure.break-into-parts\", cl);\n\tnewCheckItem(cat,\n\t    \"checklist.state.structure.can-write-characteristic-equation\",\n\t    cl);\n\tnewCheckItem(cat, \"checklist.state.structure.belong\", cl);\n\tnewCheckItem(cat, \"checklist.state.structure.make-internal\", cl);\n\tnewCheckItem(cat,\n\t    \"checklist.state.structure.is-state-in-another-machine-exclusive\",\n\t    cl);\n\n\tcat = Translator.localize(\"checklist.state.actions\");\n\tnewCheckItem(cat, \"checklist.state.actions.list-entry-actions\", cl);\n\tnewCheckItem(cat, \"checklist.state.actions.update-attribute-on-entry\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.state.actions.list-exit-action\", cl);\n\tnewCheckItem(cat, \"checklist.state.actions.update-attribute-on-exit\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.state.actions.list-do-action\", cl);\n\tnewCheckItem(cat, \"checklist.state.actions.maintained-state\", cl);\n\n\tcat = Translator.localize(\"checklist.state.transitions\");\n\tnewCheckItem(cat,\n\t    \"checklist.state.transitions.need-another-transition-into\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.state.transitions.use-all-transitions-into\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.state.transitions.combine-with-other-incoming\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.state.transitions.need-another-transition-out-of\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.state.transitions.use-all-transitions-out-of\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.state.transitions.are-transitions-out-of-exclusive\",\n\t    cl);\n\tnewCheckItem(cat,\n\t    \"checklist.state.transitions.combine-with-other-outgoing\",\n\t    cl);\n\n\tCheckManager.register(Model.getMetaTypes().getState(), cl);\n\n\n\t// Transition\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.transition.structure\");\n\tnewCheckItem(cat, \"checklist.transition.structure.start-somewhere-else\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.transition.structure.end-somewhere-else\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t\t     \"checklist.transition.structure.need-another-like-this\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t\t     \"checklist.transition.structure.unneeded-because-of-this\",\n\t\t     cl);\n\n\tcat = Translator.localize(\"checklist.transition.trigger\");\n\tnewCheckItem(cat, \"checklist.transition.trigger.needed\", cl);\n\tnewCheckItem(cat, \"checklist.transition.trigger.happen-too-often\", cl);\n\tnewCheckItem(cat, \"checklist.transition.trigger.happen-too-rarely\", cl);\n\n\tcat = Translator.localize(\"checklist.transition.guard\");\n\tnewCheckItem(cat, \"checklist.transition.guard.taken-too-often\", cl);\n\tnewCheckItem(cat, \"checklist.transition.guard.is-too-restrictive\", cl);\n\tnewCheckItem(cat, \"checklist.transition.guard.break-into-parts\", cl);\n\n\tcat = Translator.localize(\"checklist.transition.actions\");\n\tnewCheckItem(cat, \"checklist.transition.actions.should-have\", cl);\n\tnewCheckItem(cat, \"checklist.transition.actions.should-have-exit\", cl);\n\tnewCheckItem(cat, \"checklist.transition.actions.should-have-entry\", cl);\n\tnewCheckItem(cat, \"checklist.transition.actions.is-precondition-met\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.transition.actions.is-postcondition-consistant-with-\"\n            + \"destination\", cl);\n\n\tCheckManager.register(Model.getMetaTypes().getTransition(), cl);\n\n\n\t// Use Case\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.usecase.naming\");\n\tnewCheckItem(cat, \"checklist.usecase.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.usecase.naming.is-noun\", cl);\n\tnewCheckItem(cat, \"checklist.usecase.naming.misinterpret\", cl);\n\n\tcat = Translator.localize(\"checklist.usecase.encoding\");\n\tnewCheckItem(cat, \"checklist.usecase.encoding.convert-to-attribute\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.usecase.encoding.do-just-one-thing\", cl);\n\tnewCheckItem(cat, \"checklist.usecase.encoding.break-into-parts\", cl);\n\n\tcat = Translator.localize(\"checklist.usecase.value\");\n\tnewCheckItem(cat,\n\t\t     \"checklist.usecase.value.start-with-meaningful-values\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.usecase.value.convert-to-invariant\", cl);\n\tnewCheckItem(cat,\n\t    \"checklist.usecase.value.establish-invariant-in-constructors\",\n\t    cl);\n\tnewCheckItem(cat, \"checklist.usecase.value.maintain-invariant\", cl);\n\n\tcat = Translator.localize(\"checklist.usecase.location\");\n\tnewCheckItem(cat, \"checklist.usecase.location.move-somewhere\", cl);\n\tnewCheckItem(cat, \"checklist.usecase.location.planned-subclasses\", cl);\n\tnewCheckItem(cat, \"checklist.usecase.location.eliminate-from-model\",\n\t\t     cl);\n\tnewCheckItem(cat,\n\t    \"checklist.usecase.location.eliminates-or-affects-something-else\",\n\t    cl);\n\n\tcat = Translator.localize(\"checklist.usecase.updates\");\n\tnewCheckItem(cat, \"checklist.usecase.updates.reasons-for-update\", cl);\n\tnewCheckItem(cat, \"checklist.usecase.updates.affects-something-else\",\n\t\t     cl);\n\n\tCheckManager.register(Model.getMetaTypes().getUseCase(), cl);\n\n\n\t// Actor\n\tcl = new Checklist();\n\n\tcat = Translator.localize(\"checklist.actor.naming\");\n\tnewCheckItem(cat, \"checklist.actor.naming.describe-clearly\", cl);\n\tnewCheckItem(cat, \"checklist.actor.naming.is-noun\", cl);\n\tnewCheckItem(cat, \"checklist.actor.naming.misinterpret\", cl);\n\n\tcat = Translator.localize(\"checklist.actor.encoding\");\n\tnewCheckItem(cat, \"checklist.actor.encoding.convert-to-attribute\", cl);\n\tnewCheckItem(cat, \"checklist.actor.encoding.do-just-one-thing\", cl);\n\tnewCheckItem(cat, \"checklist.actor.encoding.break-into-parts\", cl);\n\n\tcat = Translator.localize(\"checklist.actor.value\");\n\tnewCheckItem(cat, \"checklist.actor.value.start-with-meaningful-values\",\n\t\t     cl);\n\tnewCheckItem(cat, \"checklist.actor.value.convert-to-invariant\", cl);\n\tnewCheckItem(cat,\n\t    \"checklist.actor.value.establish-invariant-in-constructors\",\n\t    cl);\n\tnewCheckItem(cat, \"checklist.actor.value.maintain-invariant\", cl);\n\n\tcat = Translator.localize(\"checklist.actor.location\");\n\tnewCheckItem(cat, \"checklist.actor.location.move-somewhere\", cl);\n\tnewCheckItem(cat, \"checklist.actor.location.planned-subclasses\", cl);\n\tnewCheckItem(cat, \"checklist.actor.location.eliminate-from-model\", cl);\n\tnewCheckItem(cat,\n            \"checklist.actor.location.eliminates-or-affects-something-else\",\n\t    cl);\n\n\tcat = Translator.localize(\"checklist.actor.updates\");\n\tnewCheckItem(cat, \"checklist.actor.updates.reasons-for-update\", cl);\n\tnewCheckItem(cat, \"checklist.actor.updates.affects-something-else\", cl);\n\n\tCheckManager.register(Model.getMetaTypes().getActor(), cl);\n\n    }\n\n}\n", "human_rating": 3.9999968216300004, "metadata": {"project": "argoUML", "class": "org.argouml.uml.cognitive.checklist.Init", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/cognitive/checklist/Init.java", "label_probabilities": {"readability": [0.999998, 1.60721e-06, 0.0, 0.0], "understandability": [3.91162e-06, 0.999996, 1.41145e-07, 0.0], "complexity": [0.0, 5.86e-18, 0.00754875, 0.992451], "modularization": [0.0, 0.0, 0.999997, 3.17624e-06], "overall": [2.22e-18, 0.999818, 0.000182269, 3e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.cognitive.critics.CrCircularInheritance", "source": "/* $Id: CrCircularInheritance.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    maurelio1234\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.cognitive.critics;\n\nimport java.util.HashSet;\nimport java.util.Set;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.argouml.cognitive.Critic;\nimport org.argouml.cognitive.Designer;\nimport org.argouml.cognitive.ToDoItem;\nimport org.argouml.model.Model;\nimport org.argouml.uml.cognitive.UMLDecision;\n\n/**\n * Well-formedness rule [2] for GeneralizableElement. See page 31 of UML 1.1\n * Semantics. OMG document ad/97-08-04.\n *\n * Well-formedness rule [3] for GeneralizableElement. See page 59 of UML 1.4\n * Semantics. OMG document UML 1.4.2 formal/04-07-02.\n *\n * @author jrobbins\n */\npublic class CrCircularInheritance extends CrUML {\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(CrCircularInheritance.class.getName());\n\n    /**\n     * The constructor.\n     */\n    public CrCircularInheritance() {\n        setupHeadAndDesc();\n\tsetPriority(ToDoItem.HIGH_PRIORITY);\n\taddSupportedDecision(UMLDecision.INHERITANCE);\n\tsetKnowledgeTypes(Critic.KT_SYNTAX);\n\taddTrigger(\"generalization\");\n\t// no need for trigger on \"specialization\"\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#predicate2(\n     *      java.lang.Object, org.argouml.cognitive.Designer)\n     */\n    @Override\n    public boolean predicate2(Object dm, Designer dsgr) {\n\tboolean problem = NO_PROBLEM;\n\tif (Model.getFacade().isAGeneralizableElement(dm)) {\n\t    try {\n\t\tModel.getCoreHelper().getChildren(dm);\n\t    } catch (IllegalStateException ex) {\n                problem = PROBLEM_FOUND;\n                LOG.log(Level.INFO, \"problem found for: {0}\", this);\n\t    }\n\t}\n\treturn problem;\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#getCriticizedDesignMaterials()\n     */\n    @Override\n    public Set<Object> getCriticizedDesignMaterials() {\n        Set<Object> ret = new HashSet<Object>();\n        ret.add(Model.getMetaTypes().getGeneralizableElement());\n        return ret;\n    }\n\n} /* end class CrCircularInheritance */\n", "human_rating": 3.7304071213708996, "metadata": {"project": "argoUML", "class": "org.argouml.uml.cognitive.critics.CrCircularInheritance", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/cognitive/critics/CrCircularInheritance.java", "label_probabilities": {"readability": [0.730586, 0.269235, 0.00017906, 1.3709e-09], "understandability": [0.642583, 0.357404, 1.21041e-05, 6.37924e-08], "complexity": [1.20681e-12, 1.67596e-05, 0.603246, 0.396737], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.907093, 0.0929066, 1.68325e-08, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.cognitive.critics.CrInvalidForkTriggerOrGuard", "source": "/* $Id: CrInvalidForkTriggerOrGuard.java 19577 2011-06-22 20:37:05Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    maurelio1234\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2003-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.cognitive.critics;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.argouml.cognitive.Designer;\nimport org.argouml.model.Model;\nimport org.argouml.uml.cognitive.UMLDecision;\n\n/**\n * UML 1.5 Well-formedness rule [1] for Transition, to remove\n * a trigger or guard from fork outgoing transition.\n *\n * Well-formedness rule [1] for Transition. See page 139 of UML 1.4\n * Semantics. OMG document UML 1.4.2 formal/04-07-02.\n *\n * @author pepargouml@yahoo.es\n */\npublic class CrInvalidForkTriggerOrGuard extends CrUML {\n\n    /**\n     * The constructor.\n     */\n    public CrInvalidForkTriggerOrGuard() {\n        setupHeadAndDesc();\n        addSupportedDecision(UMLDecision.STATE_MACHINES);\n        addTrigger(\"trigger\");\n        addTrigger(\"guard\");\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#predicate2(java.lang.Object,\n     *      org.argouml.cognitive.Designer)\n     */\n    @Override\n    public boolean predicate2(Object dm, Designer dsgr) {\n        if (!(Model.getFacade().isATransition(dm))) {\n            return NO_PROBLEM;\n        }\n        Object tr = dm;\n        Object t = Model.getFacade().getTrigger(tr);\n        Object g = Model.getFacade().getGuard(tr);\n        Object sv = Model.getFacade().getSource(tr);\n        if (!(Model.getFacade().isAPseudostate(sv))) {\n            return NO_PROBLEM;\n        }\n        Object k = Model.getFacade().getKind(sv);\n        if (!Model.getFacade().\n                equalsPseudostateKind(k,\n                        Model.getPseudostateKind().getFork())) {\n            return NO_PROBLEM;\n        }\n        boolean hasTrigger =\n                (t != null && Model.getFacade().getName(t) != null\n                && Model.getFacade().getName(t).length() > 0);\n        if (hasTrigger) {\n            return PROBLEM_FOUND;\n        }\n        boolean noGuard =\n            (g == null || Model.getFacade().getExpression(g) == null\n                || Model.getFacade().getBody(Model.getFacade()\n                        .getExpression(g)) == null\n                || Model.getFacade().getBody(Model.getFacade()\n                        .getExpression(g)).toString().length() == 0);\n        if (!noGuard) {\n            return PROBLEM_FOUND;\n        }\n        return NO_PROBLEM;\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#getCriticizedDesignMaterials()\n     */\n    @Override\n    public Set<Object> getCriticizedDesignMaterials() {\n        Set<Object> ret = new HashSet<Object>();\n        ret.add(Model.getMetaTypes().getTransition());\n        return ret;\n    }\n    \n    /**\n     * The UID.\n     */\n    private static final long serialVersionUID = -713044875133409390L;\n}\n", "human_rating": 3.00000769872, "metadata": {"project": "argoUML", "class": "org.argouml.uml.cognitive.critics.CrInvalidForkTriggerOrGuard", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/cognitive/critics/CrInvalidForkTriggerOrGuard.java", "label_probabilities": {"readability": [6.42468e-06, 0.999994, 0.0, 0.0], "understandability": [0.000143802, 0.447461, 0.551739, 0.00065676], "complexity": [0.0, 0.0, 0.0249573, 0.975043], "modularization": [4.08823e-09, 0.0204703, 0.00911013, 0.97042], "overall": [0.0, 0.994475, 3.15767e-08, 0.00552447]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.cognitive.critics.CrMissingClassName", "source": "/* $Id: CrMissingClassName.java 19577 2011-06-22 20:37:05Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    maurelio1234\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.cognitive.critics;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport javax.swing.Icon;\n\nimport org.argouml.cognitive.Critic;\nimport org.argouml.cognitive.Designer;\nimport org.argouml.cognitive.ToDoItem;\nimport org.argouml.cognitive.critics.Wizard;\nimport org.argouml.model.Model;\nimport org.argouml.uml.cognitive.UMLDecision;\n\n/**\n * This critics tests if a ModelElement has a name.\n */\npublic class CrMissingClassName extends CrUML {\n\n    /**\n     * The constructor.\n     */\n    public CrMissingClassName() {\n        setupHeadAndDesc();\n\taddSupportedDecision(UMLDecision.NAMING);\n\tsetKnowledgeTypes(Critic.KT_COMPLETENESS, Critic.KT_SYNTAX);\n\taddTrigger(\"name\");\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#predicate2(\n     *      java.lang.Object, org.argouml.cognitive.Designer)\n     */\n    @Override\n    public boolean predicate2(Object dm, Designer dsgr) {\n\tif (!(Model.getFacade().isAModelElement(dm))) {\n\t    return NO_PROBLEM;\n\t}\n\tObject e = dm;\n\tString myName = Model.getFacade().getName(e);\n\tif (myName == null || myName.equals(\"\") || myName.length() == 0) {\n\t    return PROBLEM_FOUND;\n\t}\n\treturn NO_PROBLEM;\n    }\n\n    /*\n     * @see org.argouml.cognitive.Poster#getClarifier()\n     */\n    @Override\n    public Icon getClarifier() {\n\treturn ClClassName.getTheInstance();\n    }\n\n    /*\n     * @see org.argouml.cognitive.critics.Critic#initWizard(\n     *         org.argouml.cognitive.ui.Wizard)\n     */\n    @Override\n    public void initWizard(Wizard w) {\n\tif (w instanceof WizMEName) {\n\t    ToDoItem item = (ToDoItem) w.getToDoItem();\n\t    Object me = item.getOffenders().get(0);\n\t    String ins = super.getInstructions();\n\t    String sug = super.getDefaultSuggestion();\n\t    int count = 1;\n\t    if (Model.getFacade().getNamespace(me) != null) {\n\t\tcount =\n\t\t    Model.getFacade().getOwnedElements(\n\t\t            Model.getFacade().getNamespace(me)).size();\n\t    }\n\t    sug = Model.getFacade().getUMLClassName(me) + (count + 1);\n\t    ((WizMEName) w).setInstructions(ins);\n\t    ((WizMEName) w).setSuggestion(sug);\n\t}\n    }\n\n    /*\n     * @see org.argouml.cognitive.critics.Critic#getWizardClass(org.argouml.cognitive.ToDoItem)\n     */\n    @Override\n    public Class getWizardClass(ToDoItem item) { return WizMEName.class; }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#getCriticizedDesignMaterials()\n     */\n    @Override\n    public Set<Object> getCriticizedDesignMaterials() {\n        Set<Object> ret = new HashSet<Object>();\n        ret.add(Model.getMetaTypes().getUMLClass());\n        return ret;\n    }\n    \n}\n", "human_rating": 3.6351765401254488, "metadata": {"project": "argoUML", "class": "org.argouml.uml.cognitive.critics.CrMissingClassName", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/cognitive/critics/CrMissingClassName.java", "label_probabilities": {"readability": [0.641942, 0.351292, 0.00676627, 1.25449e-10], "understandability": [0.544018, 0.450992, 0.00498935, 1.22217e-09], "complexity": [3.77698e-11, 0.00122445, 0.530956, 0.46782], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.0326977, 0.949994, 0.0173087, 4.76463e-08]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.cognitive.critics.CrMissingOperName", "source": "/* $Id: CrMissingOperName.java 19614 2011-07-20 12:10:13Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    maurelio1234\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.cognitive.critics;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.argouml.cognitive.Critic;\nimport org.argouml.cognitive.Designer;\nimport org.argouml.cognitive.ToDoItem;\nimport org.argouml.cognitive.critics.Wizard;\nimport org.argouml.model.Model;\nimport org.argouml.uml.cognitive.UMLDecision;\n\n/**\n * A critic to detect whether an operation has a name.\n */\npublic class CrMissingOperName extends CrUML {\n\n    /**\n     * The constructor.\n     */\n    public CrMissingOperName() {\n        setupHeadAndDesc();\n\taddSupportedDecision(UMLDecision.NAMING);\n\tsetKnowledgeTypes(Critic.KT_SYNTAX);\n\taddTrigger(\"name\");\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#predicate2(\n     *      java.lang.Object, org.argouml.cognitive.Designer)\n     */\n    @Override\n    public boolean predicate2(Object dm, Designer dsgr) {\n\tif (!(Model.getFacade().isAOperation(dm))) {\n\t    return NO_PROBLEM;\n\t}\n\tObject oper = dm;\n\tString myName = Model.getFacade().getName(oper);\n\tif (myName == null || myName.equals(\"\")) {\n\t    return PROBLEM_FOUND;\n\t}\n\tif (myName.length() == 0) {\n\t    return PROBLEM_FOUND;\n\t}\n\treturn NO_PROBLEM;\n    }\n\n    /*\n     * @see org.argouml.cognitive.critics.Critic#initWizard(\n     *         org.argouml.cognitive.ui.Wizard)\n     */\n    @Override\n    public void initWizard(Wizard w) {\n\tif (w instanceof WizMEName) {\n\t    ToDoItem item = (ToDoItem) w.getToDoItem();\n\t    Object me = item.getOffenders().get(0);\n\t    String ins = super.getInstructions();\n\t    String sug = super.getDefaultSuggestion();\n\t    if (Model.getFacade().isAOperation(me)) {\n\t\tObject a = me;\n\t\tint count = 1;\n\t\tif (Model.getFacade().getOwner(a) != null) {\n\t\t    count = Model.getFacade().getFeatures(\n\t\t            Model.getFacade().getOwner(a)).size();\n\t\t}\n\t\tsug = \"oper\" + (count + 1);\n\t    }\n\t    ((WizMEName) w).setInstructions(ins);\n\t    ((WizMEName) w).setSuggestion(sug);\n\t}\n    }\n\n    /*\n     * @see org.argouml.cognitive.critics.Critic#getWizardClass(org.argouml.cognitive.ToDoItem)\n     */\n    @Override\n    public Class getWizardClass(ToDoItem item) {\n        return WizMEName.class;\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#getCriticizedDesignMaterials()\n     */\n    @Override\n    public Set<Object> getCriticizedDesignMaterials() {\n        Set<Object> ret = new HashSet<Object>();\n        ret.add(Model.getMetaTypes().getOperation());\n        return ret;\n    }\n    \n}\n", "human_rating": 3.0470755229999997, "metadata": {"project": "argoUML", "class": "org.argouml.uml.cognitive.critics.CrMissingOperName", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/cognitive/critics/CrMissingOperName.java", "label_probabilities": {"readability": [0.0512324, 0.945141, 0.00309593, 0.000531063], "understandability": [0.0557424, 0.92879, 0.00438183, 0.0110857], "complexity": [1.87542e-10, 0.00175252, 0.508405, 0.489843], "modularization": [0.0, 1.88939e-09, 0.084304, 0.915696], "overall": [0.00450852, 0.994923, 0.000568732, 1.4737e-16]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.cognitive.critics.CrMultiComposite", "source": "/* $Id: CrMultiComposite.java 19577 2011-06-22 20:37:05Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    maurelio1234\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.cognitive.critics;\n\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.argouml.cognitive.Critic;\nimport org.argouml.cognitive.Designer;\nimport org.argouml.cognitive.ToDoItem;\nimport org.argouml.model.Model;\nimport org.argouml.uml.cognitive.UMLDecision;\n\n/**\n * Well-formedness rule [2] for MAssociationEnd. See page 2-45 of UML\n * chapter 2: Semantics. OMG document UML V1.3 June 1999.\n *\n * Well-formedness rule [1] for AssociationEnd. See page 53 of UML 1.4\n * Semantics. OMG document UML 1.4.2 formal/04-07-02.\n * \n * @author jrobbins\n */\npublic class CrMultiComposite extends CrUML {\n\n    /**\n     * The constructor.\n     */\n    public CrMultiComposite() {\n        setupHeadAndDesc();\n        addSupportedDecision(UMLDecision.CONTAINMENT);\n        setKnowledgeTypes(Critic.KT_SEMANTICS);\n        addTrigger(\"aggregation\");\n        addTrigger(\"multiplicity\");\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#predicate2(\n     *      java.lang.Object, org.argouml.cognitive.Designer)\n     */\n    @Override\n    public boolean predicate2(Object dm, Designer dsgr) {\n        boolean problem = NO_PROBLEM;\n        if (Model.getFacade().isAAssociationEnd(dm)) {\n            if (Model.getFacade().isComposite(dm)) {\n                if (Model.getFacade().getUpper(dm) > 1) {\n                    problem = PROBLEM_FOUND;\n                }\n            }\n        }\n        return problem;\n    }\n\n    /*\n     * @see org.argouml.cognitive.critics.Critic#getWizardClass(org.argouml.cognitive.ToDoItem)\n     */\n    @Override\n    public Class getWizardClass(ToDoItem item) {\n        return WizAssocComposite.class;\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#getCriticizedDesignMaterials()\n     */\n    @Override\n    public Set<Object> getCriticizedDesignMaterials() {\n        Set<Object> ret = new HashSet<Object>();\n        ret.add(Model.getMetaTypes().getAssociationEnd());\n        return ret;\n    }\n    \n} /* end class CrMultiComposite */\n", "human_rating": 3.953471301100384, "metadata": {"project": "argoUML", "class": "org.argouml.uml.cognitive.critics.CrMultiComposite", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/cognitive/critics/CrMultiComposite.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.cognitive.critics.CrNoIncomingTransitions", "source": "/* $Id: CrNoIncomingTransitions.java 19577 2011-06-22 20:37:05Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.cognitive.critics;\n\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.argouml.cognitive.Designer;\nimport org.argouml.model.Model;\nimport org.argouml.uml.cognitive.UMLDecision;\n\n/**\n * A critic to detect whether a state has no incoming transitions.\n * <p>\n * Also a transition to a state contained in the design material \n * counts as an \"incoming\" transition thanks to issue 689.\n *\n * @author jrobbins\n */\npublic class CrNoIncomingTransitions extends CrUML {\n\n    /**\n     * Constructor.\n     */\n    public CrNoIncomingTransitions() {\n        setupHeadAndDesc();\n\taddSupportedDecision(UMLDecision.STATE_MACHINES);\n\taddTrigger(\"incoming\");\n    }\n\n    /**\n     * This is the decision routine for the critic.\n     *\n     * @param dm is the design material, i.e. the \n     *     UML entity that is being checked.\n     * @param dsgr is for future development and can be ignored.\n     *\n     * @return boolean problem found\n     */\n    @Override\n    public boolean predicate2(Object dm, Designer dsgr) {\n        if (!(Model.getFacade().isAStateVertex(dm))) {\n            return NO_PROBLEM;\n        }\n        /* Now we are sure dm is a StateVertex. */\n        if (Model.getFacade().isAPseudostate(dm)) {\n            Object k = Model.getFacade().getKind(dm);\n            if (k.equals(Model.getPseudostateKind().getChoice())) {\n                return NO_PROBLEM;\n            }\n            if (k.equals(Model.getPseudostateKind().getJunction())) {\n                return NO_PROBLEM;\n            }\n            if (k.equals(Model.getPseudostateKind().getInitial())) {\n                return NO_PROBLEM;\n            }\n        }\n        if (!Model.getFacade().isAState(dm)) {\n            return NO_PROBLEM;\n        }\n        /* Now we are sure dm is a State. */\n        Object sm = Model.getStateMachinesHelper().getStateMachine(dm);\n        if (sm != null && Model.getFacade().getTop(sm) == dm) {\n            /* If dm is the top state of the statemachine, then it is \n             * not supposed to have incoming transitions. */\n            return NO_PROBLEM;\n        }\n\n        Collection incoming = Model.getFacade().getIncomings(dm);\n        if (incoming.size() > 0) {\n            return NO_PROBLEM;\n        }\n\n        if (!Model.getFacade().isACompositeState(dm)) {\n            return PROBLEM_FOUND;\n        }\n        /* Now we are sure dm is a Composite State. */\n\n        /* Issue 689: Look for a transition that arrives \n         * at a sub-state of the composite state: */\n        Collection transitions = Model.getFacade().getTransitions(sm);\n        for (Object t : transitions) {\n            Object sourceState = Model.getFacade().getSource(t);\n            Object targetState = Model.getFacade().getTarget(t);\n            if (!isSomeSubvertexOf(sourceState, dm) && isSomeSubvertexOf(targetState, dm)) {\n                return NO_PROBLEM;\n            }\n        }\n\n        return PROBLEM_FOUND;\n    }\n    \n    /**\n     * Test if a state is contained within a composite state recursively. \n     * This is done by checking if the parent of the subject \n     * equals the composite, or the parent of the parent, etc.\n     * \n     * @param subject the StateVertex that is investigated\n     * @param composite the Composite state that may or may not contain the subject\n     * @return true if and only if the given composite contains recursively the given subject\n     */\n    private boolean isSomeSubvertexOf(Object subject, Object composite) {\n        Object c = subject;\n        while (c != null) {\n            if (c == composite) {\n                return true;\n            }\n            c = Model.getFacade().getContainer(c);\n        }\n        return false;\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.CrUML#getCriticizedDesignMaterials()\n     */\n    @Override\n    public Set<Object> getCriticizedDesignMaterials() {\n        Set<Object> ret = new HashSet<Object>();\n        ret.add(Model.getMetaTypes().getStateVertex());\n        return ret;\n    }\n    \n}\n", "human_rating": 3.712125000002494, "metadata": {"project": "argoUML", "class": "org.argouml.uml.cognitive.critics.CrNoIncomingTransitions", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/cognitive/critics/CrNoIncomingTransitions.java", "label_probabilities": {"readability": [0.712125, 0.287875, 1.24705e-12, 0.0], "understandability": [0.455559, 0.543805, 0.00063664, 2.02e-18], "complexity": [5.6761e-16, 0.00126397, 0.998736, 5.36113e-08], "modularization": [3.26e-18, 0.00260662, 0.933999, 0.0633947], "overall": [0.86437, 0.135631, 1.72577e-08, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.cognitive.critics.WizMEName", "source": "/* $Id: WizMEName.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.cognitive.critics;\n\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.JPanel;\n\nimport org.argouml.cognitive.ui.WizStepTextField;\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.Model;\n\n/**\n * A non-modal wizard to help the user change the name of a\n * MModelElement to a better name.\n *\n * @author jrobbins\n */\npublic class WizMEName extends UMLWizard {\n    private static final Logger LOG =\n        Logger.getLogger(WizMEName.class.getName());\n\n    private String instructions = Translator.localize(\"critics.WizMEName-ins\");\n    private String label = Translator.localize(\"label.name\");\n    private boolean mustEdit = false;\n\n    private WizStepTextField step1 = null;\n\n    private String origSuggest;\n\n    /**\n     * The constructor.\n     *\n     */\n    public WizMEName() { }\n\n    /**\n     * @param s the instructions\n     */\n    public void setInstructions(String s) { instructions = s; }\n\n    /**\n     * @param b if true, then the wizard step needs userinput,\n     *          i.e. it must be edited\n     */\n    public void setMustEdit(boolean b) { mustEdit = b; }\n\n    /**\n     * Create a new panel for the given step.\n     *\n     * @see org.argouml.cognitive.critics.Wizard#makePanel(int)\n     */\n    public JPanel makePanel(int newStep) {\n\tswitch (newStep) {\n\tcase 1:\n\t    if (step1 == null) {\n\t\tstep1 = new WizStepTextField(this, instructions,\n\t\t\t\t\t      label, offerSuggestion());\n\t    }\n\t    return step1;\n\t}\n\treturn null;\n    }\n\n    /*\n     * @see org.argouml.uml.cognitive.critics.UMLWizard#setSuggestion(java.lang.String)\n     */\n    public void setSuggestion(String s) {\n        origSuggest = s;\n        super.setSuggestion(s);\n    }\n\n\n    /**\n     * Return false if the user has not edited the text and they were required\n     * to.\n     *\n     * @see org.argouml.cognitive.critics.Wizard#canGoNext()\n     */\n    public boolean canGoNext() {\n\tif (!super.canGoNext()) {\n\t    return false;\n\t}\n\tif (step1 != null) {\n\t    boolean changed = origSuggest.equals(step1.getText());\n\t    if (mustEdit && !changed) {\n\t        return false;\n\t    }\n\t}\n\treturn true;\n    }\n\n    /*\n     * @see org.argouml.cognitive.ui.Wizard#doAction(int)\n     */\n    public void doAction(int oldStep) {\n        LOG.log(Level.FINE, \"doAction {0}\", oldStep);\n\n\tswitch (oldStep) {\n\tcase 1:\n\t    String newName = getSuggestion();\n\t    if (step1 != null) {\n\t        newName = step1.getText();\n\t    }\n\t    try {\n\t\tObject me = getModelElement();\n\t\tModel.getCoreHelper().setName(me, newName);\n\t    }\n\t    catch (Exception pve) {\n                LOG.log(Level.SEVERE, \"could not set name\", pve);\n\t    }\n            break;\n\t}\n    }\n\n    /**\n     * @return Returns the instructions.\n     */\n    protected String getInstructions() {\n        return instructions;\n    }\n} /* end class WizMEName */\n", "human_rating": 3.9118021480232246, "metadata": {"project": "argoUML", "class": "org.argouml.uml.cognitive.critics.WizMEName", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/cognitive/critics/WizMEName.java", "label_probabilities": {"readability": [0.91221, 0.0873815, 0.000408824, 2.32251e-11], "understandability": [0.745837, 0.247616, 0.00654679, 3.69462e-08], "complexity": [2.18e-18, 6.59604e-07, 0.0155713, 0.984428], "modularization": [0.0, 8.50711e-10, 0.0354404, 0.96456], "overall": [0.850327, 0.14967, 3.52229e-06, 2.6e-19]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.activity.ui.FigSubactivityState", "source": "/* $Id: FigSubactivityState.java 18726 2010-09-10 08:37:15Z mvw $\n *****************************************************************************\n * Copyright (c) 2009-2010 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.activity.ui;\n\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Rectangle;\nimport java.beans.PropertyChangeEvent;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.Set;\n\nimport org.argouml.model.AssociationChangeEvent;\nimport org.argouml.model.AttributeChangeEvent;\nimport org.argouml.model.Model;\nimport org.argouml.uml.diagram.DiagramSettings;\nimport org.argouml.uml.diagram.state.ui.FigStateVertex;\nimport org.tigris.gef.presentation.Fig;\nimport org.tigris.gef.presentation.FigLine;\nimport org.tigris.gef.presentation.FigRRect;\nimport org.tigris.gef.presentation.FigText;\n\n\n/**\n * Class to display graphics for a UML SubactivityState in a diagram.\n *\n * @author MVW\n */\npublic class FigSubactivityState extends FigStateVertex {\n\n    private static final int PADDING = 8;\n\n    private static final int X = X0;\n    private static final int Y = Y0;\n    private static final int W = 90;\n    private static final int H = 25;\n\n    private static final int SX = 3;\n    private static final int SY = 3;\n    private static final int SW = 9;\n    private static final int SH = 5;\n\n\n    private FigRRect cover;\n\n    private FigRRect s1;\n    private FigRRect s2;\n    private FigLine s3;\n\n    \n    /**\n     * Construct a new FigSubactivityState.\n     * \n     * @param owner owning UML element\n     * @param bounds position and size\n     * @param settings rendering settings\n     */\n    public FigSubactivityState(Object owner, Rectangle bounds, \n            DiagramSettings settings) {\n        super(owner, bounds, settings);\n        initFigs();\n    }\n\n    @Override\n    protected Fig createBigPortFig() {\n        FigRRect frr = new FigRRect(X, Y, W, H, DEBUG_COLOR, DEBUG_COLOR);\n        frr.setCornerRadius(frr.getHeight() / 2);\n        frr.setLineWidth(0);\n        return frr;\n    }\n\n    private void initFigs() {\n        cover = new FigRRect(X, Y, W, H, LINE_COLOR, FILL_COLOR);\n        cover.setCornerRadius(getHeight() / 2);\n\n        getNameFig().setLineWidth(0);\n        getNameFig().setBounds(10 + PADDING, 10, 90 - PADDING * 2, 25);\n        getNameFig().setFilled(false);\n        getNameFig().setReturnAction(FigText.INSERT);\n        getNameFig().setEditable(false);\n\n        // add Figs to the FigNode in back-to-front order\n        addFig(getBigPort());\n        addFig(cover);\n        addFig(getNameFig());\n\n        makeSubStatesIcon(X + W, Y);\n\n        setBounds(getBounds());\n    }\n\n    /**\n     * @param x the x-coordinate of the right corner\n     * @param y the y coordinate of the bottom corner\n     */\n    private void makeSubStatesIcon(int x, int y) {\n        s1 = new FigRRect(x - 22, y + 3, 8, 6, LINE_COLOR, FILL_COLOR);\n        s2 = new FigRRect(x - 11, y + 9, 8, 6, LINE_COLOR, FILL_COLOR);\n        s1.setFilled(true);\n        s2.setFilled(true);\n        s1.setLineWidth(LINE_WIDTH);\n        s2.setLineWidth(LINE_WIDTH);\n        s1.setCornerRadius(SH);\n        s2.setCornerRadius(SH);\n        s3 = new FigLine(x - 18, y + 6, x - 7, y + 12, LINE_COLOR);\n\n        addFig(s3); // add them back to front\n        addFig(s1);\n        addFig(s2);\n    }\n\n    /*\n     * @see java.lang.Object#clone()\n     */\n    @Override\n    public Object clone() {\n        FigSubactivityState figClone = (FigSubactivityState) super.clone();\n        Iterator it = figClone.getFigs().iterator();\n        figClone.setBigPort((FigRRect) it.next());\n        figClone.cover = (FigRRect) it.next();\n        figClone.setNameFig((FigText) it.next());\n        return figClone;\n    }\n\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getMinimumSize()\n     */\n    @Override\n    public Dimension getMinimumSize() {\n        Dimension nameDim = getNameFig().getMinimumSize();\n        int w = nameDim.width + PADDING * 2;\n        int h = nameDim.height + PADDING;\n        return new Dimension(Math.max(w, W / 2), Math.max(h, H / 2));\n    }\n\n    /*\n     * Override setBounds to keep shapes looking right.\n     *\n     * @see org.tigris.gef.presentation.Fig#setBoundsImpl(int, int, int, int)\n     */\n    @Override\n    protected void setStandardBounds(int x, int y, int w, int h) {\n        if (getNameFig() == null) {\n            return;\n        }\n        Rectangle oldBounds = getBounds();\n\n        getNameFig().setBounds(x + PADDING, y, w - PADDING * 2, h - PADDING);\n        getBigPort().setBounds(x, y, w, h);\n        cover.setBounds(x, y, w, h);\n        ((FigRRect) getBigPort()).setCornerRadius(h);\n        cover.setCornerRadius(h);\n\n        s1.setBounds(x + w - 2 * (SX + SW), y + h - 1 * (SY + SH), SW, SH);\n        s2.setBounds(x + w - 1 * (SX + SW), y + h - 2 * (SY + SH), SW, SH);\n        s3.setShape(x + w - (SX * 2 + SW + SW / 2), y + h - (SY + SH / 2),\n                x + w - (SX + SW / 2), y + h - (SY * 2 + SH + SH / 2));\n\n        calcBounds();\n        updateEdges();\n        firePropChange(\"bounds\", oldBounds, getBounds());\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setLineColor(java.awt.Color)\n     */\n    @Override\n    public void setLineColor(Color col) {\n        cover.setLineColor(col);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getLineColor()\n     */\n    public Color getLineColor() {\n        return cover.getLineColor();\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setFillColor(java.awt.Color)\n     */\n    public void setFillColor(Color col) {\n        cover.setFillColor(col);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getFillColor()\n     */\n    public Color getFillColor() {\n        return cover.getFillColor();\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setFilled(boolean)\n     */\n    @Override\n    public void setFilled(boolean f) {\n        cover.setFilled(f);\n    }\n\n    @Override\n    public boolean isFilled() {\n        return cover.isFilled();\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setLineWidth(int)\n     */\n    @Override\n    public void setLineWidth(int w) {\n        cover.setLineWidth(w);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getLineWidth()\n     */\n    @Override\n    public int getLineWidth() {\n        return cover.getLineWidth();\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.ui.FigNodeModelElement#modelChanged(java.beans.PropertyChangeEvent)\n     */\n    @Override\n    protected void modelChanged(PropertyChangeEvent mee) {\n        // Let our superclass sort itself out first\n        super.modelChanged(mee);\n        if (mee instanceof AssociationChangeEvent \n                || mee instanceof AttributeChangeEvent) {\n            // TODO: Rather than specifically ignore some item maybe it would be better\n            // to specifically state what items are of interest. Otherwise we may still\n            // be acting on other events we don't need\n            if (!Model.getFacade().isATransition(mee.getNewValue())) {\n                renderingChanged();\n                updateListeners(getOwner(), getOwner());\n            }\n        }\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.ui.FigNodeModelElement#updateListeners(java.lang.Object)\n     */\n    @Override\n    protected void updateListeners(Object oldOwner, Object newOwner) {\n        Set<Object[]> l = new HashSet<Object[]>();\n        if (newOwner != null) {\n            // add the listeners to the newOwner\n            l.add(new Object[] {newOwner, null});\n            // and listen to name changes of the submachine\n            Object machine = Model.getFacade().getSubmachine(newOwner);\n            if (machine != null) {\n                l.add(new Object[] {machine, null});\n            }\n        }\n        updateElementListeners(l);\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.ui.FigNodeModelElement#updateNameText()\n     */\n    @Override\n    protected void updateNameText() {\n        String s = \"\";\n        if (getOwner() != null) {\n            Object machine = Model.getFacade().getSubmachine(getOwner());\n            if (machine != null) {\n                s = Model.getFacade().getName(machine);\n            }\n        }\n        if (s == null) {\n            s = \"\";\n        }\n        getNameFig().setText(s);\n    }\n\n}\n", "human_rating": 3.82840073147598, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.activity.ui.FigSubactivityState", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/activity/ui/FigSubactivityState.java", "label_probabilities": {"readability": [0.828415, 0.171571, 1.38634e-05, 4.67598e-09], "understandability": [2.33303e-06, 0.19526, 0.743761, 0.0609761], "complexity": [8.34574e-06, 0.892114, 0.10781, 6.81187e-05], "modularization": [1.02238e-06, 0.0453594, 0.81417, 0.14047], "overall": [8.24906e-06, 0.732174, 0.267817, 7.83894e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.deployment.ui.SelectionComponentInstance", "source": "/* $Id: SelectionComponentInstance.java 17857 2010-01-12 19:59:07Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.deployment.ui;\n\nimport javax.swing.Icon;\n\nimport org.argouml.application.helpers.ResourceLoaderWrapper;\nimport org.argouml.model.Model;\nimport org.argouml.uml.diagram.ui.SelectionNodeClarifiers2;\nimport org.tigris.gef.presentation.Fig;\n\n/**\n * @author 5eichler@informatik.uni-hamburg.de\n */\npublic class SelectionComponentInstance extends SelectionNodeClarifiers2 {\n\n    private static Icon dep =\n            ResourceLoaderWrapper.lookupIconResource(\"Dependency\");\n\n    private static Icon depRight =\n            ResourceLoaderWrapper.lookupIconResource(\"DependencyRight\");\n\n    private static Icon icons[] = \n    {dep,\n     dep,\n     depRight,\n     depRight,\n     null,\n    };\n    \n    // TODO: I18N required\n    private static String instructions[] = \n    {\"Add a component-instance\",\n     \"Add a component-instance\",\n     \"Add a component-instance\",\n     \"Add a component-instance\",\n     null,\n     \"Move object(s)\",\n    };\n\n    /**\n     * Construct a new SelectionComponentInstanceInstance for the given Fig.\n     *\n     * @param f The given Fig.\n     */\n    public SelectionComponentInstance(Fig f) { super(f); }\n\n\n    @Override\n    protected Icon[] getIcons() {\n        if (Model.getModelManagementHelper().isReadOnly(\n                getContent().getOwner())) {\n            return new Icon[] {null, dep, depRight, null, null };\n        }\n        return icons;\n    }\n\n    @Override\n    protected String getInstructions(int index) {\n        return instructions[index - BASE];\n    }\n\n    @Override\n    protected Object getNewEdgeType(int index) {\n        return Model.getMetaTypes().getDependency();\n    }\n\n    @Override\n    protected Object getNewNode(int index) {\n        return Model.getCommonBehaviorFactory().createComponentInstance();\n    }\n    \n    @Override\n    protected Object getNewNodeType(int index) {\n        return Model.getMetaTypes().getComponentInstance();\n    }\n\n    @Override\n    protected boolean isReverseEdge(int index) {\n        if (index == BOTTOM || index == LEFT) {\n            return true;\n        }\n        return false;\n    }\n\n}\n\n", "human_rating": 3.9168470474196435, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.deployment.ui.SelectionComponentInstance", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/deployment/ui/SelectionComponentInstance.java", "label_probabilities": {"readability": [0.916858, 0.0831304, 1.19236e-05, 2.19644e-10], "understandability": [0.695917, 0.304083, 7.98657e-09, 2.08318e-08], "complexity": [8.97639e-14, 7.61976e-07, 0.0148784, 0.985121], "modularization": [0.0, 1.45012e-10, 0.0229296, 0.97707], "overall": [0.938471, 0.0615285, 1.66049e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.deployment.ui.UMLDeploymentDiagram", "source": "/* $Id: UMLDeploymentDiagram.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Bob Tarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2003-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.deployment.ui;\n\nimport java.awt.Rectangle;\nimport java.beans.PropertyVetoException;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.Action;\n\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.DeploymentDiagram;\nimport org.argouml.model.Facade;\nimport org.argouml.model.Model;\nimport org.argouml.ui.CmdCreateNode;\nimport org.argouml.uml.diagram.DiagramElement;\nimport org.argouml.uml.diagram.DiagramSettings;\nimport org.argouml.uml.diagram.deployment.DeploymentDiagramGraphModel;\nimport org.argouml.uml.diagram.static_structure.ui.FigClass;\nimport org.argouml.uml.diagram.static_structure.ui.FigComment;\nimport org.argouml.uml.diagram.static_structure.ui.FigInterface;\nimport org.argouml.uml.diagram.ui.ActionSetAddAssociationMode;\nimport org.argouml.uml.diagram.ui.ActionSetMode;\nimport org.argouml.uml.diagram.ui.FigNodeModelElement;\nimport org.argouml.uml.diagram.ui.RadioAction;\nimport org.argouml.uml.diagram.ui.UMLDiagram;\nimport org.argouml.uml.diagram.use_case.ui.FigActor;\nimport org.argouml.util.ToolBarUtility;\nimport org.tigris.gef.base.LayerPerspective;\nimport org.tigris.gef.base.LayerPerspectiveMutable;\nimport org.tigris.gef.base.ModeCreatePolyEdge;\nimport org.tigris.gef.graph.GraphModel;\nimport org.tigris.gef.presentation.FigNode;\n\n/**\n * The base class of the deployment diagram.<p>\n *\n * Defines the toolbar, provides for its initialization and provides\n * constructors for a top level diagram and one within a defined\n * namespace.<p>\n *\n * @author Clemens Eichler\n */\npublic class UMLDeploymentDiagram extends UMLDiagram implements DeploymentDiagram {\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(UMLDeploymentDiagram.class.getName());\n\n    ////////////////\n    // actions for toolbar\n\n    private Action actionMNode;\n    private Action actionMNodeInstance;\n    private Action actionMComponent;\n    private Action actionMComponentInstance;\n    private Action actionMClass;\n    private Action actionMInterface;\n    private Action actionMObject;\n    private Action actionMDependency;\n    private Action actionMAssociation;\n    private Action actionMLink;\n    private Action actionAssociation;\n    private Action actionAggregation;\n    private Action actionComposition;\n    private Action actionUniAssociation;\n    private Action actionUniAggregation;\n    private Action actionUniComposition;\n    private Action actionMGeneralization;\n    private Action actionMAbstraction;\n\n\n    /**\n     * Constructor.\n     * @deprecated for 0.28 by tfmorris.  Use\n     * {@link #UMLActivityDiagram(String, Object, GraphModel)}.\n     */\n    @Deprecated\n    public UMLDeploymentDiagram() {\n        try {\n            setName(getNewDiagramName());\n        } catch (PropertyVetoException pve) { }\n        // TODO: All super constrcutors should take a GraphModel\n        setGraphModel(createGraphModel());\n    }\n\n    /**\n     * @param namespace the namespace for the new diagram\n     * @deprecated for 0.28 by tfmorris.  Use\n     * {@link #UMLActivityDiagram(String, Object, GraphModel)}.\n     */\n    @Deprecated\n    public UMLDeploymentDiagram(Object namespace) {\n        this();\n        setNamespace(namespace);\n    }\n\n    /**\n     * Method to perform a number of important initializations of a\n     * <em>Deployment Diagram</em>.<p>\n     *\n     * Each diagram type has a similar <em>UMLxxxDiagram</em> class.<p>\n     *\n     * Changed <em>lay</em> from <em>LayerPerspective</em> to\n     * <em>LayerPerspectiveMutable</em>.  This class is a child of\n     * <em>LayerPerspective</em> and was implemented to correct some\n     * difficulties in changing the model. <em>lay</em> is used mainly\n     * in <em>LayerManager</em>(GEF) to control the adding, changing and\n     * deleting layers on the diagram...<p>\n     *\n     * @param handle package from the model\n     * @author psager@tigris.org Jan. 24, 2002\n     */\n    public void setNamespace(Object handle) {\n        if (!Model.getFacade().isANamespace(handle)) {\n            LOG.log(Level.SEVERE,\n                \"Illegal argument. Object \" + handle + \" is not a namespace\");\n            throw new IllegalArgumentException(\n                \"Illegal argument. Object \" + handle + \" is not a namespace\");\n        }\n        Object m = handle;\n        boolean init = (null == getNamespace());\n        super.setNamespace(m);\n        DeploymentDiagramGraphModel gm = createGraphModel();\n        gm.setHomeModel(m);\n        if (init) {\n            LayerPerspective lay =\n                new LayerPerspectiveMutable(Model.getFacade().getName(m), gm);\n            DeploymentDiagramRenderer rend = new DeploymentDiagramRenderer();\n            lay.setGraphNodeRenderer(rend);\n            lay.setGraphEdgeRenderer(rend);\n            setLayer(lay);\n        }\n    }\n\n    // TODO: Needs to be tidied up after stable release. Graph model\n    // should be created in constructor\n    private DeploymentDiagramGraphModel createGraphModel() {\n\tif ((getGraphModel() instanceof DeploymentDiagramGraphModel)) {\n\t    return (DeploymentDiagramGraphModel) getGraphModel();\n\t} else {\n\t    return new DeploymentDiagramGraphModel();\n\t}\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.ui.UMLDiagram#getUmlActions()\n     */\n    protected Object[] getUmlActions() {\n        final Object[] actions = {\n            getActionMNode(),\n            getActionMNodeInstance(),\n            getActionMComponent(),\n            getActionMComponentInstance(),\n            getActionMGeneralization(),\n            getActionMAbstraction(),\n            getActionMDependency(),\n            getAssociationActions(),\n            getActionMObject(),\n            getActionMLink(),\n        };\n        return actions;\n    }\n\n    private Object[] getAssociationActions() {\n        Object[][] actions = {\n\t    {getActionAssociation(), getActionUniAssociation() },\n\t    {getActionAggregation(), getActionUniAggregation() },\n\t    {getActionComposition(), getActionUniComposition() },\n        };\n        ToolBarUtility.manageDefault(actions, \"diagram.deployment.association\");\n        return actions;\n    }\n\n    /**\n     * The UID.\n     */\n    static final long serialVersionUID = -375918274062198744L;\n\n    /*\n     * @see org.argouml.uml.diagram.ui.UMLDiagram#getLabelName()\n     */\n    public String getLabelName() {\n        return Translator.localize(\"label.deployment-diagram\");\n    }\n\n    //////////////////////////////\n    // Getters for plugin modules:\n    //////////////////////////////\n\n    /**\n     * @return Returns the actionAggregation.\n     */\n    protected Action getActionAggregation() {\n        if (actionAggregation == null) {\n            actionAggregation =\n                new RadioAction(\n                    new ActionSetAddAssociationMode(\n                        Model.getAggregationKind().getAggregate(),\n                        false,\n                        \"button.new-aggregation\"));\n        }\n        return actionAggregation;\n    }\n\n    /**\n     * @return Returns the actionAssociation.\n     */\n    protected Action getActionAssociation() {\n        if (actionAssociation == null) {\n            actionAssociation =\n                new RadioAction(\n                    new ActionSetAddAssociationMode(\n                        Model.getAggregationKind().getNone(),\n                        false,\n                        \"button.new-association\"));\n        }\n        return actionAssociation;\n    }\n\n    /**\n     * @return Returns the actionComposition.\n     */\n    protected Action getActionComposition() {\n        if (actionComposition == null) {\n            actionComposition =\n                new RadioAction(\n                    new ActionSetAddAssociationMode(\n                        Model.getAggregationKind().getComposite(),\n                        false,\n                        \"button.new-composition\"));\n        }\n        return actionComposition;\n    }\n\n    /**\n     * @return Returns the actionMAssociation.\n     */\n    protected Action getActionMAssociation() {\n        if (actionMAssociation == null) {\n            actionMAssociation =\n                new RadioAction(new ActionSetMode(\n                        ModeCreatePolyEdge.class,\n                        \"edgeClass\",\n                        Model.getMetaTypes().getAssociation(),\n                        \"button.new-association\"));\n        }\n        return actionMAssociation;\n    }\n\n    /**\n     * @return Returns the actionMClass.\n     */\n    protected Action getActionMClass() {\n        if (actionMClass == null) {\n            actionMClass =\n                new RadioAction(\n                        new CmdCreateNode(Model.getMetaTypes().getUMLClass(),\n                                \"button.new-class\"));\n        }\n        return actionMClass;\n    }\n\n    /**\n     * @return Returns the actionMComponent.\n     */\n    protected Action getActionMComponent() {\n        if (actionMComponent == null) {\n            actionMComponent =\n                new RadioAction(\n                        new CmdCreateNode(\n                                Model.getMetaTypes().getComponent(),\n                                \"button.new-component\"));\n        }\n        return actionMComponent;\n    }\n\n    /**\n     * @return Returns the actionMComponentInstance.\n     */\n    protected Action getActionMComponentInstance() {\n        if (actionMComponentInstance == null) {\n            actionMComponentInstance =\n                new RadioAction(new CmdCreateNode(\n                        Model.getMetaTypes().getComponentInstance(),\n                \t\"button.new-componentinstance\"));\n        }\n        return actionMComponentInstance;\n    }\n\n    /**\n     * @return Returns the actionMDependency.\n     */\n    protected Action getActionMDependency() {\n        if (actionMDependency == null) {\n            actionMDependency =\n                new RadioAction(new ActionSetMode(\n                        ModeCreatePolyEdge.class,\n                        \"edgeClass\",\n                        Model.getMetaTypes().getDependency(),\n                        \"button.new-dependency\"));\n        }\n        return actionMDependency;\n    }\n\n    /**\n     * @return Returns the actionMGeneralization.\n     */\n    protected Action getActionMGeneralization() {\n        if (actionMGeneralization == null) {\n            actionMGeneralization =\n                new RadioAction(new ActionSetMode(\n                        ModeCreatePolyEdge.class,\n                        \"edgeClass\",\n                        Model.getMetaTypes().getGeneralization(),\n                \t\"button.new-generalization\"));\n        }\n        return actionMGeneralization;\n    }\n\n    /**\n     * @return Returns the actionMAbstraction.\n     */\n    protected Action getActionMAbstraction() {\n        if (actionMAbstraction == null) {\n            actionMAbstraction =\n                new RadioAction(new ActionSetMode(\n                        ModeCreatePolyEdge.class,\n                        \"edgeClass\",\n                        Model.getMetaTypes().getAbstraction(),\n                \t\"button.new-realization\"));\n        }\n        return actionMAbstraction;\n    }\n\n    /**\n     * @return Returns the actionMInterface.\n     */\n    protected Action getActionMInterface() {\n        if (actionMInterface == null) {\n            actionMInterface =\n                new RadioAction(\n                        new CmdCreateNode(\n                                Model.getMetaTypes().getInterface(),\n                                \"button.new-interface\"));\n        }\n        return actionMInterface;\n    }\n\n    /**\n     * @return Returns the actionMLink.\n     */\n    protected Action getActionMLink() {\n        if (actionMLink == null) {\n            actionMLink =\n                new RadioAction(new ActionSetMode(\n                        ModeCreatePolyEdge.class,\n                        \"edgeClass\",\n                        Model.getMetaTypes().getLink(),\n                        \"button.new-link\"));\n        }\n        return actionMLink;\n    }\n\n    /**\n     * @return Returns the actionMNode.\n     */\n    protected Action getActionMNode() {\n        if (actionMNode == null) {\n            actionMNode =\n                new RadioAction(new CmdCreateNode(\n                    Model.getMetaTypes().getNode(),\n                    \"button.new-node\"));\n        }\n        return actionMNode;\n    }\n\n    /**\n     * @return Returns the actionMNodeInstance.\n     */\n    protected Action getActionMNodeInstance() {\n        if (actionMNodeInstance == null) {\n            actionMNodeInstance =\n                new RadioAction(new CmdCreateNode(\n                    Model.getMetaTypes().getNodeInstance(),\n                    \"button.new-nodeinstance\"));\n        }\n        return actionMNodeInstance;\n    }\n\n    /**\n     * @return Returns the actionMObject.\n     */\n    protected Action getActionMObject() {\n        if (actionMObject == null) {\n            actionMObject =\n                new RadioAction(\n                        new CmdCreateNode(Model.getMetaTypes().getObject(),\n                                \"button.new-object\"));\n        }\n        return actionMObject;\n    }\n\n    /**\n     * @return Returns the actionUniAggregation.\n     */\n    protected Action getActionUniAggregation() {\n        if (actionUniAggregation == null) {\n            actionUniAggregation =\n                new RadioAction(\n                    new ActionSetAddAssociationMode(\n                        Model.getAggregationKind().getAggregate(),\n                        true, \"button.new-uniaggregation\"));\n        }\n        return actionUniAggregation;\n    }\n\n    /**\n     * @return Returns the actionUniAssociation.\n     */\n    protected Action getActionUniAssociation() {\n        if (actionUniAssociation == null) {\n            actionUniAssociation =\n                new RadioAction(\n                    new ActionSetAddAssociationMode(\n                        Model.getAggregationKind().getNone(),\n                        true, \"button.new-uniassociation\"));\n        }\n        return actionUniAssociation;\n    }\n\n    /**\n     * @return Returns the actionUniComposition.\n     */\n    protected Action getActionUniComposition() {\n        if (actionUniComposition == null) {\n            actionUniComposition =\n                new RadioAction(\n                    new ActionSetAddAssociationMode(\n                        Model.getAggregationKind().getComposite(),\n                        true, \"button.new-unicomposition\"));\n        }\n        return actionUniComposition;\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.ui.UMLDiagram#isRelocationAllowed(java.lang.Object)\n     */\n    public boolean isRelocationAllowed(Object base)  {\n        return Model.getFacade().isAPackage(base);\n    }\n\n    @SuppressWarnings(\"unchecked\")\n    public Collection getRelocationCandidates(Object root) {\n        return\n        Model.getModelManagementHelper().getAllModelElementsOfKindWithModel(\n            root, Model.getMetaTypes().getPackage());\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.ui.UMLDiagram#relocate(java.lang.Object)\n     */\n    public boolean relocate(Object base) {\n        setNamespace(base);\n        damage();\n        return true;\n    }\n\n    /**\n     * Provides the standard functionality of the superclass only for\n     * deployment diagram specific model elements\n     * @param modelElement the model element\n     * @param namespace the namespace (or null for diagram)\n     * @see org.argouml.uml.diagram.ui.UMLDiagram#setModelElementNamespace(java.lang.Object, Object)\n     */\n    public void setModelElementNamespace(\n\t    Object modelElement,\n\t    Object namespace) {\n\tFacade facade = Model.getFacade();\n\tif (facade.isANode(modelElement)\n\t\t|| facade.isANodeInstance(modelElement)\n\t\t|| facade.isAComponent(modelElement)\n\t\t|| facade.isAComponentInstance(modelElement)) {\n\n            LOG.log(Level.INFO, \"Setting namespace of {0}\", modelElement);\n\n            super.setModelElementNamespace(modelElement, namespace);\n\t}\n    }\n\n    /*\n     * If the new encloser is null, and the old one is a Component,\n     * then the \"enclosed\" Fig has been moved on the diagram.\n     * This causes the model to be adapted as follows:\n     * remove the elementResidence\n     * between the \"enclosed\" and the oldEncloser.\n     *\n     * @see org.argouml.ui.ArgoDiagram#changeFigEncloser(org.tigris.gef.presentation.FigNode, org.tigris.gef.presentation.FigNode, org.tigris.gef.presentation.FigNode)\n     */\n    public void encloserChanged(FigNode enclosed, FigNode oldEncloser,\n            FigNode newEncloser) {\n        if (oldEncloser != null && newEncloser == null\n                && Model.getFacade().isAComponent(oldEncloser.getOwner())) {\n            Collection<Object> er1 = Model.getFacade().getElementResidences(\n                    enclosed.getOwner());\n            Collection er2 = Model.getFacade().getResidentElements(\n                    oldEncloser.getOwner());\n            Collection<Object> common = new ArrayList<Object>(er1);\n            common.retainAll(er2);\n            for (Object elementResidence : common) {\n                Model.getUmlFactory().delete(elementResidence);\n            }\n        }\n    }\n\n    @Override\n    public boolean doesAccept(Object objectToAccept) {\n        if (Model.getFacade().isANode(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isAAssociation(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isANodeInstance(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isAComponent(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isAComponentInstance(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isAClass(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isAInterface(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isAObject(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isAComment(objectToAccept)) {\n            return true;\n        } else if (Model.getFacade().isAActor(objectToAccept)) {\n            return true;\n        }\n        return false;\n    }\n\n\n    public DiagramElement createDiagramElement(\n            final Object modelElement,\n            final Rectangle bounds) {\n\n        FigNodeModelElement figNode = null;\n\n        DiagramSettings settings = getDiagramSettings();\n\n        if (Model.getFacade().isANode(modelElement)) {\n            figNode = new FigMNode(modelElement, bounds, settings);\n        } else if (Model.getFacade().isAAssociation(modelElement)) {\n            figNode =\n                createNaryAssociationNode(modelElement, bounds, settings);\n        } else if (Model.getFacade().isANodeInstance(modelElement)) {\n            figNode = new FigNodeInstance(modelElement, bounds, settings);\n        } else if (Model.getFacade().isAComponent(modelElement)) {\n            figNode = new FigComponent(modelElement, bounds, settings);\n        } else if (Model.getFacade().isAComponentInstance(modelElement)) {\n            figNode = new FigComponentInstance(modelElement, bounds, settings);\n        } else if (Model.getFacade().isAClass(modelElement)) {\n            figNode = new FigClass(modelElement, bounds, settings);\n        } else if (Model.getFacade().isAInterface(modelElement)) {\n            figNode = new FigInterface(modelElement, bounds, settings);\n        } else if (Model.getFacade().isAObject(modelElement)) {\n            figNode = new FigObject(modelElement, bounds, settings);\n        } else if (Model.getFacade().isAActor(modelElement)) {\n            figNode = new FigActor(modelElement, bounds, settings);\n        } else if (Model.getFacade().isAComment(modelElement)) {\n            figNode = new FigComment(modelElement, bounds, settings);\n        }\n\n        if (figNode != null) {\n            LOG.log(Level.FINE,\n                    \"Model element {0} converted to {1}\",\n                    new Object[]{modelElement, figNode});\n        } else {\n            LOG.log(Level.FINE, \"Dropped object NOT added {0}\", figNode);\n        }\n        return figNode;\n    }\n}\n", "human_rating": 2.2879230000032935, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.deployment.ui.UMLDeploymentDiagram", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/deployment/ui/UMLDeploymentDiagram.java", "label_probabilities": {"readability": [2.98838e-13, 0.287923, 0.712077, 2.09814e-12], "understandability": [5.69348e-07, 0.959215, 0.0407846, 3.35763e-14], "complexity": [4.91871e-15, 0.0865086, 0.913491, 6.4091e-10], "modularization": [1.69556e-12, 0.983191, 0.016809, 2.807e-13], "overall": [4.27751e-10, 0.0867087, 0.913291, 7.41444e-12]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.state.ui.ButtonActionNewCallEvent", "source": "/* $Id: ButtonActionNewCallEvent.java 17862 2010-01-12 20:06:14Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2006-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.state.ui;\n\nimport org.argouml.model.Model;\n\n/**\n * This is an Action to be used for Buttons to create a Call-Event.\n * \n * @author Michiel\n */\npublic class ButtonActionNewCallEvent extends ButtonActionNewEvent {\n\n    protected Object createEvent(Object ns) {\n        return Model.getStateMachinesFactory().buildCallEvent(ns);\n    }\n    \n    protected String getKeyName() {\n        return \"button.new-callevent\";\n    }\n    \n    protected String getIconName() {\n        return \"CallEvent\";\n    }\n}\n", "human_rating": 3.9012051926, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.state.ui.ButtonActionNewCallEvent", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/state/ui/ButtonActionNewCallEvent.java", "label_probabilities": {"readability": [0.90125, 0.0987045, 4.58463e-05, 0.0], "understandability": [0.846574, 0.153426, 2.38823e-07, 0.0], "complexity": [0.0, 2.22841e-10, 0.0583091, 0.941691], "modularization": [0.0, 0.00146691, 0.0712498, 0.927283], "overall": [0.977677, 0.0223232, 1.81181e-08, 1.5e-19]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.state.ui.FigCompositeState", "source": "/* $Id: FigCompositeState.java 19614 2011-07-20 12:10:13Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.state.ui;\n\nimport java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Rectangle;\nimport java.awt.event.MouseEvent;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.TreeMap;\nimport java.util.Vector;\n\nimport org.argouml.model.Model;\nimport org.argouml.model.RemoveAssociationEvent;\nimport org.argouml.model.UmlChangeEvent;\nimport org.argouml.ui.targetmanager.TargetManager;\nimport org.argouml.uml.diagram.DiagramSettings;\nimport org.argouml.uml.diagram.ui.ActionAddConcurrentRegion;\nimport org.tigris.gef.presentation.Fig;\nimport org.tigris.gef.presentation.FigLine;\nimport org.tigris.gef.presentation.FigRRect;\nimport org.tigris.gef.presentation.FigRect;\nimport org.tigris.gef.presentation.FigText;\n\n/**\n * Class to display graphics for a UML CompositeState in a diagram.\n *\n * @author jrobbins@ics.uci.edu\n */\npublic class FigCompositeState extends FigState {\n\n    private FigRect cover;\n    private FigLine divider;\n\n    \n    /**\n     * Construct a new FigStubState.\n     * \n     * @param owner owning UML element\n     * @param bounds position and size\n     * @param settings rendering settings\n     */\n    public FigCompositeState(Object owner, Rectangle bounds,\n            DiagramSettings settings) {\n        super(owner, bounds, settings);\n        initFigs();\n        updateNameText();\n    }\n\n    private void initFigs() {\n        cover =\n            new FigRRect(getInitialX(), getInitialY(),\n\t\t\t      getInitialWidth(), getInitialHeight(),\n\t\t\t      LINE_COLOR, FILL_COLOR);\n\n        getBigPort().setLineWidth(0);\n\n        divider =\n\t    new FigLine(getInitialX(),\n\t\t\tgetInitialY() + 2 + getNameFig().getBounds().height + 1,\n\t\t\tgetInitialWidth() - 1,\n\t\t\tgetInitialY() + 2 + getNameFig().getBounds().height + 1,\n\t\t\tLINE_COLOR);\n\n        // add Figs to the FigNode in back-to-front order\n        addFig(getBigPort());\n        addFig(cover);\n        addFig(getNameFig());\n        addFig(divider);\n        addFig(getInternal());\n\n        setBounds(getBounds());\n    }\n\n    /*\n     * @see java.lang.Object#clone()\n     */\n    public Object clone() {\n        FigCompositeState figClone = (FigCompositeState) super.clone();\n        Iterator it = figClone.getFigs().iterator();\n        figClone.setBigPort((FigRRect) it.next());\n        figClone.cover = (FigRect) it.next();\n        figClone.setNameFig((FigText) it.next());\n        figClone.divider = (FigLine) it.next();\n        figClone.setInternal((FigText) it.next());\n        return figClone;\n    }\n\n    ////////////////////////////////////////////////////////////////\n    // accessors\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getMinimumSize()\n     */\n    public Dimension getMinimumSize() {\n        Dimension nameDim = getNameFig().getMinimumSize();\n        Dimension internalDim = getInternal().getMinimumSize();\n\n        int h =\n            SPACE_TOP + nameDim.height\n            + SPACE_MIDDLE + internalDim.height\n            + SPACE_BOTTOM;\n        int w =\n            Math.max(nameDim.width + 2 * MARGIN,\n                     internalDim.width + 2 * MARGIN);\n        return new Dimension(w, h);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getUseTrapRect()\n     */\n    public boolean getUseTrapRect() {\n        return true;\n    }\n\n    /*\n     * Override setBounds to keep shapes looking right.\n     *\n     * @see org.tigris.gef.presentation.Fig#setBoundsImpl(int, int, int, int)\n     */\n    protected void setStandardBounds(int x, int y, int w, int h) {\n        if (getNameFig() == null) {\n            return;\n        }\n\n        Rectangle oldBounds = getBounds();\n        Dimension nameDim = getNameFig().getMinimumSize();\n        List regionsList = getEnclosedFigs();\n\n        /* If it is concurrent and contains concurrent regions,\n        the bottom region has a minimum height*/\n        if (getOwner() != null) {\n            if (isConcurrent()\n                    && !regionsList.isEmpty()\n                    && regionsList.get(regionsList.size() - 1)\n                        instanceof FigConcurrentRegion) {\n                FigConcurrentRegion f = \n                    ((FigConcurrentRegion) regionsList.get(\n                            regionsList.size() - 1));\n                Rectangle regionBounds = f.getBounds();\n                if ((h - oldBounds.height + regionBounds.height)\n                        <= (f.getMinimumSize().height)) {\n                    h = oldBounds.height;\n                    y = oldBounds.y;\n                }\n            }\n        }\n\n        getNameFig().setBounds(x + MARGIN,\n                y + SPACE_TOP,\n                w - 2 * MARGIN,\n                nameDim.height);\n        divider.setShape(x,\n                y + DIVIDER_Y + nameDim.height,\n                x + w - 1,\n                y + DIVIDER_Y + nameDim.height);\n\n        getInternal().setBounds(\n                x + MARGIN,\n                y + nameDim.height + SPACE_TOP + SPACE_MIDDLE,\n                w - 2 * MARGIN,\n                h - nameDim.height - SPACE_TOP - SPACE_MIDDLE - SPACE_BOTTOM);\n\n        getBigPort().setBounds(x, y, w, h);\n        cover.setBounds(x, y, w, h);\n\n        calcBounds(); //_x = x; _y = y; _w = w; _h = h;\n        updateEdges();\n        firePropChange(\"bounds\", oldBounds, getBounds());\n\n        /*If it is concurrent and contains concurrent regions,\n        the regions are resized*/\n        if (getOwner() != null) {\n            if (isConcurrent()\n                    && !regionsList.isEmpty()\n                    && regionsList.get(regionsList.size() - 1)\n                        instanceof FigConcurrentRegion) {\n                FigConcurrentRegion f = ((FigConcurrentRegion) regionsList\n                        .get(regionsList.size() - 1));\n                for (int i = 0; i < regionsList.size() - 1; i++) {\n                    ((FigConcurrentRegion) regionsList.get(i))\n                        .setBounds(x - oldBounds.x, y - oldBounds.y,\n                                w - 2 * FigConcurrentRegion.INSET_HORZ, true);\n                }\n                f.setBounds(x - oldBounds.x,\n                        y - oldBounds.y, \n                        w - 2 * FigConcurrentRegion.INSET_HORZ, \n                        h - oldBounds.height, true);\n            }\n        }\n\n    }\n    \n    /*\n     * The returned list of Figs is sorted according layout: from top to bottom.\n     */\n    @Override\n    public Vector<Fig> getEnclosedFigs() {\n        Vector<Fig> enclosedFigs = super.getEnclosedFigs();\n\n        if (isConcurrent()) {\n            TreeMap<Integer, Fig> figsByY = new TreeMap<Integer, Fig>();\n            for (Fig fig : enclosedFigs) {\n                if (fig instanceof FigConcurrentRegion) {\n                    figsByY.put(fig.getY(), fig);\n                }\n            }\n            return new Vector<Fig>(figsByY.values());\n        }\n        return enclosedFigs;\n    }\n    \n    /**\n     * @return true if this is a concurrent state, \n     * false otherwise, or if the owner is not known\n     */\n    public boolean isConcurrent() {\n        Object owner = getOwner();\n        if (owner == null) {\n            return false;\n        }\n        return Model.getFacade().isConcurrent(owner);\n    }\n\n    /**\n     * To resize only when a new concurrent region is added,\n     * changing the height.\n     * TODO: Probably shouldn't\n     * exist as this class should be listening for added concurrent regions\n     * and call this internally itself.\n     *\n     * @param h the new height\n     */\n    public void setCompositeStateHeight(int h) {\n        if (getNameFig() == null) {\n            return;\n        }\n        Rectangle oldBounds = getBounds();\n        Dimension nameDim = getNameFig().getMinimumSize();\n        int x = oldBounds.x;\n        int y = oldBounds.y;\n        int w = oldBounds.width;\n\n        getInternal().setBounds(\n                x + MARGIN, \n                y + nameDim.height + 4,\n                w - 2 * MARGIN, \n                h - nameDim.height - 6);\n        getBigPort().setBounds(x, y, w, h);\n        cover.setBounds(x, y, w, h);\n\n        calcBounds(); //_x = x; _y = y; _w = w; _h = h;\n        updateEdges();\n        firePropChange(\"bounds\", oldBounds, getBounds());\n    }\n\n\n    /*\n     * @see org.tigris.gef.ui.PopupGenerator#getPopUpActions(java.awt.event.MouseEvent)\n     */\n    public Vector getPopUpActions(MouseEvent me) {\n        Vector popUpActions = super.getPopUpActions(me);\n        /* Check if multiple items are selected: */\n        boolean ms = TargetManager.getInstance().getTargets().size() > 1;\n        if (!ms) {\n            popUpActions.add(\n                    popUpActions.size() - getPopupAddOffset(),\n                    new ActionAddConcurrentRegion());\n        }\n        return popUpActions;\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setLineColor(java.awt.Color)\n     */\n    public void setLineColor(Color col) {\n        cover.setLineColor(col);\n        divider.setLineColor(col);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getLineColor()\n     */\n    public Color getLineColor() {\n        return cover.getLineColor();\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setFillColor(java.awt.Color)\n     */\n    public void setFillColor(Color col) {\n        cover.setFillColor(col);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getFillColor()\n     */\n    public Color getFillColor() {\n        return cover.getFillColor();\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setFilled(boolean)\n     */\n    public void setFilled(boolean f) {\n        cover.setFilled(f);\n        getBigPort().setFilled(f);\n    }\n\n\n    @Override\n    public boolean isFilled() {\n        return cover.isFilled();\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setLineWidth(int)\n     */\n    public void setLineWidth(int w) {\n        cover.setLineWidth(w);\n        divider.setLineWidth(w);\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#getLineWidth()\n     */\n    public int getLineWidth() {\n        return cover.getLineWidth();\n    }\n\n    ////////////////////////////////////////////////////////////////\n    // event processing\n\n    @Override \n    protected void updateLayout(UmlChangeEvent event) {\n        /* We only handle the case where a region has been removed: */\n        if (!(event instanceof RemoveAssociationEvent)\n                ||  !\"subvertex\".equals(event.getPropertyName())) {\n            return;\n        }\n        \n        final Object removedRegion = event.getOldValue();\n        \n        List<FigConcurrentRegion> regionFigs =\n            ((List<FigConcurrentRegion>) getEnclosedFigs().clone());\n\n        int totHeight = getInitialHeight();\n        if (!regionFigs.isEmpty()) {\n            Fig removedFig = null;\n            for (FigConcurrentRegion figRegion : regionFigs) {\n                if (figRegion.getOwner() == removedRegion) {\n                    removedFig = figRegion;\n                    removeEnclosedFig(figRegion);\n                    break;\n                }\n            }\n            if (removedFig != null) {\n                regionFigs.remove(removedFig);\n                if (!regionFigs.isEmpty()) {\n                    for (FigConcurrentRegion figRegion : regionFigs) {\n                        if (figRegion.getY() > removedFig.getY()) {\n                            figRegion.displace(0, -removedFig.getHeight());\n                        }\n                    }\n                    totHeight = getHeight() - removedFig.getHeight();\n                }\n            }\n        }\n        \n        setBounds(getX(), getY(), getWidth(), totHeight);\n\n        // do we need to \n        renderingChanged();\n    }\n\n\n    /*\n     * @see org.argouml.uml.diagram.state.ui.FigState#getInitialHeight()\n     */\n    protected int getInitialHeight() {\n        return 150;\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.state.ui.FigState#getInitialWidth()\n     */\n    protected int getInitialWidth() {\n        return 180;\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.state.ui.FigState#getInitialX()\n     */\n    protected int getInitialX() {\n        return 0;\n    }\n\n    /*\n     * @see org.argouml.uml.diagram.state.ui.FigState#getInitialY()\n     */\n    protected int getInitialY() {\n        return 0;\n    }\n\n} /* end class FigCompositeState */\n", "human_rating": 2.0788559737624, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.state.ui.FigCompositeState", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/state/ui/FigCompositeState.java", "label_probabilities": {"readability": [1.34406e-08, 0.0820657, 0.914725, 0.00320882], "understandability": [4.80515e-06, 0.165522, 0.834105, 0.000368564], "complexity": [0.106231, 0.620041, 0.273721, 6.36862e-06], "modularization": [0.246038, 0.343541, 0.409775, 0.000645967], "overall": [1.0291e-08, 0.0329991, 0.945535, 0.0214658]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.static_structure.layout.ClassdiagramModelElementFactory", "source": "/* $Id: ClassdiagramModelElementFactory.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.static_structure.layout;\n\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.argouml.uml.diagram.layout.LayoutedObject;\nimport org.argouml.uml.diagram.static_structure.ui.FigComment;\nimport org.argouml.uml.diagram.static_structure.ui.FigEdgeNote;\nimport org.argouml.uml.diagram.ui.FigAbstraction;\nimport org.argouml.uml.diagram.ui.FigAssociation;\nimport org.argouml.uml.diagram.ui.FigGeneralization;\nimport org.argouml.uml.diagram.ui.FigNodeModelElement;\nimport org.tigris.gef.presentation.FigNode;\n\n/** a class to get the proper layouter for a Fig.\n * Currently this deals only with Generalizations and Realizations.\n *\n * @author Markus Klink\n * @stereotype singleton\n*/\npublic class ClassdiagramModelElementFactory\n{\n    private static final Logger LOG =\n        Logger.getLogger(ClassdiagramModelElementFactory.class.getName());\n\n    /**\n     * The singleton.\n     */\n    public static final ClassdiagramModelElementFactory SINGLETON =\n\tnew ClassdiagramModelElementFactory();\n\n    private ClassdiagramModelElementFactory() { }\n\n    /** create layouter object from a Fig.*\n     *\n     * @param f Object which contains the Fig\n     * @return Layouter for the Edge or Classnode or null if none exists.\n     */\n    public LayoutedObject getInstance(Object f) {\n        if (f instanceof FigComment) {\n            return (new ClassdiagramNote((FigComment) f));\n        } else if (f instanceof FigNodeModelElement) {\n            return (new ClassdiagramNode((FigNode) f));\n        } else if (f instanceof FigGeneralization) {\n            return new ClassdiagramGeneralizationEdge((FigGeneralization) f);\n        } else if (f instanceof FigAbstraction) {\n            return (new ClassdiagramRealizationEdge((FigAbstraction) f));\n        } else if (f instanceof FigAssociation) {\n            return (new ClassdiagramAssociationEdge((FigAssociation) f));\n        } else if (f instanceof FigEdgeNote) {\n            return (new ClassdiagramNoteEdge((FigEdgeNote) f));\n        }\n        LOG.log(Level.FINE,\n                \"Do not know how to deal with: {0}\\nUsing standard layout\",\n                f.getClass().getName());\n        return null;\n    }\n}\n", "human_rating": 3.2954938659999997, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.static_structure.layout.ClassdiagramModelElementFactory", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/static_structure/layout/ClassdiagramModelElementFactory.java", "label_probabilities": {"readability": [0.296371, 0.703125, 0.000131296, 0.000372274], "understandability": [0.351538, 0.641288, 0.00717371, 1.57216e-09], "complexity": [0.0, 2.28014e-11, 0.141496, 0.858504], "modularization": [0.0, 3.02134e-11, 0.0140928, 0.985907], "overall": [0.993417, 0.00658346, 7.92256e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.static_structure.layout.ClassdiagramNode", "source": "/* $Id: ClassdiagramNode.java 17863 2010-01-12 20:07:22Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.static_structure.layout;\n\nimport java.awt.Dimension;\nimport java.awt.Point;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.argouml.uml.diagram.layout.LayoutedNode;\nimport org.argouml.uml.diagram.static_structure.ui.FigComment;\nimport org.argouml.uml.diagram.static_structure.ui.FigInterface;\nimport org.argouml.uml.diagram.static_structure.ui.FigPackage;\nimport org.tigris.gef.presentation.Fig;\nimport org.tigris.gef.presentation.FigNode;\n\n/**\n * This class represents a node in the classdiagram (a class, interface or\n * package).\n * <p>\n * \n * Things a node has to know:\n * <ul>\n * <li>Up- and downlinks for positioning in the hierarchy\n * <li>Weight of this node. This weight has to be strongly influenced by the\n * parent-nodes, because otherwise the order of nodes in the current row will\n * not be compatible with the order of the nodes in the row above.\n * </ul>\n */\nclass ClassdiagramNode implements LayoutedNode, Comparable {\n\n    /**\n     * Constant to be used as an initializer when this node is not placed at an\n     * column.\n     */\n    public static final int NOCOLUMN = -1;\n\n    /**\n     * Constant to be used as an initializer when this node has no rank assigned\n     * yet.\n     */\n    public static final int NORANK = -1;\n\n    /**\n     * Constant to be used as an initializer when this node has no weight.\n     */\n    public static final int NOWEIGHT = -1;\n\n    /**\n     * The current column of this node.\n     */\n    private int column = NOCOLUMN;\n\n    /**\n     * List of the nodes that contain the figures, which\n     * are sources of edges with the figure of this node as destination.\n     */\n    private List<ClassdiagramNode> downlinks = \n        new ArrayList<ClassdiagramNode>();\n\n    /**\n     * Offset used for edges, which have this node as the \"upper\" node.\n     */\n    private int edgeOffset = 0;\n\n    /**\n     * The Fig that this ClassdiagramNode represents during the layout process.\n     */\n    private FigNode figure = null;\n\n    /**\n     * The preferred X coordinate for the node.  Hint only. May not be used.\n     */\n    private int placementHint = -1;\n\n    /**\n     * The current rank (i.e. row number) of this node.\n     */\n    private int rank = NORANK;\n\n    /**\n     * List of nodes that contain the figures, which are destinations of edges\n     * with the figure of this node as source.\n     */\n    private List<ClassdiagramNode> uplinks = new ArrayList<ClassdiagramNode>();\n\n    /**\n     * The 'weight' of this node. This is a computed\n     * attribute that is used during the horizontal placement process. It's\n     * based on the position of the 'uplinked' objects. The actual purpose is to\n     * minimize the number of link crossings in the diagram. Since we don't\n     * compute the actual number of link crossings, we look where our uplinked\n     * objects are, and then try to place our object in a way, that we can\n     * expect to have a minimal number of crossings.\n     */\n    private float weight = NOWEIGHT;\n\n    private static final float UPLINK_FACTOR = 5;\n\n    /**\n     * Construct a new ClassdiagramNode representing the given Fig.\n     * \n     * @param f\n     *            represents the figure in the diagram, that peers this layout\n     *            node.\n     */\n    public ClassdiagramNode(FigNode f) {\n        setFigure(f);\n    }\n\n    /**\n     * Add a new downlinked node to this node.\n     * \n     * @param newDownlink\n     *            The node to be added with a dowlink.\n     */\n    public void addDownlink(ClassdiagramNode newDownlink) {\n        downlinks.add(newDownlink);\n    }\n\n    /**\n     * Add a constant to the rank of this node.\n     * \n     * @param n\n     *            The value to add.\n     */\n    public void addRank(int n) {\n        setRank(n + getRank());\n    }\n\n    /**\n     * Add an uplink to this node.\n     * \n     * @param newUplink\n     *            represents the new uplinks.\n     */\n    public void addUplink(ClassdiagramNode newUplink) {\n        uplinks.add(newUplink);\n    }\n\n    /**\n     * Calculate the weight of this node. The function distinguishes between\n     * note-nodes and standard-nodes, because a note should be positioned to the\n     * right of its first related node, if it exists. Therefor the weight is a\n     * function of the weight of the related node. For standard-nodes the weight\n     * is a function of up-/downlinks, column and uplink factor.\n     * \n     * @return The weight of this node.\n     */\n    public float calculateWeight() {\n        weight = 0;\n        for (ClassdiagramNode node : uplinks) {\n            weight = Math.max(weight, node.getWeight()\n                    * UPLINK_FACTOR\n                    * (1 + 1 / Math.max(1, node.getColumn() + UPLINK_FACTOR)));\n        }\n        weight += getSubtreeWeight()\n                + (1 / Math.max(1, getColumn() + UPLINK_FACTOR));\n        return weight;\n    }\n\n    /**\n     * The \"natural order\" for ClassdiagramNodes is defined by the following\n     * order.\n     * <ul>\n     * <li>First standalone, then linked nodes\n     * <li>First Packages, then Interfaces/Classes/Notes\n     * <li>increasing rank (rownumber)\n     * <li>decreasing weight\n     * <li>name of model object\n     * <li>increasing hashcode (for uniqueness)\n     * </ul>\n     * \n     * @see java.lang.Comparable#compareTo(java.lang.Object)\n     */\n    public int compareTo(Object arg0) {\n        ClassdiagramNode node = (ClassdiagramNode) arg0;\n        int result = 0;\n        result =\n                Boolean.valueOf(node.isStandalone()).compareTo(\n                        Boolean.valueOf(isStandalone()));\n        if (result == 0) {\n            result = this.getTypeOrderNumer() - node.getTypeOrderNumer();\n        }\n        if (result == 0) {\n            result = this.getRank() - node.getRank();\n        }\n        if (result == 0) {\n            result = (int) Math.signum(node.getWeight() - this.getWeight());\n        }\n        if (result == 0) {\n            result = String.valueOf(this.getFigure().getOwner()).compareTo(\n                    String.valueOf(node.getFigure().getOwner()));\n        }\n        if (result == 0) {\n            result = node.hashCode() - this.hashCode();\n        }\n        //LOG.debug(result + \" node1: \" + this + \", node2 \" + node);\n        return result;\n    }\n\n    /**\n     * @return The column of this node.\n     */\n    public int getColumn() {\n        return column;\n    }\n\n\n    /**\n     * @return The downlinks of this node.\n     */\n    public List<ClassdiagramNode> getDownNodes() {\n        return downlinks;\n    }\n    \n    /**\n     * Get the offset which shall be used for edges with this node as parent.\n     * \n     * @return The offset\n     */\n    public int getEdgeOffset() {\n        return edgeOffset;\n    }\n\n    /**\n     * Get the underlying figure of this node.\n     * \n     * @return The figure.\n     */\n    public FigNode getFigure() {\n        return figure;\n    }\n\n    /**\n     * Get the level in the inheritance hierarchy for this node.\n     * \n     * @return The level.\n     */\n    public int getLevel() {\n        int result = 0;\n        for (ClassdiagramNode node : uplinks) {\n            result =\n                    (node == this) ? result : Math.max(\n                            node.getLevel() + 1, result);\n        }\n        return result;\n    }\n\n    /**\n     * Get the location of the underlying figure in the diagram.\n     * \n     * @return The location.\n     */\n    public Point getLocation() {\n        return getFigure().getLocation();\n    }\n\n    /**\n     * Get the current placement hint (X coordinate in the row).\n     * \n     * @return The placement hint for this node.\n     */\n    public int getPlacementHint() {\n        return placementHint;\n    }\n\n    /**\n     * @return The rank for this node.\n     */\n    public int getRank() {\n        return rank == NORANK ? getLevel() : rank;\n    }\n\n    /**\n     * Return the size of the figure associated with this\n     * layout node.\n     * \n     * @return The size of the associated figure.\n     */\n    public Dimension getSize() {\n        return getFigure().getSize();\n    }\n\n    /**\n     * Get the weight of the subtree defined by this node. Impact on weight is\n     * decreasing with increasing hierarchical distance\n     * \n     * @return The weight of the subtree.\n     */\n    private float getSubtreeWeight() {\n\n        float w = 1;\n        for (ClassdiagramNode node : downlinks) {\n            w += node.getSubtreeWeight() / UPLINK_FACTOR;\n        }\n        return w;\n    }\n\n    /**\n     * Get the type order number of this node. This number may be used to\n     * influence the sort order of ClassdiagramNodes.\n     * \n     * @return Type order number.\n     */\n    public int getTypeOrderNumer() {\n        int result = 99;\n        if (getFigure() instanceof FigPackage) {\n            result = 0;\n        } else if (getFigure() instanceof FigInterface) {\n            result = 1;\n        }\n        return result;\n    }\n\n    /**\n     * Get the uplinks of this node.\n     * \n     * @return The uplinks of this node.\n     */\n    public List<ClassdiagramNode> getUpNodes() {\n        return uplinks;\n    }\n    \n    /**\n     * Return the weight of this node, which is used for positioning in a row.\n     * \n     * @return The weight of this node.\n     */\n    public float getWeight() {\n        return weight;\n    }\n\n    /**\n     * Check if this node is associated with a note.\n     * \n     * @return Result of test.\n     */\n    public boolean isComment() {\n        return (getFigure() instanceof FigComment);\n    }\n\n    /**\n     * Check if this node is associated with a package.\n     * \n     * @return Result of test.\n     */\n    public boolean isPackage() {\n        return (getFigure() instanceof FigPackage);\n    }\n\n    /**\n     * Test whether this node has no connection to other nodes. Return\n     * <code>true</code> if node has no connections, <code>false</code>\n     * otherwise.\n     * \n     * @return Result of test.\n     */\n    public boolean isStandalone() {\n        return uplinks.isEmpty() && downlinks.isEmpty();\n    }\n\n    /**\n     * Set the column of this node. A re-calculation of the weight is performed,\n     * because the column is an input parameter for the weight.\n     * \n     * @param newColumn\n     *            The new column.\n     */\n    public void setColumn(int newColumn) {\n        column = newColumn;\n        calculateWeight();\n    }\n\n    /**\n     * Set the offset for edges to this node.\n     * \n     * @param newOffset\n     *            Offset for edges with this node as one endpoint.\n     */\n    public void setEdgeOffset(int newOffset) {\n        edgeOffset = newOffset;\n    }\n\n    /**\n     * Set the Fig represented by this node.\n     * \n     * @param newFigure\n     *            represents the new value of figure.\n     */\n    public void setFigure(FigNode newFigure) {\n        figure = newFigure;\n    }\n\n    /**\n     * Set the location of the Fig associated with this node.\n     * \n     * @param newLocation\n     *            represents the new location for this figure.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public void setLocation(Point newLocation) {\n        Point oldLocation = getFigure().getLocation();\n\n        getFigure().setLocation(newLocation);\n        int xTrans = newLocation.x - oldLocation.x;\n        int yTrans = newLocation.y - oldLocation.y;\n        for (Fig fig : (List<Fig>) getFigure().getEnclosedFigs()) {\n            fig.translate(xTrans, yTrans);\n        }\n    }\n\n    /**\n     * A placementhint gives an indication where it might be feasible to place\n     * this node. It is used by the layouter, and there is no guarantee that it\n     * will be used.\n     * \n     * @param hint\n     *            x coordinate of the desired placement\n     */\n    public void setPlacementHint(int hint) {\n        placementHint = hint;\n    }\n\n    /**\n     * Set the rank\n     * \n     * @param newRank\n     *            represents the new value of rank.\n     */\n    public void setRank(int newRank) {\n        rank = newRank;\n    }\n\n    /**\n     * Set the weight for this node.\n     * \n     * @param w\n     *            The new weight of this node.\n     */\n    public void setWeight(float w) {\n        weight = w;\n    }\n\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.static_structure.layout.ClassdiagramNode", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/static_structure/layout/ClassdiagramNode.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.55165, 0.44734, 0.00101023, 1.74959e-10], "complexity": [1.07997e-10, 0.00256924, 0.546867, 0.450564], "modularization": [4.03515e-06, 0.0203978, 0.773186, 0.206412], "overall": [0.593989, 0.406011, 5.97422e-07, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.ui.ActionStereotypeViewTextual", "source": "/* $Id: ActionStereotypeViewTextual.java 17865 2010-01-12 20:45:26Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.ui;\n\nimport org.argouml.uml.diagram.DiagramAppearance;\n\n/**\n * When this action is triggered the selected node visualization changes into \n * <code>Textual</code> mode. This is the default mode for all nodes. The \n * stereotypes are displayed as the stereotype name between guillemets.\n *\n * @author maurelio1234\n */\npublic class ActionStereotypeViewTextual extends ActionStereotypeView {\n    /**\n     * Default constructor for this action\n     * \n     * @param node the current node\n     */\n    public ActionStereotypeViewTextual(FigNodeModelElement node) {\n\tsuper(node, \"menu.popup.stereotype-view.textual\",\n\t\tDiagramAppearance.STEREOTYPE_VIEW_TEXTUAL);\n    }\n}\n", "human_rating": 3.927985835881085, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.ui.ActionStereotypeViewTextual", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/ui/ActionStereotypeViewTextual.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.ui.FigEdgePort", "source": "/* $Id: FigEdgePort.java 17865 2010-01-12 20:45:26Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.ui;\n\nimport java.awt.Rectangle;\n\nimport org.argouml.uml.diagram.DiagramSettings;\nimport org.tigris.gef.presentation.Fig;\nimport org.tigris.gef.presentation.FigCircle;\nimport org.tigris.gef.presentation.FigEdge;\n\n/**\n * This node cannot be dragged and manipulated in the same way as other\n * FigNodes in ArgoUML. It is actually an optional child fig (or more precisely\n * a path item) of a FigEdgeModelElement.\n * This allows the dashed edge of an association class to connect the\n * association edge and allows the dashed edge of a comment edge to attach a\n * comment to some other edge type.\n * GEF can only attach edges to nodes, by making this fig both a node and\n * containing it as a child of an edge we push the rules to allow edge to edge\n * connections.\n * TODO: We are inheriting a lot of functionality here that we don't really\n * require. We should attempt to make FigEdgePort extend FigNode.\n *\n * @author Bob Tarling\n */\npublic class FigEdgePort extends FigNodeModelElement {\n    private FigCircle bigPort;\n\n    private void initialize() {\n        invisibleAllowed = true;\n        bigPort = new FigCircle(0, 0, 1, 1, LINE_COLOR, FILL_COLOR);\n        addFig(bigPort);\n    }\n\n    /**\n     * @param owner owning uml element\n     * @param bounds ignored\n     * @param settings ignored\n     */\n    public FigEdgePort(Object owner, Rectangle bounds, \n            DiagramSettings settings) {\n        super(owner, bounds, settings);\n        initialize();\n        bigPort.setOwner(owner);\n    }\n    \n    /*\n     * @see org.tigris.gef.presentation.Fig#hit(java.awt.Rectangle)\n     */\n    @Override\n    public boolean hit(Rectangle r) {\n        return false;\n    }\n    \n    @Override\n    public Object getOwner() {\n\tif (super.getOwner() != null) {\n\t    return super.getOwner();\n\t}\n        Fig group = this;\n        while (group != null && !(group instanceof FigEdge)) {\n            group = group.getGroup();\n        }\n        if (group == null) {\n            return null;\n        } else {\n            return group.getOwner();\n        }\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#classNameAndBounds()\n     */\n    // USED BY PGML.tee\n    @Override\n    public String classNameAndBounds() {\n        return getClass().getName()\n            + \"[\" + getX() + \", \" + getY() + \", \"\n            + getWidth() + \", \" + getHeight() + \"]\";\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.FigNode#hitPort(int, int)\n     */\n    @Override\n    public Object hitPort(int x, int y) {\n        return null;\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.FigGroup#hitFig(java.awt.Rectangle)\n     */\n    @Override\n    public Fig hitFig(Rectangle r) {\n        return null;\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#isSelectable()\n     */\n    @Override\n    public boolean isSelectable() {\n        return false;\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.FigNode#getPortFig(java.lang.Object)\n     */\n    public Fig getPortFig(Object port) {\n        return bigPort;\n    }\n\n    /**\n     * The UID.\n     */\n    private static final long serialVersionUID = 3091219503512470458L;\n}\n", "human_rating": 3.8908215685800616, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.ui.FigEdgePort", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/ui/FigEdgePort.java", "label_probabilities": {"readability": [0.890826, 0.109171, 2.28429e-06, 6.13053e-14], "understandability": [0.755373, 0.242642, 0.00198492, 1.45969e-14], "complexity": [1.48604e-06, 0.00245094, 0.108607, 0.888941], "modularization": [2.1878e-07, 0.000424501, 0.15506, 0.844516], "overall": [0.439977, 0.560021, 1.7413e-06, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.ui.FigKeyword", "source": "/* $Id: FigKeyword.java 17865 2010-01-12 20:45:26Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2008-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.ui;\n\nimport java.awt.Rectangle;\n\nimport org.argouml.notation.providers.uml.NotationUtilityUml;\nimport org.argouml.uml.diagram.DiagramSettings;\nimport org.tigris.gef.presentation.FigText;\n\n/**\n * Fig to show a keyword within a FigStereotypesGroup,\n * which resembles a stereotype, but isn't one. \n * E.g. <<interface>>. \n * <p>\n * The keyword is not editable on the fig, hence we\n * do not use a Notation Provider. <p>\n * This Fig does not need to listen to model changes \n * and is frozen.<p>\n * \n * This Fig only supports updates of the text \n * for changes in guillemet style.\n *\n * @author Michiel\n */\npublic class FigKeyword extends FigSingleLineText {\n\n    private final String keywordText;\n\n    /**\n     * @param keyword the text to show\n     * @param bounds position and size\n     * @param settings rendering settings\n     */\n    public FigKeyword(String keyword, Rectangle bounds, \n            DiagramSettings settings) {\n        super(bounds, settings, true);\n        initialize();\n        keywordText = keyword;\n        setText(keyword);\n    }\n    \n    private void initialize() {\n        setEditable(false);\n        setTextColor(TEXT_COLOR);\n        setTextFilled(false);\n        setJustification(FigText.JUSTIFY_CENTER);\n        setRightMargin(3);\n        setLeftMargin(3);\n        super.setLineWidth(0);\n    }\n    \n    /* Force the line-width to 0, since the FigGroup that contains the \n     * stereotype may want to show a border, but we don't. */\n    @Override\n    public void setLineWidth(int w) {\n        super.setLineWidth(0);\n    }\n\n    /**\n     * This is needed for updating the guillemet style.\n     */\n    @Override\n    protected void setText() {\n        setText(keywordText);\n    }\n\n    /**\n     * Add guillemets to any text set to this Fig.\n     * {@inheritDoc}\n     */\n    @Override\n    public void setText(String text) {\n        assert keywordText.equals(text);\n        super.setText(NotationUtilityUml.formatStereotype(text,\n                getSettings().getNotationSettings().isUseGuillemets()));\n    }\n}\n", "human_rating": 3.990275310039388, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.ui.FigKeyword", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/ui/FigKeyword.java", "label_probabilities": {"readability": [0.990276, 0.00972377, 1.96938e-11, 0.0], "understandability": [0.99994, 6.00958e-05, 1.09142e-09, 1.57561e-10], "complexity": [1.76435e-12, 6.68895e-05, 0.163979, 0.835954], "modularization": [0.0, 0.000145144, 0.150557, 0.849298], "overall": [0.94422, 0.0556738, 0.000105953, 2.20192e-09]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.ui.FigStereotypesGroup", "source": "/* $Id: FigStereotypesGroup.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *******************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    Bob Tarling\n *******************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n// $Id: FigStereotypesGroup.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.ui;\n\nimport java.awt.Dimension;\nimport java.awt.Image;\nimport java.awt.Rectangle;\nimport java.beans.PropertyChangeEvent;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport org.argouml.kernel.Project;\nimport org.argouml.model.AddAssociationEvent;\nimport org.argouml.model.Model;\nimport org.argouml.model.RemoveAssociationEvent;\nimport org.argouml.uml.diagram.DiagramSettings;\nimport org.tigris.gef.presentation.Fig;\nimport org.tigris.gef.presentation.FigRect;\nimport org.tigris.gef.presentation.FigText;\n\n/**\n * A Fig designed to be the child of some FigNode or FigEdge to display the\n * stereotypes of the model element represented by the parent Fig.\n * Currently, multiple stereotypes are shown stacked one on top of the other,\n * each enclosed by guillemets.<p>\n *\n * The minimum width of this fig is the largest minimum width of its child\n * figs. The minimum height of this fig is the total minimum height of its child\n * figs.<p>\n *\n * The owner of this Fig is the UML element that is extended\n * with the stereotypes. We are listening to changes to the model:\n * addition and removal of stereotypes. <p>\n *\n * This fig supports showing one keyword\n * as the first \"stereotype\" in the list. <p>\n *\n * There is no way to remove a keyword fig, once added. <p>\n *\n * TODO: Allow for UML2 style display where all stereotypes are displayed in\n * the same guillemet pair and are delimited by commas. The style should be\n * changeable by calling getOrientation(Orientation). The swidget Orientation\n * class can be used for this.\n * @author Bob Tarling\n */\npublic class FigStereotypesGroup extends ArgoFigGroup {\n\n    private Fig bigPort;\n\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(FigStereotypesGroup.class.getName());\n\n    /**\n     * One UML keyword is allowed. These are not strictly stereotypes but are\n     * displayed as such. e.g. &lt;&lt;interface&gt;&gt;\n     */\n    private String keyword;\n\n    private int stereotypeCount = 0;\n\n    private boolean hidingStereotypesWithIcon = false;\n\n    private void constructFigs(int x, int y, int w, int h) {\n        bigPort = new FigRect(x, y, w, h, LINE_COLOR, FILL_COLOR);\n        addFig(bigPort);\n        bigPort.setFilled(false);\n\n        /* Do not show border line, make transparent: */\n        setLineWidth(0);\n        setFilled(false);\n    }\n\n    /**\n     * The constructor.\n     *\n     * @param owner owning UML element\n     * @param bounds position and size\n     * @param settings render settings\n     */\n    public FigStereotypesGroup(Object owner, Rectangle bounds,\n            DiagramSettings settings) {\n        super(owner, settings);\n        constructFigs(bounds.x, bounds.y, bounds.width, bounds.height);\n        Model.getPump().addModelEventListener(this, owner, \"stereotype\");\n        populate();\n    }\n\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#removeFromDiagram()\n     */\n    @Override\n    public void removeFromDiagram() {\n        /* Remove all items in the group,\n         * otherwise the model event listeners remain:\n         * TODO: Why does a FigGroup not do this? */\n        for (Object f : getFigs()) {\n            ((Fig) f).removeFromDiagram();\n        }\n        super.removeFromDiagram();\n        Model.getPump()\n                .removeModelEventListener(this, getOwner(), \"stereotype\");\n    }\n\n    /**\n     * @return the bigport\n     * @deprecated for 0.27.2. For backward compatibility only. The visibility\n     *             of this method will be changed to private in the next release\n     *             when FigStereotypesCompartment is removed.\n     */\n    @Deprecated\n    protected Fig getBigPort() {\n        return bigPort;\n    }\n\n    @Override\n    public void propertyChange(PropertyChangeEvent event) {\n        if (event instanceof AddAssociationEvent) {\n            AddAssociationEvent aae = (AddAssociationEvent) event;\n            if (event.getPropertyName().equals(\"stereotype\")) {\n                Object stereotype = aae.getChangedValue();\n                if (findFig(stereotype) == null) {\n                    FigText stereotypeTextFig =\n                        new FigStereotype(stereotype,\n                                getBoundsForNextStereotype(),\n                                getSettings());\n                    stereotypeCount++;\n                    addFig(stereotypeTextFig);\n                    reorderStereotypeFigs();\n                    damage();\n                }\n            } else {\n                LOG.log(Level.WARNING, \"Unexpected property \" + event.getPropertyName());\n            }\n        }\n        if (event instanceof RemoveAssociationEvent) {\n            if (event.getPropertyName().equals(\"stereotype\")) {\n                RemoveAssociationEvent rae = (RemoveAssociationEvent) event;\n                Object stereotype = rae.getChangedValue();\n                Fig f = findFig(stereotype);\n                if (f != null) {\n                    removeFig(f);\n                    f.removeFromDiagram(); // or vice versa?\n                    --stereotypeCount;\n                }\n            } else {\n                LOG.log(Level.WARNING, \"Unexpected property \" + event.getPropertyName());\n            }\n        }\n    }\n\n    /**\n     * Keep the Figs which are likely invisible at the end of the list.\n     */\n    private void reorderStereotypeFigs() {\n\tList<Fig> allFigs = getFigs();\n\tList<Fig> figsWithIcon = new ArrayList<Fig>();\n\tList<Fig> figsWithOutIcon = new ArrayList<Fig>();\n\tList<Fig> others = new ArrayList<Fig>();\n\n\t// TODO: This doesn't do anything special with keywords.\n\t// They should probably go first.\n\tfor (Fig f : allFigs) {\n            if (f instanceof FigStereotype) {\n                FigStereotype s = (FigStereotype) f;\n                if (getIconForStereotype(s) != null) {\n                    figsWithIcon.add(s);\n                } else {\n                    figsWithOutIcon.add(s);\n                }\n            } else {\n                others.add(f);\n            }\n        }\n\n\tList<Fig> n = new ArrayList<Fig>();\n\n\tn.addAll(others);\n\tn.addAll(figsWithOutIcon);\n\tn.addAll(figsWithIcon);\n\n\tsetFigs(n);\n    }\n\n    private FigStereotype findFig(Object stereotype) {\n        for (Object f : getFigs()) {\n            if (f instanceof FigStereotype) {\n                FigStereotype fs = (FigStereotype) f;\n                if (fs.getOwner() == stereotype) {\n                    return fs;\n                }\n            }\n        }\n        return null;\n    }\n\n    /**\n     * Get all the child figs that represent the individual stereotypes\n     * @return a List of the stereotype Figs\n     */\n    List<FigStereotype> getStereotypeFigs() {\n        final List<FigStereotype> stereotypeFigs =\n            new ArrayList<FigStereotype>();\n        for (Object f : getFigs()) {\n            if (f instanceof FigStereotype) {\n                FigStereotype fs = (FigStereotype) f;\n                stereotypeFigs.add(fs);\n            }\n        }\n        return stereotypeFigs;\n    }\n\n    private FigKeyword findFigKeyword() {\n        for (Object f : getFigs()) {\n            if (f instanceof FigKeyword) {\n                return (FigKeyword) f;\n            }\n        }\n        return null;\n    }\n\n    /**\n     * TODO: This should become private and only called from constructor\n     *\n     * @see org.argouml.uml.diagram.ui.FigCompartment#populate()\n     */\n    public void populate() {\n\n        stereotypeCount = 0;\n        Object modelElement = getOwner();\n        if (modelElement == null) {\n            // TODO: This block can be removed after issue 4075 is tackled\n            LOG.log(Level.FINE, \"Cannot populate the stereotype compartment \"\n                     + \"unless the parent has an owner.\");\n            return;\n        }\n\n        if (LOG.isLoggable(Level.FINE)) {\n            LOG.log(Level.FINE, \"Populating stereotypes compartment for {0}\",\n                    Model.getFacade().getName(modelElement));\n        }\n\n        /* This will contain the Figs that we do not need anymore: */\n        Collection<Fig> removeCollection = new ArrayList<Fig>(getFigs());\n\n        //There is one fig more in the group than (stereotypes + keyword):\n        if (keyword != null) {\n            FigKeyword keywordFig = findFigKeyword();\n            if (keywordFig == null) {\n                // The keyword fig does not exist yet.\n                // Let's create one:\n                keywordFig =\n                    new FigKeyword(keyword,\n                            getBoundsForNextStereotype(),\n                            getSettings());\n                // bounds not relevant here\n                addFig(keywordFig);\n            } else {\n                // The keyword fig already exists.\n                removeCollection.remove(keywordFig);\n            }\n            ++stereotypeCount;\n        }\n\n        for (Object stereo : Model.getFacade().getStereotypes(modelElement)) {\n            FigStereotype stereotypeTextFig = findFig(stereo);\n            if (stereotypeTextFig == null) {\n                stereotypeTextFig =\n                    new FigStereotype(stereo,\n                            getBoundsForNextStereotype(),\n                            getSettings());\n                // bounds not relevant here\n                addFig(stereotypeTextFig);\n            } else {\n             // The stereotype fig already exists.\n                removeCollection.remove(stereotypeTextFig);\n            }\n            ++stereotypeCount;\n        }\n\n        //cleanup of unused FigText's\n        for (Fig f : removeCollection) {\n            if (f instanceof FigStereotype || f instanceof FigKeyword) {\n                removeFig(f);\n            }\n        }\n\n        reorderStereotypeFigs();\n\n        // remove all stereotypes that have a graphical icon\n        updateHiddenStereotypes();\n\n    }\n\n    /**\n     * Get the number of stereotypes contained in this group\n     * @return the number of stereotypes in this group\n     */\n    public int getStereotypeCount() {\n        return stereotypeCount;\n    }\n\n    private Rectangle getBoundsForNextStereotype() {\n        return new Rectangle(\n                bigPort.getX() + 1,\n                bigPort.getY() + 1\n                + (stereotypeCount\n                * ROWHEIGHT),\n                0,\n                ROWHEIGHT - 2);\n    }\n\n    private void updateHiddenStereotypes() {\n        List<Fig> figs = getFigs();\n        for (Fig f : figs) {\n            if (f instanceof FigStereotype) {\n                FigStereotype fs = (FigStereotype) f;\n                fs.setVisible(getIconForStereotype(fs) == null\n                        || !isHidingStereotypesWithIcon());\n            }\n        }\n    }\n\n    private Image getIconForStereotype(FigStereotype fs) {\n        // TODO: Find a way to replace this dependency on Project\n        Project project = getProject();\n        if (project == null) {\n            LOG.log(Level.WARNING, \"getProject() returned null\");\n            return null;\n        }\n        Object owner = fs.getOwner();\n        if (owner == null) {\n            // keywords which look like a stereotype (e.g. <<interface>>) have\n            // no owner\n            return null;\n        } else {\n            return project.getProfileConfiguration().getFigNodeStrategy()\n                    .getIconForStereotype(owner);\n        }\n    }\n\n    /*\n     * @see org.tigris.gef.presentation.Fig#setBoundsImpl(int, int, int, int)\n     */\n    @Override\n    protected void setBoundsImpl(int x, int y, int w, int h) {\n        Rectangle oldBounds = getBounds();\n\n        Dimension minimumSize = getMinimumSize();\n        int newW = Math.max(w, minimumSize.width);\n        int newH = Math.max(h, minimumSize.height);\n\n        int yy = y;\n        for  (Fig fig : (Collection<Fig>) getFigs()) {\n            if (fig != bigPort) {\n                fig.setBounds(x, yy, newW,\n                              fig.getMinimumSize().height);\n                yy += fig.getMinimumSize().height;\n            }\n        }\n        bigPort.setBounds(x, y, newW, newH);\n        calcBounds();\n        firePropChange(\"bounds\", oldBounds, getBounds());\n    }\n\n    /**\n     * Allows a parent Fig to specify some keyword text to display amongst the\n     * stereotypes.\n     * An example of this usage is to display &lt;&lt;interface&gt;&gt;\n     * on FigInterface.\n     * @param word the text of the pseudo stereotype\n     */\n    public void setKeyword(String word) {\n        keyword = word;\n        populate();\n    }\n\n    /**\n     * @return true if textual stereotypes are being hidden in preference to\n     *         displaying icon.\n     */\n    public boolean isHidingStereotypesWithIcon() {\n        return hidingStereotypesWithIcon;\n    }\n\n    /**\n     * Turn on/off textual stereotype display in preference to icon.\n     *\n     * @param hideStereotypesWithIcon true to hide textual stereotypes and\n     *                show icon instead.\n     */\n    public void setHidingStereotypesWithIcon(boolean hideStereotypesWithIcon) {\n        this.hidingStereotypesWithIcon = hideStereotypesWithIcon;\n        updateHiddenStereotypes();\n    }\n\n    @Override\n    public Dimension getMinimumSize() {\n        // if there are no stereotypes, we return (0,0), preventing\n        // double lines in the class (see issue 4939)\n        Dimension dim = null;\n        Object modelElement = getOwner();\n\n        if (modelElement != null) {\n            List<FigStereotype> stereos = getStereotypeFigs();\n            if (stereos.size() > 0 || keyword != null) {\n                int minWidth = 0;\n                int minHeight = 0;\n                //set new bounds for all included figs\n                for (Fig fig : (Collection<Fig>) getFigs()) {\n                    if (fig.isVisible() && fig != bigPort) {\n                        int fw = fig.getMinimumSize().width;\n                        if (fw > minWidth) {\n                            minWidth = fw;\n                        }\n                        minHeight += fig.getMinimumSize().height;\n                    }\n                }\n\n                minHeight += 2; // 2 Pixel padding after compartment\n                dim = new Dimension(minWidth, minHeight);\n            }\n        }\n        if (dim == null) {\n            dim = new Dimension(0, 0);\n        }\n        return dim;\n    }\n}\n", "human_rating": 2.714146826516, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.ui.FigStereotypesGroup", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/ui/FigStereotypesGroup.java", "label_probabilities": {"readability": [9.41629e-07, 0.715164, 0.283816, 0.00101906], "understandability": [6.68991e-07, 0.293036, 0.696728, 0.0102362], "complexity": [0.129871, 0.847769, 0.0223599, 3.9901e-16], "modularization": [8.35648e-10, 0.655748, 0.344248, 3.7377e-06], "overall": [2.87826e-12, 0.0110794, 0.92609, 0.0628303]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.ui.FigUsage", "source": "/* $Id: FigUsage.java 17865 2010-01-12 20:45:26Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.ui;\n\nimport org.argouml.uml.diagram.DiagramSettings;\n\n/**\n * This class represents a Fig for a Usage.\n *\n * @author Markus Klink\n */\npublic class FigUsage extends FigDependency {\n\n    /**\n     * Construct a Fig.\n     * \n     * @param owner owning UML element\n     * @param settings render settings\n     */\n    public FigUsage(Object owner, DiagramSettings settings) {\n        super(owner, settings);\n    }\n    \n} \n\n", "human_rating": 3.9571827370002413, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.ui.FigUsage", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/ui/FigUsage.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.ui.PathConvPercent2", "source": "/* $Id: PathConvPercent2.java 17865 2010-01-12 20:45:26Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram.ui;\n\nimport java.awt.Point;\n\nimport org.tigris.gef.base.PathConv;\nimport org.tigris.gef.presentation.Fig;\n\n/**\n * Used to place labels as specific positions along a FigEdge. For example, a\n * label can be placed in the middle of a FigEdge by using 50%. This version\n * changes the behavior as it tries to avoid that the itemFig cuts through the\n * pathFig.\n *\n * @author abonner@ics.uci.edu\n */\npublic class PathConvPercent2 extends PathConv {\n\n    /**\n     * The item Fig.\n     */\n    private Fig itemFig;\n\n    /**\n     * The percent.\n     */\n    private int percent;\n\n    /**\n     * The offset.\n     */\n    private int offset;\n\n    /**\n     * Constructor.\n     *\n     * @param theFig The Fig.\n     * @param theItemFig The item Fig.\n     * @param newPercent The percent.\n     * @param newOffset The offset.\n     */\n    public PathConvPercent2(Fig theFig, Fig theItemFig, int newPercent,\n            int newOffset) {\n        super(theFig);\n        itemFig = theItemFig;\n        setPercentOffset(newPercent, newOffset);\n    }\n\n    /*\n     * @see org.tigris.gef.base.PathConv#stuffPoint(java.awt.Point)\n     */\n    public void stuffPoint(Point res) {\n        int figLength = _pathFigure.getPerimeterLength();\n        if (figLength < 10) {\n            res.setLocation(_pathFigure.getCenter());\n            return;\n        }\n        int pointToGet = (figLength * percent) / 100;\n\n        _pathFigure.stuffPointAlongPerimeter(pointToGet, res);\n\n        applyOffsetAmount(_pathFigure.pointAlongPerimeter(pointToGet + 5),\n                _pathFigure.pointAlongPerimeter(pointToGet - 5), offset, res);\n    }\n\n    /**\n     * Set the percent and offset again.\n     *\n     * @param newPercent The new percent.\n     * @param newOffset The new offset.\n     */\n    public void setPercentOffset(int newPercent, int newOffset) {\n        percent = newPercent;\n        offset = newOffset;\n    }\n\n    /*\n     * @see org.tigris.gef.base.PathConv#setClosestPoint(java.awt.Point)\n     */\n    public void setClosestPoint(Point newPoint) {\n    }\n\n    /*\n     * @see org.tigris.gef.base.PathConv#applyOffsetAmount(java.awt.Point, java.awt.Point, int, java.awt.Point)\n     */\n    protected void applyOffsetAmount(\n            Point p1, Point p2,\n            int theOffset, Point res) {\n        // slope of the line we're finding the normal to\n        // is slope, and the normal is the negative reciprocal\n        // slope is (p1.y - p2.y) / (p1.x - p2.x)\n        // so recip is - (p1.x - p2.x) / (p1.y - p2.y)\n        int recipnumerator = (p1.x - p2.x) * -1;\n        int recipdenominator = (p1.y - p2.y);\n\n        if (recipdenominator == 0 && recipnumerator == 0) {\n            return;\n        }\n\n\n        // find the point offset on the line that gives a\n        // correct offset\n\n        double len =\n            Math.sqrt(recipnumerator * recipnumerator\n                + recipdenominator * recipdenominator);\n        int dx = (int) ((recipdenominator * theOffset) / len);\n        int dy = (int) ((recipnumerator * theOffset) / len);\n\n        res.x += Math.abs(dx);\n        res.y -= Math.abs(dy);\n\n        int width = itemFig.getWidth() / 2;\n\n        if (recipnumerator != 0) {\n            double slope = (double) recipdenominator / (double) recipnumerator;\n\n            double factor = tanh(slope);\n            res.x += (Math.abs(factor) * width);\n        } else {\n            res.x += width;\n        }\n    }\n\n    /**\n     * Calculate the tangens hyperbolicus.\n     *\n     * @param x The argument.\n     * @return tangens hyberbolicus\n     */\n    private double tanh(double x) {\n        return ((Math.exp(x) - Math.exp(-x)) / 2)\n            / ((Math.exp(x) + Math.exp(-x)) / 2);\n    }\n\n    /**\n     * The UID.\n     */\n    private static final long serialVersionUID = -8079350336685789199L;\n}\n", "human_rating": 3.2410664399999995, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.ui.PathConvPercent2", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/ui/PathConvPercent2.java", "label_probabilities": {"readability": [0.256748, 0.733391, 0.00403962, 0.0058222], "understandability": [0.303383, 0.690694, 0.00592241, 1.95173e-09], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.619238, 0.380749, 1.34377e-05, 2.25644e-14]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.diagram.UmlDiagramRenderer", "source": "/* $Id: UmlDiagramRenderer.java 19614 2011-07-20 12:10:13Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.diagram;\n\nimport java.util.Map;\n\nimport org.argouml.model.Model;\nimport org.argouml.uml.CommentEdge;\nimport org.argouml.uml.diagram.ui.FigCompartmentBox;\nimport org.argouml.uml.diagram.ui.FigEdgeModelElement;\nimport org.tigris.gef.base.Layer;\nimport org.tigris.gef.graph.GraphEdgeRenderer;\nimport org.tigris.gef.graph.GraphNodeRenderer;\nimport org.tigris.gef.presentation.Fig;\nimport org.tigris.gef.presentation.FigEdge;\nimport org.tigris.gef.presentation.FigNode;\n\n/**\n * Factory methods to create Figs based an model elements with supplementary\n * data provided by a map of name value pairs.<p>\n *\n * Provides {@link org.tigris.gef.graph.GraphNodeRenderer#getFigNodeFor(\n * Object, int, int, Map)} to implement the {@link GraphNodeRenderer}\n * interface and {@link\n * org.tigris.gef.graph.GraphEdgeRenderer#getFigEdgeFor(Object, Map)}\n * to implement the {@link GraphEdgeRenderer} interface.\n */\npublic abstract class UmlDiagramRenderer\n    implements GraphNodeRenderer, GraphEdgeRenderer {\n\n    /**\n     * @deprecated for 0.27.3 by tfmorris. Only used by\n     *             {@link DiagramFactory#createRenderingElement(Object, Object)}\n     *             which is itself unused (and now deprecated).\n     */\n    @Deprecated\n    public FigNode getFigNodeFor(\n\t    Object node, int x, int y,\n\t    Map styleAttributes) {\n        return null;\n//        if (node == null) {\n//            throw new IllegalArgumentException(\n//                    \"A model element must be supplied\");\n//        }\n//        FigNode figNode = null;\n//        if (Model.getFacade().isAComment(node)) {\n//            figNode = new FigComment();\n//        } else if (Model.getFacade().isAStubState(node)) {\n//            return new FigStubState();\n//        } else if (Model.getFacade().isAAssociationClass(node)) {\n//            figNode = new FigClassAssociationClass(node, x, y, 10, 10);\n//        } else if (Model.getFacade().isAClass(node)) {\n//            figNode = new FigClass(node, x, y, 10, 10);\n//        } else if (Model.getFacade().isAInterface(node)) {\n//            figNode = new FigInterface();\n//        } else if (Model.getFacade().isAEnumeration(node)) {\n//            figNode = new FigEnumeration();\n//        } else if (Model.getFacade().isAStereotype(node)) {\n//            figNode = new FigStereotypeDeclaration();\n//        } else if (Model.getFacade().isADataType(node)) {\n//            figNode = new FigDataType();\n//        } else if (Model.getFacade().isAModel(node)) {\n//            figNode = new FigModel(node, x, y);\n//        } else if (Model.getFacade().isASubsystem(node)) {\n//            figNode = new FigSubsystem(node, x, y);\n//        } else if (Model.getFacade().isAPackage(node)) {\n//            figNode = new FigPackage(node, x, y);\n//        } else if (Model.getFacade().isAAssociation(node)) {\n//            figNode = new FigNodeAssociation();\n//        } else if (Model.getFacade().isAActor(node)) {\n//            figNode = new FigActor();\n//        } else if (Model.getFacade().isAUseCase(node)) {\n//            figNode = new FigUseCase();\n//        } else if (Model.getFacade().isAPartition(node)) {\n//            figNode = new FigPartition();\n//        } else if (Model.getFacade().isACallState(node)) {\n//            figNode = new FigCallState();\n//        } else if (Model.getFacade().isAObjectFlowState(node)) {\n//            figNode = new FigObjectFlowState();\n//        } else if (Model.getFacade().isASubactivityState(node)) {\n//            figNode = new FigSubactivityState();\n//        } else if (Model.getFacade().isAClassifierRole(node)) {\n//            figNode = new FigClassifierRole();\n//        } else if (Model.getFacade().isAMessage(node)) {\n//            figNode = new FigMessage();\n//        } else if (Model.getFacade().isANode(node)) {\n//            figNode = new FigMNode();\n//        } else if (Model.getFacade().isANodeInstance(node)) {\n//            figNode = new FigNodeInstance();\n//        } else if (Model.getFacade().isAComponent(node)) {\n//            figNode = new FigComponent();\n//        } else if (Model.getFacade().isAComponentInstance(node)) {\n//            figNode = new FigComponentInstance();\n//        } else if (Model.getFacade().isAObject(node)) {\n//            figNode = new FigObject();\n//        } else if (Model.getFacade().isAComment(node)) {\n//            figNode = new FigComment();\n//        } else if (Model.getFacade().isAActionState(node)) {\n//            figNode = new FigActionState();\n//        } else if (Model.getFacade().isAFinalState(node)) {\n//            figNode = new FigFinalState();\n//        } else if (Model.getFacade().isASubmachineState(node)) {\n//            figNode = new FigSubmachineState();\n//        } else if (Model.getFacade().isAConcurrentRegion(node)) {\n//            figNode = new FigConcurrentRegion();\n//        } else if (Model.getFacade().isASynchState(node)) {\n//            figNode = new FigSynchState();\n//        } else if (Model.getFacade().isACompositeState(node)) {\n//            figNode = new FigCompositeState();\n//        } else if (Model.getFacade().isAState(node)) {\n//            figNode = new FigSimpleState();\n//        } else if (Model.getFacade().isAPseudostate(node)) {\n//            Object pState = node;\n//            Object kind = Model.getFacade().getKind(pState);\n//            if (Model.getPseudostateKind().getInitial().equals(kind)) {\n//                figNode = new FigInitialState();\n//            } else if (Model.getPseudostateKind().getChoice()\n//                    .equals(kind)) {\n//                figNode = new FigBranchState();\n//            } else if (Model.getPseudostateKind().getJunction()\n//                    .equals(kind)) {\n//                figNode = new FigJunctionState();\n//            } else if (Model.getPseudostateKind().getFork().equals(kind)) {\n//                figNode = new FigForkState();\n//            } else if (Model.getPseudostateKind().getJoin().equals(kind)) {\n//                figNode = new FigJoinState();\n//            } else if (Model.getPseudostateKind().getShallowHistory()\n//                    .equals(kind)) {\n//                figNode = new FigShallowHistoryState();\n//            } else if (Model.getPseudostateKind().getDeepHistory()\n//                    .equals(kind)) {\n//                figNode = new FigDeepHistoryState();\n//            }\n//        }\n//\n//        if (figNode == null) {\n//            throw new IllegalArgumentException(\n//                    \"Failed to construct a FigNode for \" + node);\n//        }\n//        setStyleAttributes(figNode, styleAttributes);\n//\n//        return figNode;\n    }\n\n    /**\n     * Set the fig style according to attributes. <p>\n     * \n     * TODO: This is never used! Can we remove?\n     *\n     * @param fig the fig to style.\n     * @param attributeMap a map of name value pairs\n     */\n    private void setStyleAttributes(Fig fig, Map<String, String> attributeMap) {\n        String name;\n        String value;\n        for (Map.Entry<String, String> entry : attributeMap.entrySet()) {\n            name = entry.getKey();\n            value = entry.getValue();\n\n            if (fig instanceof FigCompartmentBox) {\n                FigCompartmentBox fcb = (FigCompartmentBox) fig;\n                if (\"operationsVisible\".equals(name)) {\n                    fcb.showCompartment(\n                            Model.getMetaTypes().getOperation(), \n                            value.equalsIgnoreCase(\"true\"));\n                } else if (\"attributesVisible\".equals(name)) {\n                    fcb.showCompartment(\n                            Model.getMetaTypes().getAttribute(), \n                            value.equalsIgnoreCase(\"true\"));\n                } else if (\"enumerationLiteralsVisible\".equals(name)) {\n                    fcb.showCompartment(\n                            Model.getMetaTypes().getEnumerationLiteral(), \n                            value.equalsIgnoreCase(\"true\"));\n                } else if (\"extensionPointVisible\".equals(name)) {\n                    fcb.showCompartment(\n                            Model.getMetaTypes().getExtensionPoint(), \n                            value.equalsIgnoreCase(\"true\"));\n                }\n            }\n        }\n    }\n\n    /**\n     * @deprecated for 0.27.3 by tfmorris.  Use method of same name which takes\n     * a GraphModel argument in the subclasses of this class.\n     * @see org.tigris.gef.graph.GraphEdgeRenderer#getFigEdgeFor(java.lang.Object, java.util.Map)\n     */\n    @Deprecated\n    public FigEdge getFigEdgeFor(Object edge, Map styleAttributes) {\n        return null;\n//        if (edge == null) {\n//            throw new IllegalArgumentException(\n//                    \"A model edge must be supplied\");\n//        }\n//        FigEdge newEdge = null;\n//        if (Model.getFacade().isAAssociationClass(edge)) {\n//            newEdge = new FigAssociationClass();\n//        } else if (Model.getFacade().isAAssociationEnd(edge)) {\n//            newEdge = new FigAssociationEnd();\n//        } else if (Model.getFacade().isAAssociation(edge)) {\n//            newEdge = new FigAssociation();\n//        } else if (Model.getFacade().isALink(edge)) {\n//            newEdge = new FigLink();\n//        } else if (Model.getFacade().isAGeneralization(edge)) {\n//            newEdge = new FigGeneralization();\n//        } else if (Model.getFacade().isAPackageImport(edge)) {\n//            newEdge = new FigPermission();\n//        } else if (Model.getFacade().isAUsage(edge)) {\n//            newEdge = new FigUsage();\n//        } else if (Model.getFacade().isADependency(edge)) {\n//            if (Model.getExtensionMechanismsHelper().hasStereotype(edge, \n//                    CoreFactory.REALIZE_STEREOTYPE)) {\n//                newEdge = new FigAbstraction();\n//            } else {\n//                newEdge = new FigDependency();\n//            }\n//        } else if (edge instanceof CommentEdge) {\n//            newEdge = null;\n//        } else if (Model.getFacade().isAAssociationRole(edge)) {\n//            newEdge = new FigAssociationRole();\n//        } else if (Model.getFacade().isATransition(edge)) {\n//            newEdge = new FigTransition();\n//        } else if (Model.getFacade().isAExtend(edge)) {\n//            newEdge = new FigExtend();\n//        } else if (Model.getFacade().isAInclude(edge)) {\n//            newEdge = new FigInclude();\n//        }\n//\n//        if (newEdge == null) {\n//            throw new IllegalArgumentException(\n//                    \"Failed to construct a FigEdge for \" + edge);\n//        }\n//\n//        return newEdge;\n    }\n\n    /**\n     * Find the Figs in the given layer that should be the source and\n     * destination and attach these to either end of the FigEdge\n     * @param layer the layer to look for the FigNodes\n     * @param newEdge The edge to attach\n     */\n    protected final void setPorts(Layer layer, FigEdge newEdge) {\n        Object modelElement = newEdge.getOwner();\n        if (newEdge.getSourcePortFig() == null) {\n            Object source;\n            if (modelElement instanceof CommentEdge) {\n                source = ((CommentEdge) modelElement).getSource();\n            } else {\n                source = Model.getUmlHelper().getSource(modelElement);\n            }\n            FigNode sourceNode = getNodePresentationFor(layer, source);\n            assert (sourceNode != null) : \"No FigNode found for \" + source;\n            setSourcePort(newEdge, sourceNode);\n        }\n\n        if (newEdge.getDestPortFig() == null) {\n            Object dest;\n            if (modelElement instanceof CommentEdge) {\n                dest = ((CommentEdge) modelElement).getDestination();\n            } else {\n                dest = Model.getUmlHelper().getDestination(newEdge.getOwner());\n            }\n            setDestPort(newEdge, getNodePresentationFor(layer, dest));\n        }\n        \n        if (newEdge.getSourcePortFig() == null\n                || newEdge.getDestPortFig() == null) {\n            throw new IllegalStateException(\"Edge of type \"\n                + newEdge.getClass().getName()\n                + \" created with no source or destination port\");\n        }\n    }\n\n    private void setSourcePort(FigEdge edge, FigNode source) {\n        edge.setSourcePortFig(source);\n        edge.setSourceFigNode(source);\n    }\n\n    private void setDestPort(FigEdge edge, FigNode dest) {\n        edge.setDestPortFig(dest);\n        edge.setDestFigNode(dest);\n    }\n    \n    /**\n     * Get the FigNode from the given layer that represents the given\n     * model element.\n     * The FigNode portion of an association class is returned in preference\n     * to the FigEdge portion.\n     * If no FigNode is found then a FIgEdge is searched for and the FigNode\n     * that acts as its edge port is returned.\n     * @param lay the layer containing the Fig\n     * @param modelElement the model element to find presentation for\n     * @return the FigNode presentation of the model element\n     */\n    protected FigNode getNodePresentationFor(Layer lay, Object modelElement) {\n        assert modelElement != null : \"A modelElement must be supplied\";\n        for (Object fig : lay.getContentsNoEdges()) {\n \n            if (fig instanceof FigNode\n                    && modelElement.equals(((FigNode) fig).getOwner())) {\n                return ((FigNode) fig);\n            }\n        }\n        for (Object fig : lay.getContentsEdgesOnly()) {\n            if (fig instanceof FigEdgeModelElement\n                    && modelElement.equals(((FigEdgeModelElement) fig)\n                            .getOwner())) {\n                return ((FigEdgeModelElement) fig).getEdgePort();\n            }\n        }\n        return null;\n    }\n    \n    \n    protected FigNode getFigNodeForAssociationEnd(\n            final ArgoDiagram diagram,\n            final Object associationEnd) {\n        final Object element; \n        element = \n            Model.getFacade().getClassifier(associationEnd);\n        return getNodePresentationFor(diagram.getLayer(), element);\n    }\n    \n    protected void addEdge(Layer lay, FigEdge newEdge, Object edge) {\n        if (newEdge == null) {\n            throw new IllegalArgumentException(\n                    \"Don't know how to create FigEdge for model type \"\n                    + edge.getClass().getName());\n        }\n        \n        setPorts(lay, newEdge);\n\n        assert newEdge != null : \"There has been no FigEdge created\";\n\n//        newEdge.setDiElement(\n//            GraphChangeAdapter.getInstance().createElement(gm, edge));\n\n        assert newEdge != null : \"There has been no FigEdge created\";\n        assert (newEdge.getDestFigNode() != null) \n            : \"The FigEdge has no dest node\";\n        assert (newEdge.getDestPortFig() != null) \n            : \"The FigEdge has no dest port\";\n        assert (newEdge.getSourceFigNode() != null) \n            : \"The FigEdge has no source node\";\n        assert (newEdge.getSourcePortFig() != null) \n            : \"The FigEdge has no source port\";\n\n        lay.add(newEdge);\n    }\n}\n", "human_rating": 2.99999628236, "metadata": {"project": "argoUML", "class": "org.argouml.uml.diagram.UmlDiagramRenderer", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/diagram/UmlDiagramRenderer.java", "label_probabilities": {"readability": [0.0, 0.999997, 2.64118e-06, 0.0], "understandability": [0.0, 0.0, 1.0, 0.0], "complexity": [0.0, 1.99467e-08, 1.0, 0.0], "modularization": [0.0, 0.0, 1.0, 0.0], "overall": [0.0, 0.0, 0.957485, 0.0425148]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.reveng.ui.ImportStatusScreen", "source": "/* $Id: ImportStatusScreen.java 17871 2010-01-12 20:49:55Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2008, 2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.reveng.ui;\n\nimport java.awt.BorderLayout;\nimport java.awt.Container;\nimport java.awt.Dimension;\nimport java.awt.Frame;\nimport java.awt.GridBagConstraints;\nimport java.awt.GridBagLayout;\nimport java.awt.Toolkit;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.event.WindowEvent;\nimport java.awt.event.WindowListener;\n\nimport javax.swing.JButton;\nimport javax.swing.JDialog;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JProgressBar;\nimport javax.swing.JScrollPane;\nimport javax.swing.JTextArea;\nimport javax.swing.SwingConstants;\nimport javax.swing.SwingUtilities;\n\nimport org.argouml.i18n.Translator;\nimport org.argouml.taskmgmt.ProgressEvent;\nimport org.argouml.taskmgmt.ProgressMonitor;\n\n/**\n * A window that shows the progress bar and a cancel button. As a convenience to\n * callers which may be executing on a thread other than the Swing event thread,\n * all methods use SwingUtilities.invokeLater() or\n * SwingUtilities.invokeAndWait() to make sure that Swing calls happen on the\n * appropriate thread.\n *<p>\n * TODO: React on the close button as if the Cancel button was pressed.\n */\npublic class ImportStatusScreen extends JDialog \n    implements ProgressMonitor, WindowListener {\n    \n    private JButton cancelButton;\n    private JLabel progressLabel;\n    private JProgressBar progress;\n    private JTextArea messageArea;\n    private boolean hasMessages = false;\n    private boolean canceled = false;\n\n    /**\n     * The constructor.\n     *\n     * @param title\n     * @param iconName\n     */\n    public ImportStatusScreen(Frame frame, String title, String iconName) {\n        super(frame, true);\n        if (title != null) {\n            setTitle(title);\n        }\n        Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();\n        getContentPane().setLayout(new BorderLayout(4, 4));\n        Container panel = new JPanel(new GridBagLayout());\n\n        // Parsing file x of z.\n        progressLabel = new JLabel();\n        progressLabel.setHorizontalAlignment(SwingConstants.RIGHT);\n\n        GridBagConstraints gbc = new GridBagConstraints();\n        gbc.anchor = GridBagConstraints.NORTH;\n        gbc.fill = GridBagConstraints.HORIZONTAL;\n        gbc.gridwidth = GridBagConstraints.REMAINDER;\n        gbc.gridheight = 1;\n        gbc.gridx = 0;\n        gbc.gridy = 0;\n        gbc.weightx = 0.1;\n        \n        panel.add(progressLabel, gbc);\n        gbc.gridy++;\n        \n        // progress bar\n        progress = new JProgressBar();\n        gbc.anchor = GridBagConstraints.CENTER;\n        panel.add(progress, gbc);\n        gbc.gridy++;\n        \n        panel.add(\n                new JLabel(Translator.localize(\"label.import-messages\")), gbc);\n        gbc.gridy++;\n        \n        // Error/warning messageArea\n        messageArea = new JTextArea(10, 50);\n        gbc.weighty = 0.8;\n//        gbc.gridheight = 10;\n        gbc.fill = GridBagConstraints.BOTH;\n        panel.add(new JScrollPane(messageArea), gbc);\n        gbc.gridy++;\n\n        // cancel/close button\n        cancelButton = new JButton(Translator.localize(\"button.cancel\"));\n\n        gbc.fill = GridBagConstraints.NONE;\n        gbc.anchor = GridBagConstraints.SOUTH;\n        gbc.weighty = 0.1;\n        gbc.gridheight = GridBagConstraints.REMAINDER;\n        panel.add(cancelButton, gbc);\n        gbc.gridy++;\n        \n        cancelButton.addActionListener(new ActionListener() {\n\n            public void actionPerformed(ActionEvent e) {\n                if (isComplete()) {\n                    close();\n                }\n                canceled = true;\n            }\n\n        });\n        \n        getContentPane().add(panel);\n        pack();\n        Dimension contentPaneSize = getContentPane().getPreferredSize();\n        setLocation(scrSize.width / 2 - contentPaneSize.width / 2,\n                scrSize.height / 2 - contentPaneSize.height / 2);\n        setResizable(true);\n        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);\n        addWindowListener(this);\n    }\n\n    public void setMaximumProgress(final int i) {\n        SwingUtilities.invokeLater(new Runnable () {\n            public void run() {\n                progress.setMaximum(i);\n                setVisible(true);\n            }\n        });\n    }\n\n    public void updateProgress(final int i) {\n        SwingUtilities.invokeLater(new Runnable () {\n            public void run() {\n                progress.setValue(i);\n                if (isComplete()) {\n                    if (hasMessages) {\n                        cancelButton.setText(\n                                Translator.localize(\"button.close\"));\n                    } else {\n                        close();\n                    }\n                }\n            }\n        });\n    }\n    \n    private boolean isComplete() {\n        return progress.getValue() == progress.getMaximum();\n    }\n\n    /**\n     * The UID.\n     */\n    private static final long serialVersionUID = -1336242911879462274L;\n\n    /*\n     * @see org.argouml.application.api.ProgressMonitor#close()\n     */\n    public void close() {\n        SwingUtilities.invokeLater(new Runnable () {\n            public void run() {\n                setVisible(false);\n                dispose();\n            }\n        });\n    }\n\n    /*\n     * @see org.argouml.application.api.ProgressMonitor#isCanceled()\n     */\n    public boolean isCanceled() {\n        return canceled;\n    }\n\n    /*\n     * @see org.argouml.application.api.ProgressMonitor#notifyMessage(java.lang.String, java.lang.String, java.lang.String)\n     */\n    public void notifyMessage(final String title, final String introduction,\n            final String message) {\n        hasMessages = true;\n        // TODO: Add filename ?\n        messageArea.setText(messageArea.getText() + title + \"\\n\" + introduction\n                + \"\\n\" + message + \"\\n\\n\");\n        messageArea.setCaretPosition(messageArea.getText().length());\n    }\n\n    /*\n     * @see org.argouml.application.api.ProgressMonitor#notifyNullAction()\n     */\n    public void notifyNullAction() {\n        String msg = Translator.localize(\"label.import.empty\");\n        notifyMessage(msg, msg, msg);\n    }\n\n    /*\n     * @see org.argouml.application.api.ProgressMonitor#updateMainTask(java.lang.String)\n     */\n    public void updateMainTask(final String name) {\n        SwingUtilities.invokeLater(new Runnable () {\n            public void run() {\n                setTitle(name);\n            }\n        });\n    }\n\n    /*\n     * @see org.argouml.application.api.ProgressMonitor#updateSubTask(java.lang.String)\n     */\n    public void updateSubTask(final String action) {\n        SwingUtilities.invokeLater(new Runnable () {\n            public void run() {\n                progressLabel.setText(action);\n            }\n        });\n    }\n\n    /*\n     * @see org.argouml.persistence.ProgressListener#progress(org.argouml.persistence.ProgressEvent)\n     */\n    public void progress(ProgressEvent event) throws InterruptedException {\n        // ignored\n    }\n\n    public void windowClosing(WindowEvent e) {\n        // User closing the progress window is interpreted as cancel request\n        canceled = true;\n        close();\n    }\n    \n    public void windowActivated(WindowEvent e) { }\n    public void windowClosed(WindowEvent e) { }\n    public void windowDeactivated(WindowEvent e) { }\n    public void windowDeiconified(WindowEvent e) { }\n    public void windowIconified(WindowEvent e) { }\n    public void windowOpened(WindowEvent e) { }\n\n}\n", "human_rating": 3.9571827370002413, "metadata": {"project": "argoUML", "class": "org.argouml.uml.reveng.ui.ImportStatusScreen", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/reveng/ui/ImportStatusScreen.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [4.70485e-06, 0.943148, 0.0568472, 1.39233e-07], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.619238, 0.380749, 1.34377e-05, 2.25644e-14]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.ActionImportFromSources", "source": "/* $Id: ActionImportFromSources.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.ui;\n\nimport java.awt.event.ActionEvent;\nimport java.io.File;\nimport java.util.Collection;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.Action;\nimport javax.swing.JFrame;\n\nimport org.argouml.application.api.CommandLineInterface;\nimport org.argouml.application.helpers.ResourceLoaderWrapper;\nimport org.argouml.i18n.Translator;\nimport org.argouml.ui.ExceptionDialog;\nimport org.argouml.ui.UndoableAction;\nimport org.argouml.uml.reveng.Import;\nimport org.argouml.uml.reveng.ImportInterface;\nimport org.argouml.uml.reveng.ImporterManager;\nimport org.argouml.uml.reveng.ui.ImportStatusScreen;\nimport org.argouml.util.ArgoFrame;\n\n\n/** Action to trigger importing from sources.\n * @stereotype singleton\n */\npublic class ActionImportFromSources extends UndoableAction\n        implements CommandLineInterface {\n\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(ActionImportFromSources.class.getName());\n\n    /**\n     * The singleton.\n     */\n    private static final ActionImportFromSources SINGLETON =\n        new ActionImportFromSources();\n\n    /**\n     *  The constructor.\n     */\n    public ActionImportFromSources() {\n        // this is never downlighted...\n        super(Translator.localize(\"action.import-sources\"),\n                ResourceLoaderWrapper.lookupIcon(\"action.import-sources\"));\n        // Set the tooltip string:\n        putValue(Action.SHORT_DESCRIPTION,\n                Translator.localize(\"action.import-sources\"));\n    }\n\n    /*\n     * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)\n     */\n    public void actionPerformed(ActionEvent event) {\n    \tsuper.actionPerformed(event);\n    \tif (ImporterManager.getInstance().hasImporters()) {\n            new Import(ArgoFrame.getFrame());\n    \t} else {\n            LOG.log(Level.INFO,\n                    \"Import sources dialog not shown: no importers!\");\n            ExceptionDialog ed = new ExceptionDialog(ArgoFrame.getFrame(),\n                Translator.localize(\"dialog.title.problem\"),\n                Translator.localize(\"dialog.import.no-importers.intro\"),\n                Translator.localize(\"dialog.import.no-importers.message\"));\n            ed.setModal(true);\n            ed.setVisible(true);\n    \t}\n    }\n\n    /**\n     * @return Returns the SINGLETON.\n     */\n    public static ActionImportFromSources getInstance() {\n        return SINGLETON;\n    }\n\n    /**\n     * Command line command for importing a directory or file.\n     *\n     * @param argument Formatted string (<importmodule>:<importpath>)\n     * @return true if the command was performed successfully.\n*/\n    public boolean doCommand(String argument) {\n        if (argument == null) {\n            LOG.log(Level.SEVERE, \"An argument has to be provided.\");\n            return false;\n        }\n        int index = argument.indexOf(':');\n        if (index == -1 || argument.length() <= index) {\n            LOG.log(Level.SEVERE,\n                    \"Argument must be <importmodule>:<importpath>\");\n            return false;\n        }\n        Import imp = new Import(null);\n        Collection languages = imp.getLanguages();\n        if (languages == null || languages.isEmpty()) {\n            LOG.log(Level.SEVERE, \"No importers available.\");\n            return false;\n        }\n        String importerName = argument.substring(0, index);\n        ImportInterface importer = imp.getImporter(importerName);\n        if (importer == null) {\n            LOG.log(Level.SEVERE,\n                    \"No import support for language \" + importerName);\n            return false;\n        }\n        imp.setCurrentModule(importer);\n        File file = new File(argument.substring(index + 1));\n        if (!file.exists()) {\n            LOG.log(Level.SEVERE,\n                    \"The specified file/directory doesn't exist.\");\n            return false;\n        }\n        imp.setFiles(new File[]{file});\n        ImportStatusScreen iss =\n            new ImportStatusScreen(new JFrame(), \"Importing\", \"Splash\");\n        imp.doImport(iss);\n        return true;\n    }\n}\n/* end class ActionImportFromSources */\n", "human_rating": 2.866483200000019, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.ActionImportFromSources", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/ActionImportFromSources.java", "label_probabilities": {"readability": [0.0104903, 0.845502, 0.144008, 1.89721e-14], "understandability": [1.35295e-05, 0.91556, 0.0844261, 7.86438e-14], "complexity": [1.97216e-12, 0.00792232, 0.991593, 0.000484901], "modularization": [1.62802e-09, 0.00122177, 0.186777, 0.812001], "overall": [6.96453e-05, 0.979798, 0.0201325, 2.51635e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.behavior.state_machines.ButtonActionNewGuard", "source": "/* $Id: ButtonActionNewGuard.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    bobtarling\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.ui.behavior.state_machines;\n\nimport java.awt.event.ActionEvent;\n\nimport org.argouml.application.helpers.ResourceLoaderWrapper;\nimport org.argouml.i18n.Translator;\nimport org.argouml.kernel.UmlModelMutator;\nimport org.argouml.model.Model;\nimport org.argouml.ui.UndoableAction;\nimport org.argouml.ui.targetmanager.TargetManager;\nimport org.tigris.toolbar.toolbutton.ModalAction;\n\n/**\n * This is an Action to be used for Buttons to create a guard.\n * If a guard already exists, then navigate to it.\n * \n * @author Michiel\n */\n@UmlModelMutator\npublic class ButtonActionNewGuard extends UndoableAction \n    implements ModalAction {\n\n    public ButtonActionNewGuard() {\n        super();\n        putValue(NAME, getKeyName());\n        putValue(SHORT_DESCRIPTION, Translator.localize(getKeyName()));\n        Object icon = ResourceLoaderWrapper.lookupIconResource(getIconName());\n        putValue(SMALL_ICON, icon);\n    }\n\n    public void actionPerformed(ActionEvent e) {\n        if (!isEnabled()) {\n            return;\n        }\n        super.actionPerformed(e);\n        Object target = TargetManager.getInstance().getModelTarget();\n        Object guard = Model.getFacade().getGuard(target);\n        if (guard == null) {\n            guard = Model.getStateMachinesFactory().buildGuard(target);\n        }\n        TargetManager.getInstance().setTarget(guard);\n    }\n\n    public boolean isEnabled() {\n        Object target = TargetManager.getInstance().getModelTarget();\n        return Model.getFacade().isATransition(target);\n    }\n\n    protected String getKeyName() {\n        return \"button.new-guard\";\n    }\n\n    protected String getIconName() {\n        return \"Guard\";\n    }\n}\n", "human_rating": 3.9082239103467358, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.behavior.state_machines.ButtonActionNewGuard", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/behavior/state_machines/ButtonActionNewGuard.java", "label_probabilities": {"readability": [0.908249, 0.0917257, 2.54051e-05, 1.46736e-10], "understandability": [0.958839, 0.0411602, 7.4424e-07, 1.67293e-14], "complexity": [1.14206e-12, 2.11612e-06, 0.0338668, 0.966131], "modularization": [0.0, 2.33187e-10, 0.0263247, 0.973675], "overall": [0.992887, 0.007113, 1.14254e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.behavior.state_machines.PopupMenuNewEvent", "source": "/* $Id: PopupMenuNewEvent.java 19388 2011-05-09 20:24:23Z bobtarling $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    mvw\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.ui.behavior.state_machines;\n\nimport javax.swing.Action;\nimport javax.swing.JMenu;\nimport javax.swing.JMenuItem;\nimport javax.swing.JPopupMenu;\n\nimport org.argouml.i18n.Translator;\nimport org.argouml.uml.ui.ActionRemoveModelElement;\nimport org.argouml.uml.ui.behavior.activity_graphs.ActionAddEventAsTrigger;\n\n/**\n * @since Dec 15, 2002\n * @author jaap.branderhorst@xs4all.nl\n * @deprecated by Bob Tarling in 0.33.4. This is no longer used\n */\n@Deprecated\npublic class PopupMenuNewEvent extends JPopupMenu {\n\n    /**\n     * Constructor for PopupMenuNewEvent.<p>\n     *\n     * Constructs a new popupmenu. The given parameter role determines what\n     * the purpose is of the events that can be created via this popupmenu.\n     * The parameter must comply to the interface Roles\n     * defined on ActionNewEvent.\n     *\n     * @param role the role\n     * @param target the target\n     */\n    public PopupMenuNewEvent(String role, Object target) {\n        super();\n\n        buildMenu(this, role, target);\n    }\n    \n    static void buildMenu(JPopupMenu pmenu, String role, Object target) {\n        \n        assert role != null;\n        assert target != null;\n\n        if (role.equals(ActionNewEvent.Roles.DEFERRABLE_EVENT)\n                || role.equals(ActionNewEvent.Roles.TRIGGER)) {\n            JMenu select = new JMenu(Translator.localize(\"action.select\"));\n//            select.setText(Translator.localize(\"action.select\"));\n            if (role.equals(ActionNewEvent.Roles.DEFERRABLE_EVENT)) {\n                ActionAddEventAsDeferrableEvent.SINGLETON.setTarget(target);\n                JMenuItem menuItem = new JMenuItem(\n                        ActionAddEventAsDeferrableEvent.SINGLETON);\n//                select.add(ActionAddEventAsDeferrableEvent.SINGLETON);\n                select.add(menuItem);\n            } else if (role.equals(ActionNewEvent.Roles.TRIGGER)) {\n                ActionAddEventAsTrigger.SINGLETON.setTarget(target);\n                select.add(ActionAddEventAsTrigger.SINGLETON);\n            }\n            pmenu.add(select);\n        }\n\n        JMenu newMenu = new JMenu(Translator.localize(\"action.new\"));\n//        newMenu.setText(Translator.localize(\"action.new\"));\n        newMenu.add(ActionNewCallEvent.getSingleton());\n        ActionNewCallEvent.getSingleton().setTarget(target);\n        ActionNewCallEvent.getSingleton().putValue(ActionNewEvent.ROLE, role);\n        newMenu.add(ActionNewChangeEvent.getSingleton());\n        ActionNewChangeEvent.getSingleton().setTarget(target);\n        ActionNewChangeEvent.getSingleton().putValue(ActionNewEvent.ROLE, role);\n        newMenu.add(ActionNewSignalEvent.getSingleton());\n        ActionNewSignalEvent.getSingleton().setTarget(target);\n        ActionNewSignalEvent.getSingleton().putValue(ActionNewEvent.ROLE, role);\n        newMenu.add(ActionNewTimeEvent.getSingleton());\n        ActionNewTimeEvent.getSingleton().setTarget(target);\n        ActionNewTimeEvent.getSingleton().putValue(ActionNewEvent.ROLE, role);\n        pmenu.add(newMenu);\n\n        pmenu.addSeparator();\n\n        ActionRemoveModelElement.SINGLETON.setObjectToRemove(\n                ActionNewEvent.getAction(role, target));\n        ActionRemoveModelElement.SINGLETON.putValue(Action.NAME, \n                Translator.localize(\"action.delete-from-model\"));\n        pmenu.add(ActionRemoveModelElement.SINGLETON);\n    }\n\n    /**\n     * The UID.\n     */\n    private static final long serialVersionUID = -7624618103144695448L;\n}\n", "human_rating": 2.11672920233848, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.behavior.state_machines.PopupMenuNewEvent", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/behavior/state_machines/PopupMenuNewEvent.java", "label_probabilities": {"readability": [3.12412e-09, 0.116729, 0.883271, 1.89842e-07], "understandability": [0.00124711, 0.786236, 0.203306, 0.00921029], "complexity": [0.0, 1.96091e-09, 0.794933, 0.205067], "modularization": [1.02686e-15, 0.0333863, 0.966054, 0.000559623], "overall": [0.000965477, 0.861942, 0.137093, 3.39404e-12]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.foundation.core.UMLAssociationEndOrderingCheckBox", "source": "/* $Id: UMLAssociationEndOrderingCheckBox.java 17897 2010-01-12 21:36:40Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.ui.foundation.core;\n\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.Model;\nimport org.argouml.uml.ui.UMLCheckBox2;\n\n/**\n *\n * @author jaap.branderhorst@xs4all.nl\n * @since Jan 4, 2003\n */\npublic class UMLAssociationEndOrderingCheckBox extends UMLCheckBox2 {\n\n    /**\n     * Constructor for UMLAssociationEndOrderingCheckBox.\n     */\n    public UMLAssociationEndOrderingCheckBox() {\n        super(Translator.localize(\"label.ordered\"),\n                ActionSetAssociationEndOrdering.getInstance(), \"ordering\");\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLCheckBox2#buildModel()\n     */\n    public void buildModel() {\n        if (getTarget() != null) {\n            Object associationEnd = getTarget();\n            setSelected(\n                    Model.getOrderingKind().getOrdered().equals(\n                            Model.getFacade().getOrdering(associationEnd)));\n        }\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.foundation.core.UMLAssociationEndOrderingCheckBox", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/foundation/core/UMLAssociationEndOrderingCheckBox.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.foundation.core.UMLGeneralizableElementLeafCheckBox", "source": "/* $Id: UMLGeneralizableElementLeafCheckBox.java 17897 2010-01-12 21:36:40Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2007 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.ui.foundation.core;\n\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.Model;\nimport org.argouml.uml.ui.UMLCheckBox2;\n\n/**\n *\n * @author jaap.branderhorst@xs4all.nl\n * @since Jan 27, 2003\n */\npublic class UMLGeneralizableElementLeafCheckBox extends UMLCheckBox2 {\n\n    /**\n     * Constructor for UMLGeneralizableElementLeafCheckBox.\n     */\n    public UMLGeneralizableElementLeafCheckBox() {\n        super(Translator.localize(\"checkbox.leaf-lc\"),\n                ActionSetGeneralizableElementLeaf.getInstance(), \"isLeaf\");\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLCheckBox2#buildModel()\n     */\n    public void buildModel() {\n        Object target = getTarget();\n        if (target != null && Model.getFacade().isAUMLElement(target)) {\n            setSelected(Model.getFacade().isLeaf(target));\n        } else {\n            setSelected(false);\n        }\n    }\n\n\n}\n", "human_rating": 3.898227602959944, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.foundation.core.UMLGeneralizableElementLeafCheckBox", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/foundation/core/UMLGeneralizableElementLeafCheckBox.java", "label_probabilities": {"readability": [0.898257, 0.101713, 3.03012e-05, 5.59944e-10], "understandability": [0.932443, 0.0675545, 2.60828e-06, 3.0153e-12], "complexity": [1.3279e-08, 0.000123497, 0.0845772, 0.915299], "modularization": [0.0, 2.65974e-09, 0.0958948, 0.904105], "overall": [0.977132, 0.0228685, 2.72324e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.PropPanel", "source": "/* $Id: PropPanel.java 19907 2012-12-30 13:06:01Z closettop_nightlybuild $\n *****************************************************************************\n * Copyright (c) 2009-2012 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.ui;\n\nimport java.awt.BorderLayout;\nimport java.awt.Component;\nimport java.awt.Container;\nimport java.awt.Dimension;\nimport java.awt.Font;\nimport java.awt.GridLayout;\nimport java.awt.event.ComponentEvent;\nimport java.awt.event.ComponentListener;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.HashSet;\nimport java.util.Iterator;\nimport java.util.List;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\n\nimport javax.swing.Action;\nimport javax.swing.Icon;\nimport javax.swing.ImageIcon;\nimport javax.swing.JButton;\nimport javax.swing.JLabel;\nimport javax.swing.JPanel;\nimport javax.swing.JToolBar;\nimport javax.swing.SwingConstants;\nimport javax.swing.SwingUtilities;\nimport javax.swing.border.TitledBorder;\nimport javax.swing.event.EventListenerList;\n\nimport org.argouml.application.api.AbstractArgoJPanel;\nimport org.argouml.application.helpers.ResourceLoaderWrapper;\nimport org.argouml.i18n.Translator;\nimport org.argouml.kernel.ProfileConfiguration;\nimport org.argouml.kernel.ProjectManager;\nimport org.argouml.model.Model;\nimport org.argouml.ui.ActionCreateContainedModelElement;\nimport org.argouml.ui.LookAndFeelMgr;\nimport org.argouml.ui.targetmanager.TargetEvent;\nimport org.argouml.ui.targetmanager.TargetListener;\nimport org.argouml.ui.targetmanager.TargettableModelView;\nimport org.tigris.gef.presentation.Fig;\nimport org.tigris.swidgets.GridLayout2;\nimport org.tigris.swidgets.Orientation;\nimport org.tigris.toolbar.ToolBarFactory;\n\n/**\n * This abstract class provides the basic layout and event dispatching support\n * for all Property Panels.<p>\n *\n * The property panel is {@link org.argouml.uml.ui.LabelledLayout} layed out as\n * a number (specified in the constructor) of equally sized panels that split\n * the available space. Each panel has a column of \"captions\" and matching\n * column of \"fields\" which are laid out independently from the other\n * panels.<p>\n *\n * The Properties panels for UML Model Elements are structured in an inheritance\n * hierarchy that matches the UML metamodel.\n */\npublic abstract class PropPanel extends AbstractArgoJPanel implements\n        UMLUserInterfaceContainer, ComponentListener {\n\n    /**\n     * Logger.\n     */\n    private static final Logger LOG =\n        Logger.getLogger(PropPanel.class.getName());\n\n    private Object target;\n\n    private Object modelElement;\n\n    /**\n     * List of event listeners to notify. This is computed one time and frozen\n     * the first time any target change method (e.g. setTarget, targetAdded) is\n     * called.\n     */\n    private EventListenerList listenerList;\n\n    private JPanel buttonPanel = new JPanel(new GridLayout());\n\n    private JLabel titleLabel;\n\n    /**\n     * A list with \"actions\".<p>\n     *\n     * Action in this respect are one of:<ul>\n     * <li> {@link Action}\n     * <li> {@link JButton}\n     * <li> {@link Object}[]\n     * </ul>\n     */\n    private List actions = new ArrayList();\n\n    private static Font stdFont =\n        LookAndFeelMgr.getInstance().getStandardFont();\n\n    /**\n     * Construct new PropPanel using LabelledLayout.\n     * <p>\n     * @param icon The icon to display for the panel\n     * @param label The label for the title of the panel (to be localized).\n     */\n    public PropPanel(String label, ImageIcon icon) {\n        super(Translator.localize(label));\n\n        LabelledLayout layout = new LabelledLayout();\n        layout.setHgap(5);\n        setLayout(layout);\n\n        if (icon != null) {\n            setTitleLabel(new JLabel(Translator.localize(label), icon,\n                    SwingConstants.LEFT));\n        } else {\n            setTitleLabel(new JLabel(Translator.localize(label)));\n        }\n        titleLabel.setLabelFor(buttonPanel);\n        add(titleLabel);\n        add(buttonPanel);\n\n        addComponentListener(this);\n    }\n\n\n    /*\n     * @see org.tigris.swidgets.Orientable#setOrientation(org.tigris.swidgets.Orientation)\n     */\n    @Override\n    public void setOrientation(Orientation orientation) {\n        // TODO: Do we need to change the layout manager when\n        // changing orientation to match the behavior of the constructor?\n//        if (getOrientation() != orientation) {\n//            LabelledLayout layout = new LabelledLayout(orientation == Vertical\n//                    .getInstance());\n//            setLayout(layout);\n//        }\n        super.setOrientation(orientation);\n    }\n\n    /**\n     * Add a button to the toolbar of a property panel using the action to\n     * control the behavior of the action.\n     *\n     * @param action\n     *            the action which will be used in the toolbar button.\n     */\n    protected void addAction(Action action) {\n        actions.add(action);\n    }\n\n    /**\n     * Add a button to the toolbar of a property panel using the action to\n     * control the behavior of the action.\n     *\n     * @param action\n     *            the action which will be used in the toolbar button.\n     * @param tooltip\n     *            the tooltip to set, or null to skip setting of a new tooltip.\n     */\n    protected void addAction(Action action, String tooltip) {\n        JButton button = new TargettableButton(action);\n        if (tooltip != null) {\n            button.setToolTipText(tooltip);\n        }\n        button.setText(\"\");\n        button.setFocusable(false);\n        actions.add(button);\n    }\n\n    /**\n     * Add multiple buttons at once.\n     *\n     * @param actionArray the Actions.\n     */\n    protected void addAction(Object[] actionArray) {\n        actions.add(actionArray);\n    }\n\n    public void buildToolbar() {\n        LOG.log(Level.FINE, \"Building toolbar\");\n\n        ToolBarFactory factory = new ToolBarFactory(getActions());\n        factory.setRollover(true);\n        factory.setFloatable(false);\n        JToolBar toolBar = factory.createToolBar();\n        toolBar.setName(\"misc.toolbar.properties\");\n\n\tbuttonPanel.removeAll();\n        buttonPanel.add(BorderLayout.WEST, toolBar);\n        // Set the tooltip of the arrow to open combined tools:\n        buttonPanel.putClientProperty(\"ToolBar.toolTipSelectTool\",\n                Translator.localize(\"action.select\"));\n    }\n\n    /**\n     * Get the actions that will make up the toolbar on this panel.\n     * @return The list of actions to show for this panel.\n     */\n    protected List getActions() {\n        return actions;\n    }\n\n    private static class TargettableButton extends JButton\n        implements TargettableModelView {\n\n        public TargettableButton(Action action) {\n            super(action);\n        }\n\n        public TargetListener getTargettableModel() {\n            if (getAction() instanceof TargetListener) {\n                return (TargetListener) getAction();\n            }\n            return null;\n        }\n\n    }\n\n    /**\n     * Add a component with the specified label.<p>\n     *\n     * @param label\n     *            the label for the component\n     * @param component\n     *            the component\n     * @return the label added\n     */\n    public JLabel addField(String label, Component component) {\n        JLabel jlabel = createLabelFor(label, component);\n        component.setFont(stdFont);\n        add(jlabel);\n        add(component);\n        if (component instanceof UMLStereotypeList) {\n            UMLModelElementListModel2 list =\n                (UMLModelElementListModel2) ((UMLStereotypeList) component).getModel();\n            ActionCreateContainedModelElement newAction =\n                new ActionCreateContainedModelElement(\n                        list.getMetaType(),\n                        list.getTarget(),\n                        \"New...\"); // TODO: i18n\n        }\n        return jlabel;\n    }\n\n    /**\n     * @param label The text of the label (the method cares about i18n)\n     * @param comp The component that this label is for\n     * @return a new JLabel\n     */\n    private JLabel createLabelFor(String label, Component comp) {\n        JLabel jlabel = new JLabel(Translator.localize(label));\n        jlabel.setToolTipText(Translator.localize(label));\n        jlabel.setFont(stdFont);\n        jlabel.setLabelFor(comp);\n        return jlabel;\n    }\n\n    /**\n     * Add a component with the specified label positioned after another\n     * component.\n     *\n     * @param label\n     *            the label for the component\n     * @param component\n     *            the component\n     * @param afterComponent\n     *            the component before\n     * @return the newly added label\n     */\n    public JLabel addFieldAfter(String label, Component component,\n            Component afterComponent) {\n        int nComponent = getComponentCount();\n        for (int i = 0; i < nComponent; ++i) {\n            if (getComponent(i) == afterComponent) {\n                JLabel jlabel = createLabelFor(label, component);\n                component.setFont(stdFont);\n                add(jlabel, ++i);\n                add(component, ++i);\n                return jlabel;\n            }\n        }\n        throw new IllegalArgumentException(\"Component not found\");\n    }\n\n    /**\n     * Add a component with the specified label positioned before another\n     * component.<p>\n     *\n     * @param label\n     *            the label for the component\n     * @param component\n     *            the to be added component\n     * @param beforeComponent\n     *            the component before its label we add\n     * @return the newly added component\n     */\n    public JLabel addFieldBefore(String label, Component component,\n            Component beforeComponent) {\n        int nComponent = getComponentCount();\n        for (int i = 0; i < nComponent; ++i) {\n            if (getComponent(i) == beforeComponent) {\n                JLabel jlabel = createLabelFor(label, component);\n                component.setFont(stdFont);\n                add(jlabel, i - 1);\n                add(component, i++);\n                return jlabel;\n            }\n        }\n        throw new IllegalArgumentException(\"Component not found\");\n    }\n\n    /**\n     * Add a separator.\n     */\n    protected final void addSeparator() {\n        add(LabelledLayout.getSeparator());\n    }\n\n    /**\n     * Set the target to be associated with a particular property panel.<p>\n     *\n     * This involves resetting the third party listeners.\n     *\n     * @param t\n     *            The object to be set as a target.\n     */\n    public void setTarget(Object t) {\n\n        LOG.log(Level.FINE, \"setTarget called with {0} as parameter (not target!)\", t);\n\n        t = (t instanceof Fig) ? ((Fig) t).getOwner() : t;\n\n        // If the target has changed notify the third party listener if it\n        // exists and dispatch a new element event listener to\n        // ourself. Otherwise dispatch a target reasserted to ourself.\n        Runnable dispatch = null;\n        if (t != target) {\n\n            // Set up the target and its model element variant.\n\n            target = t;\n            modelElement = null;\n            if (listenerList == null) {\n                listenerList = collectTargetListeners(this);\n            }\n\n            if (Model.getFacade().isAUMLElement(target)) {\n                modelElement = target;\n            }\n\n            // This will add a new ModelElement event listener\n            // after update is complete\n\n            dispatch = new UMLChangeDispatch(this,\n                    UMLChangeDispatch.TARGET_CHANGED_ADD);\n\n            buildToolbar();\n        } else {\n            dispatch = new UMLChangeDispatch(this,\n                    UMLChangeDispatch.TARGET_REASSERTED);\n\n        }\n        SwingUtilities.invokeLater(dispatch);\n\n        // update the titleLabel\n        // MVW: This overrules the icon set initiallly... Why do we need this?\n        if (titleLabel != null) {\n            Icon icon = null;\n            if (t != null) {\n                icon = ResourceLoaderWrapper.getInstance().lookupIcon(t);\n            }\n            if (icon != null) {\n                titleLabel.setIcon(icon);\n            }\n        }\n    }\n\n    /**\n     * Builds a eventlistenerlist of all targetlisteners that are part of this\n     * container and its children. Components do not need to register\n     * themselves. They are registered implicitly if they implement the\n     * TargetListener interface.\n     *\n     * @param container\n     *            the container to search for targetlisteners\n     * @return an EventListenerList with all TargetListeners on this container\n     *         and its children.\n     */\n    private EventListenerList collectTargetListeners(Container container) {\n        Component[] components = container.getComponents();\n        EventListenerList list = new EventListenerList();\n        for (int i = 0; i < components.length; i++) {\n            if (components[i] instanceof TargetListener) {\n                list.add(TargetListener.class, (TargetListener) components[i]);\n            }\n            if (components[i] instanceof TargettableModelView) {\n                list.add(TargetListener.class,\n                        ((TargettableModelView) components[i])\n                                .getTargettableModel());\n            }\n            if (components[i] instanceof Container) {\n                EventListenerList list2 = collectTargetListeners(\n                                                (Container) components[i]);\n                Object[] objects = list2.getListenerList();\n                for (int j = 1; j < objects.length; j += 2) {\n                    list.add(TargetListener.class, (TargetListener) objects[j]);\n                }\n            }\n        }\n        if (container instanceof PropPanel) {\n            /* We presume that the container equals this PropPanel. */\n            for (TargetListener action : collectTargetListenerActions()) {\n                list.add(TargetListener.class, action);\n            }\n        }\n        return list;\n    }\n\n    private Collection<TargetListener> collectTargetListenerActions() {\n        Collection<TargetListener> set = new HashSet<TargetListener>();\n        for (Object obj : actions) {\n            if (obj instanceof TargetListener) {\n                set.add((TargetListener) obj);\n            }\n        }\n        return set;\n    }\n\n    /*\n     * @see org.argouml.ui.TabTarget#getTarget()\n     */\n    public final Object getTarget() {\n        return target;\n    }\n\n    /*\n     * @see org.argouml.ui.TabTarget#refresh()\n     */\n    public void refresh() {\n        SwingUtilities.invokeLater(new UMLChangeDispatch(this, 0));\n    }\n\n    /*\n     * @see org.argouml.ui.TabTarget#shouldBeEnabled(java.lang.Object)\n     */\n    public boolean shouldBeEnabled(Object t) {\n        t = (t instanceof Fig) ? ((Fig) t).getOwner() : t;\n        return Model.getFacade().isAUMLElement(t);\n    }\n\n    /**\n     * This method can be overridden in derived Panels where the appropriate\n     * namespace for display may not be the same as the namespace of the target.\n     *\n     * @return the namespace\n     */\n    protected Object getDisplayNamespace() {\n        Object ns = null;\n        Object theTarget = getTarget();\n        if (Model.getFacade().isAModelElement(theTarget)) {\n            ns = Model.getFacade().getNamespace(theTarget);\n        }\n        return ns;\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLUserInterfaceContainer#getProfile()\n     */\n    public ProfileConfiguration getProfile() {\n        return ProjectManager.getManager().getCurrentProject()\n                .getProfileConfiguration();\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLUserInterfaceContainer#getModelElement()\n     */\n    public final Object getModelElement() {\n        return modelElement;\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLUserInterfaceContainer#formatElement(java.lang.Object)\n     */\n    public String formatElement(Object element) {\n        return getProfile().getFormatingStrategy().formatElement(element,\n                getDisplayNamespace());\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLUserInterfaceContainer#formatNamespace(java.lang.Object)\n     */\n    public String formatNamespace(Object namespace) {\n        return getProfile().getFormatingStrategy().formatElement(namespace,\n                null);\n    }\n\n    /*\n     * @see org.argouml.uml.ui.UMLUserInterfaceContainer#formatCollection(java.util.Iterator)\n     */\n    public String formatCollection(Iterator iter) {\n        Object namespace = getDisplayNamespace();\n        return getProfile().getFormatingStrategy().formatCollection(iter,\n                namespace);\n    }\n\n\n    /**\n     * Get the delete action.\n     *\n     * @return the delete action\n     */\n    protected final Action getDeleteAction() {\n        return ActionDeleteModelElements.getTargetFollower();\n    }\n\n    /**\n     * Check whether this element can be deleted. Currently it only checks\n     * whether we delete the main model. ArgoUML does not like that.\n     *\n     * @since 0.13.2\n     * @return whether this element can be deleted\n     */\n    public boolean isRemovableElement() {\n        return ((getTarget() != null) && (getTarget() != (ProjectManager\n                .getManager().getCurrentProject().getModel())));\n    }\n\n    /*\n     * @see TargetListener#targetAdded(TargetEvent)\n     */\n    public void targetAdded(TargetEvent e) {\n        if (listenerList == null) {\n            listenerList = collectTargetListeners(this);\n        }\n        setTarget(e.getNewTarget());\n        if (isVisible()) {\n            fireTargetAdded(e);\n        }\n    }\n\n    /*\n     * @see TargetListener#targetRemoved(TargetEvent)\n     */\n    public void targetRemoved(TargetEvent e) {\n        setTarget(e.getNewTarget());\n        if (isVisible()) {\n            fireTargetRemoved(e);\n        }\n    }\n\n    /*\n     * @see TargetListener#targetSet(TargetEvent)\n     */\n    public void targetSet(TargetEvent e) {\n        setTarget(e.getNewTarget());\n        if (isVisible()) {\n            fireTargetSet(e);\n        }\n    }\n\n    private void fireTargetSet(TargetEvent targetEvent) {\n        if (listenerList == null) {\n            listenerList = collectTargetListeners(this);\n        }\n        // Guaranteed to return a non-null array\n        Object[] listeners = listenerList.getListenerList();\n        for (int i = listeners.length - 2; i >= 0; i -= 2) {\n            if (listeners[i] == TargetListener.class) {\n                ((TargetListener) listeners[i + 1]).targetSet(targetEvent);\n            }\n        }\n    }\n\n    private void fireTargetAdded(TargetEvent targetEvent) {\n        if (listenerList == null) {\n            listenerList = collectTargetListeners(this);\n        }\n        // Guaranteed to return a non-null array\n        Object[] listeners = listenerList.getListenerList();\n\n        for (int i = listeners.length - 2; i >= 0; i -= 2) {\n            if (listeners[i] == TargetListener.class) {\n                ((TargetListener) listeners[i + 1]).targetAdded(targetEvent);\n            }\n        }\n    }\n\n    private void fireTargetRemoved(TargetEvent targetEvent) {\n        if (listenerList == null) {\n            listenerList = collectTargetListeners(this);\n        }\n        // Guaranteed to return a non-null array\n        Object[] listeners = listenerList.getListenerList();\n        for (int i = listeners.length - 2; i >= 0; i -= 2) {\n            if (listeners[i] == TargetListener.class) {\n                ((TargetListener) listeners[i + 1]).targetRemoved(targetEvent);\n            }\n        }\n    }\n\n    /**\n     * @param theTitleLabel\n     *            the title of the panel shown at the top\n     */\n    protected void setTitleLabel(JLabel theTitleLabel) {\n        titleLabel = theTitleLabel;\n        titleLabel.setFont(stdFont);\n    }\n\n    /**\n     * @return the title of the panel shown at the top\n     */\n    protected JLabel getTitleLabel() {\n        return titleLabel;\n    }\n\n    protected final JPanel createBorderPanel(String title) {\n    \treturn new GroupPanel(Translator.localize(title));\n    }\n\n    private class GroupPanel extends JPanel {\n\n        public GroupPanel(String title) {\n            super(new GridLayout2());\n            TitledBorder border = new TitledBorder(Translator.localize(title));\n            border.setTitleFont(stdFont);\n            setBorder(border);\n        }\n\n        public void setEnabled(boolean enabled) {\n            super.setEnabled(enabled);\n            for (final Component component : getComponents()) {\n                component.setEnabled(enabled);\n            }\n        }\n    }\n\n    /**\n     * If there are no buttons to show in the toolbar,\n     * then set the height to e.g. 18, so that the title\n     * is aligned right by the LabelledLayout.\n     *\n     * @param height the height\n     */\n    protected void setButtonPanelSize(int height) {\n        /* Set the minimum and preferred equal,\n         * so that the size is fixed for the labelledlayout.\n         */\n        buttonPanel.setMinimumSize(new Dimension(0, height));\n        buttonPanel.setPreferredSize(new Dimension(0, height));\n    }\n\n    /**\n     * Look up an icon.\n     *\n     * @param name\n     *            the resource name.\n     * @return an ImageIcon corresponding to the given resource name\n     */\n    protected static ImageIcon lookupIcon(String name) {\n        return ResourceLoaderWrapper.lookupIconResource(name);\n    }\n\n\n    /*\n     * @see java.awt.event.ComponentListener#componentHidden(java.awt.event.ComponentEvent)\n     */\n    public void componentHidden(ComponentEvent e) {\n        // TODO: do we want to fire targetRemoved here or is it enough to just\n        // stop updating the targets?\n    }\n\n    /*\n     * @see java.awt.event.ComponentListener#componentShown(java.awt.event.ComponentEvent)\n     */\n    public void componentShown(ComponentEvent e) {\n        // Refresh the target for all our children which weren't getting\n        // while not visible\n        fireTargetSet(new TargetEvent(\n                this, TargetEvent.TARGET_SET, null, new Object[] {target}));\n    }\n\n    /*\n     * @see java.awt.event.ComponentListener#componentMoved(java.awt.event.ComponentEvent)\n     */\n    public void componentMoved(ComponentEvent e) {\n        // ignored\n    }\n\n    /*\n     * @see java.awt.event.ComponentListener#componentResized(java.awt.event.ComponentEvent)\n     */\n    public void componentResized(ComponentEvent e) {\n        // ignored\n    }\n}\n", "human_rating": 2.99977591817602, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.PropPanel", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/PropPanel.java", "label_probabilities": {"readability": [3.58544e-07, 0.999775, 0.000224742, 2.02305e-14], "understandability": [4.75241e-08, 0.0515967, 0.948397, 6.40961e-06], "complexity": [2.475e-17, 0.00549847, 0.994496, 5.48395e-06], "modularization": [8.0594e-16, 0.00567839, 0.837219, 0.157102], "overall": [9.6352e-16, 0.203168, 0.796832, 1.39895e-11]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.UMLComboBox2", "source": "/* $Id: UMLComboBox2.java 19630 2011-08-05 07:59:26Z bobtarling $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2009 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.ui;\n\nimport java.awt.event.ActionEvent;\nimport java.awt.event.KeyEvent;\n\nimport javax.swing.Action;\nimport javax.swing.ComboBoxModel;\nimport javax.swing.JComboBox;\nimport javax.swing.ListCellRenderer;\n\nimport org.argouml.ui.LookAndFeelMgr;\nimport org.argouml.ui.targetmanager.TargetEvent;\nimport org.argouml.ui.targetmanager.TargetListener;\nimport org.argouml.ui.targetmanager.TargettableModelView;\n\n\n/**\n * ComboBox for selecting UML Elements.\n * @deprecated in 0.31.5 by Bob Tarling. Property panel controls are now\n * internal to the property panel component\n */\n@Deprecated\npublic class UMLComboBox2\n    extends JComboBox\n    implements TargettableModelView, TargetListener, \n        JComboBox.KeySelectionManager {\n\n    private static final int KEY_TIME_THRESHOLD_MILLIS = 1500;\n    private String searchString = \"\";\n    private long lastKeyEventTime;\n\n    /**\n     * Constructor for UMLComboBox2.\n     * @deprecated As of ArgoUml version unknown (before 0.13.5),\n     * replaced by {@link #UMLComboBox2(UMLComboBoxModel2, Action, boolean)}\n     * @param model the ComboBoxModel\n     */\n    @Deprecated\n    UMLComboBox2(UMLComboBoxModel2 model) {\n        super(model);\n        setFont(LookAndFeelMgr.getInstance().getStandardFont());\n        addActionListener(this);\n        addPopupMenuListener(model);\n    }\n\n    /**\n     * Construct a UMLComboBox2.\n     * \n     * @param model a UMLComboBoxModel2 which provides UML elements for the user\n     *            to choose from\n     * @param action action to invoke when an item is selected\n     * @param showIcon true if an icon should be shown in front of the items\n     */\n    public UMLComboBox2(UMLComboBoxModel2 model, Action action,\n\t\t\tboolean showIcon) {\n        super(model);\n        setFont(LookAndFeelMgr.getInstance().getStandardFont());\n        lastKeyEventTime = 0;\n        addActionListener(action);\n        // setDoubleBuffered(true);\n        setKeySelectionManager(this);\n        setRenderer(new UMLListCellRenderer2(showIcon));\n        addPopupMenuListener(model);\n    }\n\n    /*\n     * @see java.awt.event.ActionListener#actionPerformed(ActionEvent)\n     */\n    @Override\n    public void actionPerformed(ActionEvent arg0) {\n        int i = getSelectedIndex();\n        if (i >= 0) {\n            doIt(arg0);\n        }\n    }\n    \n    /**\n     * Implementation of the JComboBox.KeySelectionManager interface. Helps with\n     * navigating through the ComboBox when using the keyboard.\n     * \n     * @param key The key which has been pressed\n     * @param model Current ComboBoxModel\n     * @return int The index of the item that is to be selected\n     * @see javax.swing.JComboBox.KeySelectionManager#selectionForKey(char, javax.swing.ComboBoxModel)\n     */\n    public int selectionForKey(char key, ComboBoxModel model)\n    {        \n        long now = System.currentTimeMillis();\n        int index = -1;\n        int startAtIndex = 0;\n\n        // Implements backspace functionality\n        if (searchString != null && key == KeyEvent.VK_BACK_SPACE\n                && searchString.length() > 0) {\n            searchString = searchString.substring(0, searchString.length() - 1);\n        }\n        else {\n            if (lastKeyEventTime + KEY_TIME_THRESHOLD_MILLIS < now) {\n                searchString = Character.toString(key);\n            }\n            else {\n                searchString = searchString + key;\n                startAtIndex = getSelectedIndex();\n                if (startAtIndex < 0) {\n                    startAtIndex = 0;\n                }\n            }\n        }\n        \n        String umlElemName = \"\";\n        String searchStringLowerCase = searchString.toLowerCase();\n        ListCellRenderer cellRenderer = getRenderer();\n        \n        for (int i = startAtIndex, length = model.getSize(); i < length; i++) {\n            Object value = model.getElementAt(i);\n            if (cellRenderer instanceof UMLListCellRenderer2) {\n                umlElemName = \n                    ((UMLListCellRenderer2) cellRenderer).makeText(value);\n            } else {\n                umlElemName = value.toString();\n            }\n            if (umlElemName.toLowerCase().startsWith(searchStringLowerCase)) {\n                index = i;\n                break;\n            }\n        }\n        lastKeyEventTime = now;\n\n        return index;\n    }\n\n    /**\n     * The 'body' of the actionPerformed method. Is only called if there is\n     * actually a selection made.\n     *\n     * @param event the event\n     */\n    protected void doIt(@SuppressWarnings(\"unused\") ActionEvent event) { }\n\n    /**\n     * Utility method to get the current target.\n     *\n     * @return Object\n     */\n    public Object getTarget() {\n        return ((UMLComboBoxModel2) getModel()).getTarget();\n    }\n\n\n    /*\n     * @see org.argouml.ui.targetmanager.TargettableModelView#getTargettableModel()\n     */\n    public TargetListener getTargettableModel() {\n        return (TargetListener) getModel();\n    }\n\n    /*\n     * @see org.argouml.ui.targetmanager.TargetListener#targetAdded(org.argouml.ui.targetmanager.TargetEvent)\n     */\n    public void targetAdded(TargetEvent e) {\n        if (e.getNewTarget() != getTarget()) {\n            removeActionListener(this);\n        }\n    }\n\n    /*\n     * @see org.argouml.ui.targetmanager.TargetListener#targetRemoved(org.argouml.ui.targetmanager.TargetEvent)\n     */\n    public void targetRemoved(TargetEvent e) {\n        removeActionListener(this);\n    }\n\n    /*\n     * @see org.argouml.ui.targetmanager.TargetListener#targetSet(org.argouml.ui.targetmanager.TargetEvent)\n     */\n    public void targetSet(TargetEvent e) {\n        addActionListener(this);\n    }\n}\n", "human_rating": 3.421319198868, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.UMLComboBox2", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/UMLComboBox2.java", "label_probabilities": {"readability": [0.423138, 0.575044, 0.00181725, 6.98868e-07], "understandability": [0.0215379, 0.862136, 0.115391, 0.000934996], "complexity": [8.02047e-08, 0.00846308, 0.99091, 0.000626696], "modularization": [0.0, 9.13022e-11, 0.999348, 0.000651858], "overall": [0.00842484, 0.977727, 0.0138478, 7.38651e-14]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.UMLTableCellRenderer", "source": "/* $Id: UMLTableCellRenderer.java 19614 2011-07-20 12:10:13Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 2005-2006 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\npackage org.argouml.uml.ui;\n\nimport javax.swing.table.DefaultTableCellRenderer;\n\nimport org.argouml.model.Model;\n\n/**\n * Basic table cell renderer which uses the name of a model element as the text.\n */\npublic class UMLTableCellRenderer extends DefaultTableCellRenderer {\n\n    /**\n     * Construct a TableCellRender which uses the name of a UML element.\n     */\n    public UMLTableCellRenderer() {\n        super();\n    }\n\n    @Override\n    public void setValue(Object value) {\n        if (Model.getFacade().isAModelElement(value)) {\n            String name = Model.getFacade().getName(value);\n            setText(name);\n        } else {\n            if (value instanceof String) {\n                setText((String) value);\n            } else {\n                setText(\"\");\n            }\n        }\n    }\n}\n", "human_rating": 3.971194015056, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.UMLTableCellRenderer", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/UMLTableCellRenderer.java", "label_probabilities": {"readability": [0.971194, 0.0288058, 3.07528e-07, 8.37e-18], "understandability": [0.981314, 0.0186856, 9.88824e-08, 1.241e-17], "complexity": [4.71472e-15, 3.89538e-05, 0.301593, 0.698368], "modularization": [0.0, 4.28517e-11, 0.0203369, 0.979663], "overall": [0.996843, 0.00315683, 6.82826e-14, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.uml.ui.UMLTreeCellRenderer", "source": "/* $Id: UMLTreeCellRenderer.java 17881 2010-01-12 21:09:28Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.uml.ui;\n\nimport java.awt.Component;\n\nimport javax.swing.Icon;\nimport javax.swing.JLabel;\nimport javax.swing.JTree;\nimport javax.swing.tree.DefaultMutableTreeNode;\nimport javax.swing.tree.DefaultTreeCellRenderer;\n\nimport org.argouml.application.helpers.ResourceLoaderWrapper;\nimport org.argouml.i18n.Translator;\nimport org.argouml.model.Model;\nimport org.argouml.uml.diagram.ui.UMLDiagram;\n\n/**\n * UMTreeCellRenderer determines how the entries in the Explorerpane\n * and ToDoList will be represented graphically.<p>\n *\n * In particular it makes decisions about the icons to use,\n * in order to display an Explorerpane artifact depending on the kind\n * of object to be displayed.<p>\n *\n * This class must be efficient as it is called many 1000's of times.\n */\npublic class UMLTreeCellRenderer extends DefaultTreeCellRenderer {\n\n    // get localised strings once only\n    private static String name = Translator.localize(\"label.name\");\n    private static String typeName = Translator.localize(\"label.type\");\n\n    ////////////////////////////////////////////////////////////////\n    // TreeCellRenderer implementation\n\n    /*\n     * @see javax.swing.tree.TreeCellRenderer#getTreeCellRendererComponent(\n     *      javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int,\n     *      boolean)\n     */\n    @Override\n    public Component getTreeCellRendererComponent(\n        JTree tree,\n        Object value,\n        boolean sel,\n        boolean expanded,\n        boolean leaf,\n        int row,\n        boolean hasFocusParam) {\n\n\tif (value instanceof DefaultMutableTreeNode) {\n\t    value = ((DefaultMutableTreeNode) value).getUserObject();\n\t}\n\n        Component r =\n            super.getTreeCellRendererComponent(\n                tree,\n                value,\n                sel,\n                expanded,\n                leaf,\n                row,\n                hasFocusParam);\n\n        if (value != null && r instanceof JLabel) {\n            JLabel lab = (JLabel) r;\n\n            // setting the icon\n            Icon icon = ResourceLoaderWrapper.getInstance().lookupIcon(value);\n            if (icon != null) {\n                lab.setIcon(icon);\n            }\n\n            // setting the tooltip to type and name\n            String type = null;\n            if (Model.getFacade().isAModelElement(value)) {\n                type = Model.getFacade().getUMLClassName(value);\n            } else if (value instanceof UMLDiagram) {\n                type = ((UMLDiagram) value).getLabelName();\n            }\n\n            if (type != null) {\n                StringBuffer buf = new StringBuffer();\n                buf.append(\"<html>\");\n                buf.append(name);\n                buf.append(' ');\n                buf.append(lab.getText());\n                buf.append(\"<br>\");\n                buf.append(typeName);\n                buf.append(' ');\n                buf.append(type);\n                lab.setToolTipText(buf.toString());\n            } else {\n                lab.setToolTipText(lab.getText());\n            }\n        }\n        return r;\n    }\n\n}\n", "human_rating": 3.000000000541704, "metadata": {"project": "argoUML", "class": "org.argouml.uml.ui.UMLTreeCellRenderer", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/uml/ui/UMLTreeCellRenderer.java", "label_probabilities": {"readability": [0.0, 1.0, 2.70852e-10, 0.0], "understandability": [0.994273, 0.00572671, 6.48319e-09, 0.0], "complexity": [0.0, 2.26e-18, 0.973251, 0.0267493], "modularization": [0.0, 0.0, 0.99695, 0.00305035], "overall": [7.50647e-06, 0.999548, 0.000444602, 4.599e-16]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.util.PredicateStringMatch", "source": "/* $Id: PredicateStringMatch.java 17887 2010-01-12 21:17:18Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.util;\n\nimport java.util.StringTokenizer;\n\n/**\n * Predicate to match strings/substrings.  It only supports simple\n * wildcard processing, not full regex style matching.\n */\npublic class PredicateStringMatch implements Predicate {\n\n    public static int MAX_PATS = 10;\n\n    private String patterns[];\n\n    private int patternCount;\n\n    protected PredicateStringMatch(String matchPatterns[], int count) {\n        patterns = matchPatterns;\n        patternCount = count;\n    }\n\n    public static Predicate create(String pattern) {\n        pattern = pattern.trim();\n        if (\"*\".equals(pattern) || \"\".equals(pattern)) {\n            return PredicateTrue.getInstance();\n        }\n        String pats[] = new String[MAX_PATS];\n        int count = 0;\n        if (pattern.startsWith(\"*\")) {\n            pats[count++] = \"\";\n        }\n        StringTokenizer st = new StringTokenizer(pattern, \"*\");\n        while (st.hasMoreElements()) {\n            String token = st.nextToken();\n            pats[count++] = token;\n        }\n        if (pattern.endsWith(\"*\")) {\n            pats[count++] = \"\";\n        }\n        if (count == 0) {\n            return PredicateTrue.getInstance();\n        }\n        if (count == 1) {\n            return new PredicateEquals(pats[0]);\n        }\n        return new PredicateStringMatch(pats, count);\n    }\n\n    public boolean evaluate(Object o) {\n        if (o == null) {\n            return false;\n        }\n        String target = o.toString();\n        if (!target.startsWith(patterns[0])) {\n            return false;\n        }\n        if (!target.endsWith(patterns[patternCount - 1])) {\n            return false;\n        }\n        for (String pattern : patterns) {\n            int index = (target + \"*\").indexOf(pattern);\n            if (index == -1) {\n                return false;\n            }\n            target = target.substring(index + pattern.length());\n        }\n        return true;\n    }\n\n}\n", "human_rating": 3.973538576000013, "metadata": {"project": "argoUML", "class": "org.argouml.util.PredicateStringMatch", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/util/PredicateStringMatch.java", "label_probabilities": {"readability": [0.97354, 0.0264578, 2.588e-06, 1.30881e-14], "understandability": [0.662844, 0.336078, 0.00107777, 1.08761e-14], "complexity": [3.2423e-16, 0.00101351, 0.988515, 0.0104715], "modularization": [2.405e-17, 0.00137716, 0.402984, 0.595639], "overall": [0.756961, 0.243039, 5.99592e-08, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.util.PredicateTrue", "source": "/* $Id: PredicateTrue.java 17887 2010-01-12 21:17:18Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies. This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason. IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.util;\n\n\n/**\n * A Predicate that always returns true. Based on GEF utility class of the same\n * name. This is implemented as a singleton with a private constructor.\n * \n * @author Jason Robbins\n */\npublic class PredicateTrue implements Predicate {\n\n    private PredicateTrue() {\n    }\n\n    public boolean evaluate(Object obj) {\n        return true;\n    }\n\n    private static PredicateTrue theInstance = new PredicateTrue();\n\n    /**\n     * @return the instance\n     */\n    public static PredicateTrue getInstance() {\n        return theInstance;\n    }\n}\n\n", "human_rating": 3.9000431234099997, "metadata": {"project": "argoUML", "class": "org.argouml.util.PredicateTrue", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/util/PredicateTrue.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/argoUML/org.argouml.util.PredicateType", "source": "/* $Id: PredicateType.java 17887 2010-01-12 21:17:18Z linus $\n *****************************************************************************\n * Copyright (c) 2009 Contributors - see below\n * All rights reserved. This program and the accompanying materials\n * are made available under the terms of the Eclipse Public License v1.0\n * which accompanies this distribution, and is available at\n * http://www.eclipse.org/legal/epl-v10.html\n *\n * Contributors:\n *    tfmorris\n *****************************************************************************\n *\n * Some portions of this file was previously release using the BSD License:\n */\n\n// Copyright (c) 1996-2008 The Regents of the University of California. All\n// Rights Reserved. Permission to use, copy, modify, and distribute this\n// software and its documentation without fee, and without a written\n// agreement is hereby granted, provided that the above copyright notice\n// and this paragraph appear in all copies.  This software program and\n// documentation are copyrighted by The Regents of the University of\n// California. The software program and documentation are supplied \"AS\n// IS\", without any accompanying services from The Regents. The Regents\n// does not warrant that the operation of the program will be\n// uninterrupted or error-free. The end-user understands that the program\n// was developed for research purposes and is advised not to rely\n// exclusively on the program for any reason.  IN NO EVENT SHALL THE\n// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,\n// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\n// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF\n// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF\n// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY\n// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\n// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE\n// PROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND THE UNIVERSITY OF\n// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,\n// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.\n\npackage org.argouml.util;\n\n/**\n * A predicate which matches UML element types.\n */\npublic class PredicateType implements Predicate {\n\n    private Class patterns[];\n\n    private int patternCount;\n\n    private String printString = null;\n\n    protected PredicateType(Class pats[]) {\n        this(pats, pats.length);\n    }\n\n    protected PredicateType(Class pats[], int numPats) {\n        patterns = pats;\n        patternCount = numPats;\n    }\n\n    public static PredicateType create() {\n        return new PredicateType(null, 0);\n    }\n\n    public static PredicateType create(Class c0) {\n        Class classes[] = new Class[1];\n        classes[0] = c0;\n        return new PredicateType(classes);\n    }\n\n    public static PredicateType create(Class c0, Class c1) {\n        Class classes[] = new Class[2];\n        classes[0] = c0;\n        classes[1] = c1;\n        return new PredicateType(classes);\n    }\n\n    public static PredicateType create(Class c0, Class c1, Class c2) {\n        Class classes[] = new Class[3];\n        classes[0] = c0;\n        classes[1] = c1;\n        classes[2] = c2;\n        return new PredicateType(classes);\n    }\n\n    public boolean evaluate(Object o) {\n        if (patternCount == 0) {\n            return true;\n        }\n        for (int i = 0; i < patternCount; i++) {\n            if (patterns[i].isInstance(o)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    @Override\n    public String toString() {\n        if (printString != null) {\n            return printString;\n        }\n        if (patternCount == 0) {\n            return \"Any Type\";\n        }\n        String res = \"\";\n        for (int i = 0; i < patternCount; i++) {\n            String clsName = patterns[i].getName();\n            int lastDot = clsName.lastIndexOf(\".\");\n            clsName = clsName.substring(lastDot + 1);\n            res += clsName;\n            if (i < patternCount - 1) {\n                res += \", \";\n            }\n        }\n        printString = res;\n        return res;\n    }\n}\n", "human_rating": 3.9571827370002413, "metadata": {"project": "argoUML", "class": "org.argouml.util.PredicateType", "source_path": "argoUML/sourcefiles/src/argouml-app/src/org/argouml/util/PredicateType.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.0448683, 0.938427, 0.0167051, 1.02179e-08], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.26671, 0.733259, 3.16942e-05, 2.31577e-14]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Client.GUI.SettingsDialog", "source": "/*\n *\n *\n * Created on 15/10/2009, 11:04:35\n */\n\npackage TBA.Client.GUI;\n\nimport TBA.Sounds.SoundResources;\nimport javax.swing.JFileChooser;\nimport java.io.*;\nimport javax.swing.ComboBoxModel;\nimport java.util.Vector;\nimport TBA.MouseGestures.GesturesResource;\nimport java.util.logging.Logger;\n\n/**\n * This Class is the GUI dealing with editing program settings\n * @author Charles Jap\n */\npublic class SettingsDialog extends javax.swing.JDialog {\n\n    private SoundResources soundResources;\n    private GesturesResource gesturesResources;\n\n    private boolean isNowMute=false; //default\n    private String nowLocation=\"defaultNow.wav\";\n\n    private String user = new String();\n    private String server=\"localhost\"; //default\n    private int port=9999;// default\n\n    private final static Logger LOGIT = Logger.getLogger(SettingsDialog.class.getName());\n\n    \n    //default gestures          logon           add entry       settings\n    private String[] names = {\"Shake Sideways\", \"Clockwise\", \"Anti-Clockwise\"};\n    //all the available gestures including unassigned\n    private String[] methods = {\"Shake Sideways\", \"Clockwise\", \"Anti-Clockwise\", \"Up and Shake\", \"Down and Shake\", \"Disabled\"};\n    //holds unassigned gestures users can choose\n     Vector<String> options = new Vector<String>();\n\n    /**\n     * This function is a setter to pass down the soundfile, so the actual\n     * sound files can be changed\n     * @param soundResources - set and passed from mainclientview\n     */\n    public void setSoundResources(SoundResources soundResources) {\n        this.soundResources = soundResources;\n    }\n\n    /** Creates new form SettingsDialog\n     * @param parent\n     * @param modal\n     * @param soundResources - passed down from mainclient gui\n     */\n    public SettingsDialog(java.awt.Frame parent, boolean modal, SoundResources soundResources) {\n        super(parent, modal);\n        addWindowListener(new java.awt.event.WindowAdapter() {\n            @Override\n            public void windowClosing(java.awt.event.WindowEvent e) {\n                setVisible(false);\n            }\n        });\n\n        initComponents();\n        \n    }\n\n    /** This method is called from within the constructor to\n     * initialize the form.\n     * WARNING: Do NOT modify this code. The content of this method is\n     * always regenerated by the Form Editor.\n     */\n    @SuppressWarnings(\"unchecked\")\n    // <editor-fold defaultstate=\"collapsed\" desc=\"Generated Code\">//GEN-BEGIN:initComponents\n    private void initComponents() {\n\n        jPanel8 = new javax.swing.JPanel();\n        jTabbedPane1 = new javax.swing.JTabbedPane();\n        GeneralPanelTab = new javax.swing.JPanel();\n        SoundPanel = new javax.swing.JPanel();\n        txtNowAlert = new javax.swing.JTextField();\n        btnNowBrowse = new javax.swing.JButton();\n        chkNowtAlert = new javax.swing.JCheckBox();\n        GesturePanel = new javax.swing.JPanel();\n        jLabel6 = new javax.swing.JLabel();\n        comboName = new javax.swing.JComboBox();\n        jLabel8 = new javax.swing.JLabel();\n        comboGesture = new javax.swing.JComboBox();\n        jPanel12 = new javax.swing.JPanel();\n        ConnectionPanelTab = new javax.swing.JPanel();\n        LogonPanel = new javax.swing.JPanel();\n        jLabel4 = new javax.swing.JLabel();\n        txtUser = new javax.swing.JTextField();\n        ServerPanel = new javax.swing.JPanel();\n        jLabel2 = new javax.swing.JLabel();\n        txtServer = new javax.swing.JTextField();\n        jLabel3 = new javax.swing.JLabel();\n        txtPort = new javax.swing.JTextField();\n        btnOK = new javax.swing.JButton();\n        jbCancel = new javax.swing.JButton();\n\n        javax.swing.GroupLayout jPanel8Layout = new javax.swing.GroupLayout(jPanel8);\n        jPanel8.setLayout(jPanel8Layout);\n        jPanel8Layout.setHorizontalGroup(\n            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGap(0, 100, Short.MAX_VALUE)\n        );\n        jPanel8Layout.setVerticalGroup(\n            jPanel8Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGap(0, 100, Short.MAX_VALUE)\n        );\n\n        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);\n        setTitle(\"Settings\");\n        setName(\"SettingsDialog\"); // NOI18N\n\n        SoundPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(\"Sounds\"));\n\n        btnNowBrowse.setText(\"Browse\");\n        btnNowBrowse.addActionListener(new java.awt.event.ActionListener() {\n            public void actionPerformed(java.awt.event.ActionEvent evt) {\n                btnNowBrowseActionPerformed(evt);\n            }\n        });\n\n        chkNowtAlert.setText(\"Mute when meeting is now alert\");\n        chkNowtAlert.addActionListener(new java.awt.event.ActionListener() {\n            public void actionPerformed(java.awt.event.ActionEvent evt) {\n                chkNowtAlertActionPerformed(evt);\n            }\n        });\n\n        javax.swing.GroupLayout SoundPanelLayout = new javax.swing.GroupLayout(SoundPanel);\n        SoundPanel.setLayout(SoundPanelLayout);\n        SoundPanelLayout.setHorizontalGroup(\n            SoundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(SoundPanelLayout.createSequentialGroup()\n                .addContainerGap()\n                .addGroup(SoundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n                    .addComponent(chkNowtAlert)\n                    .addGroup(SoundPanelLayout.createSequentialGroup()\n                        .addComponent(txtNowAlert, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)\n                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                        .addComponent(btnNowBrowse, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)))\n                .addContainerGap(218, Short.MAX_VALUE))\n        );\n        SoundPanelLayout.setVerticalGroup(\n            SoundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(SoundPanelLayout.createSequentialGroup()\n                .addComponent(chkNowtAlert)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)\n                .addGroup(SoundPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n                    .addComponent(txtNowAlert, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                    .addComponent(btnNowBrowse, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE))\n                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n        );\n\n        txtNowAlert.setText(nowLocation);\n\n        GesturePanel.setBorder(javax.swing.BorderFactory.createTitledBorder(\"Gestures\"));\n\n        jLabel6.setText(\"Name\");\n\n        comboName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { \"Login\", \"Add Entry\", \"Preferences\" }));\n        comboName.addActionListener(new java.awt.event.ActionListener() {\n            public void actionPerformed(java.awt.event.ActionEvent evt) {\n                comboNameActionPerformed(evt);\n            }\n        });\n\n        jLabel8.setText(\"Gesture\");\n\n        options.add(names[comboName.getSelectedIndex()]);\n        fillComboMethods();\n\n        jPanel12.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));\n\n        javax.swing.GroupLayout jPanel12Layout = new javax.swing.GroupLayout(jPanel12);\n        jPanel12.setLayout(jPanel12Layout);\n        jPanel12Layout.setHorizontalGroup(\n            jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGap(0, 114, Short.MAX_VALUE)\n        );\n        jPanel12Layout.setVerticalGroup(\n            jPanel12Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGap(0, 109, Short.MAX_VALUE)\n        );\n\n        javax.swing.GroupLayout GesturePanelLayout = new javax.swing.GroupLayout(GesturePanel);\n        GesturePanel.setLayout(GesturePanelLayout);\n        GesturePanelLayout.setHorizontalGroup(\n            GesturePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(GesturePanelLayout.createSequentialGroup()\n                .addContainerGap()\n                .addGroup(GesturePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)\n                    .addComponent(comboName, 0, 163, Short.MAX_VALUE)\n                    .addComponent(jLabel6)\n                    .addComponent(jLabel8)\n                    .addComponent(comboGesture, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 183, Short.MAX_VALUE)\n                .addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                .addContainerGap())\n        );\n\n        GesturePanelLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {comboGesture, comboName});\n\n        GesturePanelLayout.setVerticalGroup(\n            GesturePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(GesturePanelLayout.createSequentialGroup()\n                .addGroup(GesturePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n                    .addGroup(GesturePanelLayout.createSequentialGroup()\n                        .addComponent(jLabel6)\n                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                        .addComponent(comboName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)\n                        .addComponent(jLabel8)\n                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                        .addComponent(comboGesture, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n                    .addComponent(jPanel12, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))\n                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n        );\n\n        javax.swing.GroupLayout GeneralPanelTabLayout = new javax.swing.GroupLayout(GeneralPanelTab);\n        GeneralPanelTab.setLayout(GeneralPanelTabLayout);\n        GeneralPanelTabLayout.setHorizontalGroup(\n            GeneralPanelTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(GeneralPanelTabLayout.createSequentialGroup()\n                .addContainerGap()\n                .addGroup(GeneralPanelTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n                    .addComponent(GesturePanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n                    .addComponent(SoundPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n                .addContainerGap())\n        );\n        GeneralPanelTabLayout.setVerticalGroup(\n            GeneralPanelTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(GeneralPanelTabLayout.createSequentialGroup()\n                .addContainerGap()\n                .addComponent(SoundPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)\n                .addComponent(GesturePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n                .addContainerGap())\n        );\n\n        jTabbedPane1.addTab(\"General\", GeneralPanelTab);\n\n        LogonPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(\"Default Logon Details\"));\n\n        jLabel4.setText(\"Username\");\n\n        javax.swing.GroupLayout LogonPanelLayout = new javax.swing.GroupLayout(LogonPanel);\n        LogonPanel.setLayout(LogonPanelLayout);\n        LogonPanelLayout.setHorizontalGroup(\n            LogonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(LogonPanelLayout.createSequentialGroup()\n                .addContainerGap()\n                .addGroup(LogonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)\n                    .addComponent(txtUser, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)\n                    .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING))\n                .addContainerGap(280, Short.MAX_VALUE))\n        );\n        LogonPanelLayout.setVerticalGroup(\n            LogonPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(LogonPanelLayout.createSequentialGroup()\n                .addComponent(jLabel4)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                .addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n        );\n\n        ServerPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(\"Default Server Details\"));\n\n        jLabel2.setText(\"Server\");\n\n        jLabel3.setText(\"Port\");\n\n        javax.swing.GroupLayout ServerPanelLayout = new javax.swing.GroupLayout(ServerPanel);\n        ServerPanel.setLayout(ServerPanelLayout);\n        ServerPanelLayout.setHorizontalGroup(\n            ServerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(ServerPanelLayout.createSequentialGroup()\n                .addContainerGap()\n                .addGroup(ServerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n                    .addComponent(jLabel2)\n                    .addComponent(jLabel3)\n                    .addGroup(ServerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)\n                        .addComponent(txtPort, javax.swing.GroupLayout.Alignment.LEADING)\n                        .addComponent(txtServer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)))\n                .addContainerGap(280, Short.MAX_VALUE))\n        );\n        ServerPanelLayout.setVerticalGroup(\n            ServerPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(ServerPanelLayout.createSequentialGroup()\n                .addComponent(jLabel2)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                .addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                .addComponent(jLabel3)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                .addContainerGap(32, Short.MAX_VALUE))\n        );\n\n        txtServer.setText(server);\n        txtPort.setText(Integer.toString(port));\n\n        javax.swing.GroupLayout ConnectionPanelTabLayout = new javax.swing.GroupLayout(ConnectionPanelTab);\n        ConnectionPanelTab.setLayout(ConnectionPanelTabLayout);\n        ConnectionPanelTabLayout.setHorizontalGroup(\n            ConnectionPanelTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(ConnectionPanelTabLayout.createSequentialGroup()\n                .addContainerGap()\n                .addGroup(ConnectionPanelTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n                    .addComponent(LogonPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)\n                    .addComponent(ServerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))\n                .addContainerGap())\n        );\n        ConnectionPanelTabLayout.setVerticalGroup(\n            ConnectionPanelTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(ConnectionPanelTabLayout.createSequentialGroup()\n                .addContainerGap()\n                .addComponent(LogonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)\n                .addComponent(ServerPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)\n                .addContainerGap(26, Short.MAX_VALUE))\n        );\n\n        jTabbedPane1.addTab(\"Connection\", ConnectionPanelTab);\n\n        btnOK.setText(\"OK\");\n        btnOK.addActionListener(new java.awt.event.ActionListener() {\n            public void actionPerformed(java.awt.event.ActionEvent evt) {\n                btnOKActionPerformed(evt);\n            }\n        });\n\n        jbCancel.setText(\"Cancel\");\n        jbCancel.addActionListener(new java.awt.event.ActionListener() {\n            public void actionPerformed(java.awt.event.ActionEvent evt) {\n                jbCancelActionPerformed(evt);\n            }\n        });\n\n        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());\n        getContentPane().setLayout(layout);\n        layout.setHorizontalGroup(\n            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()\n                .addContainerGap(395, Short.MAX_VALUE)\n                .addComponent(btnOK)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                .addComponent(jbCancel)\n                .addContainerGap())\n            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 523, Short.MAX_VALUE)\n        );\n        layout.setVerticalGroup(\n            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)\n            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()\n                .addComponent(jTabbedPane1)\n                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)\n                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)\n                    .addComponent(jbCancel)\n                    .addComponent(btnOK))\n                .addContainerGap())\n        );\n\n        pack();\n    }// </editor-fold>//GEN-END:initComponents\n\n    private void jbCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelActionPerformed\n        // TODO add your handling code here:\n        this.setVisible(false);\n    }//GEN-LAST:event_jbCancelActionPerformed\n\n    private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed\n\n        user = txtUser.getText();\n        server = txtServer.getText();\n        port = Integer.parseInt(txtPort.getText());\n\n        ComboBoxModel cbmMethod = comboGesture.getModel();\n        \n        switch(comboName.getSelectedIndex())\n         {\n            case 0: // Log On\n               names[0] = cbmMethod.getSelectedItem().toString();\n               break;\n            case 1: // Add Entry\n               names[1] = cbmMethod.getSelectedItem().toString();\n               break;\n            case 2: // Open Settings Dialog\n               names[2] = cbmMethod.getSelectedItem().toString();\n               break;\n            case 3:\n               break;\n            case 4:\n               break;\n         }\n\n        Update();\n\n        this.setVisible(false);\n    }//GEN-LAST:event_btnOKActionPerformed\n\n    private void comboNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_comboNameActionPerformed\n\n\n        if (evt.getActionCommand().equals(\"comboBoxChanged\")) {\n            options.clear();\n            options.add(names[comboName.getSelectedIndex()]);\n            fillComboMethods();\n        }\n}//GEN-LAST:event_comboNameActionPerformed\n\n    private void chkNowtAlertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkNowtAlertActionPerformed\n\n        if(chkNowtAlert.isSelected()) {\n            txtNowAlert.setEnabled(false);\n            btnNowBrowse.setEnabled(false);\n        } else {\n            txtNowAlert.setEnabled(true);\n            btnNowBrowse.setEnabled(true);\n        }\n}//GEN-LAST:event_chkNowtAlertActionPerformed\n\n    private void btnNowBrowseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNowBrowseActionPerformed\n\n        final JFileChooser fc = new JFileChooser();\n        fc.showOpenDialog(this);\n        File selected = fc.getSelectedFile();\n        nowLocation = selected.getPath();\n        //newSound = fc.getName(selected);\n        txtNowAlert.setText(nowLocation);\n    }//GEN-LAST:event_btnNowBrowseActionPerformed\n\n    private void fillComboMethods()\n    {\n        for(int x=0; x<5; x++)\n        {\n            boolean found = false;\n            for(int y=0; y<3; y++)\n            {\n                if(methods[x].equalsIgnoreCase(names[y]) == true)\n                {\n                    found = true;\n                }\n            }\n            if (found == false)\n            {\n                options.add(methods[x]);\n            }\n        }\n\n        options.add(methods[5]);\n        ComboBoxModel cbmOptions = new javax.swing.DefaultComboBoxModel(options);\n        comboGesture.setModel(cbmOptions);\n    }\n\n\n    /**\n    * @param args the command line arguments\n    */\n    public static void main(String args[]) {\n        /*java.awt.EventQueue.invokeLater(new Runnable() {\n            public void run() {\n                SettingsDialog dialog = new SettingsDialog(new javax.swing.JFrame(), true);\n                dialog.addWindowListener(new java.awt.event.WindowAdapter() {\n                    public void windowClosing(java.awt.event.WindowEvent e) {\n                        setVisible(false);\n                    }\n                });\n                dialog.setVisible(true);\n            }\n        });*/        \n    }\n\n    // Variables declaration - do not modify//GEN-BEGIN:variables\n    private javax.swing.JPanel ConnectionPanelTab;\n    private javax.swing.JPanel GeneralPanelTab;\n    private javax.swing.JPanel GesturePanel;\n    private javax.swing.JPanel LogonPanel;\n    private javax.swing.JPanel ServerPanel;\n    private javax.swing.JPanel SoundPanel;\n    private javax.swing.JButton btnNowBrowse;\n    private javax.swing.JButton btnOK;\n    private javax.swing.JCheckBox chkNowtAlert;\n    private javax.swing.JComboBox comboGesture;\n    private javax.swing.JComboBox comboName;\n    private javax.swing.JLabel jLabel2;\n    private javax.swing.JLabel jLabel3;\n    private javax.swing.JLabel jLabel4;\n    private javax.swing.JLabel jLabel6;\n    private javax.swing.JLabel jLabel8;\n    private javax.swing.JPanel jPanel12;\n    private javax.swing.JPanel jPanel8;\n    private javax.swing.JTabbedPane jTabbedPane1;\n    private javax.swing.JButton jbCancel;\n    private javax.swing.JTextField txtNowAlert;\n    private javax.swing.JTextField txtPort;\n    private javax.swing.JTextField txtServer;\n    private javax.swing.JTextField txtUser;\n    // End of variables declaration//GEN-END:variables\n\n    /**\n     *  This method reads from settings.ini and populates all the controls with it\n     */\n    public void LoadSettings()\n    {\n\n        File file = new File(\"settings.ini\");\n        if(file.exists())\n        {\n            try {\n                FileReader fstream = new FileReader(\"settings.ini\");\n                BufferedReader in = new BufferedReader(fstream);\n\n                String temp;\n\n                temp = in.readLine(); //general line\n                temp = in.readLine(); //sound line\n\n                temp = in.readLine(); //now alert\n                if(temp.equals(\"true\"))\n                {\n                    isNowMute = true;\n                    chkNowtAlert.setSelected(true);\n                    txtNowAlert.setEnabled(false);\n                }\n\n                temp = in.readLine(); //now alert location\n                nowLocation = temp.substring(temp.indexOf(\"=\")+1);\n                txtNowAlert.setText(nowLocation);\n\n                temp = in.readLine(); //gestures\n\n                temp = in.readLine(); //logon\n                names[0] = temp.substring(temp.indexOf(\"=\")+1);\n\n                temp = in.readLine(); //add new entry\n                names[1] = temp.substring(temp.indexOf(\"=\")+1);\n\n                temp = in.readLine(); //settings\n                names[2] = temp.substring(temp.indexOf(\"=\")+1);\n\n                options.clear();\n                options.add(names[comboName.getSelectedIndex()]);\n                fillComboMethods();\n\n                temp = in.readLine(); //connection\n\n                temp = in.readLine(); //user\n                user = temp.substring(temp.indexOf(\"=\")+1);\n                txtUser.setText(user);\n\n                temp = in.readLine(); //server\n                server = temp.substring(temp.indexOf(\"=\")+1);\n                txtServer.setText(server);\n\n                temp = in.readLine(); //port\n                temp = temp.substring(temp.indexOf(\"=\")+1);\n                port = Integer.parseInt(temp);\n                txtPort.setText(temp);\n\n                in.close();\n\n            } catch (IOException e) {\n            }\n        }\n    }\n\n    /**\n     * Getter for the port in the settings dialougue, this value is subservient\n     * to its commandline counterpart - eg if there is a port provided in the\n     * commandline, the main program will choose that over this\n     * @return port field to be retrieved\n     */\n    public int getPort() {\n        return port;\n    }\n\n    /**\n     * Setter for the port in the settings dialogue\n     * @param port - new port to set to\n     */\n    public void setPort(int port) {\n        this.port = port;\n    }\n\n    /**\n     * Getter for the server field in the settings dialogue, this value is subservient\n     * to its commandline counterpart - eg if there is a server provided in the\n     * commandline, the main program will choose that over this\n     * @return server field to be retrieved\n     */\n    public String getServer() {\n        return server;\n    }\n\n    /**\n     * Setter fo the server in the settings dialogue\n     * @param server - new server to set to\n     */\n    public void setServer(String server) {\n        this.server = server;\n    }\n\n    /**\n     * Getter for username if remembered by settings dialogue\n     * @return user field\n     */\n    public String getUser() {\n        return user;\n    }\n\n    /**\n     * Setter of the username if remembered by settings dialogue\n     * @param user - to set to\n     */\n    public void setUser(String user) {\n        this.user = user;\n    }\n\n    /**\n     * This method writes the values to file, and then recalls LoadSettings()\n     * to make sure.\n     */\n    public void Update()\n    {\n\n        try{\n            FileWriter fstream = new FileWriter(\"settings.ini\");\n            BufferedWriter out = new BufferedWriter(fstream);\n\n            //----------------to write--------------\n\n            //general tab\n            out.write(\"General\");\n            out.newLine();\n            out.write(\"Sound\");\n            out.newLine();\n            out.write(\"NowAlertMuted=\" + chkNowtAlert.isSelected());\n            out.newLine();\n            out.write(\"NowAlertLocation=\" + txtNowAlert.getText());\n            out.newLine();\n            \n            out.write(\"Gestures\");\n            out.newLine();\n            out.write(\"Logon=\"+names[0]);\n            out.newLine();\n            out.write(\"AddEntry=\"+names[1]);\n            out.newLine();\n            out.write(\"Settings=\"+names[2]);\n            out.newLine();\n\n            //connections tab\n            out.write(\"Connection\");\n            out.newLine();\n            out.write(\"User=\" + user);\n\n            out.newLine();\n            out.write(\"Server=\" + server);\n            out.newLine();\n            out.write(\"Port=\" + Integer.toString(port));\n            out.newLine();\n            \n            //---------------end write--------------\n\n            out.close();\n            \n        }catch (Exception e){\n          LOGIT.severe(\"Error: \" + e.getMessage());\n        }\n\n        LoadSettings();\n\n    }\n\n    /**\n     * This method returns whether or not the user wishes there to be sound\n     * @return true if sound is muted, false otherwise\n     */\n    public boolean IsNowMute() {\n        return isNowMute;\n    }\n\n    /**\n     * Getter for the address of the path of the filename of the sound to be\n     * played at each alert\n     * @return nowLocation - location of sound to play\n     */\n    public String getNowLocation() {\n        return nowLocation;\n    }\n\n    /**\n     * Setter of rht address of the path of the filename of the sound to be\n     * played at each alert\n     * @param nowLocation\n     */\n    public void setNowLocation(String nowLocation) {\n        this.nowLocation = nowLocation;\n    }\n\n    /**\n     * This method returns the string containing the \"gesuture\" eg shake to a\n     * corresponding method eg logon\n     * name[0] corresponds to logon\n     * name[1] corresponds to add new entry\n     * name[2] corresponds to settings\n     * @param gestureName\n     * @return name[] - gesture coresponding to gestureName (method) eg shake\n     */\n    public String getMethodName(String gestureName) {\n        if(gestureName.equalsIgnoreCase(\"Logon\"))\n        {\n            return names[0];\n        }\n        else if(gestureName.equalsIgnoreCase(\"Add New Entry\"))\n        {\n            return names[1];\n        }\n        else if(gestureName.equalsIgnoreCase(\"Settings\"))\n        {\n            return names[2];\n        }\n        \n        return \"\";\n    }\n\n    /**\n     * This is the setter to initialise the GestureResources which holds the\n     * images for each gesture.\n     * @param gesturesResources\n     */\n    public void setGesturesResources(GesturesResource gesturesResources) {\n        this.gesturesResources = gesturesResources;\n    }\n\n}\n", "human_rating": 3.0, "metadata": {"project": "diarymanagement", "class": "TBA.Client.GUI.SettingsDialog", "source_path": "diarymanagement/sourcefiles/tbaclient/src/TBA/Client/GUI/SettingsDialog.java", "label_probabilities": {"readability": [0.0, 1.0, 0.0, 0.0], "understandability": [0.999834, 0.00016572, 0.0, 0.0], "complexity": [0.0, 0.0, 4.69155e-09, 1.0], "modularization": [1.0, 0.0, 0.0, 0.0], "overall": [0.0, 0.590131, 0.409869, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Data.User#ddf7c5b75ed4", "source": "package TBA.Data;\n\nimport java.util.ArrayList;\n\n/**\n * This class provides an interface of a user\n * @author Dan McGrath\n */\npublic class User\n{\n   private String displayName;\n   private String sessionID;\n   private int defaultDiaryID;\n   private int numberOfDiaries;\n   ArrayList<Diary> Diaries;\n\n  /**\n   * This method returns the diaries of a user\n   * @return A Vector of Diaries.\n   */\n   public ArrayList<Diary> getDiaries()\n   {\n      return Diaries;\n   }\n\n  /**\n   * This method sets the diaries of a user\n   * @param Diaries A Vector of Diaries.\n   */\n   public void setDiaries(ArrayList<Diary> Diaries)\n   {\n     this.Diaries = Diaries;\n   }\n\n   /**\n    * This method returns the unique sessionID assigned to the user\n    * @return sessionID field\n    */\n   public String getSessionID()\n   {\n      return sessionID;\n   }\n\n   /**\n    * Sets the sessionID field of a user\n    * @param sessionID\n    */\n   public void setSessionID(String sessionID)\n   {\n      this.sessionID = sessionID;\n   }\n\n   /**\n    * Sets the default diary id a user has access to\n    * @param defaultDiaryID\n    */\n   public void setDefaultDiaryID(int defaultDiaryID)\n   {\n      this.defaultDiaryID = defaultDiaryID;\n   }\n\n   /**\n    * Sets name of the user\n    * @param displayName\n    */\n   public void setDisplayName(String displayName)\n   {\n      this.displayName = displayName;\n   }\n\n   /**\n    * Sets the number of diaries a user has\n    * @param numberOfDiaries\n    */\n   public void setNumberOfDiaries(int numberOfDiaries)\n   {\n      this.numberOfDiaries = numberOfDiaries;\n   }\n\n   /**\n    * This method returns the default diary id a user has access to\n    * @return defaultDiaryID field\n    */\n   public int getDefaultDiaryID()\n   {\n      return defaultDiaryID;\n   }\n\n   /**\n    * This method returns the name of the user\n    * @return displayName field\n    */\n   public String getDisplayName()\n   {\n      return displayName;\n   }\n\n   /**\n    * This method returns the number of Diaries a user has\n    * @return numberOfDiaries field\n    */\n   public int getNumberOfDiaries()\n   {\n      return numberOfDiaries;\n   }\n\n   /**\n    * Find the Diary with the same ID as the one passed in and replace all of\n    * it's details with the new ones. This is used when a new version of the\n    * diary has been recieved across the network.\n    *<p>\n    * @param newDiary The new Diary.\n    */\n   public void replaceDiary(Diary newDiary)\n   {\n      for(Diary nextDiary: Diaries)\n      {\n         if(nextDiary.getID() == newDiary.getID())\n         {\n            nextDiary.replaceDiary(newDiary);\n            break;\n         }\n      }\n   }\n}\n", "human_rating": 4.0, "metadata": {"project": "diarymanagement", "class": "TBA.Data.User", "source_path": "diarymanagement/sourcefiles/dbserver/src/TBA/Data/User.java", "label_probabilities": {"readability": [1.0, 0.0, 0.0, 0.0], "understandability": [0.99995, 4.99097e-05, 1.5657e-16, 0.0], "complexity": [0.0, 0.0, 4.79976e-05, 0.999952], "modularization": [0.0, 0.0, 0.00558938, 0.994411], "overall": [0.999906, 9.39747e-05, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Data.User#7196c89c43b9", "source": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\n\npackage TBA.Data;\n\n/**\n *\n * @author dmcgra\n */\npublic class User\n{\n   private String displayName;\n   private String sessionID;\n   private int defaultDiaryID;\n   private int numberOfDiaries;\n\n   public String getSessionID()\n   {\n      return sessionID;\n   }\n\n   public void setSessionID(String sessionID)\n   {\n      this.sessionID = sessionID;\n   }\n\n   public void setDefaultDiaryID(int defaultDiaryID)\n   {\n      this.defaultDiaryID = defaultDiaryID;\n   }\n\n   public void setDisplayName(String displayName)\n   {\n      this.displayName = displayName;\n   }\n\n   public void setNumberOfDiaries(int numberOfDiaries)\n   {\n      this.numberOfDiaries = numberOfDiaries;\n   }\n\n   public int getDefaultDiaryID()\n   {\n      return defaultDiaryID;\n   }\n\n   public String getDisplayName()\n   {\n      return displayName;\n   }\n\n   public int getNumberOfDiaries()\n   {\n      return numberOfDiaries;\n   }\n}\n", "human_rating": 4.0, "metadata": {"project": "diarymanagement", "class": "TBA.Data.User", "source_path": "diarymanagement/sourcefiles/tbaclientr/SSL/src/TBA/Data/User.java", "label_probabilities": {"readability": [1.0, 0.0, 0.0, 0.0], "understandability": [1.0, 2.43157e-15, 0.0, 0.0], "complexity": [0.0, 0.0, 8.25391e-05, 0.999917], "modularization": [0.0, 0.0, 0.021575, 0.978425], "overall": [1.0, 1.1197e-13, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Exceptions.MessagesException", "source": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\n\npackage TBA.Exceptions;\n\n/**\n *\n * @author dmcgra\n */\npublic class MessagesException extends Exception\n{\n    /**\n     * Constructor does nothing\n     */\n   public MessagesException() {}\n\n   /**\n    * This method passes message to super Exception\n    * @param message\n    */\n   public MessagesException(String message)\n   {\n      super(message);\n   }\n\n   /**\n    * This method passes cause to super Exception\n    * @param cause\n    */\n   public MessagesException(Throwable cause)\n   {\n      super(cause);\n   }\n\n   /**\n    * This method passes message and cause to super Exception\n    * @param message\n    * @param cause\n    */\n   public MessagesException(String message, Throwable cause)\n   {\n      super(message, cause);\n   }\n} ", "human_rating": 4.000001045284, "metadata": {"project": "diarymanagement", "class": "TBA.Exceptions.MessagesException", "source_path": "diarymanagement/sourcefiles/dbserver/src/TBA/Exceptions/MessagesException.java", "label_probabilities": {"readability": [1.0, 3.48428e-07, 0.0, 0.0], "understandability": [0.865871, 0.134129, 0.0, 0.0], "complexity": [0.0, 0.0, 2.20025e-08, 1.0], "modularization": [0.0, 0.0, 0.0946776, 0.905322], "overall": [0.78628, 0.21372, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Exceptions.NetworkDataException", "source": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\n\npackage TBA.Exceptions;\n\n/**\n *\n * @author dmcgra\n */\npublic class NetworkDataException extends Exception\n{\n\n    /**\n     * Constructor does nothing\n     */\n   public NetworkDataException() {}\n\n      /**\n    * This method passes the message to super Exception\n    * @param message\n    */\n   public NetworkDataException(String message)\n   {\n      super(message);\n   }\n\n   /**\n    * This method passes the cause to the super Exception\n    * @param cause\n    */\n   public NetworkDataException(Throwable cause)\n   {\n      super(cause);\n   }\n\n    /**\n    * This method passes both message and cause to exception\n    * @param message\n    * @param cause\n    */\n   public NetworkDataException(String message, Throwable cause)\n   {\n      super(message, cause);\n   }\n}", "human_rating": 3.983141400043401, "metadata": {"project": "diarymanagement", "class": "TBA.Exceptions.NetworkDataException", "source_path": "diarymanagement/sourcefiles/dbserver/src/TBA/Exceptions/NetworkDataException.java", "label_probabilities": {"readability": [0.983142, 0.0168578, 2.17005e-11, 0.0], "understandability": [0.999999, 3.85275e-10, 5.03899e-13, 7.99013e-07], "complexity": [0.0, 0.0, 8.29529e-07, 0.999999], "modularization": [0.0, 7.58898e-07, 0.0350479, 0.964951], "overall": [0.00593153, 0.343947, 0.441338, 0.208784]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Logging.TBALogger", "source": "package TBA.Logging;\n\nimport java.io.IOException;\nimport java.util.logging.FileHandler;\nimport java.util.logging.Level;\nimport java.util.logging.Logger;\nimport java.util.logging.SimpleFormatter;\nimport java.util.logging.ConsoleHandler;\nimport java.util.logging.Handler;\n\n/**\n * This class initialises the parent logger\n *<p> \n * If any loggers have been instantiated before the settings have\n * been set by this class, you must manually apply the settings to\n * those loggers as well.\n * <p>\n * Any loggers created after calling this class, will inherit the\n * settings you set here.\n * <p>\n * @author Dan McGrath\n * \n * @version $Rev:: 96            $ $Date:: 2009-09-06 #$\n * \n * @see java.util.logging.Logger\n */\npublic class TBALogger\n{\n   /**\n    * This constructor initialises the parent logger specifying the log filename\n    *<p> \n    * @param logfile Filename to write log entries to\n    * @throws IOException\n    * \n    * @see #setup() \n    */\n\tstatic public void setup(String logfile) throws IOException\n   {\n   \tFileHandler fileTxt;\n\n\t\t// Get the parent Logger and set default values\n\t\tLogger logger = Logger.getLogger(\"\");\n\t\tlogger.setLevel(Level.INFO);\n\n      if(logfile.compareTo(\"\") == 0 || logfile != null)\n      {\n         // Setup the logger to write to the filename passed in.\n         fileTxt = new FileHandler(logfile);\n         fileTxt.setFormatter(new SimpleFormatter());\n         logger.addHandler(fileTxt);\n      }\n   }\n\n   /**\n    * This constructor initialises the parent logger. A default log filename of\n    * TBALog is set\n    *<p> \n    * @throws IOException\n    * \n    * @see #setup(java.lang.String) \n    */\n   static public void setup() throws IOException\n   {\n   \tFileHandler fileTxt;\n\n\t\t// Create Logger\n\t\tLogger logger = Logger.getLogger(\"\");\n\t\tlogger.setLevel(Level.INFO);\n\n      // Setup the logger to write to file.\n      fileTxt = new FileHandler(\"TBALog\");\n      fileTxt.setFormatter(new SimpleFormatter());\n      logger.addHandler(fileTxt);\n\n      // Setup the logger to write to the console\n      logger.addHandler(new ConsoleHandler());\n\t}\n\n   /**\n    * This method sets the Level of detail to log of the parent logger and all\n    * it's handlers\n    *<p>\n    * @param loglevel The level of detail to set the logger to.\n    *<p>\n    * @throws IOException\n    *<p>\n    * @see java.util.logging.Logger#setLevel(java.util.logging.Level)\n    * @see java.util.logging.Handler#setLevel(java.util.logging.Level)\n    */\n   static public void setLevel(Level loglevel) throws IOException\n   {\n\t\t// Create Logger\n\t\tLogger logger = Logger.getLogger(\"\");\n\n      logger.setLevel(loglevel);\n      // Setup the logger to write to the console\n      for(Handler logHandler : logger.getHandlers())\n      {\n         logHandler.setLevel(loglevel);\n      }\n   }\n   \n   /**\n    * This method removes the first handler from the parent log. The first time\n    * you call this it should be the ConsoleHandler\n    *<p> \n    * @see java.util.logging.ConsoleHandler\n    * @see java.util.logging.Logger#removeHandler(java.util.logging.Handler) \n    */\n   static public void removeConsole()\n   {\n      Logger logger = Logger.getLogger(\"\");\n      \n      logger.removeHandler(logger.getHandlers()[0]);\n   }\n}", "human_rating": 2.0000871729, "metadata": {"project": "diarymanagement", "class": "TBA.Logging.TBALogger", "source_path": "diarymanagement/sourcefiles/tbaclient/src/TBA/Logging/TBALogger.java", "label_probabilities": {"readability": [3.20068e-05, 2.23819e-05, 0.999946, 0.0], "understandability": [0.481654, 0.518346, 7.7763e-16, 0.0], "complexity": [0.0, 0.0, 0.0161479, 0.983852], "modularization": [0.0, 1.04647e-15, 5.60221e-06, 0.999994], "overall": [0.0, 0.0, 0.997238, 0.00276172]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Messages.LoginResponse", "source": "package TBA.Messages;\n\nimport TBA.Exceptions.MessagesException;\nimport java.util.ArrayList;\n\n/**\n * This class is the response message to a Login Query\n *<p>\n * @author Dan McGrath\n *\n * @version $Rev:: 273           $ $Date:: 2011-10-25 #$\n */\npublic class LoginResponse extends ResponseMessage\n{\n   private String displayName = null;\n   private int diaryCount = 0;\n   private int defaultDiary = -1;\n   ArrayList<DiaryHeader> diaryHeaderRecords = new ArrayList<DiaryHeader>();\n\n   private final int displayNameLen = 32;\n   private final int diaryCountLen = 2;\n   private final int defaultDiaryLen = 4;\n   private final int loginResponseLen = displayNameLen + diaryCountLen + defaultDiaryLen;\n\n    /**\n    * Constructor does nothing\n    */\n   public LoginResponse() { }\n\n   /**\n    * The Get() Method gets the LoginResponse message including the\n    * reponse and message headers\n    *<p>\n    * @param dummy \n    * @return The actual message string you can send\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Set(java.lang.String)\n    */\n   @Override\n   public String Get(String dummy) throws MessagesException\n   {\n      String message = null;\n\n      if(displayName == null)\n      {\n         throw new MessagesException(\"Display Name is not set\");\n      }\n      if(defaultDiary == -1)\n      {\n         throw new MessagesException(\"Default Diary ID is not set\");\n      }\n\n      message = String.format(\"%1$-\" + Integer.toString(displayNameLen) + \"s\", displayName);\n      message += String.format(\"%0\" + Integer.toString(diaryCountLen) + \"x\", diaryCount);\n      message += String.format(\"%0\" + Integer.toString(defaultDiaryLen) + \"x\", defaultDiary);\n   \n      for(int i=0; i < diaryCount; i++)\n      {\n         // The following line can throw a MessagesException if the diary record is not valid.\n         message += diaryHeaderRecords.get(i).Get();\n      }\n      super.SetErrorCode(0);\n      return super.Get(message);\n   }\n\n   /**\n    * The Set() Method strips out all the fields of a Login Query message. They\n    * are then available by the Get methods of this class.\n    *<p>\n    * @param message The message as recieved.\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Get(java.lang.String)\n    */\n   @Override\n   public String Set(String message) throws MessagesException\n   {\n      String diaryCountStr;\n      String defaultDiaryStr;\n      DiaryHeader tempRecord;\n\n      message = super.Set(message);\n\n      if(GetErrorCode() > 0)\n      {\n         return \"\";\n      }\n      if(message.length() < loginResponseLen)\n      {\n         throw new MessagesException(\"The Login Response is incomplete\");\n      }\n      displayName = message.substring(0, displayNameLen);\n      message = message.substring(displayNameLen, message.length());\n\n      try\n      {\n         diaryCountStr = message.substring(0,diaryCountLen);\n         diaryCount = Integer.parseInt(diaryCountStr, 16);\n         message = message.substring(diaryCountLen, message.length());\n      }\n      catch (NumberFormatException ex)\n      {\n         throw new MessagesException(\"The Diary Count is invalid\");\n      }\n\n      try\n      {\n         defaultDiaryStr = message.substring(0, defaultDiaryLen);\n         defaultDiary = Integer.parseInt(defaultDiaryStr, 16);\n         message = message.substring(defaultDiaryLen, message.length());\n      }\n      catch (NumberFormatException ex)\n      {\n         throw new MessagesException(\"The Diary Count is invalid\");\n      }\n      \n      for(int i=0; i < diaryCount; i++)\n      {\n         // The following line can throw a MessagesException if the diary record is not valid.\n         tempRecord = new DiaryHeader();\n         message = tempRecord.Set(message);\n         diaryHeaderRecords.add(tempRecord);\n      }\n\n      return null;\n   }\n\n   /**\n    * This method returns the 'Display name' field. You must have called either\n    * SetResponse() or SetDisplayName() first.\n    *<p>\n    * @return The Error Code:\n    * 0 = Success\n    * >0 = A Failure\n    *<p>\n    * @see #SetDisplayName(java.lang.String)\n    */\n   public String GetDisplayName()\n   {\n      return displayName;\n   }\n\n   /**\n    * This method allows you to set the 'Display name' field.\n    *<p>\n    * @param name The display name of the user\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #GetDisplayName()\n    */\n   public void SetDisplayName(String name) throws MessagesException\n   {\n      if(name == null)\n      {\n         displayName = null;\n         throw new MessagesException(\"The Display name is null\");\n      }\n      else\n      {\n         displayName = name;\n      }\n   }\n\n   /**\n    * This method returns the 'Default Diary' field. You must have called either\n    * SetResponse() or SetDefaultDiary() first.\n    *<p>\n    * @return The Default Diary's ID\n    *<p>\n    * @see #SetErrorMessage(java.lang.String)\n    */\n   public int GetDefaultDiary()\n   {\n      return defaultDiary;\n   }\n\n   /**\n    * This method allows you to set the 'Default Diary' field.\n    *<p>\n    * @param diary The ID of the Diary that is set as the default\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #GetDefaultDiary()\n    */\n   public void SetDefaultDiary(int diary) throws MessagesException\n   {\n      if(diary < 0)\n      {\n         defaultDiary = -1;\n         throw new MessagesException(\"The Default Diary is invalid\");\n      }\n      else\n      {\n         defaultDiary = diary;\n      }\n   }\n\n   /**\n    * This method returns all the 'Diary Header' recprds. You must have called either\n    * SetResponse() or SetDiaryHeaders() first.\n    *<p>\n    * @return A Vector containing all the Diary Header records.\n    *<p>\n    * @see #SetErrorMessage(java.lang.String)\n    */\n   @SuppressWarnings(\"unchecked\")\n   public ArrayList<DiaryHeader> GetDiaryHeaders()\n   {\n      return (ArrayList<DiaryHeader>)diaryHeaderRecords.clone();\n   }\n\n   /**\n    * This method allows you to set all the 'Diary Header' records.\n    *<p>\n    * @param records A vector of all the Diary Header records to add to the response\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #GetDiaryHeaders() \n    */\n   @SuppressWarnings(\"unchecked\")\n   public void SetDiaryHeaders(ArrayList<DiaryHeader> records) throws MessagesException\n   {\n      if(records == null)\n      {\n         diaryHeaderRecords = new ArrayList<DiaryHeader>();\n         throw new MessagesException(\"The Diary header records are null\");\n      }\n      else\n      {\n         diaryHeaderRecords = (ArrayList<DiaryHeader>)records.clone();\n         diaryCount = diaryHeaderRecords.size();\n      }\n   }\n}", "human_rating": 2.6169718, "metadata": {"project": "diarymanagement", "class": "TBA.Messages.LoginResponse", "source_path": "diarymanagement/sourcefiles/dbserver/src/TBA/Messages/LoginResponse.java", "label_probabilities": {"readability": [0.002444, 0.627544, 0.354552, 0.0154598], "understandability": [0.942242, 0.0552206, 0.00253737, 4.73798e-12], "complexity": [0.0, 0.0, 0.00221422, 0.997786], "modularization": [5.081e-17, 2.59347e-09, 0.0877939, 0.912206], "overall": [0.980362, 0.0183597, 0.000943958, 0.000334124]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Messages.LogoutResponse", "source": "package TBA.Messages;\n\nimport TBA.Exceptions.MessagesException;\n\n/**\n * This class is the response message to a Logout Query\n *<p>\n * @author Dan McGrath\n *\n * @version $Rev:: 204           $ $Date:: 2009-10-15 #$\n */\npublic class LogoutResponse extends ResponseMessage\n{\n   /**\n    * Constructor does nothing\n    */\n   public LogoutResponse() {}\n\n   /**\n    * The Get() Method gets the LOGOUT message\n    *<p>\n    * @return The actual message string you can send\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Set(java.lang.String)\n    * @see TBA.Messages.ResponseMessage#Get(java.lang.String)\n    * @see TBA.Messages.Messages#Get(java.lang.String)\n    * @param dummy - to override Super Get(String)\n    */\n   @Override\n   public String Get(String dummy) throws MessagesException\n   {\n      return super.Get(\"\");\n   }\n\n   /**\n    * The Set() Method strips out all the fields of a Logout Query message. They\n    * are then available by the Get methods of this class.\n    *<p>\n    * @param message The message as recieved.\n    *<p>\n    * @return The message without the 'Response Header'\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Get(java.lang.String)\n    * @see TBA.Messages.ResponseMessage#Set(java.lang.String)\n    * @see TBA.Messages.Messages#Set(java.lang.String)\n    */\n   @Override\n   public String Set(String message) throws MessagesException\n   {\n      message = super.Set(message);\n      return null;\n   }\n}", "human_rating": 4.000000000031203, "metadata": {"project": "diarymanagement", "class": "TBA.Messages.LogoutResponse", "source_path": "diarymanagement/sourcefiles/tbaclient/src/TBA/Messages/LogoutResponse.java", "label_probabilities": {"readability": [1.0, 1.04008e-11, 0.0, 0.0], "understandability": [0.999992, 8.02978e-06, 0.0, 0.0], "complexity": [0.0, 0.0, 2.94932e-12, 1.0], "modularization": [0.0, 0.0, 0.02413, 0.97587], "overall": [1.0, 4.19334e-07, 1.16448e-09, 8.6548e-16]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Messages.Messages", "source": "package TBA.Messages;\n\nimport TBA.Exceptions.MessagesException;\n\n/**\n * This class is the root of all messages between the client and\n * the server. It handles the 'Message Header' section of the message only.\n *<p> \n * @author Dan McGrath\n * \n * @version $Rev:: 247           $ $Date:: 2009-10-23 #$\n */\npublic class Messages\n{\n   private char messageType = '\\0';\n   private String sessionID = null;\n   private int messageLen = 0;\n   private final int messageLenSize = 6;\n   private final int sessionIDLen = 36;\n   /** This field represents the length of the message header **/\n   public static final int messageHeaderLen =  43;//messageLenSize+sessionIDLen+1\n   /**\n    * Constructor does nothing\n    */\n   public Messages(){ }\n   \n   /**\n    * This method converts the message length (int) to the message length (hex)\n    * included the length of the message length field.\n    *<p> \n    * @param len The length of the message, not included the message length field\n    * @returns A zero-padded string of the message length\n    */\n   private String FormatLen(int len)\n   {\n      len += messageLenSize;\n      return String.format(\"%0\"+Integer.toString(messageLenSize)+\"x\", len);\n   }\n   \n   /**\n    * The Get() Method adds the 'Message Header' to the beginning of the message\n    * passed into it. It automatically calculates the message length field\n    * for you.\n    *<p> \n    * @param childMessage The message to send, not including the 'Message Header'\n    *<p>\n    * @return The actual message string you can send\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Set(java.lang.String) \n    */\n   protected String Get(String childMessage) throws MessagesException\n   {\n      String message = null;\n      \n      if(messageType == '\\0')\n      {\n         throw new MessagesException(\"Message Type not set\");\n      }\n      if(sessionID == null)\n      {\n         sessionID = String.format(\"%0\"+Integer.toString(sessionIDLen)+\"d\",0);\n      } else if (sessionID.length() != sessionIDLen)\n      {\n         throw new MessagesException(\"Invalid Session ID\");\n      }\n      if(childMessage == null)\n      {\n         childMessage = \"\";\n      }\n      \n      message = Character.toString(messageType);\n      message += sessionID;\n      message += FormatLen(message.length()+childMessage.length());\n      message += childMessage;\n      \n      return message;\n   }\n   \n   /**\n    * The Set() Method takes a Message and strips out the message header information\n    * returning the rest of the message back so that it can then be processed.\n    *<p> \n    * @param message The message as recieved.\n    *<p>\n    * @return The message without the 'Message Header'\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Get(java.lang.String) \n    */\n   public String Set(String message) throws MessagesException\n   {\n      int messageLenPos = sessionIDLen + messageLenSize + 1;\n      String messageLenString;\n\n      if(message.length() < messageLenPos)\n      {\n         throw new MessagesException(\"The Message Header is incomplete\");\n      }\n\n      messageLenString = message.substring(sessionIDLen + 2, messageLenPos);\n      try\n      {\n         messageLen = Integer.parseInt(messageLenString, 16);\n      }\n      catch(NumberFormatException ex)\n      {\n         throw new MessagesException(\"The Message length is formatted incorrectly!\");\n      }\n  \n      messageType = message.charAt(0);\n      if(messageType != 'R' && messageType !='Q')\n      {\n         messageType = '\\0';\n         throw new MessagesException(\"The message is of an unknown type\");\n      }\n      \n      sessionID = message.substring(1, sessionIDLen+1);\n\n      return message.substring(messageLenPos, message.length());\n   }\n   \n   /**\n    * This method returns the 'Message Type' field. You must have called either\n    * Set() or SetMessageType() first.\n    *<p> \n    * @return The Message Type. Possible values are:\n    * 'Q' for Query,\n    * 'R' for Response, or\n    * '\\0' for Message not currently set.\n    *<p>\n    * @see #SetMessageType(char) \n    */\n   public char GetMessageType()\n   {\n      return messageType;\n   }\n   \n   /**\n    * This method allows you to set the Message Type in the 'Message Header'.\n    *<p> \n    * @param Type Valid values are 'Q' for query or 'R' for Response. All others\n    * will throw an exception\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #GetMessageType() \n    */\n   protected void SetMessageType(char Type) throws MessagesException\n   {\n      if(Type != 'R' && Type !='Q')\n      {\n         messageType = '\\0';\n         throw new MessagesException(\"The message type is invalid\");\n      }\n      else\n      {\n         messageType = Type;\n      }\n   }\n\n   /**\n    * This method returns the message length\n    *<p>\n    * @return The Message length\n    *<p>\n    */\n   public int GetMessageLen()\n   {\n      return messageLen;\n   }\n   \n   /**\n    * This method gets the Session ID from the 'Message Header'. You must have\n    * called either Set() or SetSessionID() first.\n    *<p> \n    * @return The Session ID or null if one is not set.\n    *<p>\n    * @see #SetSessionID(java.lang.String) \n    */\n   public String GetSessionID()\n   {\n      return sessionID;\n   }\n   \n   /**\n    * This method allows you to set the 'Session ID' field.\n    *<p> \n    * @param ID The Session ID to set. Must be a 36-digit Hex number, as a string.\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #GetSessionID() \n    */\n   public void SetSessionID(String ID) throws MessagesException\n   {\n      if(ID.length() != sessionIDLen)\n      {\n         sessionID = null;\n         throw new MessagesException(\"The SessionID invalid\");\n      }\n      else\n      {\n         sessionID = ID;\n      }\n   }\n}", "human_rating": 3.000000049661058, "metadata": {"project": "diarymanagement", "class": "TBA.Messages.Messages", "source_path": "diarymanagement/sourcefiles/dbserver/src/TBA/Messages/Messages.java", "label_probabilities": {"readability": [4.14446e-13, 1.0, 2.48297e-08, 0.0], "understandability": [0.966216, 0.000404666, 0.033378, 1.49994e-06], "complexity": [0.0, 8.10571e-05, 0.155264, 0.844654], "modularization": [0.0, 2.08882e-09, 0.999999, 6.03558e-07], "overall": [0.863657, 0.136343, 8.96458e-13, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Messages.QueryMessage", "source": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\n\npackage TBA.Messages;\n\nimport TBA.Exceptions.MessagesException;\n\n/**\n * This class is the root of all query messages between the client and\n * the server. It handles the 'query Header' section of the message only.\n *<p>\n * @author Dan McGrath\n *\n * @version $Rev:: 247           $ $Date:: 2009-10-23 #$\n */\npublic class QueryMessage extends Messages\n{\n   private String queryType = null;\n   private final int queryTypeLen = 8;\n   /**\n    * Constructor does nothing\n    */\n   public QueryMessage() { }\n\n   /**\n    * The Get() Method adds the 'Query Header' to the beginning of the message\n    * passed into it. It then passes it on to Messages to process the\n    * 'Message Header'\n    *<p>\n    * @param childMessage The message to send, not including the 'Message Header'\n    *<p>\n    * @return The actual message string you can send\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Set(java.lang.String)\n    */\n   @Override\n   protected String Get(String childMessage) throws MessagesException\n   {\n      String message = null;\n\n      if(queryType == null)\n      {\n         throw new MessagesException(\"Query Type not set\");\n      }\n\n      message = String.format(\"%1$-\" + Integer.toString(queryTypeLen) + \"s\", queryType);\n\n      if(childMessage == null)\n      {\n         childMessage = \"\";\n      }\n\n      super.SetMessageType('Q');\n      return super.Get(message + childMessage);\n   }\n\n   /**\n    * The Set() Method takes a Message and strips out the 'Query Header'\n    * information, returning the rest of the message back so that it can then\n    * be processed.\n    *<p>s\n    * @param message The message as recieved.\n    *<p>\n    * @return The message without the 'Query Header'\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Get(java.lang.String)\n    */\n   @Override\n   public String Set(String message) throws MessagesException\n   {\n      message = super.Set(message);\n\n      if(message.length() < queryTypeLen)\n      {\n         throw new MessagesException(\"The Query Header is incomplete\");\n      }\n\n      queryType = message.substring(0, queryTypeLen).trim();\n      message = message.substring(queryTypeLen, message.length());\n\n      return message;\n   }\n\n   /**\n    * This method returns the 'Query Type' field. You must have called either\n    * Set() or SetQueryType() first.\n    *<p>\n    * @return The Query Type\n    *<p>\n    * @see #SetQueryType(java.lang.String)\n    */\n   public String GetQueryType()\n   {\n      return queryType;\n   }\n\n   /**\n    * This method allows you to set the Query Type field.\n    *<p>\n    * @param Type The Query to set\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #GetQueryType()\n    */\n   public void SetQueryType(String Type) throws MessagesException\n   {\n      if(Type == null)\n      {\n         queryType = null;\n         throw new MessagesException(\"The Query Type is null\");\n      }\n      else\n      {\n         queryType = Type;\n      }\n   }\n}", "human_rating": 3.9795178837727923, "metadata": {"project": "diarymanagement", "class": "TBA.Messages.QueryMessage", "source_path": "diarymanagement/sourcefiles/dbserver/src/TBA/Messages/QueryMessage.java", "label_probabilities": {"readability": [0.979592, 0.0203333, 7.49917e-05, 3.72792e-10], "understandability": [0.999963, 3.66231e-05, 6.71697e-09, 1.80795e-11], "complexity": [0.0, 0.0, 7.45918e-08, 1.0], "modularization": [0.0, 2.0248e-13, 0.100472, 0.899528], "overall": [0.681455, 0.316455, 0.00154406, 0.000546533]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/diarymanagement/TBA.Messages.ResponseMessage", "source": "/*\n * To change this template, choose Tools | Templates\n * and open the template in the editor.\n */\n\npackage TBA.Messages;\n\nimport TBA.Exceptions.MessagesException;\n\n/**\n * This class is the root of all response messages between the client and\n * the server. It handles the 'Response Header' section of the message only.\n *<p>\n * @author Dan McGrath\n *\n * @version $Rev:: 247           $ $Date:: 2009-10-23 #$\n */\npublic class ResponseMessage extends Messages\n{\n   private int errorCode = -1;\n   private String errorMessage = null;\n   private final int errorCodeLen = 1;\n   /**\n    * Constructor does nothing\n    */\n   public ResponseMessage() { }\n\n   /**\n    * The Get() Method adds the 'Response Header' to the beginning of the message\n    * passed into it. It then passes it on to Messages to process the\n    * 'Message Header'\n    *<p>\n    * @param childMessage The message to send, not including the 'Message Header'\n    *<p>\n    * @return The actual message string you can send\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Set(java.lang.String)\n    */\n   @Override\n   public String Get(String childMessage) throws MessagesException\n   {\n      String message = null;\n\n      if(errorCode == -1)\n      {\n         throw new MessagesException(\"Error/Success code not set\");\n      }\n\n      if(errorCode > 0)\n      {\n         childMessage = errorMessage + '|';\n      }\n\n      if(childMessage == null)\n      {\n         childMessage = \"\";\n      }\n\n      message = String.format(\"%0\" + Integer.toString(errorCodeLen) + \"x\", errorCode) + childMessage;\n\n      super.SetMessageType('R');\n      return super.Get(message);\n   }\n\n   /**\n    * The Set() Method takes a Message and strips out the 'Response Header'\n    * information, returning the rest of the message back so that it can then\n    * be processed.\n    *<p>\n    * @param message The message as recieved.\n    *<p>\n    * @return The message without the 'Response Header'\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #Get(java.lang.String)\n    */\n   @Override\n   public String Set(String message) throws MessagesException\n   { \n      message = super.Set(message);\n\n      if(message.length() < 1)\n      {\n         throw new MessagesException(\"The Response Header is incomplete\");\n      }\n\n      try\n      {\n         errorCode = Integer.parseInt(message.substring(0,errorCodeLen), 16);\n         message = message.substring(errorCodeLen, message.length());\n      }\n      catch (NumberFormatException ex)\n      {\n         throw new MessagesException(\"The Error Code is invalid\");\n      }\n\n      if(errorCode > 0)\n      {\n         int delimPos = message.indexOf(\"|\");\n         errorMessage = message.substring(0,delimPos);\n         message = message.substring(delimPos + 1, message.length());\n      }\n\n      return message;\n   }\n\n   /**\n    * This method returns the 'Error Code' field. You must have called either\n    * Set() or SetErrorCode() first.\n    *<p>\n    * @return The Error Code:\n    * 0 = Success\n    * >0 = A Failure\n    *<p>\n    * @see #SetErrorCode(int)\n    */\n   public int GetErrorCode()\n   {\n      return errorCode;\n   }\n\n   /**\n    * This method allows you to set the Error Code field.\n    *<p>\n    * @param Code The 'Error Code' to set\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #GetErrorCode()\n    */\n   public void SetErrorCode(int Code) throws MessagesException\n   {\n      if(Code < 0 || Code > 15)\n      {\n         errorCode = -1;\n         throw new MessagesException(\"The Error Code is out of range\");\n      }\n      else\n      {\n         errorCode = Code;\n      }\n   }\n\n   /**\n    * This method returns the 'Error Message' field. You must have called either\n    * Set() or SetErrorMessage() first.\n    *<p>\n    * @return The Error Message:\n    *<p>\n    * @see #SetErrorMessage(java.lang.String)\n    */\n   public String GetErrorMessage()\n   {\n      return errorMessage;\n   }\n\n   /**\n    * This method allows you to set the 'Error Message' field. Note, this field\n    * will only be sent if the Error Code field is > 0.\n    *<p>\n    * @param Message The Error Message to set\n    *<p>\n    * @throws MessagesException\n    *<p>\n    * @see #GetErrorMessage()\n    */\n   public void SetErrorMessage(String Message) throws MessagesException\n   {\n      if(Message == null)\n      {\n         errorMessage = null;\n         throw new MessagesException(\"The Error Message is null\");\n      }\n      else\n      {\n         errorMessage = Message;\n      }\n   }\n}", "human_rating": 3.1691620000006675, "metadata": {"project": "diarymanagement", "class": "TBA.Messages.ResponseMessage", "source_path": "diarymanagement/sourcefiles/dbserver/src/TBA/Messages/ResponseMessage.java", "label_probabilities": {"readability": [0.169162, 0.830838, 3.33671e-13, 7.289e-17], "understandability": [3.73211e-05, 0.991286, 0.00867665, 1.7e-19], "complexity": [0.0, 1.64501e-09, 0.995885, 0.00411496], "modularization": [0.0, 4.71359e-14, 0.191145, 0.808855], "overall": [0.439312, 0.560684, 3.73367e-06, 4.0393e-16]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.ANGLE_instanced_arrays", "source": "package def.dom;\n\nimport def.js.Object;\n\npublic class ANGLE_instanced_arrays extends def.js.Object {\n    native public void drawArraysInstancedANGLE(double mode, double first, double count, double primcount);\n    native public void drawElementsInstancedANGLE(double mode, double count, double type, double offset, double primcount);\n    native public void vertexAttribDivisorANGLE(double index, double divisor);\n    public double VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE;\n    public static ANGLE_instanced_arrays prototype;\n    public ANGLE_instanced_arrays(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.ANGLE_instanced_arrays", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/ANGLE_instanced_arrays.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.AudioParam", "source": "package def.dom;\nimport def.js.Float32Array;\npublic class AudioParam extends def.js.Object {\n    public double defaultValue;\n    public double value;\n    native public void cancelScheduledValues(double startTime);\n    native public void exponentialRampToValueAtTime(double value, double endTime);\n    native public void linearRampToValueAtTime(double value, double endTime);\n    native public void setTargetAtTime(double target, double startTime, double timeConstant);\n    native public void setValueAtTime(double value, double startTime);\n    native public void setValueCurveAtTime(Float32Array values, double startTime, double duration);\n    public static AudioParam prototype;\n    public AudioParam(){}\n}\n\n", "human_rating": 3.9571827370002413, "metadata": {"project": "jsweet", "class": "def.dom.AudioParam", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/AudioParam.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.CanvasRenderingContext2D", "source": "package def.dom;\nimport jsweet.util.union.Union3;\npublic class CanvasRenderingContext2D extends def.js.Object {\n    public HTMLCanvasElement canvas;\n    public Union3<String,CanvasGradient,CanvasPattern> fillStyle;\n    public String font;\n    public double globalAlpha;\n    public String globalCompositeOperation;\n    public String lineCap;\n    public double lineDashOffset;\n    public String lineJoin;\n    public double lineWidth;\n    public double miterLimit;\n    public String msFillRule;\n    public Boolean msImageSmoothingEnabled;\n    public double shadowBlur;\n    public String shadowColor;\n    public double shadowOffsetX;\n    public double shadowOffsetY;\n    public Union3<String,CanvasGradient,CanvasPattern> strokeStyle;\n    public String textAlign;\n    public String textBaseline;\n    native public void arc(double x, double y, double radius, double startAngle, double endAngle, Boolean anticlockwise);\n    native public void arcTo(double x1, double y1, double x2, double y2, double radius);\n    native public void beginPath();\n    native public void bezierCurveTo(double cp1x, double cp1y, double cp2x, double cp2y, double x, double y);\n    native public void clearRect(double x, double y, double w, double h);\n    native public void clip(String fillRule);\n    native public void closePath();\n    native public ImageData createImageData(double imageDataOrSw, double sh);\n    native public CanvasGradient createLinearGradient(double x0, double y0, double x1, double y1);\n    native public CanvasPattern createPattern(HTMLImageElement image, String repetition);\n    native public CanvasGradient createRadialGradient(double x0, double y0, double r0, double x1, double y1, double r1);\n    native public void drawImage(HTMLImageElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY, double canvasImageWidth, double canvasImageHeight);\n    native public void fill(String fillRule);\n    native public void fillRect(double x, double y, double w, double h);\n    native public void fillText(String text, double x, double y, double maxWidth);\n    native public ImageData getImageData(double sx, double sy, double sw, double sh);\n    native public double[] getLineDash();\n    native public Boolean isPointInPath(double x, double y, String fillRule);\n    native public void lineTo(double x, double y);\n    native public TextMetrics measureText(String text);\n    native public void moveTo(double x, double y);\n    native public void putImageData(ImageData imagedata, double dx, double dy, double dirtyX, double dirtyY, double dirtyWidth, double dirtyHeight);\n    native public void quadraticCurveTo(double cpx, double cpy, double x, double y);\n    native public void rect(double x, double y, double w, double h);\n    native public void restore();\n    native public void rotate(double angle);\n    native public void save();\n    native public void scale(double x, double y);\n    native public void setLineDash(double[] segments);\n    native public void setTransform(double m11, double m12, double m21, double m22, double dx, double dy);\n    native public void stroke();\n    native public void strokeRect(double x, double y, double w, double h);\n    native public void strokeText(String text, double x, double y, double maxWidth);\n    native public void transform(double m11, double m12, double m21, double m22, double dx, double dy);\n    native public void translate(double x, double y);\n    public static CanvasRenderingContext2D prototype;\n    public CanvasRenderingContext2D(){}\n    native public void arc(double x, double y, double radius, double startAngle, double endAngle);\n    native public void clip();\n    native public ImageData createImageData(double imageDataOrSw);\n    native public void drawImage(HTMLImageElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY, double canvasImageWidth);\n    native public void drawImage(HTMLImageElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY);\n    native public void drawImage(HTMLImageElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX);\n    native public void drawImage(HTMLImageElement image, double offsetX, double offsetY, double width, double height);\n    native public void drawImage(HTMLImageElement image, double offsetX, double offsetY, double width);\n    native public void drawImage(HTMLImageElement image, double offsetX, double offsetY);\n    native public void fill();\n    native public void fillText(String text, double x, double y);\n    native public Boolean isPointInPath(double x, double y);\n    native public void putImageData(ImageData imagedata, double dx, double dy, double dirtyX, double dirtyY, double dirtyWidth);\n    native public void putImageData(ImageData imagedata, double dx, double dy, double dirtyX, double dirtyY);\n    native public void putImageData(ImageData imagedata, double dx, double dy, double dirtyX);\n    native public void putImageData(ImageData imagedata, double dx, double dy);\n    native public void strokeText(String text, double x, double y);\n    native public ImageData createImageData(ImageData imageDataOrSw, double sh);\n    native public CanvasPattern createPattern(HTMLVideoElement image, String repetition);\n    native public CanvasPattern createPattern(HTMLCanvasElement image, String repetition);\n    native public void drawImage(HTMLCanvasElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY, double canvasImageWidth, double canvasImageHeight);\n    native public void drawImage(HTMLVideoElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY, double canvasImageWidth, double canvasImageHeight);\n    native public ImageData createImageData(ImageData imageDataOrSw);\n    native public void drawImage(HTMLCanvasElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY, double canvasImageWidth);\n    native public void drawImage(HTMLVideoElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY, double canvasImageWidth);\n    native public void drawImage(HTMLVideoElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY);\n    native public void drawImage(HTMLCanvasElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX, double canvasOffsetY);\n    native public void drawImage(HTMLCanvasElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX);\n    native public void drawImage(HTMLVideoElement image, double offsetX, double offsetY, double width, double height, double canvasOffsetX);\n    native public void drawImage(HTMLCanvasElement image, double offsetX, double offsetY, double width, double height);\n    native public void drawImage(HTMLVideoElement image, double offsetX, double offsetY, double width, double height);\n    native public void drawImage(HTMLCanvasElement image, double offsetX, double offsetY, double width);\n    native public void drawImage(HTMLVideoElement image, double offsetX, double offsetY, double width);\n    native public void drawImage(HTMLVideoElement image, double offsetX, double offsetY);\n    native public void drawImage(HTMLCanvasElement image, double offsetX, double offsetY);\n}\n\n", "human_rating": 3.9000431234099997, "metadata": {"project": "jsweet", "class": "def.dom.CanvasRenderingContext2D", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/CanvasRenderingContext2D.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.ChildNode", "source": "package def.dom;\n@jsweet.lang.Interface\npublic abstract class ChildNode extends def.js.Object {\n    native public void remove();\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.ChildNode", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/ChildNode.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.CloseEvent", "source": "package def.dom;\n\npublic class CloseEvent extends Event {\n    public double code;\n    public java.lang.String reason;\n    public java.lang.Boolean wasClean;\n    native public void initCloseEvent(java.lang.String typeArg, java.lang.Boolean canBubbleArg, java.lang.Boolean cancelableArg, java.lang.Boolean wasCleanArg, double codeArg, java.lang.String reasonArg);\n    public static CloseEvent prototype;\n    public CloseEvent(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.CloseEvent", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/CloseEvent.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.CSSConditionRule", "source": "package def.dom;\npublic class CSSConditionRule extends CSSGroupingRule {\n    public String conditionText;\n    public static CSSConditionRule prototype;\n    public CSSConditionRule(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.CSSConditionRule", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/CSSConditionRule.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.GainNode", "source": "package def.dom;\npublic class GainNode extends AudioNode {\n    public AudioParam gain;\n    public static GainNode prototype;\n    public GainNode(){}\n}\n\n", "human_rating": 2.6169718, "metadata": {"project": "jsweet", "class": "def.dom.GainNode", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/GainNode.java", "label_probabilities": {"readability": [0.002444, 0.627544, 0.354552, 0.0154598], "understandability": [0.999813, 0.000187114, 1.02606e-07, 7.1434e-16], "complexity": [0.0, 0.0, 2.40634e-10, 1.0], "modularization": [1.79e-18, 3.22372e-10, 0.0346899, 0.96531], "overall": [0.980362, 0.0183597, 0.000943958, 0.000334124]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.GamepadEvent", "source": "package def.dom;\npublic class GamepadEvent extends Event {\n    public Gamepad gamepad;\n    public static GamepadEvent prototype;\n    public GamepadEvent(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.GamepadEvent", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/GamepadEvent.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLAllCollection", "source": "package def.dom;\n\npublic class HTMLAllCollection extends HTMLCollection {\n    native public Element namedItem(java.lang.String name);\n    public static HTMLAllCollection prototype;\n    public HTMLAllCollection(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.HTMLAllCollection", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/HTMLAllCollection.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLBaseElement", "source": "package def.dom;\npublic class HTMLBaseElement extends HTMLElement {\n    /**\n      * Gets or sets the baseline URL on which relative links are based.\n      */\n    public String href;\n    /**\n      * Sets or retrieves the window or frame at which to target content.\n      */\n    public String target;\n    public static HTMLBaseElement prototype;\n    public HTMLBaseElement(){}\n}\n\n", "human_rating": 3.9000431234099997, "metadata": {"project": "jsweet", "class": "def.dom.HTMLBaseElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/HTMLBaseElement.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLBodyElement", "source": "package def.dom;\n\nimport jsweet.util.StringTypes;\nimport jsweet.util.StringTypes.MSContentZoom;\nimport jsweet.util.StringTypes.afterprint;\nimport jsweet.util.StringTypes.beforeprint;\nimport jsweet.util.StringTypes.beforeunload;\nimport jsweet.util.StringTypes.hashchange;\nimport jsweet.util.StringTypes.message;\nimport jsweet.util.StringTypes.offline;\nimport jsweet.util.StringTypes.online;\nimport jsweet.util.StringTypes.orientationchange;\nimport jsweet.util.StringTypes.pagehide;\nimport jsweet.util.StringTypes.pageshow;\nimport jsweet.util.StringTypes.popstate;\nimport jsweet.util.StringTypes.resize;\nimport jsweet.util.StringTypes.storage;\nimport jsweet.util.StringTypes.unload;\n\npublic class HTMLBodyElement extends HTMLElement {\n    public java.lang.Object aLink;\n    public java.lang.String background;\n    public java.lang.Object bgColor;\n    public java.lang.String bgProperties;\n    public java.lang.Object link;\n    public java.lang.Boolean noWrap;\n    public java.util.function.Function<Event,java.lang.Object> onafterprint;\n    public java.util.function.Function<Event,java.lang.Object> onbeforeprint;\n    public java.util.function.Function<BeforeUnloadEvent,java.lang.Object> onbeforeunload;\n    public java.util.function.Function<FocusEvent,java.lang.Object> onblur;\n    public java.util.function.Function<Event,java.lang.Object> onerror;\n    public java.util.function.Function<FocusEvent,java.lang.Object> onfocus;\n    public java.util.function.Function<HashChangeEvent,java.lang.Object> onhashchange;\n    public java.util.function.Function<Event,java.lang.Object> onload;\n    public java.util.function.Function<MessageEvent,java.lang.Object> onmessage;\n    public java.util.function.Function<Event,java.lang.Object> onoffline;\n    public java.util.function.Function<Event,java.lang.Object> ononline;\n    public java.util.function.Function<Event,java.lang.Object> onorientationchange;\n    public java.util.function.Function<PageTransitionEvent,java.lang.Object> onpagehide;\n    public java.util.function.Function<PageTransitionEvent,java.lang.Object> onpageshow;\n    public java.util.function.Function<PopStateEvent,java.lang.Object> onpopstate;\n    public java.util.function.Function<UIEvent,java.lang.Object> onresize;\n    public java.util.function.Function<StorageEvent,java.lang.Object> onstorage;\n    public java.util.function.Function<Event,java.lang.Object> onunload;\n    public java.lang.Object text;\n    public java.lang.Object vLink;\n    native public TextRange createTextRange();\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMSGestureEventAny(MSContentZoom type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMSManipulationEventAny(MSContentZoom type, java.util.function.Function<MSManipulationEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMSPointerEventAny(MSContentZoom type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.afterprint type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerAriaRequestEventAny(MSContentZoom type, java.util.function.Function<AriaRequestEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforeprint type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforeunload type, java.util.function.Function<BeforeUnloadEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerCommandEventAny(MSContentZoom type, java.util.function.Function<CommandEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerErrorEventAny(MSContentZoom type, java.util.function.Function<ErrorEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerFocusEventAny(MSContentZoom type, java.util.function.Function<FocusEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.hashchange type, java.util.function.Function<HashChangeEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerKeyboardEventAny(MSContentZoom type, java.util.function.Function<KeyboardEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.message type, java.util.function.Function<MessageEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMouseEventAny(MSContentZoom type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMouseWheelEventAny(MSContentZoom type, java.util.function.Function<MouseWheelEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.offline type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.online type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.orientationchange type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pagehide type, java.util.function.Function<PageTransitionEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pageshow type, java.util.function.Function<PageTransitionEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerDragEventAny(MSContentZoom type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerPointerEventAny(MSContentZoom type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.popstate type, java.util.function.Function<PopStateEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerProgressEventAny(MSContentZoom type, java.util.function.Function<ProgressEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.resize type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerUIEventAny(MSContentZoom type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.storage type, java.util.function.Function<StorageEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerTouchEventAny(MSContentZoom type, java.util.function.Function<TouchEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.unload type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerEventAny(MSContentZoom type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerWheelEventAny(MSContentZoom type, java.util.function.Function<WheelEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(java.lang.String type, EventListener listener, java.lang.Boolean useCapture);\n    public static HTMLBodyElement prototype;\n    public HTMLBodyElement(){}\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMSGestureEventAny(MSContentZoom type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMSManipulationEventAny(MSContentZoom type, java.util.function.Function<MSManipulationEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMSPointerEventAny(MSContentZoom type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.afterprint type, java.util.function.Function<Event,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerAriaRequestEventAny(MSContentZoom type, java.util.function.Function<AriaRequestEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforeprint type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforeunload type, java.util.function.Function<BeforeUnloadEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerCommandEventAny(MSContentZoom type, java.util.function.Function<CommandEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerErrorEventAny(MSContentZoom type, java.util.function.Function<ErrorEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerFocusEventAny(MSContentZoom type, java.util.function.Function<FocusEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.hashchange type, java.util.function.Function<HashChangeEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerKeyboardEventAny(MSContentZoom type, java.util.function.Function<KeyboardEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.message type, java.util.function.Function<MessageEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMouseEventAny(MSContentZoom type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerMouseWheelEventAny(MSContentZoom type, java.util.function.Function<MouseWheelEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.offline type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.online type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.orientationchange type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pagehide type, java.util.function.Function<PageTransitionEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pageshow type, java.util.function.Function<PageTransitionEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerDragEventAny(MSContentZoom type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerPointerEventAny(MSContentZoom type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.popstate type, java.util.function.Function<PopStateEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerProgressEventAny(MSContentZoom type, java.util.function.Function<ProgressEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.resize type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerUIEventAny(MSContentZoom type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.storage type, java.util.function.Function<StorageEvent,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerTouchEventAny(MSContentZoom type, java.util.function.Function<TouchEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.unload type, java.util.function.Function<Event,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerEventAny(MSContentZoom type, java.util.function.Function<Event,java.lang.Object> listener);\n    @jsweet.lang.Name(\"addEventListener\")\n    native public void addEventListenerListenerWheelEventAny(MSContentZoom type, java.util.function.Function<WheelEvent,java.lang.Object> listener);\n    native public void addEventListener(java.lang.String type, EventListener listener);\n    native public void addEventListener(java.lang.String type, EventListenerObject listener, java.lang.Boolean useCapture);\n    native public void addEventListener(java.lang.String type, EventListenerObject listener);\n}\n\n", "human_rating": 1.00171665886692, "metadata": {"project": "jsweet", "class": "def.dom.HTMLBodyElement", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/HTMLBodyElement.java", "label_probabilities": {"readability": [2.21673e-09, 0.00026995, 0.0011764, 0.998554], "understandability": [0.0189295, 0.966209, 0.0148612, 1.52459e-08], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.106415, 0.893578, 7.31166e-06, 1e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLDTElement", "source": "package def.dom;\npublic class HTMLDTElement extends HTMLElement {\n    /**\n      * Sets or retrieves whether the browser automatically performs wordwrap.\n      */\n    public java.lang.Boolean noWrap;\n    public static HTMLDTElement prototype;\n    public HTMLDTElement(){}\n}\n\n", "human_rating": 3.9000431234099997, "metadata": {"project": "jsweet", "class": "def.dom.HTMLDTElement", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/HTMLDTElement.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLFrameElement", "source": "package def.dom;\n@jsweet.lang.Extends({GetSVGDocument.class})\npublic class HTMLFrameElement extends HTMLElement {\n    /**\n      * Specifies the properties of a border drawn around an object.\n      */\n    public String border;\n    /**\n      * Sets or retrieves the border color of the object.\n      */\n    public Object borderColor;\n    /**\n      * Retrieves the document object of the page or frame.\n      */\n    public Document contentDocument;\n    /**\n      * Retrieves the object of the specified.\n      */\n    public Window contentWindow;\n    /**\n      * Sets or retrieves whether to display a border for the frame.\n      */\n    public String frameBorder;\n    /**\n      * Sets or retrieves the amount of additional space between the frames.\n      */\n    public Object frameSpacing;\n    /**\n      * Sets or retrieves the height of the object.\n      */\n    public jsweet.util.union.Union<String,Double> height;\n    /**\n      * Sets or retrieves a URI to a long description of the object.\n      */\n    public String longDesc;\n    /**\n      * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n      */\n    public String marginHeight;\n    /**\n      * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n      */\n    public String marginWidth;\n    /**\n      * Sets or retrieves the frame name.\n      */\n    public String name;\n    /**\n      * Sets or retrieves whether the user can resize the frame.\n      */\n    public Boolean noResize;\n    /**\n      * Raised when the object has been completely received from the server.\n      */\n    public java.util.function.Function<Event,Object> onload;\n    /**\n      * Sets or retrieves whether the frame can be scrolled.\n      */\n    public String scrolling;\n    /**\n      * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied.\n      */\n    public Object security;\n    /**\n      * Sets or retrieves a URL to be loaded by the object.\n      */\n    public String src;\n    /**\n      * Sets or retrieves the width of the object.\n      */\n    public jsweet.util.union.Union<String,Double> width;\n    native public void addEventListener(jsweet.util.StringTypes.MSContentZoom type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureChange type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureDoubleTap type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureEnd type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureHold type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureStart type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureTap type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGotPointerCapture type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSInertiaStart type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSLostPointerCapture type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSManipulationStateChanged type, java.util.function.Function<MSManipulationEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerCancel type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerDown type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerEnter type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerLeave type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerMove type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOut type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOver type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerUp type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.abort type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.activate type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.ariarequest type, java.util.function.Function<AriaRequestEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforeactivate type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforecopy type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforecut type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforedeactivate type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforepaste type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.blur type, java.util.function.Function<FocusEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.canplay type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.canplaythrough type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.change type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.click type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.command type, java.util.function.Function<CommandEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.contextmenu type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.copy type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.cuechange type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.cut type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dblclick type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.deactivate type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.drag type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragend type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragenter type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragleave type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragover type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragstart type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.drop type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.durationchange type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.emptied type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.ended type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.error type, java.util.function.Function<ErrorEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.focus type, java.util.function.Function<FocusEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.gotpointercapture type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.input type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.keydown type, java.util.function.Function<KeyboardEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.keypress type, java.util.function.Function<KeyboardEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.keyup type, java.util.function.Function<KeyboardEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadeddata type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadedmetadata type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadstart type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.lostpointercapture type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mousedown type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseenter type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseleave type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mousemove type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseout type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseover type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseup type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mousewheel type, java.util.function.Function<MouseWheelEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.paste type, java.util.function.Function<DragEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pause type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.play type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.playing type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointercancel type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerdown type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerenter type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerleave type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointermove type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerout type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerover type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerup type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.progress type, java.util.function.Function<ProgressEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.ratechange type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.reset type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.scroll type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.seeked type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.seeking type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.select type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.selectstart type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.stalled type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.submit type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.suspend type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.timeupdate type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchcancel type, java.util.function.Function<TouchEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchend type, java.util.function.Function<TouchEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchmove type, java.util.function.Function<TouchEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchstart type, java.util.function.Function<TouchEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.volumechange type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.waiting type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenchange type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenerror type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.wheel type, java.util.function.Function<WheelEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListener listener, Boolean useCapture);\n    public static HTMLFrameElement prototype;\n    public HTMLFrameElement(){}\n    native public Document getSVGDocument();\n    native public void addEventListener(jsweet.util.StringTypes.MSContentZoom type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureChange type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureDoubleTap type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureEnd type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureHold type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureStart type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureTap type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGotPointerCapture type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSInertiaStart type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSLostPointerCapture type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSManipulationStateChanged type, java.util.function.Function<MSManipulationEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerCancel type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerDown type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerEnter type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerLeave type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerMove type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOut type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOver type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerUp type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.abort type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.activate type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.ariarequest type, java.util.function.Function<AriaRequestEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforeactivate type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforecopy type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforecut type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforedeactivate type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforepaste type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.blur type, java.util.function.Function<FocusEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.canplay type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.canplaythrough type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.change type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.click type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.command type, java.util.function.Function<CommandEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.contextmenu type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.copy type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.cuechange type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.cut type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dblclick type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.deactivate type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.drag type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragend type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragenter type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragleave type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragover type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragstart type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.drop type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.durationchange type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.emptied type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.ended type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.error type, java.util.function.Function<ErrorEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.focus type, java.util.function.Function<FocusEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.gotpointercapture type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.input type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.keydown type, java.util.function.Function<KeyboardEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.keypress type, java.util.function.Function<KeyboardEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.keyup type, java.util.function.Function<KeyboardEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadeddata type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadedmetadata type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadstart type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.lostpointercapture type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mousedown type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseenter type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseleave type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mousemove type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseout type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseover type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseup type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mousewheel type, java.util.function.Function<MouseWheelEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.paste type, java.util.function.Function<DragEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pause type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.play type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.playing type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointercancel type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerdown type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerenter type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerleave type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointermove type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerout type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerover type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerup type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.progress type, java.util.function.Function<ProgressEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.ratechange type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.reset type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.scroll type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.seeked type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.seeking type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.select type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.selectstart type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.stalled type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.submit type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.suspend type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.timeupdate type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchcancel type, java.util.function.Function<TouchEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchend type, java.util.function.Function<TouchEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchmove type, java.util.function.Function<TouchEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchstart type, java.util.function.Function<TouchEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.volumechange type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.waiting type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenchange type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenerror type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.wheel type, java.util.function.Function<WheelEvent,Object> listener);\n    native public void addEventListener(String type, EventListener listener);\n    native public void addEventListener(String type, EventListenerObject listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListenerObject listener);\n}\n\n", "human_rating": 3.000000000334494, "metadata": {"project": "jsweet", "class": "def.dom.HTMLFrameElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/HTMLFrameElement.java", "label_probabilities": {"readability": [8.36236e-11, 1.0, 0.0, 0.0], "understandability": [0.0374993, 0.945202, 0.0156891, 0.00160983], "complexity": [0.0, 0.0, 6.1891e-07, 0.999999], "modularization": [8.29049e-08, 0.0274663, 0.00162287, 0.970911], "overall": [1.53764e-05, 0.932514, 1.98499e-05, 0.0674503]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLIFrameElement", "source": "package def.dom;\n\nimport jsweet.util.StringTypes;\nimport jsweet.util.StringTypes.*;\n\n@jsweet.lang.Extends({GetSVGDocument.class})\npublic class HTMLIFrameElement extends HTMLElement {\n    /**\n      * Sets or retrieves how the object is aligned with adjacent text.\n      */\n    public java.lang.String align;\n    public java.lang.Boolean allowFullscreen;\n    /**\n      * Specifies the properties of a border drawn around an object.\n      */\n    public java.lang.String border;\n    /**\n      * Retrieves the document object of the page or frame.\n      */\n    public Document contentDocument;\n    /**\n      * Retrieves the object of the specified.\n      */\n    public Window contentWindow;\n    /**\n      * Sets or retrieves whether to display a border for the frame.\n      */\n    public java.lang.String frameBorder;\n    /**\n      * Sets or retrieves the amount of additional space between the frames.\n      */\n    public java.lang.Object frameSpacing;\n    /**\n      * Sets or retrieves the height of the object.\n      */\n    public java.lang.String height;\n    /**\n      * Sets or retrieves the horizontal margin for the object.\n      */\n    public double hspace;\n    /**\n      * Sets or retrieves a URI to a long description of the object.\n      */\n    public java.lang.String longDesc;\n    /**\n      * Sets or retrieves the top and bottom margin heights before displaying the text in a frame.\n      */\n    public java.lang.String marginHeight;\n    /**\n      * Sets or retrieves the left and right margin widths before displaying the text in a frame.\n      */\n    public java.lang.String marginWidth;\n    /**\n      * Sets or retrieves the frame name.\n      */\n    public java.lang.String name;\n    /**\n      * Sets or retrieves whether the user can resize the frame.\n      */\n    public java.lang.Boolean noResize;\n    /**\n      * Raised when the object has been completely received from the server.\n      */\n    public java.util.function.Function<Event,java.lang.Object> onload;\n    public DOMSettableTokenList sandbox;\n    /**\n      * Sets or retrieves whether the frame can be scrolled.\n      */\n    public java.lang.String scrolling;\n    /**\n      * Sets the value indicating whether the source file of a frame or iframe has specific security restrictions applied.\n      */\n    public java.lang.Object security;\n    /**\n      * Sets or retrieves a URL to be loaded by the object.\n      */\n    public java.lang.String src;\n    /**\n      * Sets or retrieves the vertical margin for the object.\n      */\n    public double vspace;\n    /**\n      * Sets or retrieves the width of the object.\n      */\n    public java.lang.String width;\n    native public void addEventListener(jsweet.util.StringTypes.MSContentZoom type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureChange type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureDoubleTap type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureEnd type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureHold type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureStart type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureTap type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGotPointerCapture type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSInertiaStart type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSLostPointerCapture type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSManipulationStateChanged type, java.util.function.Function<MSManipulationEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerCancel type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerDown type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerEnter type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerLeave type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerMove type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOut type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOver type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerUp type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.abort type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.activate type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.ariarequest type, java.util.function.Function<AriaRequestEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforeactivate type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforecopy type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforecut type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforedeactivate type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.beforepaste type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.blur type, java.util.function.Function<FocusEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.canplay type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.canplaythrough type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.change type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.click type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.command type, java.util.function.Function<CommandEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.contextmenu type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.copy type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.cuechange type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.cut type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dblclick type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.deactivate type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.drag type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragend type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragenter type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragleave type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragover type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dragstart type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.drop type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.durationchange type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.emptied type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.ended type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.error type, java.util.function.Function<ErrorEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.focus type, java.util.function.Function<FocusEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.gotpointercapture type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.input type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.keydown type, java.util.function.Function<KeyboardEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.keypress type, java.util.function.Function<KeyboardEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.keyup type, java.util.function.Function<KeyboardEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadeddata type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadedmetadata type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadstart type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.lostpointercapture type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mousedown type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseenter type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseleave type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mousemove type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseout type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseover type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseup type, java.util.function.Function<MouseEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mousewheel type, java.util.function.Function<MouseWheelEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.paste type, java.util.function.Function<DragEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pause type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.play type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.playing type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointercancel type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerdown type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerenter type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerleave type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointermove type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerout type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerover type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerup type, java.util.function.Function<PointerEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.progress type, java.util.function.Function<ProgressEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.ratechange type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.reset type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.scroll type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.seeked type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.seeking type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.select type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.selectstart type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.stalled type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.submit type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.suspend type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.timeupdate type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchcancel type, java.util.function.Function<TouchEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchend type, java.util.function.Function<TouchEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchmove type, java.util.function.Function<TouchEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchstart type, java.util.function.Function<TouchEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.volumechange type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.waiting type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenchange type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenerror type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.wheel type, java.util.function.Function<WheelEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(java.lang.String type, EventListener listener, java.lang.Boolean useCapture);\n    public static HTMLIFrameElement prototype;\n    public HTMLIFrameElement(){}\n    native public Document getSVGDocument();\n    native public void addEventListener(jsweet.util.StringTypes.MSContentZoom type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureChange type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureDoubleTap type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureEnd type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureHold type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureStart type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureTap type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGotPointerCapture type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSInertiaStart type, java.util.function.Function<MSGestureEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSLostPointerCapture type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSManipulationStateChanged type, java.util.function.Function<MSManipulationEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerCancel type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerDown type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerEnter type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerLeave type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerMove type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOut type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOver type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerUp type, java.util.function.Function<MSPointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.abort type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.activate type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.ariarequest type, java.util.function.Function<AriaRequestEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforeactivate type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforecopy type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforecut type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforedeactivate type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.beforepaste type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.blur type, java.util.function.Function<FocusEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.canplay type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.canplaythrough type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.change type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.click type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.command type, java.util.function.Function<CommandEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.contextmenu type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.copy type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.cuechange type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.cut type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dblclick type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.deactivate type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.drag type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragend type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragenter type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragleave type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragover type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dragstart type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.drop type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.durationchange type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.emptied type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.ended type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.error type, java.util.function.Function<ErrorEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.focus type, java.util.function.Function<FocusEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.gotpointercapture type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.input type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.keydown type, java.util.function.Function<KeyboardEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.keypress type, java.util.function.Function<KeyboardEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.keyup type, java.util.function.Function<KeyboardEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadeddata type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadedmetadata type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadstart type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.lostpointercapture type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mousedown type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseenter type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseleave type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mousemove type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseout type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseover type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseup type, java.util.function.Function<MouseEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mousewheel type, java.util.function.Function<MouseWheelEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.paste type, java.util.function.Function<DragEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pause type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.play type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.playing type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointercancel type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerdown type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerenter type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerleave type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointermove type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerout type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerover type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerup type, java.util.function.Function<PointerEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.progress type, java.util.function.Function<ProgressEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.ratechange type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.reset type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.scroll type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.seeked type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.seeking type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.select type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.selectstart type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.stalled type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.submit type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.suspend type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.timeupdate type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchcancel type, java.util.function.Function<TouchEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchend type, java.util.function.Function<TouchEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchmove type, java.util.function.Function<TouchEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchstart type, java.util.function.Function<TouchEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.volumechange type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.waiting type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenchange type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenerror type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.wheel type, java.util.function.Function<WheelEvent,java.lang.Object> listener);\n    native public void addEventListener(java.lang.String type, EventListener listener);\n    native public void addEventListener(java.lang.String type, EventListenerObject listener, java.lang.Boolean useCapture);\n    native public void addEventListener(java.lang.String type, EventListenerObject listener);\n}\n\n", "human_rating": 1.9435548, "metadata": {"project": "jsweet", "class": "def.dom.HTMLIFrameElement", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/HTMLIFrameElement.java", "label_probabilities": {"readability": [0.0, 0.0, 0.943555, 0.0564448], "understandability": [0.0, 1.38169e-15, 0.406819, 0.593181], "complexity": [0.0523685, 0.0091004, 0.938531, 0.0], "modularization": [0.0, 0.552427, 0.447572, 8.28654e-07], "overall": [0.0, 0.0, 0.13161, 0.868389]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLLegendElement", "source": "package def.dom;\npublic class HTMLLegendElement extends HTMLElement {\n    /**\n      * Retrieves a reference to the form that the object is embedded in.\n      */\n    public String align;\n    /**\n      * Retrieves a reference to the form that the object is embedded in.\n      */\n    public HTMLFormElement form;\n    public static HTMLLegendElement prototype;\n    public HTMLLegendElement(){}\n}\n\n", "human_rating": 3.927985835881085, "metadata": {"project": "jsweet", "class": "def.dom.HTMLLegendElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/HTMLLegendElement.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLMapElement", "source": "package def.dom;\npublic class HTMLMapElement extends HTMLElement {\n    /**\n      * Retrieves a collection of the area objects defined for the given map object.\n      */\n    public HTMLAreasCollection areas;\n    /**\n      * Sets or retrieves the name of the object.\n      */\n    public String name;\n    public static HTMLMapElement prototype;\n    public HTMLMapElement(){}\n}\n\n", "human_rating": 3.927985835881085, "metadata": {"project": "jsweet", "class": "def.dom.HTMLMapElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/HTMLMapElement.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLNextIdElement", "source": "package def.dom;\npublic class HTMLNextIdElement extends HTMLElement {\n    public String n;\n    public static HTMLNextIdElement prototype;\n    public HTMLNextIdElement(){}\n}\n\n", "human_rating": 3.8402408869999998, "metadata": {"project": "jsweet", "class": "def.dom.HTMLNextIdElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/HTMLNextIdElement.java", "label_probabilities": {"readability": [0.847062, 0.149497, 6.06285e-05, 0.00338063], "understandability": [0.250255, 0.731038, 0.0187068, 3.72393e-08], "complexity": [0.0, 2.48818e-12, 0.0163121, 0.983688], "modularization": [9e-20, 6.32847e-05, 0.0270903, 0.972846], "overall": [0.958454, 0.0415457, 3.55536e-08, 1e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLOListElement", "source": "package def.dom;\npublic class HTMLOListElement extends HTMLElement {\n    public java.lang.Boolean compact;\n    /**\n      * The starting number.\n      */\n    public double start;\n    public java.lang.String type;\n    public static HTMLOListElement prototype;\n    public HTMLOListElement(){}\n}\n\n", "human_rating": 3.227401988, "metadata": {"project": "jsweet", "class": "def.dom.HTMLOListElement", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/HTMLOListElement.java", "label_probabilities": {"readability": [0.227521, 0.77236, 0.000118994, 1.6658e-16], "understandability": [0.250771, 0.749229, 6.61735e-08, 0.0], "complexity": [0.0, 2.31458e-11, 0.0427667, 0.957233], "modularization": [0.0, 5.30263e-05, 0.0363115, 0.963636], "overall": [0.888751, 0.111249, 1.00282e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLUListElement", "source": "package def.dom;\npublic class HTMLUListElement extends HTMLElement {\n    public Boolean compact;\n    public String type;\n    public static HTMLUListElement prototype;\n    public HTMLUListElement(){}\n}\n\n", "human_rating": 4.0, "metadata": {"project": "jsweet", "class": "def.dom.HTMLUListElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/HTMLUListElement.java", "label_probabilities": {"readability": [1.0, 0.0, 0.0, 0.0], "understandability": [0.0, 0.840556, 0.159444, 0.0], "complexity": [0.0, 0.0, 0.000170523, 0.999829], "modularization": [0.0, 0.0, 0.021575, 0.978425], "overall": [4e-20, 0.995325, 0.00467461, 4.27428e-10]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.HTMLUnknownElement", "source": "package def.dom;\npublic class HTMLUnknownElement extends HTMLElement {\n    public static HTMLUnknownElement prototype;\n    public HTMLUnknownElement(){}\n}\n\n", "human_rating": 3.961635758076289, "metadata": {"project": "jsweet", "class": "def.dom.HTMLUnknownElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/HTMLUnknownElement.java", "label_probabilities": {"readability": [0.961645, 0.0383463, 8.42896e-06, 1.56289e-10], "understandability": [0.949126, 0.0507472, 0.000126645, 3.24991e-13], "complexity": [6.2976e-16, 8.3078e-06, 0.0398721, 0.96012], "modularization": [2.209e-17, 6.29103e-05, 0.0339099, 0.966027], "overall": [0.984911, 0.0150895, 1.29179e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.intl.CollatorOptions", "source": "package def.dom.intl;\n@jsweet.lang.Interface\npublic abstract class CollatorOptions extends def.js.Object {\n    @jsweet.lang.Optional\n    public String usage;\n    @jsweet.lang.Optional\n    public String localeMatcher;\n    @jsweet.lang.Optional\n    public Boolean numeric;\n    @jsweet.lang.Optional\n    public String caseFirst;\n    @jsweet.lang.Optional\n    public String sensitivity;\n    @jsweet.lang.Optional\n    public Boolean ignorePunctuation;\n}\n\n", "human_rating": 4.000000000031203, "metadata": {"project": "jsweet", "class": "def.dom.intl.CollatorOptions", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/intl/CollatorOptions.java", "label_probabilities": {"readability": [1.0, 1.04008e-11, 0.0, 0.0], "understandability": [0.999999, 6.10829e-07, 0.0, 0.0], "complexity": [0.0, 0.0, 2.94932e-12, 1.0], "modularization": [0.0, 0.0, 0.02413, 0.97587], "overall": [1.0, 1.71768e-07, 8.27e-18, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.intl.ResolvedCollatorOptions", "source": "package def.dom.intl;\n@jsweet.lang.Interface\npublic abstract class ResolvedCollatorOptions extends def.js.Object {\n    public String locale;\n    public String usage;\n    public String sensitivity;\n    public Boolean ignorePunctuation;\n    public String collation;\n    public String caseFirst;\n    public Boolean numeric;\n}\n\n", "human_rating": 3.9582949010401, "metadata": {"project": "jsweet", "class": "def.dom.intl.ResolvedCollatorOptions", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/intl/ResolvedCollatorOptions.java", "label_probabilities": {"readability": [0.958295, 0.0417043, 1.00052e-06, 9.98987e-14], "understandability": [0.968477, 0.0315224, 4.69583e-07, 1.31449e-13], "complexity": [2.5e-19, 1.88871e-07, 0.0258059, 0.974194], "modularization": [0.0, 4.84987e-11, 0.0203369, 0.979663], "overall": [0.994958, 0.00504182, 1.47754e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.intl.ResolvedNumberFormatOptions", "source": "package def.dom.intl;\n@jsweet.lang.Interface\npublic abstract class ResolvedNumberFormatOptions extends def.js.Object {\n    public String locale;\n    public String numberingSystem;\n    public String style;\n    @jsweet.lang.Optional\n    public String currency;\n    @jsweet.lang.Optional\n    public String currencyDisplay;\n    public double minimumintegerDigits;\n    public double minimumFractionDigits;\n    public double maximumFractionDigits;\n    @jsweet.lang.Optional\n    public double minimumSignificantDigits;\n    @jsweet.lang.Optional\n    public double maximumSignificantDigits;\n    public Boolean useGrouping;\n}\n\n", "human_rating": 3.971194015056, "metadata": {"project": "jsweet", "class": "def.dom.intl.ResolvedNumberFormatOptions", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/intl/ResolvedNumberFormatOptions.java", "label_probabilities": {"readability": [0.971194, 0.0288058, 3.07528e-07, 8.37e-18], "understandability": [0.888599, 0.111397, 3.26292e-06, 5.89971e-15], "complexity": [9e-20, 1.1399e-07, 0.0242425, 0.975757], "modularization": [0.0, 4.28517e-11, 0.0203369, 0.979663], "overall": [0.986171, 0.0138287, 9.98904e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.KeyAlgorithm#3f2133f2d081", "source": "package def.dom;\n@jsweet.lang.Interface\npublic abstract class KeyAlgorithm extends def.js.Object {\n    @jsweet.lang.Optional\n    public String name;\n}\n\n", "human_rating": 3.9571827370002413, "metadata": {"project": "jsweet", "class": "def.dom.KeyAlgorithm", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/KeyAlgorithm.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.KeyAlgorithm#12cf543952c2", "source": "package def.dom;\n\nimport def.js.Object;\n\n@jsweet.lang.Interface\npublic abstract class KeyAlgorithm extends def.js.Object {\n    @jsweet.lang.Optional\n    public java.lang.String name;\n}\n\n", "human_rating": 3.9704242222400503, "metadata": {"project": "jsweet", "class": "def.dom.KeyAlgorithm", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/KeyAlgorithm.java", "label_probabilities": {"readability": [0.970427, 0.02957, 3.11112e-06, 5.03385e-14], "understandability": [0.949766, 0.0501387, 9.49146e-05, 5.61813e-15], "complexity": [2.52283e-12, 0.000291194, 0.0930862, 0.906623], "modularization": [3.43356e-09, 0.000620866, 0.120966, 0.878413], "overall": [0.96967, 0.0303301, 1.42078e-08, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MediaSource", "source": "package def.dom;\n\npublic class MediaSource extends EventTarget {\n    public SourceBufferList activeSourceBuffers;\n    public double duration;\n    public double readyState;\n    public SourceBufferList sourceBuffers;\n    native public SourceBuffer addSourceBuffer(java.lang.String type);\n    native public void endOfStream(double error);\n    native public void removeSourceBuffer(SourceBuffer sourceBuffer);\n    public static MediaSource prototype;\n    public MediaSource(){}\n    native public static java.lang.Boolean isTypeSupported(java.lang.String type);\n    native public void endOfStream();\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.MediaSource", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/MediaSource.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MimeTypeArray", "source": "package def.dom;\n\nimport def.js.Iterable;\n\n@jsweet.lang.SyntacticIterable\npublic class MimeTypeArray extends Iterable<Plugin> {\n    public double length;\n    native public Plugin item(double index);\n    native public Plugin namedItem(java.lang.String type);\n    native public Plugin $get(double index);\n    public static MimeTypeArray prototype;\n    public MimeTypeArray(){}\n    /** From Iterable, to allow foreach loop (do not use directly). */\n    @jsweet.lang.Erased\n    native public java.util.Iterator<Plugin> iterator();\n}\n\n", "human_rating": 3.9000431234099997, "metadata": {"project": "jsweet", "class": "def.dom.MimeTypeArray", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/MimeTypeArray.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MouseEvent", "source": "package def.dom;\n\npublic class MouseEvent extends UIEvent {\n    public java.lang.Boolean altKey;\n    public int button;\n    public int buttons;\n    public double clientX;\n    public double clientY;\n    public java.lang.Boolean ctrlKey;\n    public Element fromElement;\n    public double layerX;\n    public double layerY;\n    public java.lang.Boolean metaKey;\n    public double movementX;\n    public double movementY;\n    public double offsetX;\n    public double offsetY;\n    public double pageX;\n    public double pageY;\n    public EventTarget relatedTarget;\n    public double screenX;\n    public double screenY;\n    public java.lang.Boolean shiftKey;\n    public Element toElement;\n    public int which;\n    public double x;\n    public double y;\n    native public java.lang.Boolean getModifierState(java.lang.String keyArg);\n    native public void initMouseEvent(java.lang.String typeArg, java.lang.Boolean canBubbleArg, java.lang.Boolean cancelableArg, Window viewArg, double detailArg, double screenXArg, double screenYArg, double clientXArg, double clientYArg, java.lang.Boolean ctrlKeyArg, java.lang.Boolean altKeyArg, java.lang.Boolean shiftKeyArg, java.lang.Boolean metaKeyArg, double buttonArg, EventTarget relatedTargetArg);\n    public static MouseEvent prototype;\n    public MouseEvent(java.lang.String typeArg, MouseEventInit eventInitDict){}\n    public MouseEvent(java.lang.String typeArg){}\n    protected MouseEvent(){}\n}\n\n", "human_rating": 3.999665671, "metadata": {"project": "jsweet", "class": "def.dom.MouseEvent", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/MouseEvent.java", "label_probabilities": {"readability": [0.999667, 0.000332557, 8.3e-19, 0.0], "understandability": [0.934011, 0.0659889, 6.27492e-10, 0.0], "complexity": [0.0, 1e-20, 1.24632e-07, 1.0], "modularization": [0.0, 6.69e-18, 0.0180733, 0.981927], "overall": [0.986966, 0.0130335, 3.7896e-15, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MouseEventInit", "source": "package def.dom;\n\n@jsweet.lang.Interface\npublic abstract class MouseEventInit extends SharedKeyboardAndMouseEventInit {\n    @jsweet.lang.Optional\n    public double screenX;\n    @jsweet.lang.Optional\n    public double screenY;\n    @jsweet.lang.Optional\n    public double clientX;\n    @jsweet.lang.Optional\n    public double clientY;\n    @jsweet.lang.Optional\n    public double button;\n    @jsweet.lang.Optional\n    public double buttons;\n    @jsweet.lang.Optional\n    public EventTarget relatedTarget;\n}\n\n", "human_rating": 3.8707873388799996, "metadata": {"project": "jsweet", "class": "def.dom.MouseEventInit", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/MouseEventInit.java", "label_probabilities": {"readability": [0.870871, 0.129047, 8.0319e-05, 1.70088e-06], "understandability": [0.931635, 0.0683612, 3.47957e-06, 1.74392e-10], "complexity": [3.29649e-12, 3.50398e-06, 0.0360278, 0.963969], "modularization": [0.0, 2.63917e-10, 0.0263247, 0.973675], "overall": [0.988667, 0.0113334, 2.46646e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MSApp", "source": "package def.dom;\n\nimport def.js.Object;\n\n@jsweet.lang.Interface\npublic abstract class MSApp extends def.js.Object {\n    native public static MSAppAsyncOperation clearTemporaryWebDataAsync();\n    native public static Blob createBlobFromRandomAccessStream(java.lang.String type, java.lang.Object seeker);\n    native public static java.lang.Object createDataPackage(java.lang.Object object);\n    native public static java.lang.Object createDataPackageFromSelection();\n    native public static File createFileFromStorageFile(java.lang.Object storageFile);\n    native public static MSStream createStreamFromInputStream(java.lang.String type, java.lang.Object inputStream);\n    native public static void execAsyncAtPriority(MSExecAtPriorityFunctionCallback asynchronousCallback, java.lang.String priority, java.lang.Object... args);\n    native public static java.lang.Object execAtPriority(MSExecAtPriorityFunctionCallback synchronousCallback, java.lang.String priority, java.lang.Object... args);\n    native public static java.lang.String getCurrentPriority();\n    native public static java.lang.Object getHtmlPrintDocumentSourceAsync(java.lang.Object htmlDoc);\n    native public static java.lang.Object getViewId(java.lang.Object view);\n    native public static java.lang.Boolean isTaskScheduledAtPriorityOrHigher(java.lang.String priority);\n    native public static void pageHandlesAllApplicationActivations(java.lang.Boolean enabled);\n    native public static void suppressSubdownloadCredentialPrompts(java.lang.Boolean suppress);\n    native public static void terminateApp(java.lang.Object exceptionObject);\n    public static java.lang.String CURRENT;\n    public static java.lang.String HIGH;\n    public static java.lang.String IDLE;\n    public static java.lang.String NORMAL;\n}\n\n", "human_rating": 3.0197191527290004, "metadata": {"project": "jsweet", "class": "def.dom.MSApp", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/MSApp.java", "label_probabilities": {"readability": [0.0207181, 0.978284, 0.000997222, 3.08729e-07], "understandability": [0.872715, 0.127283, 2.26467e-06, 1.48193e-14], "complexity": [1e-20, 4.08177e-08, 0.0105911, 0.989409], "modularization": [0.0, 2.66271e-11, 0.0177, 0.9823], "overall": [0.99356, 0.00643998, 1.91094e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MSBaseReader", "source": "package def.dom;\n\nimport def.js.Object;\nimport jsweet.util.StringTypes;\nimport jsweet.util.StringTypes.abort;\nimport jsweet.util.StringTypes.error;\nimport jsweet.util.StringTypes.load;\nimport jsweet.util.StringTypes.loadend;\nimport jsweet.util.StringTypes.loadstart;\nimport jsweet.util.StringTypes.progress;\n\n@jsweet.lang.Interface\npublic abstract class MSBaseReader extends def.js.Object {\n    public java.util.function.Function<Event,java.lang.Object> onabort;\n    public java.util.function.Function<Event,java.lang.Object> onerror;\n    public java.util.function.Function<Event,java.lang.Object> onload;\n    public java.util.function.Function<ProgressEvent,java.lang.Object> onloadend;\n    public java.util.function.Function<Event,java.lang.Object> onloadstart;\n    public java.util.function.Function<ProgressEvent,java.lang.Object> onprogress;\n    public double readyState;\n    public java.lang.Object result;\n    native public void abort();\n    public double DONE;\n    public double EMPTY;\n    public double LOADING;\n    native public void addEventListener(jsweet.util.StringTypes.abort type, java.util.function.Function<UIEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.error type, java.util.function.Function<ErrorEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadend type, java.util.function.Function<ProgressEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadstart type, java.util.function.Function<Event,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.progress type, java.util.function.Function<ProgressEvent,java.lang.Object> listener, java.lang.Boolean useCapture);\n    native public void addEventListener(java.lang.String type, EventListener listener, java.lang.Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.abort type, java.util.function.Function<UIEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.error type, java.util.function.Function<ErrorEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadend type, java.util.function.Function<ProgressEvent,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadstart type, java.util.function.Function<Event,java.lang.Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.progress type, java.util.function.Function<ProgressEvent,java.lang.Object> listener);\n    native public void addEventListener(java.lang.String type, EventListener listener);\n    native public void addEventListener(java.lang.String type, EventListenerObject listener, java.lang.Boolean useCapture);\n    native public void addEventListener(java.lang.String type, EventListenerObject listener);\n}\n\n", "human_rating": 3.9972610800000004, "metadata": {"project": "jsweet", "class": "def.dom.MSBaseReader", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/MSBaseReader.java", "label_probabilities": {"readability": [0.99726, 0.00274036, 7.272e-17, 0.0], "understandability": [0.769791, 0.230209, 2.52692e-07, 0.0], "complexity": [0.0, 3.4e-19, 1.95389e-07, 1.0], "modularization": [0.0, 5.74298e-11, 0.127985, 0.872015], "overall": [0.814165, 0.185835, 1.25247e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MSFileSaver", "source": "package def.dom;\n@jsweet.lang.Interface\npublic abstract class MSFileSaver extends def.js.Object {\n    native public Boolean msSaveBlob(Object blob, String defaultName);\n    native public Boolean msSaveOrOpenBlob(Object blob, String defaultName);\n    native public Boolean msSaveBlob(Object blob);\n    native public Boolean msSaveOrOpenBlob(Object blob);\n}\n\n", "human_rating": 3.8908215685800616, "metadata": {"project": "jsweet", "class": "def.dom.MSFileSaver", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/MSFileSaver.java", "label_probabilities": {"readability": [0.890826, 0.109171, 2.28429e-06, 6.13053e-14], "understandability": [0.825915, 0.173218, 0.000867019, 9.57171e-12], "complexity": [1.48604e-06, 0.00245094, 0.108607, 0.888941], "modularization": [2.1878e-07, 0.000424501, 0.15506, 0.844516], "overall": [0.950442, 0.0495582, 2.2555e-07, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MSInputMethodContext", "source": "package def.dom;\npublic class MSInputMethodContext extends EventTarget {\n    public double compositionEndOffset;\n    public double compositionStartOffset;\n    public java.util.function.Function<Event,Object> oncandidatewindowhide;\n    public java.util.function.Function<Event,Object> oncandidatewindowshow;\n    public java.util.function.Function<Event,Object> oncandidatewindowupdate;\n    public HTMLElement target;\n    native public ClientRect getCandidateWindowClientRect();\n    native public String[] getCompositionAlternatives();\n    native public Boolean hasComposition();\n    native public Boolean isCandidateWindowVisible();\n    native public void addEventListener(jsweet.util.StringTypes.MSCandidateWindowHide type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSCandidateWindowShow type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSCandidateWindowUpdate type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListener listener, Boolean useCapture);\n    public static MSInputMethodContext prototype;\n    public MSInputMethodContext(){}\n    native public void addEventListener(jsweet.util.StringTypes.MSCandidateWindowHide type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSCandidateWindowShow type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSCandidateWindowUpdate type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(String type, EventListener listener);\n    native public void addEventListener(String type, EventListenerObject listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListenerObject listener);\n}\n\n", "human_rating": 3.2708058251, "metadata": {"project": "jsweet", "class": "def.dom.MSInputMethodContext", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/MSInputMethodContext.java", "label_probabilities": {"readability": [0.271862, 0.727103, 0.00101403, 2.07651e-05], "understandability": [0.968477, 0.0315224, 4.69583e-07, 1.31449e-13], "complexity": [2.5e-19, 1.88871e-07, 0.0258059, 0.974194], "modularization": [0.0, 4.84987e-11, 0.0203369, 0.979663], "overall": [0.941396, 0.0586041, 9.55033e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MSManipulationEvent", "source": "package def.dom;\npublic class MSManipulationEvent extends UIEvent {\n    public double currentState;\n    public double inertiaDestinationX;\n    public double inertiaDestinationY;\n    public double lastState;\n    native public void initMSManipulationEvent(String typeArg, Boolean canBubbleArg, Boolean cancelableArg, Window viewArg, double detailArg, double lastState, double currentState);\n    public double MS_MANIPULATION_STATE_ACTIVE;\n    public double MS_MANIPULATION_STATE_CANCELLED;\n    public double MS_MANIPULATION_STATE_COMMITTED;\n    public double MS_MANIPULATION_STATE_DRAGGING;\n    public double MS_MANIPULATION_STATE_INERTIA;\n    public double MS_MANIPULATION_STATE_PRESELECT;\n    public double MS_MANIPULATION_STATE_SELECTING;\n    public double MS_MANIPULATION_STATE_STOPPED;\n    public static MSManipulationEvent prototype;\n    public MSManipulationEvent(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.MSManipulationEvent", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/MSManipulationEvent.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MSMediaKeySession", "source": "package def.dom;\n\nimport def.js.Uint8Array;\n\npublic class MSMediaKeySession extends EventTarget {\n    public MSMediaKeyError error;\n    public java.lang.String keySystem;\n    public java.lang.String sessionId;\n    native public void close();\n    native public void update(Uint8Array key);\n    public static MSMediaKeySession prototype;\n    public MSMediaKeySession(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.MSMediaKeySession", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/MSMediaKeySession.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MSStreamReader", "source": "package def.dom;\n@jsweet.lang.Extends({MSBaseReader.class})\npublic class MSStreamReader extends EventTarget {\n    public DOMError error;\n    native public void readAsArrayBuffer(MSStream stream, double size);\n    native public void readAsBinaryString(MSStream stream, double size);\n    native public void readAsBlob(MSStream stream, double size);\n    native public void readAsDataURL(MSStream stream, double size);\n    native public void readAsText(MSStream stream, String encoding, double size);\n    public static MSStreamReader prototype;\n    public MSStreamReader(){}\n    public java.util.function.Function<Event,Object> onabort;\n    public java.util.function.Function<Event,Object> onerror;\n    public java.util.function.Function<Event,Object> onload;\n    public java.util.function.Function<ProgressEvent,Object> onloadend;\n    public java.util.function.Function<Event,Object> onloadstart;\n    public java.util.function.Function<ProgressEvent,Object> onprogress;\n    public double readyState;\n    public Object result;\n    native public void abort();\n    public double DONE;\n    public double EMPTY;\n    public double LOADING;\n    native public void addEventListener(jsweet.util.StringTypes.abort type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.error type, java.util.function.Function<ErrorEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadend type, java.util.function.Function<ProgressEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.loadstart type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.progress type, java.util.function.Function<ProgressEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListener listener, Boolean useCapture);\n    native public void readAsArrayBuffer(MSStream stream);\n    native public void readAsBinaryString(MSStream stream);\n    native public void readAsBlob(MSStream stream);\n    native public void readAsDataURL(MSStream stream);\n    native public void readAsText(MSStream stream, String encoding);\n    native public void readAsText(MSStream stream);\n    native public void addEventListener(String type, EventListener listener);\n    native public void addEventListener(jsweet.util.StringTypes.abort type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.error type, java.util.function.Function<ErrorEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadend type, java.util.function.Function<ProgressEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.loadstart type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.progress type, java.util.function.Function<ProgressEvent,Object> listener);\n    native public void addEventListener(String type, EventListenerObject listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListenerObject listener);\n}\n\n", "human_rating": 3.8707873388799996, "metadata": {"project": "jsweet", "class": "def.dom.MSStreamReader", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/MSStreamReader.java", "label_probabilities": {"readability": [0.870871, 0.129047, 8.0319e-05, 1.70088e-06], "understandability": [0.931635, 0.0683612, 3.47957e-06, 1.74392e-10], "complexity": [3.29649e-12, 3.50398e-06, 0.0360278, 0.963969], "modularization": [0.0, 2.63917e-10, 0.0263247, 0.973675], "overall": [0.988667, 0.0113334, 2.46646e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MSWebViewSettings", "source": "package def.dom;\npublic class MSWebViewSettings extends def.js.Object {\n    public Boolean isIndexedDBEnabled;\n    public Boolean isJavaScriptEnabled;\n    public static MSWebViewSettings prototype;\n    public MSWebViewSettings(){}\n}\n\n", "human_rating": 3.9000431234099997, "metadata": {"project": "jsweet", "class": "def.dom.MSWebViewSettings", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/MSWebViewSettings.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.MutationRecord", "source": "package def.dom;\n\nimport def.js.Object;\n\npublic class MutationRecord extends def.js.Object {\n    public NodeList addedNodes;\n    public java.lang.String attributeName;\n    public java.lang.String attributeNamespace;\n    public Node nextSibling;\n    public java.lang.String oldValue;\n    public Node previousSibling;\n    public NodeList removedNodes;\n    public Node target;\n    public java.lang.String type;\n    public static MutationRecord prototype;\n    public MutationRecord(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.MutationRecord", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/MutationRecord.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.NavigatorOnLine", "source": "package def.dom;\n\nimport def.js.Object;\n\n@jsweet.lang.Interface\npublic abstract class NavigatorOnLine extends def.js.Object {\n    public java.lang.Boolean onLine;\n}\n\n", "human_rating": 3.914887512491, "metadata": {"project": "jsweet", "class": "def.dom.NavigatorOnLine", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/NavigatorOnLine.java", "label_probabilities": {"readability": [0.915104, 0.0846805, 0.000214891, 2.30491e-07], "understandability": [0.845965, 0.153715, 0.000320836, 7.71632e-13], "complexity": [2.42755e-06, 0.00437358, 0.153036, 0.842588], "modularization": [1.6234e-16, 0.000301179, 0.0437053, 0.955994], "overall": [0.9788, 0.0212003, 9.94779e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.NodeList", "source": "package def.dom;\n\n@jsweet.lang.Interface\npublic abstract class NodeList {\n\tpublic int length;\n\n\tnative public Node item(int index);\n\n\tnative public Node $get(int index);\n\n\tpublic static NodeList prototype;\n}\n", "human_rating": 3.999771442, "metadata": {"project": "jsweet", "class": "def.dom.NodeList", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/NodeList.java", "label_probabilities": {"readability": [0.999772, 0.000227814, 5.2e-19, 0.0], "understandability": [0.982762, 0.0172384, 2.17138e-09, 0.0], "complexity": [0.0, 0.0, 1.30003e-07, 1.0], "modularization": [0.0, 2.41832e-13, 0.00696887, 0.993031], "overall": [0.995794, 0.00420588, 6.4084e-16, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.NodeSelector", "source": "package def.dom;\n@jsweet.lang.Interface\npublic abstract class NodeSelector extends def.js.Object {\n    native public Element querySelector(String selectors);\n    native public NodeListOf<Element> querySelectorAll(String selectors);\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.NodeSelector", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/NodeSelector.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.OES_standard_derivatives", "source": "package def.dom;\n\nimport def.js.Object;\n\npublic class OES_standard_derivatives extends def.js.Object {\n    public double FRAGMENT_SHADER_DERIVATIVE_HINT_OES;\n    public static OES_standard_derivatives prototype;\n    public OES_standard_derivatives(){}\n}\n\n", "human_rating": 3.9571827370002413, "metadata": {"project": "jsweet", "class": "def.dom.OES_standard_derivatives", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/OES_standard_derivatives.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.PointerEvent", "source": "package def.dom;\npublic class PointerEvent extends MouseEvent {\n    public Object currentPoint;\n    public double height;\n    public double hwTimestamp;\n    public Object intermediatePoints;\n    public Boolean isPrimary;\n    public double pointerId;\n    public Object pointerType;\n    public double pressure;\n    public double rotation;\n    public double tiltX;\n    public double tiltY;\n    public double width;\n    native public void getCurrentPoint(Element element);\n    native public void getIntermediatePoints(Element element);\n    native public void initPointerEvent(String typeArg, Boolean canBubbleArg, Boolean cancelableArg, Window viewArg, double detailArg, double screenXArg, double screenYArg, double clientXArg, double clientYArg, Boolean ctrlKeyArg, Boolean altKeyArg, Boolean shiftKeyArg, Boolean metaKeyArg, double buttonArg, EventTarget relatedTargetArg, double offsetXArg, double offsetYArg, double widthArg, double heightArg, double pressure, double rotation, double tiltX, double tiltY, double pointerIdArg, Object pointerType, double hwTimestampArg, Boolean isPrimary);\n    public static PointerEvent prototype;\n    public PointerEvent(String typeArg, PointerEventInit eventInitDict){}\n    public PointerEvent(String typeArg){}\n    protected PointerEvent(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.PointerEvent", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/PointerEvent.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.Selection", "source": "package def.dom;\npublic class Selection extends def.js.Object {\n    public Node anchorNode;\n    public double anchorOffset;\n    public Node focusNode;\n    public double focusOffset;\n    public Boolean isCollapsed;\n    public double rangeCount;\n    public String type;\n    native public void addRange(Range range);\n    native public void collapse(Node parentNode, double offset);\n    native public void collapseToEnd();\n    native public void collapseToStart();\n    native public Boolean containsNode(Node node, Boolean partlyContained);\n    native public void deleteFromDocument();\n    native public void empty();\n    native public void extend(Node newNode, double offset);\n    native public Range getRangeAt(double index);\n    native public void removeAllRanges();\n    native public void removeRange(Range range);\n    native public void selectAllChildren(Node parentNode);\n    native public void setBaseAndExtent(Node baseNode, double baseOffset, Node extentNode, double extentOffset);\n    native public String toString();\n    public static Selection prototype;\n    public Selection(){}\n}\n\n", "human_rating": 4.0, "metadata": {"project": "jsweet", "class": "def.dom.Selection", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/Selection.java", "label_probabilities": {"readability": [1.0, 0.0, 0.0, 0.0], "understandability": [0.0465805, 0.953419, 8.2885e-07, 0.0], "complexity": [0.0, 1.75576e-05, 0.0804699, 0.919513], "modularization": [0.0, 0.0, 7.61754e-07, 0.999999], "overall": [0.930096, 0.0699042, 1.92093e-13, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGAnimatedBoolean", "source": "package def.dom;\npublic class SVGAnimatedBoolean extends def.js.Object {\n    public Boolean animVal;\n    public Boolean baseVal;\n    public static SVGAnimatedBoolean prototype;\n    public SVGAnimatedBoolean(){}\n}\n\n", "human_rating": 3.4853730000012098, "metadata": {"project": "jsweet", "class": "def.dom.SVGAnimatedBoolean", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGAnimatedBoolean.java", "label_probabilities": {"readability": [0.485373, 0.514627, 6.04746e-13, 2.324e-17], "understandability": [8.2714e-05, 0.910884, 0.0890334, 5.48e-18], "complexity": [0.0, 0.0, 7.954e-06, 0.999992], "modularization": [0.0, 2.1029e-16, 3.97137e-07, 1.0], "overall": [0.998245, 0.00175512, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGAnimatedString", "source": "package def.dom;\npublic class SVGAnimatedString extends def.js.Object {\n    public String animVal;\n    public String baseVal;\n    public static SVGAnimatedString prototype;\n    public SVGAnimatedString(){}\n}\n\n", "human_rating": 3.9000431234099997, "metadata": {"project": "jsweet", "class": "def.dom.SVGAnimatedString", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGAnimatedString.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGElementInstance", "source": "package def.dom;\n\npublic class SVGElementInstance extends EventTarget {\n    public SVGElementInstanceList childNodes;\n    public SVGElement correspondingElement;\n    public SVGUseElement correspondingUseElement;\n    public SVGElementInstance firstChild;\n    public SVGElementInstance lastChild;\n    public SVGElementInstance nextSibling;\n    public SVGElementInstance parentNode;\n    public SVGElementInstance previousSibling;\n    public static SVGElementInstance prototype;\n    public SVGElementInstance(){}\n}\n\n", "human_rating": 3.9571827370002413, "metadata": {"project": "jsweet", "class": "def.dom.SVGElementInstance", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/SVGElementInstance.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGFEColorMatrixElement", "source": "package def.dom;\n@jsweet.lang.Extends({SVGFilterPrimitiveStandardAttributes.class})\npublic class SVGFEColorMatrixElement extends SVGElement {\n    public SVGAnimatedString in1;\n    public SVGAnimatedEnumeration type;\n    public SVGAnimatedNumberList values;\n    public double SVG_FECOLORMATRIX_TYPE_HUEROTATE;\n    public double SVG_FECOLORMATRIX_TYPE_LUMINANCETOALPHA;\n    public double SVG_FECOLORMATRIX_TYPE_MATRIX;\n    public double SVG_FECOLORMATRIX_TYPE_SATURATE;\n    public double SVG_FECOLORMATRIX_TYPE_UNKNOWN;\n    native public void addEventListener(String type, EventListener listener, Boolean useCapture);\n    public static SVGFEColorMatrixElement prototype;\n    public SVGFEColorMatrixElement(){}\n    public SVGAnimatedLength height;\n    public SVGAnimatedString result;\n    public SVGAnimatedLength width;\n    public SVGAnimatedLength x;\n    public SVGAnimatedLength y;\n    native public void addEventListener(String type, EventListener listener);\n    native public void addEventListener(String type, EventListenerObject listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListenerObject listener);\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.SVGFEColorMatrixElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGFEColorMatrixElement.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGFEFuncBElement", "source": "package def.dom;\npublic class SVGFEFuncBElement extends SVGComponentTransferFunctionElement {\n    public static SVGFEFuncBElement prototype;\n    public SVGFEFuncBElement(){}\n}\n\n", "human_rating": 3.9684204944362738, "metadata": {"project": "jsweet", "class": "def.dom.SVGFEFuncBElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGFEFuncBElement.java", "label_probabilities": {"readability": [0.968421, 0.0315788, 4.7218e-08, 2.73951e-13], "understandability": [0.964244, 0.0357549, 8.31796e-07, 1.83488e-12], "complexity": [0.0, 6.52016e-14, 0.00844262, 0.991557], "modularization": [0.0, 6.59152e-11, 0.0412797, 0.95872], "overall": [0.99052, 0.00947958, 1.13886e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGFEMergeElement", "source": "package def.dom;\n@jsweet.lang.Extends({SVGFilterPrimitiveStandardAttributes.class})\npublic class SVGFEMergeElement extends SVGElement {\n    native public void addEventListener(String type, EventListener listener, Boolean useCapture);\n    public static SVGFEMergeElement prototype;\n    public SVGFEMergeElement(){}\n    public SVGAnimatedLength height;\n    public SVGAnimatedString result;\n    public SVGAnimatedLength width;\n    public SVGAnimatedLength x;\n    public SVGAnimatedLength y;\n    native public void addEventListener(String type, EventListener listener);\n    native public void addEventListener(String type, EventListenerObject listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListenerObject listener);\n}\n\n", "human_rating": 1.9327868004118278, "metadata": {"project": "jsweet", "class": "def.dom.SVGFEMergeElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGFEMergeElement.java", "label_probabilities": {"readability": [1.02957e-10, 0.0210714, 0.890644, 0.0882846], "understandability": [3.2426e-06, 0.353263, 0.641107, 0.00562637], "complexity": [1.76435e-12, 6.68895e-05, 0.163979, 0.835954], "modularization": [0.0, 8.11247e-05, 0.00379842, 0.99612], "overall": [0.771182, 0.228818, 4.19827e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGMaskElement", "source": "package def.dom;\n@jsweet.lang.Extends({SVGStylable.class,SVGTests.class,SVGLangSpace.class,SVGExternalResourcesRequired.class,SVGUnitTypes.class})\npublic class SVGMaskElement extends SVGElement {\n    public SVGAnimatedLength height;\n    public SVGAnimatedEnumeration maskContentUnits;\n    public SVGAnimatedEnumeration maskUnits;\n    public SVGAnimatedLength width;\n    public SVGAnimatedLength x;\n    public SVGAnimatedLength y;\n    native public void addEventListener(String type, EventListener listener, Boolean useCapture);\n    public static SVGMaskElement prototype;\n    public SVGMaskElement(){}\n    public Object className;\n    public CSSStyleDeclaration style;\n    public SVGStringList requiredExtensions;\n    public SVGStringList requiredFeatures;\n    public SVGStringList systemLanguage;\n    native public Boolean hasExtension(String extension);\n    public String xmllang;\n    public String xmlspace;\n    public SVGAnimatedBoolean externalResourcesRequired;\n    public static double SVG_UNIT_TYPE_OBJECTBOUNDINGBOX;\n    public static double SVG_UNIT_TYPE_UNKNOWN;\n    public static double SVG_UNIT_TYPE_USERSPACEONUSE;\n    native public void addEventListener(String type, EventListener listener);\n    native public void addEventListener(String type, EventListenerObject listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListenerObject listener);\n}\n\n", "human_rating": 3.8707873388799996, "metadata": {"project": "jsweet", "class": "def.dom.SVGMaskElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGMaskElement.java", "label_probabilities": {"readability": [0.870871, 0.129047, 8.0319e-05, 1.70088e-06], "understandability": [0.931635, 0.0683612, 3.47957e-06, 1.74392e-10], "complexity": [3.29649e-12, 3.50398e-06, 0.0360278, 0.963969], "modularization": [0.0, 2.63917e-10, 0.0263247, 0.973675], "overall": [0.988667, 0.0113334, 2.46646e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGPathSegMovetoRel", "source": "package def.dom;\npublic class SVGPathSegMovetoRel extends SVGPathSeg {\n    public double x;\n    public double y;\n    public static SVGPathSegMovetoRel prototype;\n    public SVGPathSegMovetoRel(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.SVGPathSegMovetoRel", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/SVGPathSegMovetoRel.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGStringList", "source": "package def.dom;\npublic class SVGStringList extends def.js.Object {\n    public double numberOfItems;\n    native public String appendItem(String newItem);\n    native public void clear();\n    native public String getItem(double index);\n    native public String initialize(String newItem);\n    native public String insertItemBefore(String newItem, double index);\n    native public String removeItem(double index);\n    native public String replaceItem(String newItem, double index);\n    public static SVGStringList prototype;\n    public SVGStringList(){}\n}\n\n", "human_rating": 3.94698447464706, "metadata": {"project": "jsweet", "class": "def.dom.SVGStringList", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGStringList.java", "label_probabilities": {"readability": [0.947515, 0.0519537, 0.000531683, 8.64706e-09], "understandability": [0.999307, 0.000689334, 3.39549e-06, 3.69179e-07], "complexity": [0.0, 0.0, 7.45918e-08, 1.0], "modularization": [0.0, 2.0248e-13, 0.100472, 0.899528], "overall": [0.965083, 0.0349167, 2.01465e-14, 7.4247e-16]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGSVGElement", "source": "package def.dom;\n@jsweet.lang.Extends({DocumentEvent.class,SVGLocatable.class,SVGTests.class,SVGStylable.class,SVGLangSpace.class,SVGExternalResourcesRequired.class,SVGFitToViewBox.class,SVGZoomAndPan.class})\npublic class SVGSVGElement extends SVGElement {\n    public String contentScriptType;\n    public String contentStyleType;\n    public double currentScale;\n    public SVGPoint currentTranslate;\n    public SVGAnimatedLength height;\n    public java.util.function.Function<Event,Object> onabort;\n    public java.util.function.Function<Event,Object> onerror;\n    public java.util.function.Function<UIEvent,Object> onresize;\n    public java.util.function.Function<UIEvent,Object> onscroll;\n    public java.util.function.Function<Event,Object> onunload;\n    public java.util.function.Function<SVGZoomEvent,Object> onzoom;\n    public double pixelUnitToMillimeterX;\n    public double pixelUnitToMillimeterY;\n    public double screenPixelToMillimeterX;\n    public double screenPixelToMillimeterY;\n    public SVGRect viewport;\n    public SVGAnimatedLength width;\n    public SVGAnimatedLength x;\n    public SVGAnimatedLength y;\n    native public Boolean checkEnclosure(SVGElement element, SVGRect rect);\n    native public Boolean checkIntersection(SVGElement element, SVGRect rect);\n    native public SVGAngle createSVGAngle();\n    native public SVGLength createSVGLength();\n    native public SVGMatrix createSVGMatrix();\n    native public SVGNumber createSVGNumber();\n    native public SVGPoint createSVGPoint();\n    native public SVGRect createSVGRect();\n    native public SVGTransform createSVGTransform();\n    native public SVGTransform createSVGTransformFromMatrix(SVGMatrix matrix);\n    native public void deselectAll();\n    native public void forceRedraw();\n    native public CSSStyleDeclaration getComputedStyle(Element elt, String pseudoElt);\n    native public double getCurrentTime();\n    native public Element getElementById(String elementId);\n    native public NodeList getEnclosureList(SVGRect rect, SVGElement referenceElement);\n    native public NodeList getIntersectionList(SVGRect rect, SVGElement referenceElement);\n    native public void pauseAnimations();\n    native public void setCurrentTime(double seconds);\n    native public double suspendRedraw(double maxWaitMilliseconds);\n    native public void unpauseAnimations();\n    native public void unsuspendRedraw(double suspendHandleID);\n    native public void unsuspendRedrawAll();\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureChange type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureDoubleTap type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureEnd type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureHold type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureStart type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureTap type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSGotPointerCapture type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSInertiaStart type, java.util.function.Function<MSGestureEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSLostPointerCapture type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerCancel type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerDown type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerEnter type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerLeave type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerMove type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOut type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOver type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerUp type, java.util.function.Function<MSPointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.SVGAbort type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.SVGError type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.SVGUnload type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.SVGZoom type, java.util.function.Function<SVGZoomEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.ariarequest type, java.util.function.Function<AriaRequestEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.click type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.command type, java.util.function.Function<CommandEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.dblclick type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.focusin type, java.util.function.Function<FocusEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.focusout type, java.util.function.Function<FocusEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.gotpointercapture type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.lostpointercapture type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mousedown type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mousemove type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseout type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseover type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.mouseup type, java.util.function.Function<MouseEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointercancel type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerdown type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerenter type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerleave type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointermove type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerout type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerover type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.pointerup type, java.util.function.Function<PointerEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.resize type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.scroll type, java.util.function.Function<UIEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchcancel type, java.util.function.Function<TouchEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchend type, java.util.function.Function<TouchEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchmove type, java.util.function.Function<TouchEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.touchstart type, java.util.function.Function<TouchEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenchange type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenerror type, java.util.function.Function<Event,Object> listener, Boolean useCapture);\n    native public void addEventListener(jsweet.util.StringTypes.wheel type, java.util.function.Function<WheelEvent,Object> listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListener listener, Boolean useCapture);\n    public static SVGSVGElement prototype;\n    public SVGSVGElement(){}\n    native public AnimationEvent createEvent(jsweet.util.StringTypes.AnimationEvent eventInterface);\n    native public AriaRequestEvent createEvent(jsweet.util.StringTypes.AriaRequestEvent eventInterface);\n    native public AudioProcessingEvent createEvent(jsweet.util.StringTypes.AudioProcessingEvent eventInterface);\n    native public BeforeUnloadEvent createEvent(jsweet.util.StringTypes.BeforeUnloadEvent eventInterface);\n    native public ClipboardEvent createEvent(jsweet.util.StringTypes.ClipboardEvent eventInterface);\n    native public CloseEvent createEvent(jsweet.util.StringTypes.CloseEvent eventInterface);\n    native public CommandEvent createEvent(jsweet.util.StringTypes.CommandEvent eventInterface);\n    native public CompositionEvent createEvent(jsweet.util.StringTypes.CompositionEvent eventInterface);\n    native public CustomEvent createEvent(jsweet.util.StringTypes.CustomEvent eventInterface);\n    native public DeviceMotionEvent createEvent(jsweet.util.StringTypes.DeviceMotionEvent eventInterface);\n    native public DeviceOrientationEvent createEvent(jsweet.util.StringTypes.DeviceOrientationEvent eventInterface);\n    native public DragEvent createEvent(jsweet.util.StringTypes.DragEvent eventInterface);\n    native public ErrorEvent createEvent(jsweet.util.StringTypes.ErrorEvent eventInterface);\n    native public Event createEvent(jsweet.util.StringTypes.Event eventInterface);\n    native public Event createEvent(jsweet.util.StringTypes.Events eventInterface);\n    native public FocusEvent createEvent(jsweet.util.StringTypes.FocusEvent eventInterface);\n    native public GamepadEvent createEvent(jsweet.util.StringTypes.GamepadEvent eventInterface);\n    native public HashChangeEvent createEvent(jsweet.util.StringTypes.HashChangeEvent eventInterface);\n    native public IDBVersionChangeEvent createEvent(jsweet.util.StringTypes.IDBVersionChangeEvent eventInterface);\n    native public KeyboardEvent createEvent(jsweet.util.StringTypes.KeyboardEvent eventInterface);\n    native public LongRunningScriptDetectedEvent createEvent(jsweet.util.StringTypes.LongRunningScriptDetectedEvent eventInterface);\n    native public MSGestureEvent createEvent(jsweet.util.StringTypes.MSGestureEvent eventInterface);\n    native public MSManipulationEvent createEvent(jsweet.util.StringTypes.MSManipulationEvent eventInterface);\n    native public MSMediaKeyMessageEvent createEvent(jsweet.util.StringTypes.MSMediaKeyMessageEvent eventInterface);\n    native public MSMediaKeyNeededEvent createEvent(jsweet.util.StringTypes.MSMediaKeyNeededEvent eventInterface);\n    native public MSPointerEvent createEvent(jsweet.util.StringTypes.MSPointerEvent eventInterface);\n    native public MSSiteModeEvent createEvent(jsweet.util.StringTypes.MSSiteModeEvent eventInterface);\n    native public MessageEvent createEvent(jsweet.util.StringTypes.MessageEvent eventInterface);\n    native public MouseEvent createEvent(jsweet.util.StringTypes.MouseEvent eventInterface);\n    native public MouseEvent createEvent(jsweet.util.StringTypes.MouseEvents eventInterface);\n    native public MouseWheelEvent createEvent(jsweet.util.StringTypes.MouseWheelEvent eventInterface);\n    native public MutationEvent createEvent(jsweet.util.StringTypes.MutationEvent eventInterface);\n    native public MutationEvent createEvent(jsweet.util.StringTypes.MutationEvents eventInterface);\n    native public NavigationCompletedEvent createEvent(jsweet.util.StringTypes.NavigationCompletedEvent eventInterface);\n    native public NavigationEvent createEvent(jsweet.util.StringTypes.NavigationEvent eventInterface);\n    native public NavigationEventWithReferrer createEvent(jsweet.util.StringTypes.NavigationEventWithReferrer eventInterface);\n    native public OfflineAudioCompletionEvent createEvent(jsweet.util.StringTypes.OfflineAudioCompletionEvent eventInterface);\n    native public PageTransitionEvent createEvent(jsweet.util.StringTypes.PageTransitionEvent eventInterface);\n    native public PermissionRequestedEvent createEvent(jsweet.util.StringTypes.PermissionRequestedEvent eventInterface);\n    native public PointerEvent createEvent(jsweet.util.StringTypes.PointerEvent eventInterface);\n    native public PopStateEvent createEvent(jsweet.util.StringTypes.PopStateEvent eventInterface);\n    native public ProgressEvent createEvent(jsweet.util.StringTypes.ProgressEvent eventInterface);\n    native public SVGZoomEvent createEvent(jsweet.util.StringTypes.SVGZoomEvent eventInterface);\n    native public SVGZoomEvent createEvent(jsweet.util.StringTypes.SVGZoomEvents eventInterface);\n    native public ScriptNotifyEvent createEvent(jsweet.util.StringTypes.ScriptNotifyEvent eventInterface);\n    native public StorageEvent createEvent(jsweet.util.StringTypes.StorageEvent eventInterface);\n    native public TextEvent createEvent(jsweet.util.StringTypes.TextEvent eventInterface);\n    native public TouchEvent createEvent(jsweet.util.StringTypes.TouchEvent eventInterface);\n    native public TrackEvent createEvent(jsweet.util.StringTypes.TrackEvent eventInterface);\n    native public TransitionEvent createEvent(jsweet.util.StringTypes.TransitionEvent eventInterface);\n    native public UIEvent createEvent(jsweet.util.StringTypes.UIEvent eventInterface);\n    native public UIEvent createEvent(jsweet.util.StringTypes.UIEvents eventInterface);\n    native public UnviewableContentIdentifiedEvent createEvent(jsweet.util.StringTypes.UnviewableContentIdentifiedEvent eventInterface);\n    native public WebGLContextEvent createEvent(jsweet.util.StringTypes.WebGLContextEvent eventInterface);\n    native public WheelEvent createEvent(jsweet.util.StringTypes.WheelEvent eventInterface);\n    native public Event createEvent(String eventInterface);\n    public SVGElement farthestViewportElement;\n    public SVGElement nearestViewportElement;\n    native public SVGRect getBBox();\n    native public SVGMatrix getCTM();\n    native public SVGMatrix getScreenCTM();\n    native public SVGMatrix getTransformToElement(SVGElement element);\n    public SVGStringList requiredExtensions;\n    public SVGStringList requiredFeatures;\n    public SVGStringList systemLanguage;\n    native public Boolean hasExtension(String extension);\n    public Object className;\n    public CSSStyleDeclaration style;\n    public String xmllang;\n    public String xmlspace;\n    public SVGAnimatedBoolean externalResourcesRequired;\n    public SVGAnimatedPreserveAspectRatio preserveAspectRatio;\n    public SVGAnimatedRect viewBox;\n    public double zoomAndPan;\n    public static double SVG_ZOOMANDPAN_DISABLE;\n    public static double SVG_ZOOMANDPAN_MAGNIFY;\n    public static double SVG_ZOOMANDPAN_UNKNOWN;\n    native public CSSStyleDeclaration getComputedStyle(Element elt);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureChange type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureDoubleTap type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureEnd type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureHold type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureStart type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGestureTap type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSGotPointerCapture type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSInertiaStart type, java.util.function.Function<MSGestureEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSLostPointerCapture type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerCancel type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerDown type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerEnter type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerLeave type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerMove type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOut type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerOver type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.MSPointerUp type, java.util.function.Function<MSPointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.SVGAbort type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.SVGError type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.SVGUnload type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.SVGZoom type, java.util.function.Function<SVGZoomEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.ariarequest type, java.util.function.Function<AriaRequestEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.click type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.command type, java.util.function.Function<CommandEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.dblclick type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.focusin type, java.util.function.Function<FocusEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.focusout type, java.util.function.Function<FocusEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.gotpointercapture type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.load type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.lostpointercapture type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mousedown type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mousemove type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseout type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseover type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.mouseup type, java.util.function.Function<MouseEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointercancel type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerdown type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerenter type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerleave type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointermove type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerout type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerover type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.pointerup type, java.util.function.Function<PointerEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.resize type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.scroll type, java.util.function.Function<UIEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchcancel type, java.util.function.Function<TouchEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchend type, java.util.function.Function<TouchEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchmove type, java.util.function.Function<TouchEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.touchstart type, java.util.function.Function<TouchEvent,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenchange type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.webkitfullscreenerror type, java.util.function.Function<Event,Object> listener);\n    native public void addEventListener(jsweet.util.StringTypes.wheel type, java.util.function.Function<WheelEvent,Object> listener);\n    native public void addEventListener(String type, EventListener listener);\n    native public void addEventListener(String type, EventListenerObject listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListenerObject listener);\n}\n\n", "human_rating": 2.997457043, "metadata": {"project": "jsweet", "class": "def.dom.SVGSVGElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGSVGElement.java", "label_probabilities": {"readability": [0.000161469, 0.997269, 0.00243421, 0.000135747], "understandability": [0.994906, 0.00509389, 3e-20, 0.0], "complexity": [2.28519e-12, 1.79312e-05, 0.0521229, 0.947859], "modularization": [8.25353e-14, 0.0308204, 0.969137, 4.26536e-05], "overall": [7.87246e-07, 0.999999, 4.05606e-08, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.SVGTextPathElement", "source": "package def.dom;\n@jsweet.lang.Extends({SVGURIReference.class})\npublic class SVGTextPathElement extends SVGTextContentElement {\n    public SVGAnimatedEnumeration method;\n    public SVGAnimatedEnumeration spacing;\n    public SVGAnimatedLength startOffset;\n    public double TEXTPATH_METHODTYPE_ALIGN;\n    public double TEXTPATH_METHODTYPE_STRETCH;\n    public double TEXTPATH_METHODTYPE_UNKNOWN;\n    public double TEXTPATH_SPACINGTYPE_AUTO;\n    public double TEXTPATH_SPACINGTYPE_EXACT;\n    public double TEXTPATH_SPACINGTYPE_UNKNOWN;\n    native public void addEventListener(String type, EventListener listener, Boolean useCapture);\n    public static SVGTextPathElement prototype;\n    public SVGTextPathElement(){}\n    public SVGAnimatedString href;\n    native public void addEventListener(String type, EventListener listener);\n    native public void addEventListener(String type, EventListenerObject listener, Boolean useCapture);\n    native public void addEventListener(String type, EventListenerObject listener);\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.SVGTextPathElement", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/SVGTextPathElement.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.TextEvent", "source": "package def.dom;\npublic class TextEvent extends UIEvent {\n    public String data;\n    public double inputMethod;\n    public String locale;\n    native public void initTextEvent(String typeArg, Boolean canBubbleArg, Boolean cancelableArg, Window viewArg, String dataArg, double inputMethod, String locale);\n    public double DOM_INPUT_METHOD_DROP;\n    public double DOM_INPUT_METHOD_HANDWRITING;\n    public double DOM_INPUT_METHOD_IME;\n    public double DOM_INPUT_METHOD_KEYBOARD;\n    public double DOM_INPUT_METHOD_MULTIMODAL;\n    public double DOM_INPUT_METHOD_OPTION;\n    public double DOM_INPUT_METHOD_PASTE;\n    public double DOM_INPUT_METHOD_SCRIPT;\n    public double DOM_INPUT_METHOD_UNKNOWN;\n    public double DOM_INPUT_METHOD_VOICE;\n    public static TextEvent prototype;\n    public TextEvent(){}\n}\n\n", "human_rating": 3.9678160391699997, "metadata": {"project": "jsweet", "class": "def.dom.TextEvent", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/TextEvent.java", "label_probabilities": {"readability": [0.967815, 0.0321851, 3.69585e-07, 3.22e-17], "understandability": [0.968864, 0.0311358, 3.51835e-07, 2.27174e-15], "complexity": [1.02515e-15, 6.754e-06, 0.0614659, 0.938527], "modularization": [0.0, 4.96842e-10, 0.0753064, 0.924694], "overall": [0.98976, 0.0102397, 1.642e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.WebGLObject", "source": "package def.dom;\n\nimport def.js.Object;\n\npublic class WebGLObject extends def.js.Object {\n    public static WebGLObject prototype;\n    public WebGLObject(){}\n}\n\n", "human_rating": 3.953471301100384, "metadata": {"project": "jsweet", "class": "def.dom.WebGLObject", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/WebGLObject.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.WebGLTexture", "source": "package def.dom;\npublic class WebGLTexture extends WebGLObject {\n    public static WebGLTexture prototype;\n    public WebGLTexture(){}\n}\n\n", "human_rating": 3.92120987271, "metadata": {"project": "jsweet", "class": "def.dom.WebGLTexture", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/dom/WebGLTexture.java", "label_probabilities": {"readability": [0.921261, 0.0786921, 4.29238e-05, 3.72511e-06], "understandability": [0.87406, 0.125931, 8.31417e-06, 7.75585e-08], "complexity": [3.10321e-09, 7.58485e-05, 0.0407163, 0.959208], "modularization": [0.0, 1.88939e-09, 0.084304, 0.915696], "overall": [0.982984, 0.0170157, 1.12775e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.WindowSessionStorage", "source": "package def.dom;\n@jsweet.lang.Interface\npublic abstract class WindowSessionStorage extends def.js.Object {\n    public Storage sessionStorage;\n}\n\n", "human_rating": 3.9571827370002413, "metadata": {"project": "jsweet", "class": "def.dom.WindowSessionStorage", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/WindowSessionStorage.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.dom.XPathEvaluator", "source": "package def.dom;\npublic class XPathEvaluator extends def.js.Object {\n    native public XPathExpression createExpression(String expression, XPathNSResolver resolver);\n    native public XPathNSResolver createNSResolver(Node nodeResolver);\n    native public XPathResult evaluate(String expression, Node contextNode, XPathNSResolver resolver, double type, XPathResult result);\n    public static XPathEvaluator prototype;\n    public XPathEvaluator(){}\n    native public XPathNSResolver createNSResolver();\n}\n\n", "human_rating": 3.927985835881085, "metadata": {"project": "jsweet", "class": "def.dom.XPathEvaluator", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/dom/XPathEvaluator.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.js.Float64Array", "source": "package def.js;\nimport jsweet.util.function.Function4;\n/**\n  * A typed array of 64-bit float values. The contents are initialized to 0. If the requested \n  * number of bytes could not be allocated an exception is raised.\n  */\n@jsweet.lang.SyntacticIterable\npublic class Float64Array extends Iterable<java.lang.Double> {\n    /**\n      * The size in bytes of each element in the array. \n      */\n    public int BYTES_PER_ELEMENT;\n    /**\n      * The ArrayBuffer instance referenced by the array. \n      */\n    public ArrayBuffer buffer;\n    /**\n      * The length in bytes of the array.\n      */\n    public int byteLength;\n    /**\n      * The offset in bytes of the array.\n      */\n    public int byteOffset;\n    /** \n      * Returns the this object after copying a section of the array identified by start and end\n      * to the same array starting at position target\n      * @param target If target is negative, it is treated as length+target where length is the \n      * length of the array. \n      * @param start If start is negative, it is treated as length+start. If end is negative, it \n      * is treated as length+end.\n      * @param end If not specified, length of the this object is used as its default value. \n      */\n    native public Float64Array copyWithin(double target, int start, int end);\n    /** \n      * Returns an array of key, value pairs for every entry in the array\n      */\n    native public IterableIterator<jsweet.util.tuple.Tuple2<Double,Double>> entries();\n    /**\n      * Determines whether all the members of an array satisfy the specified test.\n      * @param callbackfn A function that accepts up to three arguments. The every method calls \n      * the callbackfn function for each element in array1 until the callbackfn returns false, \n      * or until the end of the array.\n      * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public java.lang.Boolean every(jsweet.util.function.TriFunction<Double,Double,Float64Array,java.lang.Boolean> callbackfn, java.lang.Object thisArg);\n    /**\n        * Returns the this object after filling the section identified by start and end with value\n        * @param value value to fill array section with\n        * @param start index to start filling the array at. If start is negative, it is treated as \n        * length+start where length is the length of the array. \n        * @param end index to stop filling the array at. If end is negative, it is treated as \n        * length+end.\n        */\n    native public Float64Array fill(double value, int start, int end);\n    /**\n      * Returns the elements of an array that meet the condition specified in a callback function. \n      * @param callbackfn A function that accepts up to three arguments. The filter method calls \n      * the callbackfn function one time for each element in the array. \n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public Float64Array filter(jsweet.util.function.TriFunction<Double,Double,Float64Array,java.lang.Boolean> callbackfn, java.lang.Object thisArg);\n    /** \n      * Returns the value of the first element in the array where predicate is true, and undefined \n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending \n      * order, until it finds one where predicate returns true. If such an element is found, find \n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of \n      * predicate. If it is not provided, undefined is used instead.\n      */\n    native public double find(jsweet.util.function.TriFunction<Double,Double,Array<Double>,java.lang.Boolean> predicate, java.lang.Object thisArg);\n    /** \n      * Returns the index of the first element in the array where predicate is true, and undefined \n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending \n      * order, until it finds one where predicate returns true. If such an element is found, find \n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of \n      * predicate. If it is not provided, undefined is used instead.\n      */\n    native public double findIndex(java.util.function.Function<Double,java.lang.Boolean> predicate, java.lang.Object thisArg);\n    /**\n      * Performs the specified action for each element in an array.\n      * @param callbackfn  A function that accepts up to three arguments. forEach calls the \n      * callbackfn function one time for each element in the array. \n      * @param thisArg  An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public void forEach(jsweet.util.function.TriConsumer<Double,Double,Float64Array> callbackfn, java.lang.Object thisArg);\n    /**\n      * Returns the index of the first occurrence of a value in an array.\n      * @param searchElement The value to locate in the array.\n      * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n      *  search starts at index 0.\n      */\n    native public double indexOf(double searchElement, int fromIndex);\n    /**\n      * Adds all the elements of an array separated by the specified separator string.\n      * @param separator A string used to separate one element of an array from the next in the \n      * resulting String. If omitted, the array elements are separated with a comma.\n      */\n    native public java.lang.String join(java.lang.String separator);\n    /** \n      * Returns an list of keys in the array\n      */\n    native public IterableIterator<Double> keys();\n    /**\n      * Returns the index of the last occurrence of a value in an array.\n      * @param searchElement The value to locate in the array.\n      * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the \n      * search starts at index 0.\n      */\n    native public double lastIndexOf(double searchElement, int fromIndex);\n    /**\n      * The length of the array.\n      */\n    public int length;\n    /**\n      * Calls a defined callback function on each element of an array, and returns an array that \n      * contains the results.\n      * @param callbackfn A function that accepts up to three arguments. The map method calls the \n      * callbackfn function one time for each element in the array. \n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public Float64Array map(jsweet.util.function.TriFunction<Double,Double,Float64Array,Double> callbackfn, java.lang.Object thisArg);\n    /**\n      * Calls the specified callback function for all the elements in an array. The return value of \n      * the callback function is the accumulated result, and is provided as an argument in the next \n      * call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduce method calls the \n      * callbackfn function one time for each element in the array.\n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an argument\n      * instead of an array value.\n      */\n    native public double reduce(Function4<Double,Double,Double,Float64Array,Double> callbackfn, double initialValue);\n    /**\n      * Calls the specified callback function for all the elements in an array. The return value of \n      * the callback function is the accumulated result, and is provided as an argument in the next \n      * call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduce method calls the \n      * callbackfn function one time for each element in the array.\n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an argument \n      * instead of an array value.\n      */\n    native public <U> U reduce(Function4<U,Double,Double,Float64Array,U> callbackfn, U initialValue);\n    /** \n      * Calls the specified callback function for all the elements in an array, in descending order. \n      * The return value of the callback function is the accumulated result, and is provided as an \n      * argument in the next call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls \n      * the callbackfn function one time for each element in the array. \n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an \n      * argument instead of an array value.\n      */\n    native public double reduceRight(Function4<Double,Double,Double,Float64Array,Double> callbackfn, double initialValue);\n    /** \n      * Calls the specified callback function for all the elements in an array, in descending order. \n      * The return value of the callback function is the accumulated result, and is provided as an \n      * argument in the next call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n      * the callbackfn function one time for each element in the array. \n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an argument\n      * instead of an array value.\n      */\n    native public <U> U reduceRight(Function4<U,Double,Double,Float64Array,U> callbackfn, U initialValue);\n    /**\n      * Reverses the elements in an Array. \n      */\n    native public Float64Array reverse();\n    /**\n      * Sets a value or an array of values.\n      * @param index The index of the location to set.\n      * @param value The value to set.\n      */\n    native public void set(int index, double value);\n    /**\n      * Sets a value or an array of values.\n      * @param array A typed or untyped array of values to set.\n      * @param offset The index in the current array at which the values are to be written.\n      */\n    native public void set(Float64Array array, int offset);\n    /** \n      * Returns a section of an array.\n      * @param start The beginning of the specified portion of the array.\n      * @param end The end of the specified portion of the array.\n      */\n    native public Float64Array slice(double start, int end);\n    /**\n      * Determines whether the specified callback function returns true for any element of an array.\n      * @param callbackfn A function that accepts up to three arguments. The some method calls the \n      * callbackfn function for each element in array1 until the callbackfn returns true, or until \n      * the end of the array.\n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public java.lang.Boolean some(jsweet.util.function.TriFunction<Double,Double,Float64Array,java.lang.Boolean> callbackfn, java.lang.Object thisArg);\n    /**\n      * Sorts an array.\n      * @param compareFn The name of the function used to determine the order of the elements. If \n      * omitted, the elements are sorted in ascending, ASCII character order.\n      */\n    native public Float64Array sort(java.util.function.BiFunction<Double,Double,Double> compareFn);\n    /**\n      * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements\n      * at begin, inclusive, up to end, exclusive. \n      * @param begin The index of the beginning of the array.\n      * @param end The index of the end of the array.\n      */\n    native public Float64Array subarray(int begin, int end);\n    /** \n      * Returns an list of values in the array\n      */\n    native public IterableIterator<Double> values();\n    native public java.lang.Double $get(int index);\n    native public void $set(int index, java.lang.Double value);\n    public static Float64Array prototype;\n    public Float64Array(int length){}\n    public Float64Array(Float64Array array){}\n    public Float64Array(double[] array){}\n    public Float64Array(ArrayBuffer buffer, int byteOffset, int length){}\n    /**\n      * Returns a new array from a set of elements.\n      * @param items A set of elements to include in the new array object.\n      */\n    native public static Float64Array of(double... items);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(ArrayLike<Double> arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn, java.lang.Object thisArg);\n    /** \n      * Returns the this object after copying a section of the array identified by start and end\n      * to the same array starting at position target\n      * @param target If target is negative, it is treated as length+target where length is the \n      * length of the array. \n      * @param start If start is negative, it is treated as length+start. If end is negative, it \n      * is treated as length+end.\n      * @param end If not specified, length of the this object is used as its default value. \n      */\n    native public Float64Array copyWithin(double target, int start);\n    /**\n      * Determines whether all the members of an array satisfy the specified test.\n      * @param callbackfn A function that accepts up to three arguments. The every method calls \n      * the callbackfn function for each element in array1 until the callbackfn returns false, \n      * or until the end of the array.\n      * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public java.lang.Boolean every(jsweet.util.function.TriFunction<Double,Double,Float64Array,java.lang.Boolean> callbackfn);\n    /**\n        * Returns the this object after filling the section identified by start and end with value\n        * @param value value to fill array section with\n        * @param start index to start filling the array at. If start is negative, it is treated as \n        * length+start where length is the length of the array. \n        * @param end index to stop filling the array at. If end is negative, it is treated as \n        * length+end.\n        */\n    native public Float64Array fill(double value, int start);\n    /**\n        * Returns the this object after filling the section identified by start and end with value\n        * @param value value to fill array section with\n        * @param start index to start filling the array at. If start is negative, it is treated as \n        * length+start where length is the length of the array. \n        * @param end index to stop filling the array at. If end is negative, it is treated as \n        * length+end.\n        */\n    native public Float64Array fill(double value);\n    /**\n      * Returns the elements of an array that meet the condition specified in a callback function. \n      * @param callbackfn A function that accepts up to three arguments. The filter method calls \n      * the callbackfn function one time for each element in the array. \n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public Float64Array filter(jsweet.util.function.TriFunction<Double,Double,Float64Array,java.lang.Boolean> callbackfn);\n    /** \n      * Returns the value of the first element in the array where predicate is true, and undefined \n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending \n      * order, until it finds one where predicate returns true. If such an element is found, find \n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of \n      * predicate. If it is not provided, undefined is used instead.\n      */\n    native public double find(jsweet.util.function.TriFunction<Double,Double,Array<Double>,java.lang.Boolean> predicate);\n    /** \n      * Returns the index of the first element in the array where predicate is true, and undefined \n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending \n      * order, until it finds one where predicate returns true. If such an element is found, find \n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of \n      * predicate. If it is not provided, undefined is used instead.\n      */\n    native public double findIndex(java.util.function.Function<Double,java.lang.Boolean> predicate);\n    /**\n      * Performs the specified action for each element in an array.\n      * @param callbackfn  A function that accepts up to three arguments. forEach calls the \n      * callbackfn function one time for each element in the array. \n      * @param thisArg  An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public void forEach(jsweet.util.function.TriConsumer<Double,Double,Float64Array> callbackfn);\n    /**\n      * Returns the index of the first occurrence of a value in an array.\n      * @param searchElement The value to locate in the array.\n      * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n      *  search starts at index 0.\n      */\n    native public double indexOf(double searchElement);\n    /**\n      * Adds all the elements of an array separated by the specified separator string.\n      * @param separator A string used to separate one element of an array from the next in the \n      * resulting String. If omitted, the array elements are separated with a comma.\n      */\n    native public java.lang.String join();\n    /**\n      * Returns the index of the last occurrence of a value in an array.\n      * @param searchElement The value to locate in the array.\n      * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the \n      * search starts at index 0.\n      */\n    native public double lastIndexOf(double searchElement);\n    /**\n      * Calls a defined callback function on each element of an array, and returns an array that \n      * contains the results.\n      * @param callbackfn A function that accepts up to three arguments. The map method calls the \n      * callbackfn function one time for each element in the array. \n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public Float64Array map(jsweet.util.function.TriFunction<Double,Double,Float64Array,Double> callbackfn);\n    /**\n      * Calls the specified callback function for all the elements in an array. The return value of \n      * the callback function is the accumulated result, and is provided as an argument in the next \n      * call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduce method calls the \n      * callbackfn function one time for each element in the array.\n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an argument\n      * instead of an array value.\n      */\n    native public double reduce(Function4<Double,Double,Double,Float64Array,Double> callbackfn);\n    /** \n      * Calls the specified callback function for all the elements in an array, in descending order. \n      * The return value of the callback function is the accumulated result, and is provided as an \n      * argument in the next call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls \n      * the callbackfn function one time for each element in the array. \n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an \n      * argument instead of an array value.\n      */\n    native public double reduceRight(Function4<Double,Double,Double,Float64Array,Double> callbackfn);\n    /**\n      * Sets a value or an array of values.\n      * @param array A typed or untyped array of values to set.\n      * @param offset The index in the current array at which the values are to be written.\n      */\n    native public void set(Float64Array array);\n    /** \n      * Returns a section of an array.\n      * @param start The beginning of the specified portion of the array.\n      * @param end The end of the specified portion of the array.\n      */\n    native public Float64Array slice(double start);\n    /** \n      * Returns a section of an array.\n      * @param start The beginning of the specified portion of the array.\n      * @param end The end of the specified portion of the array.\n      */\n    native public Float64Array slice();\n    /**\n      * Determines whether the specified callback function returns true for any element of an array.\n      * @param callbackfn A function that accepts up to three arguments. The some method calls the \n      * callbackfn function for each element in array1 until the callbackfn returns true, or until \n      * the end of the array.\n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public java.lang.Boolean some(jsweet.util.function.TriFunction<Double,Double,Float64Array,java.lang.Boolean> callbackfn);\n    /**\n      * Sorts an array.\n      * @param compareFn The name of the function used to determine the order of the elements. If \n      * omitted, the elements are sorted in ascending, ASCII character order.\n      */\n    native public Float64Array sort();\n    /**\n      * Gets a new Float64Array view of the ArrayBuffer store for this array, referencing the elements\n      * at begin, inclusive, up to end, exclusive. \n      * @param begin The index of the beginning of the array.\n      * @param end The index of the end of the array.\n      */\n    native public Float64Array subarray(int begin);\n    public Float64Array(ArrayBuffer buffer, int byteOffset){}\n    public Float64Array(ArrayBuffer buffer){}\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(ArrayLike<Double> arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(ArrayLike<Double> arrayLike);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(Iterable<Double> arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn, java.lang.Object thisArg);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(Iterable<Double> arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(Iterable<Double> arrayLike);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(Double[] arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn, java.lang.Object thisArg);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(Double[] arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Float64Array from(Double[] arrayLike);\n    /** From Iterable, to allow foreach loop (do not use directly). */\n    @jsweet.lang.Erased\n    native public java.util.Iterator<java.lang.Double> iterator();\n    protected Float64Array(){}\n}\n\n", "human_rating": 3.99999213426, "metadata": {"project": "jsweet", "class": "def.js.Float64Array", "source_path": "Jsweet/sourcefiles/core-lib/es6/src/main/java/def/js/Float64Array.java", "label_probabilities": {"readability": [0.999993, 6.71142e-06, 0.0, 0.0], "understandability": [0.999593, 0.000407031, 0.0, 0.0], "complexity": [0.0, 0.0, 0.00844928, 0.991551], "modularization": [0.0, 0.0, 0.062613, 0.937387], "overall": [0.784686, 0.215314, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.js.PropertyDescriptorMap", "source": "package def.js;\n@jsweet.lang.Interface\npublic abstract class PropertyDescriptorMap extends def.js.Object {\n    native public PropertyDescriptor $get(java.lang.String s);\n}\n\n", "human_rating": 3.9998458279999998, "metadata": {"project": "jsweet", "class": "def.js.PropertyDescriptorMap", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/js/PropertyDescriptorMap.java", "label_probabilities": {"readability": [0.999845, 0.000155276, 1.6e-19, 0.0], "understandability": [0.989843, 0.0101574, 4.54508e-10, 0.0], "complexity": [0.0, 0.0, 1.21932e-07, 1.0], "modularization": [0.0, 2.13674e-13, 0.00696887, 0.993031], "overall": [0.997367, 0.0026326, 2.961e-17, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.js.String", "source": "package def.js;\n\npublic class String extends def.js.Object implements Iterable<String> {\n\t/**\n\t * Returns the character at the specified index.\n\t * \n\t * @param pos\n\t *            The zero-based index of the desired character.\n\t */\n\tnative public String charAt(int pos);\n\n\t/**\n\t * Returns the Unicode value of the character at the specified location.\n\t * \n\t * @param index\n\t *            The zero-based index of the desired character. If there is no\n\t *            character at the specified index, NaN is returned.\n\t */\n\tnative public int charCodeAt(int index);\n\n\t/**\n\t * Returns a string that contains the concatenation of two or more strings.\n\t * \n\t * @param strings\n\t *            The strings to append to the end of the string.\n\t */\n\tnative public String concat(java.lang.String... strings);\n\n\t/**\n\t * Returns a string that contains the concatenation of two or more strings.\n\t * \n\t * @param strings\n\t *            The strings to append to the end of the string.\n\t */\n\tnative public String concat(String... strings);\n\n\t/**\n\t * Returns the position of the first occurrence of a substring.\n\t * \n\t * @param searchString\n\t *            The substring to search for in the string\n\t * @param position\n\t *            The index at which to begin searching the String object. If\n\t *            omitted, search starts at the beginning of the string.\n\t */\n\tnative public int indexOf(java.lang.String searchString, int position);\n\n\t/**\n\t * Returns the position of the first occurrence of a substring.\n\t * \n\t * @param searchString\n\t *            The substring to search for in the string\n\t * @param position\n\t *            The index at which to begin searching the String object. If\n\t *            omitted, search starts at the beginning of the string.\n\t */\n\tnative public int indexOf(String searchString, int position);\n\n\t/**\n\t * Returns the last occurrence of a substring in the string.\n\t * \n\t * @param searchString\n\t *            The substring to search for.\n\t * @param position\n\t *            The index at which to begin searching. If omitted, the search\n\t *            begins at the end of the string.\n\t */\n\tnative public int lastIndexOf(java.lang.String searchString, int position);\n\n\t/**\n\t * Returns the last occurrence of a substring in the string.\n\t * \n\t * @param searchString\n\t *            The substring to search for.\n\t * @param position\n\t *            The index at which to begin searching. If omitted, the search\n\t *            begins at the end of the string.\n\t */\n\tnative public int lastIndexOf(String searchString, int position);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t */\n\tnative public int localeCompare(java.lang.String that);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t */\n\tnative public int localeCompare(String that);\n\n\t/**\n\t * Matches a string with a regular expression, and returns an array\n\t * containing the results of that search.\n\t * \n\t * @param regexp\n\t *            A variable name or string literal containing the regular\n\t *            expression pattern and flags.\n\t */\n\tnative public RegExpMatchArray match(java.lang.String regexp);\n\n\t/**\n\t * Matches a string with a regular expression, and returns an array\n\t * containing the results of that search.\n\t * \n\t * @param regexp\n\t *            A variable name or string literal containing the regular\n\t *            expression pattern and flags.\n\t */\n\tnative public RegExpMatchArray match(String regexp);\n\n\t/**\n\t * Matches a string with a regular expression, and returns an array\n\t * containing the results of that search.\n\t * \n\t * @param regexp\n\t *            A regular expression object that contains the regular\n\t *            expression pattern and applicable flags.\n\t */\n\tnative public RegExpMatchArray match(RegExp regexp);\n\n\t/**\n\t * Replaces text in a string, using a regular expression or search string.\n\t * \n\t * @param searchValue\n\t *            A string that represents the regular expression.\n\t * @param replaceValue\n\t *            A string containing the text to replace for every successful\n\t *            match of searchValue in this string.\n\t */\n\tnative public String replace(java.lang.String searchValue, java.lang.String replaceValue);\n\n\t/**\n\t * Replaces text in a string, using a regular expression or search string.\n\t * \n\t * @param searchValue\n\t *            A string that represents the regular expression.\n\t * @param replaceValue\n\t *            A string containing the text to replace for every successful\n\t *            match of searchValue in this string.\n\t */\n\tnative public String replace(String searchValue, String replaceValue);\n\n\t/**\n\t * Replaces text in a string, using a regular expression or search string.\n\t * \n\t * @param searchValue\n\t *            A string that represents the regular expression.\n\t * @param replacer\n\t *            A function that returns the replacement text.\n\t */\n\tnative public <T> String replace(java.lang.String searchValue,\n\t\t\tjava.util.function.BiFunction<String, T, String> replacer);\n\n    /**\n     * Replaces text in a string, using a regular expression or search string.\n     * \n     * @param searchValue\n     *            A string that represents the regular expression.\n     * @param replacer\n     *            A function that returns the replacement text.\n     */\n    native public <T> String replace(java.lang.String searchValue,\n            java.util.function.Supplier<String> replacer);\n\n\t/**\n\t * Replaces text in a string, using a regular expression or search string.\n\t * \n\t * @param searchValue\n\t *            A string that represents the regular expression.\n\t * @param replacer\n\t *            A function that returns the replacement text.\n\t */\n\tnative public <T> String replace(String searchValue, java.util.function.BiFunction<String, T, String> replacer);\n\n    /**\n     * Replaces text in a string, using a regular expression or search string.\n     * \n     * @param searchValue\n     *            A string that represents the regular expression.\n     * @param replacer\n     *            A function that returns the replacement text.\n     */\n    native public <T> String replace(String searchValue, java.util.function.Supplier<String> replacer);\n\t\n\t/**\n\t * Replaces text in a string, using a regular expression or search string.\n\t * \n\t * @param searchValue\n\t *            A Regular Expression object containing the regular expression\n\t *            pattern and applicable flags.\n\t * @param replaceValue\n\t *            A string containing the text to replace for every successful\n\t *            match of searchValue in this string.\n\t */\n\tnative public String replace(RegExp searchValue, java.lang.String replaceValue);\n\n\t/**\n\t * Replaces text in a string, using a regular expression or search string.\n\t * \n\t * @param searchValue\n\t *            A Regular Expression object containing the regular expression\n\t *            pattern and applicable flags.\n\t * @param replaceValue\n\t *            A string containing the text to replace for every successful\n\t *            match of searchValue in this string.\n\t */\n\tnative public String replace(RegExp searchValue, String replaceValue);\n\n\t/**\n\t * Replaces text in a string, using a regular expression or search string.\n\t * \n\t * @param searchValue\n\t *            A Regular Expression object containing the regular expression\n\t *            pattern and applicable flags\n\t * @param replacer\n\t *            A function that returns the replacement text.\n\t */\n\tnative public <T> String replace(RegExp searchValue, java.util.function.BiFunction<String, T, String> replacer);\n\n    /**\n     * Replaces text in a string, using a regular expression or search string.\n     * \n     * @param searchValue\n     *            A Regular Expression object containing the regular expression\n     *            pattern and applicable flags\n     * @param replacer\n     *            A function that returns the replacement text.\n     */\n    native public <T> String replace(RegExp searchValue, java.util.function.Supplier<String> replacer);\n\t\n\t/**\n\t * Finds the first substring match in a regular expression search.\n\t * \n\t * @param regexp\n\t *            The regular expression pattern and applicable flags.\n\t */\n\tnative public int search(java.lang.String regexp);\n\n\t/**\n\t * Finds the first substring match in a regular expression search.\n\t * \n\t * @param regexp\n\t *            The regular expression pattern and applicable flags.\n\t */\n\tnative public int search(String regexp);\n\n\t/**\n\t * Finds the first substring match in a regular expression search.\n\t * \n\t * @param regexp\n\t *            The regular expression pattern and applicable flags.\n\t */\n\tnative public int search(RegExp regexp);\n\n\t/**\n\t * Returns a section of a string.\n\t * \n\t * @param start\n\t *            The index to the beginning of the specified portion of\n\t *            stringObj.\n\t * @param end\n\t *            The index to the end of the specified portion of stringObj.\n\t *            The substring includes the characters up to, but not\n\t *            including, the character indicated by end. If this value is\n\t *            not specified, the substring continues to the end of\n\t *            stringObj.\n\t */\n\tnative public String slice(int start, int end);\n\n\t/**\n\t * Split a string into substrings using the specified separator and return\n\t * them as an array.\n\t * \n\t * @param separator\n\t *            A string that identifies character or characters to use in\n\t *            separating the string. If omitted, a single-element array\n\t *            containing the entire string is returned.\n\t * @param limit\n\t *            A value used to limit the number of elements returned in the\n\t *            array.\n\t */\n\tnative public Array<String> split(java.lang.String separator, int limit);\n\n\t/**\n\t * Split a string into substrings using the specified separator and return\n\t * them as an array.\n\t * \n\t * @param separator\n\t *            A string that identifies character or characters to use in\n\t *            separating the string. If omitted, a single-element array\n\t *            containing the entire string is returned.\n\t * @param limit\n\t *            A value used to limit the number of elements returned in the\n\t *            array.\n\t */\n\tnative public Array<String> split(String separator, int limit);\n\n\t/**\n\t * Split a string into substrings using the specified separator and return\n\t * them as an array.\n\t * \n\t * @param separator\n\t *            A Regular Express that identifies character or characters to\n\t *            use in separating the string. If omitted, a single-element\n\t *            array containing the entire string is returned.\n\t * @param limit\n\t *            A value used to limit the number of elements returned in the\n\t *            array.\n\t */\n\tnative public Array<String> split(RegExp separator, int limit);\n\n\t/**\n\t * Returns the substring at the specified location within a String object.\n\t * \n\t * @param start\n\t *            The zero-based index number indicating the beginning of the\n\t *            substring.\n\t * @param end\n\t *            Zero-based index number indicating the end of the substring.\n\t *            The substring includes the characters up to, but not\n\t *            including, the character indicated by end. If end is omitted,\n\t *            the characters from start through the end of the original\n\t *            string are returned.\n\t */\n\tnative public String substring(int start, int end);\n\n\t/** Converts all the alphabetic characters in a string to lowercase. */\n\tnative public String toLowerCase();\n\n\t/**\n\t * Converts all alphabetic characters to lowercase, taking into account the\n\t * host environment's current locale.\n\t */\n\tnative public String toLocaleLowerCase();\n\n\t/** Converts all the alphabetic characters in a string to uppercase. */\n\tnative public String toUpperCase();\n\n\t/**\n\t * Returns a string where all alphabetic characters have been converted to\n\t * uppercase, taking into account the host environment's current locale.\n\t */\n\tnative public String toLocaleUpperCase();\n\n\t/**\n\t * Removes the leading and trailing white space and line terminator\n\t * characters from a string.\n\t */\n\tnative public String trim();\n\n\t/** Returns the length of a String object. */\n\tpublic final int length = 0;\n\n\t/**\n\t * Gets a substring beginning at the specified location and having the\n\t * specified length.\n\t * \n\t * @param from\n\t *            The starting position of the desired substring. The index of\n\t *            the first character in the string is zero.\n\t * @param length\n\t *            The number of characters to include in the returned substring.\n\t */\n\tnative public String substr(int from, int length);\n\n\t/** Returns the primitive value of the specified object. */\n\tnative public String valueOf();\n\n\tnative public String $get(int index);\n\n\tpublic String(java.lang.Object value) {\n\t}\n\n\tnative public static String $applyStatic(java.lang.Object value);\n\n\tpublic static final String prototype = null;\n\n\tnative public static String fromCharCode(int... codes);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t * @param locales\n\t *            An array of locale strings that contain one or more language\n\t *            or locale tags. If you include more than one locale string,\n\t *            list them in descending order of priority so that the first\n\t *            entry is the preferred locale. If you omit this parameter, the\n\t *            default locale of the JavaScript runtime is used. This\n\t *            parameter must conform to BCP 47 standards; see the\n\t *            Intl.Collator object for details.\n\t * @param options\n\t *            An object that contains one or more properties that specify\n\t *            comparison options. see the Intl.Collator object for details.\n\t */\n\tnative public int localeCompare(java.lang.String that, java.lang.String[] locales,\n\t\t\tdef.dom.intl.CollatorOptions options);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t * @param locales\n\t *            An array of locale strings that contain one or more language\n\t *            or locale tags. If you include more than one locale string,\n\t *            list them in descending order of priority so that the first\n\t *            entry is the preferred locale. If you omit this parameter, the\n\t *            default locale of the JavaScript runtime is used. This\n\t *            parameter must conform to BCP 47 standards; see the\n\t *            Intl.Collator object for details.\n\t * @param options\n\t *            An object that contains one or more properties that specify\n\t *            comparison options. see the Intl.Collator object for details.\n\t */\n\tnative public int localeCompare(String that, Array<String> locales, def.dom.intl.CollatorOptions options);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t * @param locale\n\t *            Locale tag. If you omit this parameter, the default locale of\n\t *            the JavaScript runtime is used. This parameter must conform to\n\t *            BCP 47 standards; see the Intl.Collator object for details.\n\t * @param options\n\t *            An object that contains one or more properties that specify\n\t *            comparison options. see the Intl.Collator object for details.\n\t */\n\tnative public int localeCompare(java.lang.String that, java.lang.String locale,\n\t\t\tdef.dom.intl.CollatorOptions options);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t * @param locale\n\t *            Locale tag. If you omit this parameter, the default locale of\n\t *            the JavaScript runtime is used. This parameter must conform to\n\t *            BCP 47 standards; see the Intl.Collator object for details.\n\t * @param options\n\t *            An object that contains one or more properties that specify\n\t *            comparison options. see the Intl.Collator object for details.\n\t */\n\tnative public int localeCompare(String that, String locale, def.dom.intl.CollatorOptions options);\n\n\t/**\n\t * Returns the position of the first occurrence of a substring.\n\t * \n\t * @param searchString\n\t *            The substring to search for in the string\n\t * @param position\n\t *            The index at which to begin searching the String object. If\n\t *            omitted, search starts at the beginning of the string.\n\t */\n\tnative public int indexOf(java.lang.String searchString);\n\n\t/**\n\t * Returns the position of the first occurrence of a substring.\n\t * \n\t * @param searchString\n\t *            The substring to search for in the string\n\t * @param position\n\t *            The index at which to begin searching the String object. If\n\t *            omitted, search starts at the beginning of the string.\n\t */\n\tnative public int indexOf(String searchString);\n\n\t/**\n\t * Returns the last occurrence of a substring in the string.\n\t * \n\t * @param searchString\n\t *            The substring to search for.\n\t * @param position\n\t *            The index at which to begin searching. If omitted, the search\n\t *            begins at the end of the string.\n\t */\n\tnative public int lastIndexOf(java.lang.String searchString);\n\n\t/**\n\t * Returns the last occurrence of a substring in the string.\n\t * \n\t * @param searchString\n\t *            The substring to search for.\n\t * @param position\n\t *            The index at which to begin searching. If omitted, the search\n\t *            begins at the end of the string.\n\t */\n\tnative public int lastIndexOf(String searchString);\n\n\t/**\n\t * Returns a section of a string.\n\t * \n\t * @param start\n\t *            The index to the beginning of the specified portion of\n\t *            stringObj.\n\t * @param end\n\t *            The index to the end of the specified portion of stringObj.\n\t *            The substring includes the characters up to, but not\n\t *            including, the character indicated by end. If this value is\n\t *            not specified, the substring continues to the end of\n\t *            stringObj.\n\t */\n\tnative public String slice(int start);\n\n\t/**\n\t * Returns a section of a string.\n\t * \n\t * @param start\n\t *            The index to the beginning of the specified portion of\n\t *            stringObj.\n\t * @param end\n\t *            The index to the end of the specified portion of stringObj.\n\t *            The substring includes the characters up to, but not\n\t *            including, the character indicated by end. If this value is\n\t *            not specified, the substring continues to the end of\n\t *            stringObj.\n\t */\n\tnative public String slice();\n\n\t/**\n\t * Split a string into substrings using the specified separator and return\n\t * them as an array.\n\t * \n\t * @param separator\n\t *            A string that identifies character or characters to use in\n\t *            separating the string. If omitted, a single-element array\n\t *            containing the entire string is returned.\n\t * @param limit\n\t *            A value used to limit the number of elements returned in the\n\t *            array.\n\t */\n\tnative public Array<String> split(java.lang.String separator);\n\n\t/**\n\t * Split a string into substrings using the specified separator and return\n\t * them as an array.\n\t * \n\t * @param separator\n\t *            A string that identifies character or characters to use in\n\t *            separating the string. If omitted, a single-element array\n\t *            containing the entire string is returned.\n\t * @param limit\n\t *            A value used to limit the number of elements returned in the\n\t *            array.\n\t */\n\tnative public Array<String> split(String separator);\n\n\t/**\n\t * Split a string into substrings using the specified separator and return\n\t * them as an array.\n\t * \n\t * @param separator\n\t *            A Regular Express that identifies character or characters to\n\t *            use in separating the string. If omitted, a single-element\n\t *            array containing the entire string is returned.\n\t * @param limit\n\t *            A value used to limit the number of elements returned in the\n\t *            array.\n\t */\n\tnative public Array<String> split(RegExp separator);\n\n\t/**\n\t * Returns the substring at the specified location within a String object.\n\t * \n\t * @param start\n\t *            The zero-based index number indicating the beginning of the\n\t *            substring.\n\t * @param end\n\t *            Zero-based index number indicating the end of the substring.\n\t *            The substring includes the characters up to, but not\n\t *            including, the character indicated by end. If end is omitted,\n\t *            the characters from start through the end of the original\n\t *            string are returned.\n\t */\n\tnative public String substring(int start);\n\n\t/**\n\t * Gets a substring beginning at the specified location and having the\n\t * specified length.\n\t * \n\t * @param from\n\t *            The starting position of the desired substring. The index of\n\t *            the first character in the string is zero.\n\t * @param length\n\t *            The number of characters to include in the returned substring.\n\t */\n\tnative public String substr(int from);\n\n\tpublic String() {\n\t}\n\n\tnative public static String $applyStatic();\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t * @param locales\n\t *            An array of locale strings that contain one or more language\n\t *            or locale tags. If you include more than one locale string,\n\t *            list them in descending order of priority so that the first\n\t *            entry is the preferred locale. If you omit this parameter, the\n\t *            default locale of the JavaScript runtime is used. This\n\t *            parameter must conform to BCP 47 standards; see the\n\t *            Intl.Collator object for details.\n\t * @param options\n\t *            An object that contains one or more properties that specify\n\t *            comparison options. see the Intl.Collator object for details.\n\t */\n\tnative public int localeCompare(java.lang.String that, java.lang.String[] locales);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t * @param locales\n\t *            An array of locale strings that contain one or more language\n\t *            or locale tags. If you include more than one locale string,\n\t *            list them in descending order of priority so that the first\n\t *            entry is the preferred locale. If you omit this parameter, the\n\t *            default locale of the JavaScript runtime is used. This\n\t *            parameter must conform to BCP 47 standards; see the\n\t *            Intl.Collator object for details.\n\t * @param options\n\t *            An object that contains one or more properties that specify\n\t *            comparison options. see the Intl.Collator object for details.\n\t */\n\tnative public int localeCompare(String that, Array<String> locales);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t * @param locale\n\t *            Locale tag. If you omit this parameter, the default locale of\n\t *            the JavaScript runtime is used. This parameter must conform to\n\t *            BCP 47 standards; see the Intl.Collator object for details.\n\t * @param options\n\t *            An object that contains one or more properties that specify\n\t *            comparison options. see the Intl.Collator object for details.\n\t */\n\tnative public int localeCompare(java.lang.String that, java.lang.String locale);\n\n\t/**\n\t * Determines whether two strings are equivalent in the current locale.\n\t * \n\t * @param that\n\t *            String to compare to target string\n\t * @param locale\n\t *            Locale tag. If you omit this parameter, the default locale of\n\t *            the JavaScript runtime is used. This parameter must conform to\n\t *            BCP 47 standards; see the Intl.Collator object for details.\n\t * @param options\n\t *            An object that contains one or more properties that specify\n\t *            comparison options. see the Intl.Collator object for details.\n\t */\n\tnative public int localeCompare(String that, String locale);\n\n\t/** From Iterable, to allow foreach loop (do not use directly). */\n\t@jsweet.lang.Erased\n\tnative public java.util.Iterator<String> iterator();\n}\n", "human_rating": 3.9012051926, "metadata": {"project": "jsweet", "class": "def.js.String", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/js/String.java", "label_probabilities": {"readability": [0.90125, 0.0987045, 4.58463e-05, 0.0], "understandability": [0.846574, 0.153426, 2.38823e-07, 0.0], "complexity": [0.0, 2.22841e-10, 0.0583091, 0.941691], "modularization": [0.0, 2.0134e-13, 4.85961e-05, 0.999951], "overall": [0.977677, 0.0223232, 1.81181e-08, 1.5e-19]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/def.js.Uint8Array", "source": "package def.js;\nimport jsweet.util.function.Function4;\n/**\n  * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the \n  * requested number of bytes could not be allocated an exception is raised.\n  */\npublic class Uint8Array extends def.js.Object implements Iterable<java.lang.Double> {\n    /**\n      * The size in bytes of each element in the array. \n      */\n    public final double BYTES_PER_ELEMENT=0;\n    /**\n      * The ArrayBuffer instance referenced by the array. \n      */\n    public final ArrayBuffer buffer=null;\n    /**\n      * The length in bytes of the array.\n      */\n    public final double byteLength=0;\n    /**\n      * The offset in bytes of the array.\n      */\n    public final double byteOffset=0;\n    /** \n      * Returns the this object after copying a section of the array identified by start and end\n      * to the same array starting at position target\n      * @param target If target is negative, it is treated as length+target where length is the \n      * length of the array. \n      * @param start If start is negative, it is treated as length+start. If end is negative, it \n      * is treated as length+end.\n      * @param end If not specified, length of the this object is used as its default value. \n      */\n    native public Uint8Array copyWithin(double target, double start, double end);\n    /**\n      * Determines whether all the members of an array satisfy the specified test.\n      * @param callbackfn A function that accepts up to three arguments. The every method calls \n      * the callbackfn function for each element in array1 until the callbackfn returns false, \n      * or until the end of the array.\n      * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public java.lang.Boolean every(jsweet.util.function.TriFunction<Double,Double,Uint8Array,java.lang.Boolean> callbackfn, java.lang.Object thisArg);\n    /**\n        * Returns the this object after filling the section identified by start and end with value\n        * @param value value to fill array section with\n        * @param start index to start filling the array at. If start is negative, it is treated as \n        * length+start where length is the length of the array. \n        * @param end index to stop filling the array at. If end is negative, it is treated as \n        * length+end.\n        */\n    native public Uint8Array fill(double value, double start, double end);\n    /**\n      * Returns the elements of an array that meet the condition specified in a callback function. \n      * @param callbackfn A function that accepts up to three arguments. The filter method calls \n      * the callbackfn function one time for each element in the array. \n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public Uint8Array filter(jsweet.util.function.TriFunction<Double,Double,Uint8Array,java.lang.Boolean> callbackfn, java.lang.Object thisArg);\n    /** \n      * Returns the value of the first element in the array where predicate is true, and undefined \n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending \n      * order, until it finds one where predicate returns true. If such an element is found, find \n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of \n      * predicate. If it is not provided, undefined is used instead.\n      */\n    native public double find(jsweet.util.function.TriFunction<Double,Double,Array<Double>,java.lang.Boolean> predicate, java.lang.Object thisArg);\n    /** \n      * Returns the index of the first element in the array where predicate is true, and undefined \n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending \n      * order, until it finds one where predicate returns true. If such an element is found, find \n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of \n      * predicate. If it is not provided, undefined is used instead.\n      */\n    native public double findIndex(java.util.function.Function<Double,java.lang.Boolean> predicate, java.lang.Object thisArg);\n    /**\n      * Performs the specified action for each element in an array.\n      * @param callbackfn  A function that accepts up to three arguments. forEach calls the \n      * callbackfn function one time for each element in the array. \n      * @param thisArg  An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public void forEach(jsweet.util.function.TriConsumer<Double,Double,Uint8Array> callbackfn, java.lang.Object thisArg);\n    /**\n      * Returns the index of the first occurrence of a value in an array.\n      * @param searchElement The value to locate in the array.\n      * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n      *  search starts at index 0.\n      */\n    native public double indexOf(double searchElement, double fromIndex);\n    /**\n      * Adds all the elements of an array separated by the specified separator string.\n      * @param separator A string used to separate one element of an array from the next in the \n      * resulting String. If omitted, the array elements are separated with a comma.\n      */\n    native public java.lang.String join(java.lang.String separator);\n    /**\n      * Returns the index of the last occurrence of a value in an array.\n      * @param searchElement The value to locate in the array.\n      * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the \n      * search starts at index 0.\n      */\n    native public double lastIndexOf(double searchElement, double fromIndex);\n    /**\n      * The length of the array.\n      */\n    public final double length=0;\n    /**\n      * Calls a defined callback function on each element of an array, and returns an array that \n      * contains the results.\n      * @param callbackfn A function that accepts up to three arguments. The map method calls the \n      * callbackfn function one time for each element in the array. \n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public Uint8Array map(jsweet.util.function.TriFunction<Double,Double,Uint8Array,Double> callbackfn, java.lang.Object thisArg);\n    /**\n      * Calls the specified callback function for all the elements in an array. The return value of \n      * the callback function is the accumulated result, and is provided as an argument in the next \n      * call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduce method calls the \n      * callbackfn function one time for each element in the array.\n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an argument\n      * instead of an array value.\n      */\n    native public double reduce(Function4<Double,Double,Double,Uint8Array,Double> callbackfn, double initialValue);\n    /**\n      * Calls the specified callback function for all the elements in an array. The return value of \n      * the callback function is the accumulated result, and is provided as an argument in the next \n      * call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduce method calls the \n      * callbackfn function one time for each element in the array.\n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an argument \n      * instead of an array value.\n      */\n    native public <U> U reduce(Function4<U,Double,Double,Uint8Array,U> callbackfn, U initialValue);\n    /** \n      * Calls the specified callback function for all the elements in an array, in descending order. \n      * The return value of the callback function is the accumulated result, and is provided as an \n      * argument in the next call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls \n      * the callbackfn function one time for each element in the array. \n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an \n      * argument instead of an array value.\n      */\n    native public double reduceRight(Function4<Double,Double,Double,Uint8Array,Double> callbackfn, double initialValue);\n    /** \n      * Calls the specified callback function for all the elements in an array, in descending order. \n      * The return value of the callback function is the accumulated result, and is provided as an \n      * argument in the next call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls\n      * the callbackfn function one time for each element in the array. \n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an argument\n      * instead of an array value.\n      */\n    native public <U> U reduceRight(Function4<U,Double,Double,Uint8Array,U> callbackfn, U initialValue);\n    /**\n      * Reverses the elements in an Array. \n      */\n    native public Uint8Array reverse();\n    /**\n      * Sets a value or an array of values.\n      * @param index The index of the location to set.\n      * @param value The value to set.\n      */\n    native public void set(double index, double value);\n    /**\n      * Sets a value or an array of values.\n      * @param array A typed or untyped array of values to set.\n      * @param offset The index in the current array at which the values are to be written.\n      */\n    native public void set(ArrayLike<Double> array, double offset);\n    /** \n      * Returns a section of an array.\n      * @param start The beginning of the specified portion of the array.\n      * @param end The end of the specified portion of the array.\n      */\n    native public Uint8Array slice(double start, double end);\n    /**\n      * Determines whether the specified callback function returns true for any element of an array.\n      * @param callbackfn A function that accepts up to three arguments. The some method calls the \n      * callbackfn function for each element in array1 until the callbackfn returns true, or until \n      * the end of the array.\n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public java.lang.Boolean some(jsweet.util.function.TriFunction<Double,Double,Uint8Array,java.lang.Boolean> callbackfn, java.lang.Object thisArg);\n    /**\n      * Sorts an array.\n      * @param compareFn The name of the function used to determine the order of the elements. If \n      * omitted, the elements are sorted in ascending, ASCII character order.\n      */\n    native public Uint8Array sort(java.util.function.BiFunction<Double,Double,Double> compareFn);\n    /**\n      * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements\n      * at begin, inclusive, up to end, exclusive. \n      * @param begin The index of the beginning of the array.\n      * @param end The index of the end of the array.\n      */\n    native public Uint8Array subarray(double begin, double end);\n    /**\n      * Converts a number to a string by using the current locale. \n      */\n    native public String toLocaleString();\n    /**\n      * Returns a string representation of an array.\n      */\n    native public java.lang.String toString();\n    native public java.lang.Double $get(double index);\n    public static final Uint8Array prototype=null;\n    public Uint8Array(double length){}\n    public Uint8Array(ArrayLike<Double> array){}\n    public Uint8Array(ArrayBuffer buffer, double byteOffset, double length){}\n    /**\n      * Returns a new array from a set of elements.\n      * @param items A set of elements to include in the new array object.\n      */\n    native public static Uint8Array of(double... items);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Uint8Array from(ArrayLike<Double> arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn, java.lang.Object thisArg);\n    /** \n      * Returns the this object after copying a section of the array identified by start and end\n      * to the same array starting at position target\n      * @param target If target is negative, it is treated as length+target where length is the \n      * length of the array. \n      * @param start If start is negative, it is treated as length+start. If end is negative, it \n      * is treated as length+end.\n      * @param end If not specified, length of the this object is used as its default value. \n      */\n    native public Uint8Array copyWithin(double target, double start);\n    /**\n      * Determines whether all the members of an array satisfy the specified test.\n      * @param callbackfn A function that accepts up to three arguments. The every method calls \n      * the callbackfn function for each element in array1 until the callbackfn returns false, \n      * or until the end of the array.\n      * @param thisArg An object to which the this keyword can refer in the callbackfn function.\n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public java.lang.Boolean every(jsweet.util.function.TriFunction<Double,Double,Uint8Array,java.lang.Boolean> callbackfn);\n    /**\n        * Returns the this object after filling the section identified by start and end with value\n        * @param value value to fill array section with\n        * @param start index to start filling the array at. If start is negative, it is treated as \n        * length+start where length is the length of the array. \n        * @param end index to stop filling the array at. If end is negative, it is treated as \n        * length+end.\n        */\n    native public Uint8Array fill(double value, double start);\n    /**\n        * Returns the this object after filling the section identified by start and end with value\n        * @param value value to fill array section with\n        * @param start index to start filling the array at. If start is negative, it is treated as \n        * length+start where length is the length of the array. \n        * @param end index to stop filling the array at. If end is negative, it is treated as \n        * length+end.\n        */\n    native public Uint8Array fill(double value);\n    /**\n      * Returns the elements of an array that meet the condition specified in a callback function. \n      * @param callbackfn A function that accepts up to three arguments. The filter method calls \n      * the callbackfn function one time for each element in the array. \n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public Uint8Array filter(jsweet.util.function.TriFunction<Double,Double,Uint8Array,java.lang.Boolean> callbackfn);\n    /** \n      * Returns the value of the first element in the array where predicate is true, and undefined \n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending \n      * order, until it finds one where predicate returns true. If such an element is found, find \n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of \n      * predicate. If it is not provided, undefined is used instead.\n      */\n    native public double find(jsweet.util.function.TriFunction<Double,Double,Array<Double>,java.lang.Boolean> predicate);\n    /** \n      * Returns the index of the first element in the array where predicate is true, and undefined \n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending \n      * order, until it finds one where predicate returns true. If such an element is found, find \n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of \n      * predicate. If it is not provided, undefined is used instead.\n      */\n    native public double findIndex(java.util.function.Function<Double,java.lang.Boolean> predicate);\n    /**\n      * Performs the specified action for each element in an array.\n      * @param callbackfn  A function that accepts up to three arguments. forEach calls the \n      * callbackfn function one time for each element in the array. \n      * @param thisArg  An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public void forEach(jsweet.util.function.TriConsumer<Double,Double,Uint8Array> callbackfn);\n    /**\n      * Returns the index of the first occurrence of a value in an array.\n      * @param searchElement The value to locate in the array.\n      * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the\n      *  search starts at index 0.\n      */\n    native public double indexOf(double searchElement);\n    /**\n      * Adds all the elements of an array separated by the specified separator string.\n      * @param separator A string used to separate one element of an array from the next in the \n      * resulting String. If omitted, the array elements are separated with a comma.\n      */\n    native public java.lang.String join();\n    /**\n      * Returns the index of the last occurrence of a value in an array.\n      * @param searchElement The value to locate in the array.\n      * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the \n      * search starts at index 0.\n      */\n    native public double lastIndexOf(double searchElement);\n    /**\n      * Calls a defined callback function on each element of an array, and returns an array that \n      * contains the results.\n      * @param callbackfn A function that accepts up to three arguments. The map method calls the \n      * callbackfn function one time for each element in the array. \n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public Uint8Array map(jsweet.util.function.TriFunction<Double,Double,Uint8Array,Double> callbackfn);\n    /**\n      * Calls the specified callback function for all the elements in an array. The return value of \n      * the callback function is the accumulated result, and is provided as an argument in the next \n      * call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduce method calls the \n      * callbackfn function one time for each element in the array.\n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an argument\n      * instead of an array value.\n      */\n    native public double reduce(Function4<Double,Double,Double,Uint8Array,Double> callbackfn);\n    /** \n      * Calls the specified callback function for all the elements in an array, in descending order. \n      * The return value of the callback function is the accumulated result, and is provided as an \n      * argument in the next call to the callback function.\n      * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls \n      * the callbackfn function one time for each element in the array. \n      * @param initialValue If initialValue is specified, it is used as the initial value to start \n      * the accumulation. The first call to the callbackfn function provides this value as an \n      * argument instead of an array value.\n      */\n    native public double reduceRight(Function4<Double,Double,Double,Uint8Array,Double> callbackfn);\n    /**\n      * Sets a value or an array of values.\n      * @param array A typed or untyped array of values to set.\n      * @param offset The index in the current array at which the values are to be written.\n      */\n    native public void set(ArrayLike<Double> array);\n    /** \n      * Returns a section of an array.\n      * @param start The beginning of the specified portion of the array.\n      * @param end The end of the specified portion of the array.\n      */\n    native public Uint8Array slice(double start);\n    /** \n      * Returns a section of an array.\n      * @param start The beginning of the specified portion of the array.\n      * @param end The end of the specified portion of the array.\n      */\n    native public Uint8Array slice();\n    /**\n      * Determines whether the specified callback function returns true for any element of an array.\n      * @param callbackfn A function that accepts up to three arguments. The some method calls the \n      * callbackfn function for each element in array1 until the callbackfn returns true, or until \n      * the end of the array.\n      * @param thisArg An object to which the this keyword can refer in the callbackfn function. \n      * If thisArg is omitted, undefined is used as the this value.\n      */\n    native public java.lang.Boolean some(jsweet.util.function.TriFunction<Double,Double,Uint8Array,java.lang.Boolean> callbackfn);\n    /**\n      * Sorts an array.\n      * @param compareFn The name of the function used to determine the order of the elements. If \n      * omitted, the elements are sorted in ascending, ASCII character order.\n      */\n    native public Uint8Array sort();\n    /**\n      * Gets a new Uint8Array view of the ArrayBuffer store for this array, referencing the elements\n      * at begin, inclusive, up to end, exclusive. \n      * @param begin The index of the beginning of the array.\n      * @param end The index of the end of the array.\n      */\n    native public Uint8Array subarray(double begin);\n    public Uint8Array(ArrayBuffer buffer, double byteOffset){}\n    public Uint8Array(ArrayBuffer buffer){}\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Uint8Array from(ArrayLike<Double> arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Uint8Array from(ArrayLike<Double> arrayLike);\n    /**\n      * Sets a value or an array of values.\n      * @param array A typed or untyped array of values to set.\n      * @param offset The index in the current array at which the values are to be written.\n      */\n    native public void set(Double[] array, double offset);\n    public Uint8Array(Double[] array){}\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Uint8Array from(Double[] arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn, java.lang.Object thisArg);\n    /**\n      * Sets a value or an array of values.\n      * @param array A typed or untyped array of values to set.\n      * @param offset The index in the current array at which the values are to be written.\n      */\n    native public void set(Double[] array);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Uint8Array from(Double[] arrayLike, java.util.function.BiFunction<Double,Double,Double> mapfn);\n    /**\n      * Creates an array from an array-like or iterable object.\n      * @param arrayLike An array-like or iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    native public static Uint8Array from(Double[] arrayLike);\n    /** From Iterable, to allow foreach loop (do not use directly). */\n    @jsweet.lang.Erased\n    native public java.util.Iterator<java.lang.Double> iterator();\n    protected Uint8Array(){}\n}\n\n", "human_rating": 3.9000431234099997, "metadata": {"project": "jsweet", "class": "def.js.Uint8Array", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/def/js/Uint8Array.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [0.0, 1.21824e-12, 0.0118707, 0.988129], "modularization": [0.0, 2.94558e-05, 0.331741, 0.668229], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/jsweet.util.Lang", "source": "/* \n * JSweet - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n *     http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage jsweet.util;\n\nimport java.util.Map;\nimport java.util.function.BiConsumer;\nimport java.util.function.BiFunction;\nimport java.util.function.Consumer;\nimport java.util.function.Function;\nimport java.util.function.Supplier;\n\nimport jsweet.util.function.Consumer4;\nimport jsweet.util.function.Consumer5;\nimport jsweet.util.function.Consumer6;\nimport jsweet.util.function.Function4;\nimport jsweet.util.function.Function5;\nimport jsweet.util.function.Function6;\nimport jsweet.util.function.TriConsumer;\nimport jsweet.util.function.TriFunction;\nimport jsweet.util.union.Union;\nimport jsweet.util.union.Union3;\nimport jsweet.util.union.Union4;\n\n/**\n * A set of helper methods for manipulating JavaScript core lang features and\n * relate them to the Java lang.\n * \n * <p>\n * Be aware that these functions have no corresponding implementation. They are\n * used mainly for typing and syntax purpose. By convention, most functions\n * starting with $ are syntax macros to support JavaScript syntactic constructs.\n * Most other functions are cast functions to switch from Java to JavaScript\n * objects. The later are erased during the generation process or are translated\n * to TypeScript casts (in any case they have no runtime counterparts).\n * \n * <p>\n * To work with JSweet, programmers may import these helpers most of the time,\n * as well as JavaScript's {@link def.js.Globals} (and DOM's\n * {@link def.dom.Globals}).\n * \n * @author Renaud Pawlak\n * @see def.js.Globals\n * @see def.dom.Globals\n */\npublic final class Lang {\n\n    private static final ThreadLocal<Map<String, Object>> EXPORTED_VARS = new ThreadLocal<>();\n\n    private Lang() {\n    }\n\n    /**\n     * An accessor to the module id, only when using modules.\n     */\n    public static final class module {\n\tpublic final static String id = null;\n    }\n\n    /**\n     * Casts a JavaScript array object to a native Java array.\n     * \n     * @param array\n     *            a JavaScript array\n     * @return a Java array\n     */\n    native public static <T> T[] array(def.js.Array<T> array);\n\n    /**\n     * Casts a native Java array to a JavaScript array object.\n     * \n     * @param array\n     *            a Java array\n     * @return a JavaScript array\n     */\n    native public static <T> def.js.Array<T> array(T[] array);\n\n    /**\n     * Casts a native Java array of primitive booleans to a JavaScript array\n     * object.\n     * \n     * @param array\n     *            a Java array\n     * @return a JavaScript array\n     */\n    native public static def.js.Array<Boolean> array(boolean[] array);\n\n    /**\n     * Casts a native Java array of primitive ints to a JavaScript array object.\n     * \n     * @param array\n     *            a Java array\n     * @return a JavaScript array\n     */\n    native public static def.js.Array<Integer> array(int[] array);\n\n    /**\n     * Casts a native Java array of primitive doubles to a JavaScript array\n     * object.\n     * \n     * @param array\n     *            a Java array\n     * @return a JavaScript array\n     */\n    native public static def.js.Array<Double> array(double[] array);\n\n    /**\n     * Casts a native Java array of primitive shorts to a JavaScript array\n     * object.\n     * \n     * @param array\n     *            a Java array\n     * @return a JavaScript array\n     */\n    native public static def.js.Array<Short> array(short[] array);\n\n    /**\n     * Casts a native Java array of primitive bytes to a JavaScript array\n     * object.\n     * \n     * @param array\n     *            a Java array\n     * @return a JavaScript array\n     */\n    native public static def.js.Array<Byte> array(byte[] array);\n\n    /**\n     * Casts a native Java array of primitive longs to a JavaScript array\n     * object.\n     * \n     * @param array\n     *            a Java array\n     * @return a JavaScript array\n     */\n    native public static def.js.Array<Long> array(long[] array);\n\n    /**\n     * Casts a native Java array of primitive floats to a JavaScript array\n     * object.\n     * \n     * @param array\n     *            a Java array\n     * @return a JavaScript array\n     */\n    native public static def.js.Array<Float> array(float[] array);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Runnable function);\n\n    /**\n     * Casts a type to a JavaScript function object.\n     * \n     * <p>\n     * Indeed, type references are functions in javascript.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Class<?> type);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Consumer<?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Supplier<?> function);\n\n    /**\n     * Forces JSweet to create a plain JavaScript function rather than an\n     * \"arrow\" function.\n     * \n     * <p>\n     * Hence, <code>function((a) -> { return a * a; })</code> transpiles to\n     * <code>(a) => { return a * a; }</code>. But\n     * <code>$noarrow(function((a) -> { return a * a; }))</code> transpiles to\n     * <code>function(a) { return a * a; }</code>\n     */\n    native public static def.js.Function $noarrow(def.js.Function function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(BiConsumer<?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(TriConsumer<?, ?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Consumer4<?, ?, ?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Consumer5<?, ?, ?, ?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Consumer6<?, ?, ?, ?, ?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Function<?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(BiFunction<?, ?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(TriFunction<?, ?, ?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Function4<?, ?, ?, ?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Function5<?, ?, ?, ?, ?, ?> function);\n\n    /**\n     * Casts a functional interface to a JavaScript function object.\n     * \n     * <p>\n     * Note that this casts allows for a reflective access to the function as a\n     * plain object, but it looses the actual function type. Various APIs take\n     * function objects as arguments, and this function can be useful in such\n     * circumstances.\n     * \n     * @see jsweet.util.function\n     */\n    native public static def.js.Function function(Function6<?, ?, ?, ?, ?, ?, ?> function);\n\n    /**\n     * Casts a native Java Boolean to a JavaScript Boolean.\n     */\n    native public static def.js.Boolean bool(Boolean bool);\n\n    /**\n     * Casts back a JavaScript boolean to a Java boolean.\n     */\n    native public static Boolean bool(def.js.Boolean bool);\n\n    /**\n     * Casts a native Java number to a JavaScript Number.\n     */\n    native public static def.js.Number number(Number number);\n\n    /**\n     * Casts back a JavaScript number to a Java integer.\n     */\n    native public static Integer integer(def.js.Number number);\n\n    /**\n     * Casts a JavaScript number to a Java double.\n     */\n    native public static Double number(def.js.Number number);\n\n    /**\n     * Casts a native Java string to a JavaScript string.\n     * \n     * <p>\n     * By default, JSweet API use plain Java strings so that the program can\n     * easily use string literals. However, when the programmer needs to access\n     * to runtime string manipulation functions, then need to cast to a\n     * JavaScript string, which allows the access to the standard Web API.\n     */\n    native public static def.js.String string(String string);\n\n    /**\n     * Casts a native Java char to a JavaScript string.\n     */\n    native public static def.js.String string(char c);\n\n    /**\n     * Casts back a JavaScript string to a Java string.\n     * \n     * <p>\n     * By default, JSweet API use plain Java strings so that the program can\n     * easily use string literals. However, when the programmer needs to access\n     * to runtime string manipulation functions, then need to cast to a\n     * JavaScript string, which allows the access to the standard Web API.\n     */\n    native public static String string(def.js.String string);\n\n    /**\n     * Casts a native Java object to a JavaScript object.\n     * \n     * <p>\n     * By default, JSweet API use plain Java objects. However, when the\n     * programmer needs to access to the standard Web API, they need to cast\n     * through this function.\n     */\n    native public static def.js.Object object(Object object);\n\n    /**\n     * This syntax macro should be used to create untyped JavaScript\n     * objects/maps. It takes a list of key/value pairs, where the keys must be\n     * string literals and values are objects.\n     * \n     * <p>\n     * For instance, the expression:\n     * \n     * <pre>\n     * $map(\"responsive\", true, \"defaultSize\", \"100px\")\n     * </pre>\n     * \n     * <p>\n     * Will be transpiled to:\n     * \n     * <pre>\n     * {responsive:true, defaultSize:\"100px\"}\n     * </pre>\n     * \n     * @param keyValues\n     *            the key values pairs that initialize the object (keys must be\n     *            string literals)\n     * @return an untyped object containing the given key/value pairs\n     */\n    native public static def.js.Object $map(Object... keyValues);\n\n    /**\n     * A syntax macro to construct an array with the given elements.\n     * \n     * <p>\n     * For instance, the expression:\n     * \n     * <pre>\n     * $array(\"a\", \"b\", \"c\")\n     * </pre>\n     * \n     * <p>\n     * Will be transpiled to:\n     * \n     * <pre>\n     * [\"a\", \"b\", \"c\"]\n     * </pre>\n     * \n     * \n     * @param elements\n     *            the elements initializing the array\n     * @return a new array\n     */\n    @SafeVarargs\n    native public static <E> def.js.Array<E> $array(E... elements);\n\n    /**\n     * Uses the target object as a function and call it. This is not typesafe\n     * and should be avoided.\n     * \n     * @param target\n     *            the functional object\n     * @param arguments\n     *            the call arguments\n     * @return the function result\n     */\n    native public static <T> T $apply(Object target, Object... arguments);\n\n    /**\n     * Uses the target object as a constructor and call it. This is not typesafe\n     * and should be avoided.\n     * \n     * @param target\n     *            the constructor object\n     * @param arguments\n     *            the call arguments\n     * @return the constructor result\n     */\n    native public static <T> T $new(Object target, Object... arguments);\n\n    /**\n     * This helper casts an object to one of the types in a given union type.\n     * \n     * <p>\n     * The JSweet transpiler will ensure that T is one of T1 and T2. If not, it\n     * will raise an error.\n     * \n     * @param union\n     *            the object typed after a union type\n     * @return the same object, but typed after one of the types of the union\n     *         type\n     */\n    native public static <T1, T2, T> T union(Union<T1, T2> union);\n\n    /**\n     * This helper casts an object to an union type.\n     * \n     * <p>\n     * The JSweet transpiler will ensure that T is one of actual type elements\n     * of U. If not, it will raise an error.\n     * \n     * @param union\n     *            the object typed after one of the types of the union type\n     * @return the same object, but typed after a union type\n     */\n    native public static <U extends Union<?, ?>, T> U union(T object);\n\n    /**\n     * This helper casts an object to an union type.\n     * \n     * <p>\n     * The JSweet transpiler will ensure that T is one of actual type elements\n     * of U. If not, it will raise an error.\n     * \n     * @param union\n     *            the object typed after one of the types of the union type\n     * @return the same object, but typed after a union type\n     */\n    native public static <T> Union3<?, ?, ?> union3(T object);\n\n    /**\n     * This helper casts an object to an union type.\n     * \n     * <p>\n     * The JSweet transpiler will ensure that T is one of actual type elements\n     * of U. If not, it will raise an error.\n     * \n     * @param union\n     *            the object typed after one of the types of the union type\n     * @return the same object, but typed after a union type\n     */\n    native public static <T> Union4<?, ?, ?, ?> union4(T object);\n\n    /**\n     * This utility function allows using the <code>typeof</code> JavaScript\n     * operator.\n     * \n     * The expression <code>typeof(o)</code> transpiles to <code>typeof o</code>\n     * . See the JavaScript documentation for more details.\n     */\n    native public static String typeof(Object o);\n\n    /**\n     * This syntax macro allows using the <code>==</code> or <code>!=</code>\n     * JavaScript operators. Note that this macro will have no effect on other\n     * operators than <code>==</code> or <code>!=</code>, but will recursively\n     * apply to all operators contained in the macro.\n     * \n     * <p>\n     * Since JSweet version 1.1, the Java expression <code>o1!=o2</code>\n     * transpiles to <code>o1!==o2</code> to remain close to the Java strict\n     * inequality (except when diffing with the <code>null</code> literal where\n     * the <code>==</code> operator is used).\n     * \n     * <p>\n     * Examples:\n     * \n     * <pre>\n     * if(a == b) { ... }\n     * if(a != b) { ... }\n     * if($loose(a == b)) { ... }\n     * if($loose(a != b)) { ... }\n     * if($strict(a == b)) { ... }\n     * if(a == undefined) { ... }\n     * if(a != null) { ... }\n     * if($strict(a != null)) { ... }\n     * if($loose(a == f(b != a))) { ... }\n     * </pre>\n     * \n     * Transpile to:\n     * \n     * <pre>\n     * if(a === b) { ... }\n     * if(a !== b) { ... }\n     * if(a == b) { ... }\n     * if(a != b) { ... }\n     * if(a === b) { ... }\n     * if(a === undefined) { ... }\n     * if(a != null) { ... }\n     * if(a !== null) { ... }\n     * if(a == f(b != a)) { ... }\n     * </pre>\n     * \n     * @param expression\n     *            can be any expression returning a boolean, but only\n     *            (in)equalities operators will be impacted\n     * @return the expression modified to use loose JavaScript (in)equalities\n     *         operators\n     * @since 2.0\n     */\n    native public static boolean $loose(boolean expression);\n\n    /**\n     * This syntax macro is the reverse of {@link #$loose(boolean)}, and\n     * enforces strict (in)equalities when it makes sense.\n     * \n     * @param expression\n     *            can be any expression returning a boolean, but only\n     *            (in)equalities operators will be impacted\n     * @return the expression modified to use strict JavaScript (in)equalities\n     *         operators\n     */\n    native public static boolean $strict(boolean expression);\n\n    /**\n     * Disable type checking on the target object (cast to any). This helper is\n     * valid in Java.\n     */\n    @SuppressWarnings(\"unchecked\")\n    public static <T> T any(Object object) {\n\treturn (T) object;\n    }\n\n    /**\n     * This helper function allows the programmer to reflectively set a global\n     * variable named <code>\"_exportedVar_\"+name</code>.\n     * \n     * <p>\n     * This function must only be used in specifically cases, typically to\n     * define results when testing from Java.\n     * \n     * @param name\n     *            the base name of the exported global variable, necessarily as\n     *            a string literal\n     * @param value\n     *            the value to set to the variable\n     */\n    public static void $export(String name, Object value) {\n\t// default Java implementation when running in Java (usually for testing\n\t// purposes)\n\tEXPORTED_VARS.get().put(\"_exportedVar_\" + name, value);\n    }\n\n    /**\n     * Accesses the current JavaScript <code>this</code>. Within an object\n     * scope, <code>$this</code> corresponds to a regular object oriented\n     * <code>this</code>. Outside on an object (i.e. within a global function),\n     * <code>$this</code> has the JavaScript meaning, representing the current\n     * function object.\n     */\n    public static final def.js.Object $this = null;\n\n    /**\n     * Defines a template string.\n     * \n     * <p>\n     * For example:\n     * \n     * <pre>\n     * console.info($template(\"Get: ${key} => ${_val}\"));\n     * </pre>\n     * \n     * <p>\n     * gets transpiled to:\n     * </p>\n     * \n     * <pre>\n     * console.info(`Get: ${key} => ${_val}`));\n     * </pre>\n     * \n     * @param templateString\n     *            the regular Java string to be turned into a template string\n     * @return a JavaScript template string\n     */\n    public static native String $template(String templateString);\n\n    /**\n     * Defines a template string with a tag.\n     * \n     * @see #$template(String)\n     */\n    public static native String $template(Object tag, String templateString);\n\n    /**\n     * Inserts a TypeScript string as is in the generated program (not\n     * recommended). This can be seen as a compile-time eval.\n     * \n     * <p>\n     * Although the TypeScript compiler will check the inserted code by\n     * compiling it, it is obviously a dangerous macro that should be used only\n     * in last resort.\n     * \n     * @see def.js.Globals#eval(String)\n     */\n    public static native <T> T $insert(String typescriptString);\n\n}\n", "human_rating": 3.42636910745187, "metadata": {"project": "jsweet", "class": "jsweet.util.Lang", "source_path": "Jsweet/sourcefiles/core-lib/es5/src/main/java/jsweet/util/Lang.java", "label_probabilities": {"readability": [0.426399, 0.573571, 3.00532e-05, 1.05187e-09], "understandability": [0.831352, 0.16864, 8.71507e-06, 8.88476e-13], "complexity": [0.0, 2.61077e-13, 0.00483114, 0.995169], "modularization": [5.30072e-11, 0.0102359, 0.684171, 0.305593], "overall": [0.00882751, 0.99115, 2.23127e-05, 1e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/org.jsweet.input.typescriptdef.parser.GenParser", "source": "/* \n * TypeScript definitions to Java translator - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *  \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\npackage org.jsweet.input.typescriptdef.parser;\n\npublic class GenParser {\n\n\tpublic static void main(String[] args) throws Exception {\n\t\tjava_cup.Main.main(new String[] { \"-expect\", \"0\", \"-package\", \"org.jsweet.input.typescriptdef.parser\", \"-expect\", \"0\", \"-parser\", \"TypescriptDefParser\",\n\t\t\t\t\"typescriptdef.cup\" });\n\t\tJFlex.Main.main(new String[] { \"typescriptdef.lex\" });\n\t}\n\t\n}\n", "human_rating": 3.9153708844086172, "metadata": {"project": "jsweet", "class": "org.jsweet.input.typescriptdef.parser.GenParser", "source_path": "Jsweet/sourcefiles/candy-generator/src/main/java/org/jsweet/input/typescriptdef/parser/GenParser.java", "label_probabilities": {"readability": [0.915374, 0.0846228, 3.242e-06, 4.08617e-10], "understandability": [0.703903, 0.293584, 0.00251276, 2.23845e-07], "complexity": [3.52432e-07, 0.00152765, 0.0530604, 0.945412], "modularization": [1.6961e-07, 0.000303995, 0.137422, 0.862274], "overall": [0.819319, 0.180645, 3.63084e-05, 4.06596e-14]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/org.jsweet.input.typescriptdef.visitor.TypeReferenceExpander", "source": "/* \n * TypeScript definitions to Java translator - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *  \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\npackage org.jsweet.input.typescriptdef.visitor;\n\nimport org.jsweet.JSweetDefTranslatorConfig;\nimport org.jsweet.input.typescriptdef.ast.Context;\nimport org.jsweet.input.typescriptdef.ast.Scanner;\nimport org.jsweet.input.typescriptdef.ast.Type;\nimport org.jsweet.input.typescriptdef.ast.TypeDeclaration;\nimport org.jsweet.input.typescriptdef.ast.TypeReference;\nimport org.jsweet.input.typescriptdef.util.Util;\n\n/**\n * This scanner expands the partial type references to fully qualified type\n * references, so that it is unambiguous to Java. It the case JSWeet is not in\n * JDK replacement mode, it also forces core types in the JSWeet's lang package\n * to reference java.lang package core types.\n * \n * @author Renaud Pawlak\n */\npublic class TypeReferenceExpander extends Scanner {\n\n\tprivate int typeCount = 0;\n\n\tpublic TypeReferenceExpander(Context context) {\n\t\tsuper(context);\n\t}\n\n\t@Override\n\tpublic void visitTypeReference(TypeReference typeReference) {\n\t\tif (typeReference.getName() != null) {\n\t\t\tif (!JSweetDefTranslatorConfig.isJDKReplacementMode() && !\"any\".equals(typeReference.getName())\n\t\t\t\t\t&& Util.coreTypeMap.containsKey(typeReference.getName())) {\n\t\t\t\tString name = Util.coreTypeMap.get(typeReference.getName());\n\t\t\t\ttypeCount++;\n\t\t\t\tif (context.verbose) {\n\t\t\t\t\tlogger.debug(\"WARNING: rewriting type ref \" + typeReference.getName() + \" -> \" + name + \" at \"\n\t\t\t\t\t\t\t+ getCurrentToken().getLocation());\n\t\t\t\t}\n\t\t\t\ttypeReference.setName(name);\n\t\t\t} else {\n\t\t\t\tif (typeReference.getName().contains(\".\")) {\n\t\t\t\t\tType t = lookupType(typeReference, null);\n\t\t\t\t\tif (t instanceof TypeDeclaration && !((TypeDeclaration) t).isExternal()) {\n\t\t\t\t\t\tTypeDeclaration typeDeclaration = (TypeDeclaration) t;\n\t\t\t\t\t\tString typeName = context.getTypeName(typeDeclaration);\n\t\t\t\t\t\tif (!typeName.equals(typeReference.getName())) {\n\t\t\t\t\t\t\ttypeCount++;\n\t\t\t\t\t\t\tif (context.verbose) {\n\t\t\t\t\t\t\t\tlogger.debug(\"WARNING: rewriting type ref \" + typeReference.getName() + \" -> \"\n\t\t\t\t\t\t\t\t\t\t+ typeName + \" at \" + getCurrentToken().getLocation());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttypeReference.setName(typeName);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsuper.visitTypeReference(typeReference);\n\t}\n\n\t@Override\n\tpublic void onScanEnded() {\n\t\tif (typeCount > 0) {\n\t\t\tlogger.debug(typeCount + \" type reference(s) rewritten/expanded.\");\n\t\t}\n\t}\n\n}\n", "human_rating": 2.1716152900000276, "metadata": {"project": "jsweet", "class": "org.jsweet.input.typescriptdef.visitor.TypeReferenceExpander", "source_path": "Jsweet/sourcefiles/candy-generator/src/main/java/org/jsweet/input/typescriptdef/visitor/TypeReferenceExpander.java", "label_probabilities": {"readability": [6.88315e-15, 0.175425, 0.820765, 0.00381029], "understandability": [0.0, 7.65177e-09, 1.0, 2.72932e-12], "complexity": [0.269265, 0.730735, 0.0, 0.0], "modularization": [0.0, 0.0530719, 0.946537, 0.000390736], "overall": [7.48278e-12, 0.254377, 0.745623, 7.82124e-08]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/org.jsweet.transpiler.extension.RemoveJavaDependenciesAdapter", "source": "/* \n * JSweet transpiler - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *  \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\npackage org.jsweet.transpiler.extension;\n\nimport static org.jsweet.JSweetConfig.isJDKPath;\n\nimport java.io.BufferedReader;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.lang.ref.WeakReference;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.nio.charset.Charset;\nimport java.text.Collator;\nimport java.util.AbstractList;\nimport java.util.AbstractMap;\nimport java.util.ArrayList;\nimport java.util.Calendar;\nimport java.util.Collection;\nimport java.util.Comparator;\nimport java.util.Deque;\nimport java.util.EnumSet;\nimport java.util.Enumeration;\nimport java.util.EventObject;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.HashSet;\nimport java.util.Hashtable;\nimport java.util.Iterator;\nimport java.util.LinkedHashMap;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.ListIterator;\nimport java.util.Locale;\nimport java.util.Map;\nimport java.util.Properties;\nimport java.util.Queue;\nimport java.util.Set;\nimport java.util.Stack;\nimport java.util.TimeZone;\nimport java.util.TreeMap;\nimport java.util.TreeSet;\nimport java.util.Vector;\nimport java.util.WeakHashMap;\n\nimport javax.lang.model.element.Modifier;\nimport javax.lang.model.element.TypeElement;\nimport javax.lang.model.type.ArrayType;\nimport javax.lang.model.type.DeclaredType;\nimport javax.lang.model.type.TypeMirror;\n\nimport org.jsweet.transpiler.JSweetContext;\nimport org.jsweet.transpiler.Java2TypeScriptTranslator;\nimport org.jsweet.transpiler.ModuleKind;\nimport org.jsweet.transpiler.model.BinaryOperatorElement;\nimport org.jsweet.transpiler.model.ExtendedElement;\nimport org.jsweet.transpiler.model.ExtendedElementFactory;\nimport org.jsweet.transpiler.model.ForeachLoopElement;\nimport org.jsweet.transpiler.model.ImportElement;\nimport org.jsweet.transpiler.model.LiteralElement;\nimport org.jsweet.transpiler.model.MethodInvocationElement;\nimport org.jsweet.transpiler.model.NewArrayElement;\nimport org.jsweet.transpiler.model.NewClassElement;\nimport org.jsweet.transpiler.model.VariableAccessElement;\nimport org.jsweet.transpiler.model.support.ForeachLoopElementSupport;\nimport org.jsweet.transpiler.util.Util;\n\nimport com.sun.tools.javac.tree.JCTree.JCEnhancedForLoop;\nimport com.sun.tools.javac.tree.JCTree.JCLiteral;\nimport com.sun.tools.javac.tree.JCTree.JCTypeApply;\n\n/**\n * An adapter that removes many uses of Java APIs and replace them with\n * JavaScript equivalent when possible.\n * \n * @author Renaud Pawlak\n */\npublic class RemoveJavaDependenciesAdapter extends Java2TypeScriptAdapter {\n\n\tprotected Map<String, String> extTypesMapping = new HashMap<>();\n\tprivate final String ERASED_CLASS_HIERARCHY_FIELD = \"__classes\";\n\tprivate Set<String> excludedJavaSuperTypes = new HashSet<>();\n\n\tpublic RemoveJavaDependenciesAdapter(JSweetContext context) {\n\t\tsuper(context);\n\t\tinit();\n\t}\n\n\tpublic RemoveJavaDependenciesAdapter(PrinterAdapter parentAdapter) {\n\t\tsuper(parentAdapter);\n\t\tinit();\n\t}\n\n\tprivate void init() {\n\t\taddTypeMapping(Class.class.getName(), \"any\");\n\t\tcontext.getLangTypeMappings().put(RuntimeException.class.getName(), \"Error\");\n\t\tcontext.getBaseThrowables().add(RuntimeException.class.getName());\n\n\t\textTypesMapping.put(List.class.getName(), \"Array\");\n\t\textTypesMapping.put(AbstractList.class.getName(), \"Array\");\n\t\textTypesMapping.put(ArrayList.class.getName(), \"Array\");\n\t\textTypesMapping.put(Iterable.class.getName(), \"Array\");\n\t\textTypesMapping.put(LinkedList.class.getName(), \"Array\");\n\t\textTypesMapping.put(Collection.class.getName(), \"Array\");\n\t\textTypesMapping.put(Set.class.getName(), \"Array\");\n\t\textTypesMapping.put(EnumSet.class.getName(), \"Array\");\n\t\textTypesMapping.put(Deque.class.getName(), \"Array\");\n\t\textTypesMapping.put(Queue.class.getName(), \"Array\");\n\t\textTypesMapping.put(Stack.class.getName(), \"Array\");\n\t\textTypesMapping.put(HashSet.class.getName(), \"Array\");\n\t\textTypesMapping.put(TreeSet.class.getName(), \"Array\");\n\t\textTypesMapping.put(Vector.class.getName(), \"Array\");\n\t\textTypesMapping.put(Enumeration.class.getName(), \"any\");\n\t\textTypesMapping.put(Iterator.class.getName(), \"any\");\n\t\textTypesMapping.put(ListIterator.class.getName(), \"any\");\n\t\textTypesMapping.put(Map.class.getName(), \"any\");\n\t\textTypesMapping.put(Properties.class.getName(), \"any\");\n\t\textTypesMapping.put(AbstractMap.class.getName(), \"any\");\n\t\textTypesMapping.put(HashMap.class.getName(), \"any\");\n\t\textTypesMapping.put(TreeMap.class.getName(), \"any\");\n\t\textTypesMapping.put(WeakHashMap.class.getName(), \"any\");\n\t\textTypesMapping.put(LinkedHashMap.class.getName(), \"any\");\n\t\textTypesMapping.put(Hashtable.class.getName(), \"any\");\n\t\textTypesMapping.put(Comparator.class.getName(), \"any\");\n\t\textTypesMapping.put(Exception.class.getName(), \"Error\");\n\t\textTypesMapping.put(RuntimeException.class.getName(), \"Error\");\n\t\textTypesMapping.put(Throwable.class.getName(), \"Error\");\n\t\textTypesMapping.put(Error.class.getName(), \"Error\");\n\t\textTypesMapping.put(StringBuffer.class.getName(), \"{ str: string, toString: Function }\");\n\t\textTypesMapping.put(StringBuilder.class.getName(), \"{ str: string, toString: Function }\");\n\t\textTypesMapping.put(Collator.class.getName(), \"any\");\n\t\textTypesMapping.put(Calendar.class.getName(), \"Date\");\n\t\textTypesMapping.put(GregorianCalendar.class.getName(), \"Date\");\n\t\textTypesMapping.put(TimeZone.class.getName(), \"string\");\n\t\textTypesMapping.put(Locale.class.getName(), \"string\");\n\t\textTypesMapping.put(Charset.class.getName(), \"string\");\n\t\textTypesMapping.put(Reader.class.getName(), \"{ str: string, cursor: number }\");\n\t\textTypesMapping.put(StringReader.class.getName(), \"{ str: string, cursor: number }\");\n\t\textTypesMapping.put(InputStream.class.getName(), \"{ str: string, cursor: number }\");\n\t\textTypesMapping.put(InputStreamReader.class.getName(), \"{ str: string, cursor: number }\");\n\t\textTypesMapping.put(BufferedReader.class.getName(), \"{ str: string, cursor: number }\");\n\n\t\textTypesMapping.put(Method.class.getName(), \"{ owner: any, name: string, fn : Function }\");\n\n\t\taddTypeMappings(extTypesMapping);\n\t\taddTypeMapping(\n\t\t\t\t(typeTree,\n\t\t\t\t\t\tname) -> name.startsWith(\"java.\")\n\t\t\t\t\t\t\t\t&& types().isSubtype(typeTree.getType(), util().getType(Throwable.class)) ? \"Error\"\n\t\t\t\t\t\t\t\t\t\t: null);\n\t\t// TODO: use standard API\n\t\t// addTypeMapping((typeTree,\n\t\t// name) -> typeTree.asType() instanceof DeclaredType\n\t\t// &&\n\t\t// WeakReference.class.getName().equals(types().getQualifiedName(typeTree.asType()))\n\t\t// ? ((DeclaredType) typeTree.asType()).getTypeArguments().get(0) :\n\t\t// null);\n\t\taddTypeMapping((typeTree,\n\t\t\t\tname) -> ExtendedElementFactory.toTree(typeTree) instanceof JCTypeApply && WeakReference.class.getName()\n\t\t\t\t\t\t.equals(ExtendedElementFactory.toTree(typeTree).type.tsym.getQualifiedName().toString())\n\t\t\t\t\t\t\t\t? ((JCTypeApply) ExtendedElementFactory.toTree(typeTree)).arguments.head\n\t\t\t\t\t\t\t\t: null);\n\t\texcludedJavaSuperTypes.add(EventObject.class.getName());\n\t}\n\n\t@Override\n\tpublic String needsImport(ImportElement importElement, String qualifiedName) {\n\t\tif (isJDKPath(qualifiedName)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn super.needsImport(importElement, qualifiedName);\n\t}\n\n\tprotected RemoveJavaDependenciesAdapter print(ExtendedElement expression, boolean delegate) {\n\t\tif (delegate) {\n\t\t\tprint(\"(<any>\").print(expression).print(\").__delegate\");\n\t\t} else {\n\t\t\tprint(expression);\n\t\t}\n\t\tdelegate = false;\n\t\treturn this;\n\t}\n\n\t@Override\n\tpublic boolean substituteMethodInvocation(MethodInvocationElement invocation) {\n\t\tString targetMethodName = invocation.getMethodName();\n\t\tString targetClassName = invocation.getMethod().getEnclosingElement().toString();\n\t\tExtendedElement targetExpression = invocation.getTargetExpression();\n\t\tif (targetExpression != null) {\n\t\t\ttargetClassName = targetExpression.getTypeAsElement().toString();\n\t\t}\n\t\tTypeMirror jdkSuperclass = context.getJdkSuperclass(targetClassName, excludedJavaSuperTypes);\n\t\tboolean delegate = jdkSuperclass != null;\n\t\tif (delegate) {\n\t\t\ttargetClassName = jdkSuperclass.toString();\n\t\t}\n\n\t\tif (targetClassName != null\n\t\t\t\t&& (targetExpression != null || invocation.getMethod().getModifiers().contains(Modifier.STATIC))) {\n\t\t\tswitch (targetClassName) {\n\n\t\t\tcase \"java.lang.Float\":\n\t\t\tcase \"java.lang.Double\":\n\t\t\tcase \"java.lang.Integer\":\n\t\t\tcase \"java.lang.Byte\":\n\t\t\tcase \"java.lang.Long\":\n\t\t\tcase \"java.lang.Short\":\n\t\t\t\tif (substituteMethodInvocationOnNumber(invocation, targetMethodName)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.lang.Character\":\n\t\t\t\tif (substituteMethodInvocationOnCharacter(invocation, targetMethodName)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.util.Collection\":\n\t\t\tcase \"java.util.List\":\n\t\t\tcase \"java.util.AbstractList\":\n\t\t\tcase \"java.util.AbstractSet\":\n\t\t\tcase \"java.util.AbstractCollection\":\n\t\t\tcase \"java.util.Queue\":\n\t\t\tcase \"java.util.Deque\":\n\t\t\tcase \"java.util.LinkedList\":\n\t\t\tcase \"java.util.ArrayList\":\n\t\t\tcase \"java.util.Stack\":\n\t\t\tcase \"java.util.Vector\":\n\t\t\tcase \"java.util.Set\":\n\t\t\tcase \"java.util.EnumSet\":\n\t\t\tcase \"java.util.HashSet\":\n\t\t\tcase \"java.util.TreeSet\":\n\t\t\t\tif (substituteMethodInvocationOnArray(invocation, targetMethodName, targetClassName, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"java.util.Properties\":\n\t\t\tcase \"java.util.Dictionary\":\n\t\t\tcase \"java.util.Map\":\n\t\t\tcase \"java.util.AbstractMap\":\n\t\t\tcase \"java.util.HashMap\":\n\t\t\tcase \"java.util.TreeMap\":\n\t\t\tcase \"java.util.Hashtable\":\n\t\t\tcase \"java.util.WeakHashMap\":\n\t\t\tcase \"java.util.LinkedHashMap\":\n\t\t\t\tif (substituteMethodInvocationOnMap(invocation, targetMethodName, targetExpression, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.util.Collections\":\n\t\t\t\tif (substituteMethodInvocationOnCollections(invocation, targetMethodName, targetExpression, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.util.Arrays\":\n\t\t\t\tif (substituteMethodInvocationOnArrays(invocation, targetMethodName, targetExpression, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.lang.System\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"arraycopy\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((srcPts, srcOff, dstPts, dstOff, size) => { if(srcPts !== dstPts || dstOff >= srcOff + size) { while (--size >= 0) dstPts[dstOff++] = srcPts[srcOff++];\"\n\t\t\t\t\t\t\t+ \"} else { let tmp = srcPts.slice(srcOff, srcOff + size); for (let i = 0; i < size; i++) dstPts[dstOff++] = tmp[i]; }})(\")\n\t\t\t\t\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"currentTimeMillis\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"Date.now()\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"nanoTime\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(Date.now() * 1000000)\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"java.util.Objects\":\n\t\t\t\tif (substituteMethodInvocationOnObjects(invocation, targetMethodName, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.lang.StringBuffer\":\n\t\t\tcase \"java.lang.StringBuilder\":\n\t\t\t\tif (substituteMethodInvocationOnStringBuilder(invocation, targetMethodName, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.lang.ref.WeakReference\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"get\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.text.Collator\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"getInstance\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((o1, o2) => o1.toString().localeCompare(o2.toString()))\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.nio.charset.Charset\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"forName\":\n\t\t\t\t\tprint(invocation.getArgument(0));\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.util.Locale\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"getDefault\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tgetPrinter().print(\"(window.navigator['userLanguage'] || window.navigator.language)\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.util.TimeZone\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"getTimeZone\":\n\t\t\t\t\tif (invocation.getArgumentCount() == 1) {\n\t\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\t\tprint(invocation.getArgument(0));\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"getDefault\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tgetPrinter().print(\"\\\"UTC\\\"\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"getID\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.util.Calendar\":\n\t\t\tcase \"java.util.GregorianCalendar\":\n\t\t\t\tif (substituteMethodInvocationOnCalendar(invocation, targetMethodName, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"java.io.Reader\":\n\t\t\tcase \"java.io.StringReader\":\n\t\t\tcase \"java.io.InputStream\":\n\t\t\tcase \"java.io.InputStreamReader\":\n\t\t\tcase \"java.io.BufferedReader\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"read\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(r => r.str.charCodeAt(r.cursor++))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"skip\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".cursor+=\")\n\t\t\t\t\t\t\t.print(invocation.getArgument(0));\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"reset\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".cursor=0\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"close\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\t// ignore but we could flag it and throw an error...\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.lang.ThreadLocal\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"get\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\n\t\t\t\t\tprint(\"((tlObj: any) => {\" //\n\t\t\t\t\t\t\t+ \"    if (tlObj.___value) { return tlObj.___value } \" //\n\t\t\t\t\t\t\t+ \"    else { return tlObj.___value = tlObj.initialValue() } \" //\n\t\t\t\t\t\t\t+ \"  })(\");\n\t\t\t\t\tprint(invocation.getTargetExpression());\n\t\t\t\t\tprint(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"java.lang.Class\":\n\t\t\t\tif (substituteMethodInvocationOnClass(invocation, targetMethodName, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"java.lang.reflect.Method\":\n\t\t\t\tif (substituteMethodInvocationOnMethod(invocation, targetMethodName, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"java.lang.reflect.Field\":\n\t\t\t\tif (substituteMethodInvocationOnField(invocation, targetMethodName, delegate)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"java.lang.reflect.Array\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"newInstance\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tif (invocation.getArgumentCount() == 2) {\n\t\t\t\t\t\tprint(\"new Array<any>(\").print(invocation.getArgument(1)).print(\")\");\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\tcase \"getLength\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(invocation.getArgument(0)).print(\".length\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"get\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(invocation.getArgument(0)).print(\"[\").print(invocation.getArgument(1)).print(\"]\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"set\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(\").print(invocation.getArgument(0)).print(\"[\").print(invocation.getArgument(1)).print(\"]=\")\n\t\t\t\t\t\t\t.print(invocation.getArgument(1)).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tcase \"java.lang.Math\":\n\t\t\tcase \"java.lang.StrictMath\":\n\t\t\t\tswitch (targetMethodName) {\n\t\t\t\tcase \"ulp\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((x) => { let buffer = new ArrayBuffer(8); let dataView = new DataView(buffer); dataView.setFloat64(0, x); let first = dataView.getUint32(0); let second = dataView.getUint32(4); let rawExponent = first & 0x7ff00000; if (rawExponent == 0x7ff00000) { dataView.setUint32(0,first & 0x7fffffff); } else if (rawExponent == 0) { dataView.setUint32(4,1); dataView.setUint32(0,0); } else if (rawExponent >= (52 << 20) + 0x00100000) { dataView.setUint32(0,rawExponent - (52 << 20)); dataView.setUint32(4,0); } else if (rawExponent >= (33 << 20)) { dataView.setUint32(0,1 << ((rawExponent - (33 << 20))  >>> 20 )); dataView.setUint32(4,0); } else { dataView.setUint32(4,1 << ((rawExponent - 0x00100000)  >>> 20)); dataView.setUint32(0,0); } return dataView.getFloat64(0); })(\")\n\t\t\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"IEEEremainder\":\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\t// credits: Ray Cromwell\n\t\t\t\t\tprint(\"((f1, f2) => { let r = Math.abs(f1 % f2); if (isNaN(r) || r == f2 || r <= Math.abs(f2) / 2.0) { return r; } else { return (f1 > 0 ? 1 : -1) * (r - f2); } })(\")\n\t\t\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch (targetMethodName) {\n\t\t\tcase \"clone\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tif (targetExpression != null && invocation.getTargetExpression().getType() instanceof ArrayType) {\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".slice(0)\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t}\n\n\t\treturn super.substituteMethodInvocation(invocation);\n\t}\n\n\tprotected boolean substituteMethodInvocationOnObjects(MethodInvocationElement invocation, String targetMethodName,\n\t\t\tboolean delegate) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"hash\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"0\");\n\t\t\treturn true;\n\t\tcase \"requireNonNull\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"if(\").print(invocation.getArgument(0)).print(\"==null){throw new Error('cannot be null')}\");\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnField(MethodInvocationElement invocation, String targetMethodName,\n\t\t\tboolean delegate) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"getName\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression()).print(\".name\");\n\t\t\treturn true;\n\t\tcase \"get\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getArgument(0)).print(\"[\").print(invocation.getTargetExpression()).print(\".name\")\n\t\t\t\t\t.print(\"]\");\n\t\t\treturn true;\n\t\tcase \"set\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(\").print(invocation.getArgument(0)).print(\"[\").print(invocation.getTargetExpression())\n\t\t\t\t\t.print(\".name\").print(\"]=\").print(invocation.getArgument(1)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"getDeclaringClass\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression()).print(\".owner\");\n\t\t\treturn true;\n\t\tcase \"setAccessible\":\n\t\t\t// ignore\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnMethod(MethodInvocationElement invocation, String targetMethodName,\n\t\t\tboolean delegate) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"getName\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression()).print(\".name\");\n\t\t\treturn true;\n\t\tcase \"invoke\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression()).print(\".fn.apply(\").print(invocation.getArgument(0));\n\t\t\tif (invocation.getArgumentCount() > 1) {\n\t\t\t\tprint(\", [\").printArgList(invocation.getArgumentTail()).print(\"]\");\n\t\t\t}\n\t\t\tprint(\")\");\n\t\t\treturn true;\n\t\tcase \"getDeclaringClass\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression()).print(\".owner\");\n\t\t\treturn true;\n\t\tcase \"setAccessible\":\n\t\t\t// ignore\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnClass(MethodInvocationElement invocation, String targetMethodName,\n\t\t\tboolean delegate) {\n\n\t\tswitch (targetMethodName) {\n\t\tcase \"forName\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (getContext().options.getModuleKind() != ModuleKind.none) {\n\t\t\t\tprint(\"eval(\").print(invocation.getArgument(0)).print(\".split('.').slice(-1)[0])\");\n\t\t\t} else {\n\t\t\t\tprint(\"eval(\").print(invocation.getArgument(0)).print(\")\");\n\t\t\t}\n\t\t\treturn true;\n\t\tcase \"newInstance\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"new (\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")(\").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"isInstance\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((c:any,o:any) => { if(typeof c === 'string') return (o.constructor && o.constructor\")\n\t\t\t\t\t.print(\"[\\\"\" + Java2TypeScriptTranslator.INTERFACES_FIELD_NAME + \"\\\"] && o.constructor\")\n\t\t\t\t\t.print(\"[\\\"\" + Java2TypeScriptTranslator.INTERFACES_FIELD_NAME + \"\\\"].indexOf(c) >= 0) || (o\")\n\t\t\t\t\t.print(\"[\\\"\" + Java2TypeScriptTranslator.INTERFACES_FIELD_NAME + \"\\\"] && o\")\n\t\t\t\t\t.print(\"[\\\"\" + Java2TypeScriptTranslator.INTERFACES_FIELD_NAME\n\t\t\t\t\t\t\t+ \"\\\"].indexOf(c) >= 0); else if(typeof c === 'function') return (o instanceof c) || (o.constructor && o.constructor === c); })(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"isPrimitive\":\n\t\t\t// primitive class types are never used in JSweet, so it\n\t\t\t// will always return false\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(\").print(invocation.getTargetExpression()).print(\" === <any>'__erasedPrimitiveType__'\").print(\")\");\n\t\t\treturn true;\n\t\tcase \"getMethods\":\n\t\tcase \"getDeclaredMethods\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(c => Object.getOwnPropertyNames(c.prototype).filter(n => typeof c.prototype[n] == 'function').map(n => ({owner:c,name:n,fn:c.prototype[n]}) ) )(\")\n\t\t\t\t\t.print(invocation.getTargetExpression()).print(\")\");\n\t\t\treturn true;\n\t\tcase \"getMethod\":\n\t\tcase \"getDeclaredMethod\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((c,p) => { if(c.prototype.hasOwnProperty(p) && typeof c.prototype[p] == 'function') return {owner:c,name:p,fn:c.prototype[p]}; else return null; })(\")\n\t\t\t\t\t.print(invocation.getTargetExpression()).print(\",\").print(invocation.getArgument(0)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"getField\":\n\t\tcase \"getDeclaredField\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((c,p) => { return {owner:c,name:p}; })(\").print(invocation.getTargetExpression()).print(\",\")\n\t\t\t\t\t.print(invocation.getArgument(0)).print(\")\");\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnArrays(MethodInvocationElement invocation, String targetMethodName,\n\t\t\tExtendedElement targetExpression, boolean delegate) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"asList\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (invocation.getArgumentCount() == 1 && invocation.getArgument(0).getType() instanceof ArrayType) {\n\t\t\t\tprintArgList(invocation.getArguments()).print(\".slice(0)\");\n\t\t\t} else {\n\t\t\t\tprint(\"[\").printArgList(invocation.getArguments()).print(\"]\");\n\t\t\t}\n\t\t\treturn true;\n\t\tcase \"copyOf\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getArgument(0)).print(\".slice(0,\").print(invocation.getArgument(1)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"fill\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a, v) => { for(let i=0;i<a.length;i++) a[i]=v; })(\").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\t// ES6 implementation\n\t\t\t// print(invocation.getArgument(0)).print(\".fill(\").printArgList(invocation.getArgumentTail())\n\t\t\t// .print(\")\");\n\t\t\treturn true;\n\t\tcase \"equals\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a1, a2) => { if(a1==null && a2==null) return true; if(a1==null || a2==null) return false; if(a1.length != a2.length) return false; for(let i = 0; i < a1.length; i++) { if(<any>a1[i] != <any>a2[i]) return false; } return true; })(\")\n\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")\");\n\t\t\treturn true;\n\t\tcase \"deepEquals\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(JSON.stringify(\").print(invocation.getArgument(0)).print(\") === JSON.stringify(\")\n\t\t\t\t\t.print(invocation.getArgument(1)).print(\"))\");\n\t\t\treturn true;\n\t\tcase \"sort\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (invocation.getArgumentCount() > 2) {\n\t\t\t\tprint(\"((arr, start, end, f?) => ((arr1, arr2) => arr1.splice.apply(arr1, (<any[]>[start, arr2.length]).concat(arr2)))(\")\n\t\t\t\t\t\t.print(invocation.getArgument(0)).print(\", \").print(invocation.getArgument(0))\n\t\t\t\t\t\t.print(\".slice(start, end).sort(f)))(\").printArgList(invocation.getArguments()).print(\")\");\n\t\t\t} else if (invocation.getArgumentCount() == 2) {\n\t\t\t\tprint(\"((l,c) => { if((<any>c).compare) l.sort((e1,e2)=>(<any>c).compare(e1,e2)); else l.sort(<any>c); })(\")\n\t\t\t\t\t\t.print(invocation.getArgument(0)).print(\",\").print(invocation.getArgument(1)).print(\")\");\n\t\t\t} else {\n\t\t\t\tprint(\"((l) => {l.sort(); })(\").print(invocation.getArgument(0)).print(\")\");\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnCollections(MethodInvocationElement invocation,\n\t\t\tString targetMethodName, ExtendedElement targetExpression, boolean delegate) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"emptyList\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"[]\");\n\t\t\treturn true;\n\t\tcase \"emptySet\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"[]\");\n\t\t\treturn true;\n\t\tcase \"emptyMap\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"{}\");\n\t\t\treturn true;\n\t\tcase \"unmodifiableList\":\n\t\tcase \"unmodifiableCollection\":\n\t\tcase \"unmodifiableSet\":\n\t\tcase \"unmodifiableSortedSet\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprintArgList(invocation.getArguments()).print(\".slice(0)\");\n\t\t\treturn true;\n\t\tcase \"singleton\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"[\").print(invocation.getArgument(0)).print(\"]\");\n\t\t\treturn true;\n\t\tcase \"singletonList\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"[\").print(invocation.getArgument(0)).print(\"]\");\n\t\t\treturn true;\n\t\tcase \"nCopies\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((n,v)=>{let c=[];for(let i=0;i<n;i++)c.push(v);return c;})(\");\n\t\t\tprint(invocation.getArgument(0));\n\t\t\tprint(\",\");\n\t\t\tprint(invocation.getArgument(1));\n\t\t\tprint(\")\");\n\t\t\treturn true;\n\t\tcase \"singletonMap\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (types().isSameType(invocation.getArgument(0).getType(), util().getType(String.class))) {\n\t\t\t\tif (invocation.getArgument(0) instanceof JCLiteral) {\n\t\t\t\t\tprint(\"{ \").print(invocation.getArgument(0)).print(\": \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\" }\");\n\t\t\t\t} else {\n\t\t\t\t\tprint(\"(k => { let o = {}; o[k] = \").print(invocation.getArgument(1)).print(\"; return o; })(\")\n\t\t\t\t\t\t\t.print(invocation.getArgument(0)).print(\")\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tprint(\"(k => { let o = {entries: [{getKey: function() { return this.key }, getValue: function() { return this.value },key:k, value:\")\n\t\t\t\t\t\t.print(invocation.getArgument(1)).print(\"}]}; return o; })(\").print(invocation.getArgument(0))\n\t\t\t\t\t\t.print(\")\");\n\t\t\t}\n\t\t\treturn true;\n\t\tcase \"binarySearch\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (invocation.getArgumentCount() == 3) {\n\t\t\t\tprint(\"((l, key, c) => { let comp : any = c; if(typeof c != 'function') { comp = (a,b)=>c.compare(a,b); } let low = 0; let high = l.length-1; while (low <= high) { let mid = (low + high) >>> 1; let midVal = l[mid]; \"\n\t\t\t\t\t\t+ \"let cmp = comp(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; } \"\n\t\t\t\t\t\t+ \"return -(low + 1); })(\").printArgList(invocation.getArguments()).print(\")\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tif (invocation.getArgumentCount() == 2) {\n\t\t\t\tif (util().isNumber(invocation.getArgument(1).getType())) {\n\t\t\t\t\tprint(\"((l, key) => { let comp = (a,b)=>a-b; let low = 0; let high = l.length-1; while (low <= high) { let mid = (low + high) >>> 1; let midVal = l[mid]; \"\n\t\t\t\t\t\t\t+ \"let cmp = comp(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; } \"\n\t\t\t\t\t\t\t+ \"return -(low + 1); })(\").printArgList(invocation.getArguments()).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\tprint(\"((l, key) => { let comp = (a,b)=>a.localeCompare(b); let low = 0; let high = l.length-1; while (low <= high) { let mid = (low + high) >>> 1; let midVal = l[mid]; \"\n\t\t\t\t\t\t\t+ \"let cmp = comp(midVal, key); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; } \"\n\t\t\t\t\t\t\t+ \"return -(low + 1); })(\").printArgList(invocation.getArguments()).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\tcase \"sort\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (invocation.getArgumentCount() == 2) {\n\t\t\t\tprint(\"((l,c) => { if((<any>c).compare) l.sort((e1,e2)=>(<any>c).compare(e1,e2)); else l.sort(<any>c); })(\")\n\t\t\t\t\t\t.print(invocation.getArgument(0)).print(\",\").print(invocation.getArgument(1)).print(\")\");\n\t\t\t} else {\n\t\t\t\tprint(invocation.getArgument(0)).print(\".sort(\").printArgList(invocation.getArgumentTail()).print(\")\");\n\t\t\t}\n\t\t\treturn true;\n\t\tcase \"reverse\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getArgument(0)).print(\".reverse()\");\n\t\t\treturn true;\n\t\tcase \"disjoint\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((c1, c2) => { for(let i=0;i<c1.length;i++) { if(c2.indexOf(<any>c1[i])>=0) return false; } return true; } )(\")\n\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")\");\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprivate boolean substituteMethodInvocationOnStringBuilder(MethodInvocationElement invocation,\n\t\t\tString targetMethodName, boolean delegate) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"append\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (invocation.getArgumentCount() == 1) {\n\t\t\t\tprint(\"(sb => { sb.str = sb.str.concat(<any>\").printArgList(invocation.getArguments())\n\t\t\t\t\t\t.print(\"); return sb; })(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t} else {\n\t\t\t\tprint(\"(sb => { sb.str = sb.str.concat((<any>\").print(invocation.getArgument(0)).print(\").substr(\")\n\t\t\t\t\t\t.printArgList(invocation.getArgumentTail()).print(\")); return sb; })(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t}\n\t\t\treturn true;\n\t\tcase \"insert\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((sb, index, c) => { sb.str = sb.str.substr(0, index) + c + sb.str.substr(index); return sb; })(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"setCharAt\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((sb, index, c) => sb.str = sb.str.substr(0, index) + c + sb.str.substr(index + 1))(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"deleteCharAt\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((sb, index) => { sb.str = sb.str.substr(0, index) + sb.str.substr(index + 1); return sb; })(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"delete\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((sb, i1, i2) => { sb.str = sb.str.substr(0, i1) + sb.str.substr(i2); return sb; })(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"length\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".str.length\");\n\t\t\treturn true;\n\t\tcase \"charAt\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".str.charAt(\").print(invocation.getArgument(0))\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"setLength\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((sb, length) => sb.str = sb.str.substring(0, length))(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"toString\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".str\");\n\t\t\treturn true;\n\t\tcase \"lastIndexOf\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".str.lastIndexOf(\").print(invocation.getArgument(0))\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"substring\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".str.substring(\").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnCalendar(MethodInvocationElement invocation, String targetMethodName,\n\t\t\tboolean delegate) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"set\":\n\t\t\tif (invocation.getArgumentCount() == 2) {\n\t\t\t\tString first = invocation.getArgument(0).toString();\n\t\t\t\tif (first.endsWith(\"YEAR\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((d, p) => d[\\\"UTC\\\"]?d.setUTCFullYear(p):d.setFullYear(p))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"DAY_OF_MONTH\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((d, p) => d[\\\"UTC\\\"]?d.setUTCDate(p):d.setDate(p))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"DAY_OF_WEEK\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((d, p) => d[\\\"UTC\\\"]?d.setUTCDay(p):d.setDay(p))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"MONTH\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((d, p) => d[\\\"UTC\\\"]?d.setUTCMonth(p):d.setMonth(p))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"HOUR_OF_DAY\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((d, p) => d[\\\"UTC\\\"]?d.setUTCHours(p):d.setHours(p))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"MINUTE\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((d, p) => d[\\\"UTC\\\"]?d.setUTCMinutes(p):d.setMinutes(p))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"MILLISECOND\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((d, p) => d[\\\"UTC\\\"]?d.setUTCMilliseconds(p):d.setMilliseconds(p))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"SECOND\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"((d, p) => d[\\\"UTC\\\"]?d.setUTCSeconds(p):d.setSeconds(p))(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(1))\n\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"get\":\n\t\t\tif (invocation.getArgumentCount() == 1) {\n\t\t\t\tString first = invocation.getArgument(0).toString();\n\t\t\t\tif (first.endsWith(\"YEAR\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(d => d[\\\"UTC\\\"]?d.getUTCFullYear():d.getFullYear())(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"DAY_OF_MONTH\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(d => d[\\\"UTC\\\"]?d.getUTCDate():d.getDate())(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"DAY_OF_WEEK\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(d => d[\\\"UTC\\\"]?d.getUTCDay():d.getDay())(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"MONTH\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(d => d[\\\"UTC\\\"]?d.getUTCMonth():d.getMonth())(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"HOUR_OF_DAY\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(d => d[\\\"UTC\\\"]?d.getUTCHours():d.getHours())(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"MINUTE\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(d => d[\\\"UTC\\\"]?d.getUTCMinutes():d.getMinutes())(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"MILLISECOND\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(d => d[\\\"UTC\\\"]?d.getUTCMilliseconds():d.getMilliseconds())(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (first.endsWith(\"SECOND\")) {\n\t\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\t\tprint(\"(d => d[\\\"UTC\\\"]?d.getUTCSeconds():d.getSeconds())(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"setTimeInMillis\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".setTime(\").print(invocation.getArgument(0))\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"getTimeInMillis\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".getTime()\");\n\t\t\treturn true;\n\t\tcase \"setTime\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".setTime(\").print(invocation.getArgument(0))\n\t\t\t\t\t.print(\".getTime())\");\n\t\t\treturn true;\n\t\tcase \"getTime\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(new Date(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".getTime()))\");\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnMap(MethodInvocationElement invocation, String targetMethodName,\n\t\t\tExtendedElement targetExpression, boolean delegate) {\n\t\tif (targetExpression == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (((DeclaredType) targetExpression.getType()).getTypeArguments().size() == 2 && types().isSameType(\n\t\t\t\t((DeclaredType) targetExpression.getType()).getTypeArguments().get(0), util().getType(String.class))) {\n\t\t\tswitch (targetMethodName) {\n\t\t\tcase \"put\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\"[\").print(invocation.getArgument(0))\n\t\t\t\t\t\t.print(\"] = \").print(invocation.getArgument(1)).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"get\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m,k) => m[k]===undefined?null:m[k])(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(0))\n\t\t\t\t\t\t.print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"containsKey\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".hasOwnProperty(\")\n\t\t\t\t\t\t.print(invocation.getArgument(0)).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"keySet\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"Object.keys(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"values\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(obj => Object.keys(obj).map(key => obj[key]))(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"size\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"Object.keys(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\").length\");\n\t\t\t\treturn true;\n\t\t\tcase \"isEmpty\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(Object.keys(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\").length == 0)\");\n\t\t\t\treturn true;\n\t\t\tcase \"remove\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(map => { let deleted = \");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\"[\").print(invocation.getArgument(0))\n\t\t\t\t\t\t.print(\"];\");\n\t\t\t\tprint(\"delete \");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\"[\").print(invocation.getArgument(0))\n\t\t\t\t\t\t.print(\"];\");\n\t\t\t\tprint(\"return deleted;})\").print(\"(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"clear\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(obj => { for (let member in obj) delete obj[member]; })(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"entrySet\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(o => { let s = []; for (let e in o) s.push({ k: e, v: o[e], getKey: function() { return this.k }, getValue: function() { return this.v } }); return s; })(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"clone\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(o => { let c = {}; for (let k in Object.keys(o)){ c[k] = o[k] } return c; })(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} else {\n\t\t\tString newEntry = \"{key:k,value:v,getKey: function() { return this.key }, getValue: function() { return this.value }}\";\n\t\t\tswitch (targetMethodName) {\n\t\t\tcase \"put\":\n\t\t\tcase \"setProperty\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m,k,v) => { if(m.entries==null) m.entries=[]; for(let i=0;i<m.entries.length;i++) if(m.entries[i].key.equals!=null && m.entries[i].key.equals(k) || m.entries[i].key===k) { m.entries[i].value=v; return; } m.entries.push(\"\n\t\t\t\t\t\t+ newEntry + \"); })(\").print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t\t.print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"get\":\n\t\t\tcase \"getProperty\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m,k) => { if(m.entries==null) m.entries=[]; for(let i=0;i<m.entries.length;i++) if(m.entries[i].key.equals!=null && m.entries[i].key.equals(k) || m.entries[i].key===k) { return m.entries[i].value; } return null; })(\")\n\t\t\t\t\t\t.print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t\t.print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"containsKey\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m,k) => { if(m.entries==null) m.entries=[]; for(let i=0;i<m.entries.length;i++) if(m.entries[i].key.equals!=null && m.entries[i].key.equals(k) || m.entries[i].key===k) { return true; } return false; })(\")\n\t\t\t\t\t\t.print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t\t.print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"keySet\":\n\t\t\tcase \"stringPropertyNames\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m) => { let r=[]; if(m.entries==null) m.entries=[]; for(let i=0;i<m.entries.length;i++) r.push(m.entries[i].key); return r; })(\")\n\t\t\t\t\t\t.print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"values\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m) => { let r=[]; if(m.entries==null) m.entries=[]; for(let i=0;i<m.entries.length;i++) r.push(m.entries[i].value); return r; })(\")\n\t\t\t\t\t\t.print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"size\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m) => { if(m.entries==null) m.entries=[]; return m.entries.length; })(\").print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"isEmpty\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m) => { if(m.entries==null) m.entries=[]; return m.entries.length == 0; })(\").print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"remove\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m,k) => { if(m.entries==null) m.entries=[]; for(let i=0;i<m.entries.length;i++) if(m.entries[i].key.equals!=null && m.entries[i].key.equals(k) || m.entries[i].key===k) { return m.entries.splice(i,1)[0]; } })(\")\n\t\t\t\t\t\t.print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t\t.print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"clear\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\").entries=[]\");\n\t\t\t\treturn true;\n\t\t\tcase \"entrySet\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"((m) => { if(m.entries==null) m.entries=[]; return m.entries; })(\").print(\"<any>\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\tcase \"clone\":\n\t\t\t\tprintMacroName(targetMethodName);\n\t\t\t\tprint(\"(m => { if(m.entries==null) m.entries=[]; let c = {entries: []}; for(let i=0;i<m.entries.length;i++) { let k = m.entries[i].key, v = m.entries[i].value; c.entries[i] = \"\n\t\t\t\t\t\t+ newEntry + \"; } return c; })(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnArray(MethodInvocationElement invocation, String targetMethodName,\n\t\t\tString targetClassName, boolean delegate) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"add\":\n\t\tcase \"addLast\":\n\t\tcase \"push\":\n\t\tcase \"addElement\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tswitch (targetClassName) {\n\t\t\tcase \"java.util.Set\":\n\t\t\tcase \"java.util.HashSet\":\n\t\t\tcase \"java.util.TreeSet\":\n\t\t\t\tprint(\"((s, e) => { if(s.indexOf(e)==-1) { s.push(e); return true; } else { return false; } })(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").print(invocation.getArgument(0))\n\t\t\t\t\t\t.print(\")\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (invocation.getArgumentCount() == 2) {\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".splice(\").print(invocation.getArgument(0))\n\t\t\t\t\t\t\t.print(\", 0, \").print(invocation.getArgument(1)).print(\")\");\n\t\t\t\t} else {\n\t\t\t\t\tprint(\"(\");\n\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".push(\")\n\t\t\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")>0)\");\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\tcase \"addAll\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (invocation.getArgumentCount() == 2) {\n\t\t\t\tprint(\"((l1, ndx, l2) => { for(let i=l2.length-1;i>=0;i--) l1.splice(ndx,0,l2[i]); })(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t\t.print(\")\");\n\t\t\t} else {\n\t\t\t\tprint(\"((l1, l2) => l1.push.apply(l1, l2))(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t\t.print(\")\");\n\t\t\t}\n\t\t\treturn true;\n\t\tcase \"pop\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".pop(\").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"peek\":\n\t\tcase \"lastElement\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((s) => { return s[s.length-1]; })(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\treturn true;\n\t\tcase \"remove\":\n\t\tcase \"removeFirst\": // in Deque\n\t\tcase \"removeElement\": // in Vector: functionally equivalent to List.remove(int idx)\n\t\t\tprintMacroName(targetMethodName);\n\t\t\t/* in Queue: interface contains a no-arg method remove()\n\t\t\t * which is functionally identical to Deque.removeFirst()\n\t\t\t */\n\t\t\tif (invocation.getArgumentCount() == 0) {\n\t\t\t\tprint(invocation.getTargetExpression(), delegate)\n\t\t\t\t\t.print(\".splice(0, 1)[0]\");\n\t\t\t} else if (Util.isNumber(invocation.getArgument(0).getType())\n\t\t\t\t\t&& types().isSubtype(types().erasure(invocation.getTargetExpression().getType()),\n\t\t\t\t\t\t\ttypes().erasure(util().getType(List.class)))) {\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".splice(\")\n\t\t\t\t\t\t.printArgList(invocation.getArguments()).print(\", 1)[0]\");\n\t\t\t} else {\n\t\t\t\tprint(\"(a => { let index = a.indexOf(\").print(invocation.getArgument(0))\n\t\t\t\t\t\t.print(\"); if(index>=0) { a.splice(index\").print(invocation.getArgumentCount() == 1 ? \"\" : \", \")\n\t\t\t\t\t\t.printArgList(invocation.getArgumentTail())\n\t\t\t\t\t\t.print(\", 1); return true; } else { return false; }})(\");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t}\n\t\t\treturn true;\n\t\tcase \"removeAll\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a, r) => { let b=false; for(let i=0;i<r.length;i++) { let ndx=a.indexOf(r[i]); if(ndx>=0) { a.splice(ndx, 1); b=true; } } return b; })(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\",\").print(invocation.getArgument(0)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"containsAll\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a, r) => { for(let i=0;i<r.length;i++) { if(a.indexOf(<any>r[i])<0) return false; } return true; } )(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\",\").print(invocation.getArgument(0)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"retainAll\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a, r) => { let b=false; for(let i=0;i<a.length;i++) { let ndx=r.indexOf(a[i]); if(ndx<0) { a.splice(i, 1); i--; b=true; } } return b; })(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\",\").print(invocation.getArgument(0)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"addFirst\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".unshift(\").print(invocation.getArgument(0))\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"poll\":\n\t\tcase \"pollFirst\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(a => a.length==0?null:a.shift())(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\treturn true;\n\t\tcase \"pollLast\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(a => a.length==0?null:a.pop())(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\treturn true;\n\t\tcase \"removeElementAt\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".splice(\").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\", 1)\");\n\t\t\treturn true;\n\t\tcase \"subList\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".slice(\").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\tcase \"size\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(<number>\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".length)\");\n\t\t\treturn true;\n\t\tcase \"get\":\n\t\tcase \"elementAt\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\"[\").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\"]\");\n\t\t\treturn true;\n\t\tcase \"set\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\"[\").print(invocation.getArgument(0)).print(\"] = \")\n\t\t\t\t\t.print(invocation.getArgument(1)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"clear\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".length = 0)\");\n\t\t\treturn true;\n\t\tcase \"isEmpty\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".length == 0)\");\n\t\t\treturn true;\n\t\tcase \"contains\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".indexOf(<any>(\").print(invocation.getArgument(0))\n\t\t\t\t\t.print(\")) >= 0)\");\n\t\t\treturn true;\n\t\tcase \"toArray\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tif (invocation.getArgumentCount() == 1) {\n\t\t\t\tExtendedElement e = invocation.getArgument(0);\n\t\t\t\tif (invocation.getTargetExpression() instanceof VariableAccessElement && e instanceof NewArrayElement) {\n\t\t\t\t\tNewArrayElement newArray = (NewArrayElement) e;\n\t\t\t\t\tboolean simplified = false;\n\t\t\t\t\tif (newArray.getDimensionCount() == 1) {\n\t\t\t\t\t\tExtendedElement d = newArray.getDimension(0);\n\t\t\t\t\t\tif (d.isConstant() && d.toString().equals(\"0\")) {\n\t\t\t\t\t\t\tsimplified = true;\n\t\t\t\t\t\t} else if (d instanceof MethodInvocationElement) {\n\t\t\t\t\t\t\tif (((MethodInvocationElement) d).getMethodName().equals(\"size\")\n\t\t\t\t\t\t\t\t\t&& ((MethodInvocationElement) d).getTargetExpression().toString()\n\t\t\t\t\t\t\t\t\t\t\t.equals(invocation.getTargetExpression().toString())) {\n\t\t\t\t\t\t\t\tsimplified = true;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (simplified) {\n\t\t\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".slice(0)\");\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprint(\"((a1, a2) => { if(a1.length >= a2.length) { a1.length=0; a1.push.apply(a1, a2); return a1; } else { return a2.slice(0); } })(\")\n\t\t\t\t\t\t.print(invocation.getArgument(0)).print(\", \");\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".slice(0)\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\tcase \"elements\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a) => { var i = 0; return { nextElement: function() { return i<a.length?a[i++]:null; }, hasMoreElements: function() { return i<a.length; }}})(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\treturn true;\n\t\tcase \"iterator\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a) => { var i = 0; return { next: function() { return i<a.length?a[i++]:null; }, hasNext: function() { return i<a.length; }}})(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\treturn true;\n\t\tcase \"listIterator\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a) => { var i = 0; return { next: function() { return i<a.length?a[i++]:null; }, hasNext: function() { return i<a.length; }}})(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\")\");\n\t\t\treturn true;\n\t\tcase \"ensureCapacity\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\treturn true;\n\t\tcase \"toString\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"('['+\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\".join(', ')+']')\");\n\t\t\treturn true;\n\t\tcase \"allOf\":\n\t\t\tprint(\"function() { \" + Java2TypeScriptTranslator.VAR_DECL_KEYWORD + \" result: number[] = []; for(\"\n\t\t\t\t\t+ Java2TypeScriptTranslator.VAR_DECL_KEYWORD + \" val in \").print(invocation.getArgument(0))\n\t\t\t\t\t\t\t.print(\") { if(!isNaN(<any>val)) { result.push(parseInt(val,10)); } } return result; }()\");\n\t\t\treturn true;\n\t\tcase \"equals\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((a1, a2) => { if(a1==null && a2==null) return true; if(a1==null || a2==null) return false; if(a1.length != a2.length) return false; for(let i = 0; i < a1.length; i++) { if(<any>a1[i] != <any>a2[i]) return false; } return true; })(\");\n\t\t\tprint(invocation.getTargetExpression(), delegate).print(\", \").printArgList(invocation.getArguments())\n\t\t\t\t\t.print(\")\");\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnNumber(MethodInvocationElement invocation, String targetMethodName) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"parseInt\":\n\t\tcase \"parseLong\":\n\t\tcase \"parseShort\":\n\t\tcase \"parseByte\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"parseInt\").print(\"(\").printArgList(invocation.getArguments()).print(\")\");\n\t\t\treturn true;\n\t\tcase \"parseFloat\":\n\t\tcase \"parseDouble\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"parseFloat\").print(\"(\").printArgList(invocation.getArguments()).print(\")\");\n\t\t\treturn true;\n\t\tcase \"floatToIntBits\":\n\t\tcase \"floatToRawIntBits\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((f) => { let buf = new ArrayBuffer(4); (new Float32Array(buf))[0]=f; return (new Uint32Array(buf))[0]; })(\")\n\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")\");\n\t\t\treturn true;\n\t\tcase \"intBitsToFloat\":\n\t\t\tprint(\"((v) => { let buf = new ArrayBuffer(4); (new Uint32Array(buf))[0]=v; return (new Float32Array(buf))[0]; })(\")\n\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")\");\n\t\t\treturn true;\n\t\tcase \"doubleToLongBits\":\n\t\tcase \"doubleToRawLongBits\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"((f) => { let buf = new ArrayBuffer(4); (new Float32Array(buf))[0]=f; return (new Uint32Array(buf))[0]; })((<any>Math).fround(\")\n\t\t\t\t\t.printArgList(invocation.getArguments()).print(\"))\");\n\t\t\treturn true;\n\t\tcase \"longBitsToDouble\":\n\t\t\tprint(\"((v) => { let buf = new ArrayBuffer(4); (new Uint32Array(buf))[0]=v; return (new Float32Array(buf))[0]; })(\")\n\t\t\t\t\t.printArgList(invocation.getArguments()).print(\")\");\n\t\t\treturn true;\n\t\tcase \"valueOf\":\n\t\t\tif (util().isNumber(invocation.getArgument(0).getType())) {\n\t\t\t\tprint(invocation.getArgument(0));\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tprint(\"parseFloat\").print(\"(\").printArgList(invocation.getArguments()).print(\")\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprotected boolean substituteMethodInvocationOnCharacter(MethodInvocationElement invocation,\n\t\t\tString targetMethodName) {\n\t\tswitch (targetMethodName) {\n\t\tcase \"isDigit\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"/\\\\d/.test(\").printArgList(invocation.getArguments()).print(\"[0])\");\n\t\t\treturn true;\n\t\tcase \"isLetter\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"/[a-zA-Z]/.test(\").printArgList(invocation.getArguments()).print(\"[0])\");\n\t\t\treturn true;\n\t\tcase \"isAlphabetic\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"/[a-zA-Z]/.test(\").printArgList(invocation.getArguments()).print(\"[0])\");\n\t\t\treturn true;\n\t\tcase \"isLetterOrDigit\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"/[a-zA-Z\\\\d]/.test(\").printArgList(invocation.getArguments()).print(\"[0])\");\n\t\t\treturn true;\n\t\tcase \"toLowerCase\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getArgument(0)).print(\".toLowerCase()\");\n\t\t\treturn true;\n\t\tcase \"toUpperCase\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getArgument(0)).print(\".toUpperCase()\");\n\t\t\treturn true;\n\t\tcase \"isLowerCase\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(s => s.toLowerCase() === s)(\").print(invocation.getArgument(0)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"isUpperCase\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(\"(s => s.toUpperCase() === s)(\").print(invocation.getArgument(0)).print(\")\");\n\t\t\treturn true;\n\t\tcase \"charValue\":\n\t\t\tprintMacroName(targetMethodName);\n\t\t\tprint(invocation.getTargetExpression());\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean substituteVariableAccess(VariableAccessElement variableAccess) {\n\t\tString targetClassName = variableAccess.getTargetElement().toString();\n\t\tString variableName = variableAccess.getVariableName();\n\t\tif (variableAccess.getVariable().getModifiers().contains(Modifier.STATIC) && isMappedType(targetClassName)\n\t\t\t\t&& targetClassName.startsWith(\"java.lang.\") && !\"class\".equals(variableName)) {\n\n\t\t\tswitch (targetClassName) {\n\t\t\tcase \"java.lang.Float\":\n\t\t\tcase \"java.lang.Double\":\n\t\t\tcase \"java.lang.Integer\":\n\t\t\tcase \"java.lang.Byte\":\n\t\t\tcase \"java.lang.Long\":\n\t\t\tcase \"java.lang.Short\":\n\t\t\t\tswitch (variableName) {\n\t\t\t\tcase \"MIN_VALUE\":\n\t\t\t\tcase \"MAX_VALUE\":\n\t\t\t\tcase \"POSITIVE_INFINITY\":\n\t\t\t\tcase \"NEGATIVE_INFINITY\":\n\n\t\t\t\t\ttry {\n\t\t\t\t\t\tField constantField = Class.forName(targetClassName).getDeclaredField(variableName);\n\t\t\t\t\t\tprint(\"\" + constantField.get(null));\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\tlogger.warn(\"unable to read Java constant value \" + targetClassName + \".\" + variableName, e);\n\t\t\t\t\t\tprint(\"Number.\" + variableName);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"NaN\":\n\t\t\t\t\tprint(\"NaN\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"java.lang.Boolean\":\n\t\t\t\tswitch (variableName) {\n\t\t\t\tcase \"TRUE\":\n\t\t\t\t\tprint(\"true\");\n\t\t\t\t\treturn true;\n\t\t\t\tcase \"FALSE\":\n\t\t\t\t\tprint(\"false\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\treturn super.substituteVariableAccess(variableAccess);\n\t}\n\n\t@Override\n\tpublic boolean substituteNewClass(NewClassElement newClass) {\n\t\tString className = newClass.getTypeAsElement().toString();\n\n\t\tTypeMirror jdkSuperclass = context.getJdkSuperclass(className, excludedJavaSuperTypes);\n\t\tboolean extendsJava = jdkSuperclass != null;\n\t\tif (extendsJava) {\n\t\t\tclassName = jdkSuperclass.toString();\n\t\t\tprint(\"(() => { let __o : any = new \").print(newClass.getConstructorAccess()).print(\"(\")\n\t\t\t\t\t.printArgList(newClass.getArguments()).print(\"); __o.__delegate = \");\n\t\t}\n\t\tboolean substitute = false;\n\n\t\tswitch (className) {\n\t\tcase \"java.lang.Integer\":\n\t\tcase \"java.lang.Long\":\n\t\tcase \"java.lang.Double\":\n\t\tcase \"java.lang.Float\":\n\t\tcase \"java.long.Short\":\n\t\tcase \"java.util.Byte\":\n\t\t\tprint(\"new Number(\").print(newClass.getArgument(0)).print(\").valueOf()\");\n\t\t\tsubstitute = true;\n\t\t\tbreak;\n\t\tcase \"java.util.ArrayList\":\n\t\tcase \"java.util.LinkedList\":\n\t\tcase \"java.util.Vector\":\n\t\tcase \"java.util.Stack\":\n\t\tcase \"java.util.TreeSet\":\n\t\tcase \"java.util.HashSet\":\n\t\tcase \"java.util.AbstractSet\":\n\t\tcase \"java.util.AbstractCollection\":\n\t\tcase \"java.util.AbstractList\":\n\t\tcase \"java.util.AbstractQueue\":\n\t\t\tif (newClass.getArgumentCount() == 0) {\n\t\t\t\tprint(\"[]\");\n\t\t\t} else {\n\t\t\t\tif (Util.isNumber(newClass.getArgument(0).getType())\n\t\t\t\t\t\t|| (newClass.getArgument(0) instanceof LiteralElement)) {\n\t\t\t\t\tprint(\"[]\");\n\t\t\t\t} else {\n\t\t\t\t\tprint(newClass.getArgument(0)).print(\".slice(0)\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tsubstitute = true;\n\t\t\tbreak;\n\t\tcase \"java.util.HashMap\":\n\t\tcase \"java.util.TreeMap\":\n\t\tcase \"java.util.Hashtable\":\n\t\tcase \"java.util.WeakHashMap\":\n\t\tcase \"java.util.LinkedHashMap\":\n\t\t\tif (newClass.getArgumentCount() == 0) {\n\t\t\t\tprint(\"{}\");\n\t\t\t} else {\n\t\t\t\tif (((DeclaredType) newClass.getType()).getTypeArguments().size() == 2 && types().isSameType(\n\t\t\t\t\t\t((DeclaredType) newClass.getType()).getTypeArguments().get(0), util().getType(String.class))) {\n\t\t\t\t\tprint(\"((o) => { let r = {}; for(let p in o) r[p]=o[p]; return r; })(\")\n\t\t\t\t\t\t\t.print(newClass.getArgument(0)).print(\")\");\n\t\t\t\t} else {\n\t\t\t\t\tprint(\"((o) => { let r = {}; r['entries'] = o.entries!=null?o.entries.slice():null; return r; })(\")\n\t\t\t\t\t\t\t.print(newClass.getArgument(0)).print(\")\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tsubstitute = true;\n\t\t\tbreak;\n\t\tcase \"java.lang.String\":\n\t\t\tif (newClass.getArgumentCount() == 0) {\n\t\t\t\tprint(\"\\\"\\\"\");\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tExtendedElement firstArgument = newClass.getArgument(0);\n\t\t\t\tif (firstArgument.getType() instanceof ArrayType) {\n\t\t\t\t\tif (util().isIntegral(((ArrayType) firstArgument.getType()).getComponentType())) {\n\t\t\t\t\t\tprint(\"String.fromCharCode.apply(null, \").print(firstArgument).print(\")\");\n\t\t\t\t\t\tif (newClass.getArgumentCount() >= 3 && util().isIntegral(newClass.getArgument(1).getType())\n\t\t\t\t\t\t\t\t&& util().isIntegral(newClass.getArgument(2).getType())) {\n\t\t\t\t\t\t\tprint(\".substr(\").print(newClass.getArgument(1)).print(\", \").print(newClass.getArgument(2))\n\t\t\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tprint(firstArgument).print(\".join('')\");\n\t\t\t\t\t\tif (newClass.getArgumentCount() >= 3 && util().isIntegral(newClass.getArgument(1).getType())\n\t\t\t\t\t\t\t\t&& util().isIntegral(newClass.getArgument(2).getType())) {\n\t\t\t\t\t\t\tprint(\".substr(\").print(newClass.getArgument(1)).print(\", \").print(newClass.getArgument(2))\n\t\t\t\t\t\t\t\t\t.print(\")\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t} else if (StringBuffer.class.getName().equals(firstArgument.getTypeAsElement().toString())\n\t\t\t\t\t\t|| StringBuilder.class.getName().equals(firstArgument.getTypeAsElement().toString())) {\n\t\t\t\t\tprint(firstArgument).print(\".str\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase \"java.lang.StringBuffer\":\n\t\tcase \"java.lang.StringBuilder\":\n\t\t\tif (newClass.getArgumentCount() == 0 || Util.isNumber(newClass.getArgument(0).getType())) {\n\t\t\t\tprint(\"{ str: \\\"\\\", toString: function() { return this.str; } }\");\n\t\t\t} else {\n\t\t\t\tprint(\"{ str: \").print(newClass.getArgument(0)).print(\", toString: function() { return this.str; } }\");\n\t\t\t}\n\t\t\tsubstitute = true;\n\t\t\tbreak;\n\t\tcase \"java.lang.ref.WeakReference\":\n\t\t\tprint(newClass.getArgument(0));\n\t\t\tsubstitute = true;\n\t\t\tbreak;\n\t\tcase \"java.io.StringReader\":\n\t\t\tprint(\"{ str: \").print(newClass.getArgument(0)).print(\", cursor: 0 }\");\n\t\t\tsubstitute = true;\n\t\t\tbreak;\n\t\tcase \"java.io.InputStreamReader\":\n\t\tcase \"java.io.BufferedReader\":\n\t\t\tprint(newClass.getArgument(0));\n\t\t\tsubstitute = true;\n\t\t\tbreak;\n\t\tcase \"java.util.GregorianCalendar\":\n\t\t\tif (newClass.getArgumentCount() == 0) {\n\t\t\t\tgetPrinter().print(\"new Date()\");\n\t\t\t\tsubstitute = true;\n\t\t\t\tbreak;\n\t\t\t} else if (newClass.getArgumentCount() == 1\n\t\t\t\t\t&& TimeZone.class.getName().equals(newClass.getArgument(0).getType().toString())) {\n\t\t\t\tif (newClass.getArgument(0) instanceof MethodInvocationElement) {\n\t\t\t\t\tMethodInvocationElement inv = (MethodInvocationElement) newClass.getArgument(0);\n\t\t\t\t\tif (inv.getMethodName().equals(\"getTimeZone\") && inv.getArgument(0) instanceof LiteralElement\n\t\t\t\t\t\t\t&& ((LiteralElement) inv.getArgument(0)).getValue().equals(\"UTC\")) {\n\t\t\t\t\t\tgetPrinter().print(\"(d => { d[\\\"UTC\\\"]=true; return d; })(new Date())\");\n\t\t\t\t\t\tsubstitute = true;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\n\t\tif (!extendsJava && className.startsWith(\"java.\")) {\n\t\t\tif (types().isSubtype(newClass.getType(), context.symtab.throwableType)) {\n\t\t\t\tprint(\"Object.defineProperty(\");\n\t\t\t\tprint(\"new Error(\");\n\t\t\t\tif (newClass.getArgumentCount() > 0) {\n\t\t\t\t\tif (String.class.getName().equals(newClass.getArgument(0).getType().toString())) {\n\t\t\t\t\t\tprint(newClass.getArgument(0));\n\t\t\t\t\t} else if (types().isSubtype(newClass.getArgument(0).getType(), context.symtab.throwableType)) {\n\t\t\t\t\t\tprint(newClass.getArgument(0)).print(\".message\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tprint(\")\");\n\t\t\t\tSet<String> classes = new HashSet<>();\n\t\t\t\tcontext.grabSuperClassNames(classes, newClass.getTypeAsElement());\n\t\t\t\tprint(\", '\" + ERASED_CLASS_HIERARCHY_FIELD + \"', { configurable: true, value: [\");\n\t\t\t\tfor (String c : classes) {\n\t\t\t\t\tprint(\"'\" + c + \"',\");\n\t\t\t\t}\n\t\t\t\tif (!classes.isEmpty()) {\n\t\t\t\t\tremoveLastChar();\n\t\t\t\t}\n\t\t\t\tprint(\"] })\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\tif (!substitute) {\n\t\t\tsubstitute = super.substituteNewClass(newClass);\n\t\t}\n\n\t\tif (extendsJava) {\n\t\t\tprint(\"; return __o; })()\");\n\t\t}\n\n\t\treturn substitute;\n\n\t}\n\n\t@Override\n\tpublic boolean substituteForEachLoop(ForeachLoopElement foreachLoop, boolean targetHasLength, String indexVarName) {\n\t\tJCEnhancedForLoop loop = ((ForeachLoopElementSupport) foreachLoop).getTree();\n\t\tif (!targetHasLength && !isJDKPath(loop.expr.type.toString())\n\t\t\t\t&& types().isSubtype(loop.expr.type, types().erasure(util().getType(Iterable.class)))) {\n\t\t\tprintForEachLoop(loop, indexVarName);\n\t\t\treturn true;\n\t\t}\n\t\t// return super.substituteForEachLoop(foreachLoop, targetHasLength,\n\t\t// indexVarName);\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean eraseSuperClass(TypeElement classdecl, TypeElement superClass) {\n\t\treturn superClass.getQualifiedName().toString().startsWith(\"java.\")\n\t\t\t\t&& !(superClass.asType().equals(context.symtab.throwableType)\n\t\t\t\t\t\t|| superClass.asType().equals(context.symtab.exceptionType)\n\t\t\t\t\t\t|| superClass.asType().equals(context.symtab.runtimeExceptionType)\n\t\t\t\t\t\t|| superClass.asType().equals(context.symtab.errorType))\n\t\t\t\t&& !Util.isSourceElement(superClass);\n\t}\n\n\t@Override\n\tpublic boolean eraseSuperInterface(TypeElement classdecl, TypeElement superInterface) {\n\t\treturn superInterface.getQualifiedName().toString().startsWith(\"java.\")\n\t\t\t\t&& !Util.isSourceElement(superInterface);\n\t}\n\n\t@Override\n\tpublic boolean isSubstituteSuperTypes() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean substituteInstanceof(String exprStr, ExtendedElement expr, TypeMirror typeMirror) {\n\t\tcom.sun.tools.javac.code.Type type = (com.sun.tools.javac.code.Type) typeMirror;\n\t\tString typeName = type.tsym.getQualifiedName().toString();\n\t\tif (typeName.startsWith(\"java.\") && context.types.isSubtype(type, context.symtab.throwableType)) {\n\t\t\tprint(exprStr, expr);\n\t\t\tprint(\" != null && \");\n\t\t\tprint(\"(\");\n\t\t\tprint(exprStr, expr);\n\t\t\tprint(\"[\\\"\" + ERASED_CLASS_HIERARCHY_FIELD + \"\\\"] && \");\n\t\t\tprint(exprStr, expr);\n\t\t\tprint(\"[\\\"\" + ERASED_CLASS_HIERARCHY_FIELD + \"\\\"].indexOf(\\\"\" + type.tsym.getQualifiedName().toString()\n\t\t\t\t\t+ \"\\\") >= 0\");\n\t\t\tprint(\")\");\n\t\t\tif (context.getBaseThrowables().contains(typeName)) {\n\t\t\t\tprint(\" || \");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\tString mappedType = extTypesMapping.get(typeName);\n\t\tif (\"string\".equals(mappedType)) {\n\t\t\tmappedType = \"String\";\n\t\t}\n\t\tif (\"boolean\".equals(mappedType)) {\n\t\t\tmappedType = \"Boolean\";\n\t\t}\n\t\tif (\"any\".equals(mappedType) || (mappedType != null && mappedType.startsWith(\"{\"))) {\n\t\t\tmappedType = \"Object\";\n\t\t}\n\t\tif (mappedType != null) {\n\t\t\tif (\"String\".equals(mappedType)) {\n\t\t\t\tprint(\"typeof \");\n\t\t\t\tprint(exprStr, expr);\n\t\t\t\tprint(\" === \").print(\"'string'\");\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\tprint(exprStr, expr);\n\t\t\t\tprint(\" != null && \");\n\t\t\t\tprint(\"(\");\n\t\t\t\tprint(exprStr, expr);\n\t\t\t\tprint(\" instanceof \" + mappedType);\n\t\t\t\tprint(\")\");\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn super.substituteInstanceof(exprStr, expr, type);\n\t}\n\n\t@Override\n\tpublic boolean substituteBinaryOperator(BinaryOperatorElement binaryOperator) {\n\t\tif (\"+\".equals(binaryOperator.getOperator())) {\n\t\t\tif (types().isSameType(util().getType(String.class), binaryOperator.getOperatorType().getReturnType())) {\n\t\t\t\tif (\"Array\".equals(\n\t\t\t\t\t\textTypesMapping.get(types().erasure(binaryOperator.getLeftHandSide().getType()).toString()))) {\n\t\t\t\t\tprint(\"/* implicit toString */ (a => a?'['+a.join(', ')+']':'null')(\")\n\t\t\t\t\t\t\t.print(binaryOperator.getLeftHandSide()).print(\") + \")\n\t\t\t\t\t\t\t.print(binaryOperator.getRightHandSide());\n\t\t\t\t\treturn true;\n\t\t\t\t} else if (\"Array\".equals(\n\t\t\t\t\t\textTypesMapping.get(types().erasure(binaryOperator.getRightHandSide().getType()).toString()))) {\n\t\t\t\t\tprint(binaryOperator.getLeftHandSide())\n\t\t\t\t\t\t\t.print(\" + /* implicit toString */ (a => a?'['+a.join(', ')+']':'null')(\")\n\t\t\t\t\t\t\t.print(binaryOperator.getRightHandSide()).print(\")\");\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn super.substituteBinaryOperator(binaryOperator);\n\t}\n\n}\n", "human_rating": 1.00024461676, "metadata": {"project": "jsweet", "class": "org.jsweet.transpiler.extension.RemoveJavaDependenciesAdapter", "source_path": "Jsweet/sourcefiles/transpiler/src/main/java/org/jsweet/transpiler/extension/RemoveJavaDependenciesAdapter.java", "label_probabilities": {"readability": [0.0, 0.000121611, 1.39188e-06, 0.999877], "understandability": [0.0, 0.0, 1.47304e-06, 0.999999], "complexity": [1.0, 3.0613e-11, 0.0, 0.0], "modularization": [0.987841, 0.0121585, 2.09339e-07, 0.0], "overall": [0.0, 5.38807e-09, 0.0188836, 0.981116]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/org.jsweet.transpiler.GlobalBeforeTranslationScanner", "source": "/* \n * JSweet transpiler - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *  \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\npackage org.jsweet.transpiler;\n\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport javax.lang.model.element.ElementKind;\nimport javax.lang.model.element.Modifier;\nimport javax.lang.model.element.TypeElement;\nimport javax.lang.model.type.TypeMirror;\n\nimport org.jsweet.JSweetConfig;\nimport org.jsweet.transpiler.util.AbstractTreeScanner;\nimport org.jsweet.transpiler.util.Util;\n\nimport com.sun.tools.javac.code.Symbol;\nimport com.sun.tools.javac.code.Symbol.ClassSymbol;\nimport com.sun.tools.javac.code.Symbol.MethodSymbol;\nimport com.sun.tools.javac.code.Symbol.VarSymbol;\nimport com.sun.tools.javac.code.Type;\nimport com.sun.tools.javac.tree.JCTree;\nimport com.sun.tools.javac.tree.JCTree.JCBlock;\nimport com.sun.tools.javac.tree.JCTree.JCClassDecl;\nimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;\nimport com.sun.tools.javac.tree.JCTree.JCLiteral;\nimport com.sun.tools.javac.tree.JCTree.JCMethodDecl;\nimport com.sun.tools.javac.tree.JCTree.JCVariableDecl;\nimport com.sun.tools.javac.tree.JCTree.JCWildcard;\n\n/**\n * This AST scanner performs global analysis and fills up the context with\n * information that will be used by the translator.\n * \n * @see JSweetContext\n * @author Renaud Pawlak\n */\npublic class GlobalBeforeTranslationScanner extends AbstractTreeScanner {\n\n\tSet<JCVariableDecl> lazyInitializedStaticCandidates = new HashSet<>();\n\n\t/**\n\t * Creates a new global scanner.\n\t */\n\tpublic GlobalBeforeTranslationScanner(TranspilationHandler logHandler, JSweetContext context) {\n\t\tsuper(logHandler, context, null);\n\t}\n\n\t@Override\n\tpublic void visitTopLevel(JCCompilationUnit topLevel) {\n\t\tif (topLevel.packge.getQualifiedName().toString().startsWith(JSweetConfig.LIBS_PACKAGE + \".\")) {\n\t\t\treturn;\n\t\t}\n\t\tthis.compilationUnit = topLevel;\n\t\tsuper.visitTopLevel(topLevel);\n\t}\n\n\t@Override\n\tpublic void visitClassDef(JCClassDecl classdecl) {\n\t\tif (getCompilationUnit().docComments.hasComment(classdecl)) {\n\t\t\tcontext.docComments.put(classdecl.sym, getCompilationUnit().docComments.getCommentText(classdecl));\n\t\t}\n\n\t\tTypeMirror superClassType = context.modelTypes.erasure(((TypeElement) classdecl.sym).getSuperclass());\n\t\tif (superClassType.toString().startsWith(\"java.\") && !superClassType.toString().equals(Object.class.getName())\n\t\t\t\t&& !context.types.isSubtype(classdecl.type, context.symtab.throwableType)\n\t\t\t\t&& !Util.isSourceElement(context.modelTypes.asElement(superClassType))) {\n\t\t\t// the class extends a JDK class\n\t\t\tcontext.addJdkSubclass(classdecl.sym.toString(), superClassType);\n\t\t}\n\n\t\tif (classdecl.sym.getEnclosingElement() instanceof ClassSymbol) {\n\t\t\tType superClass = ((ClassSymbol) classdecl.sym.getEnclosingElement()).getSuperclass();\n\t\t\tif (superClass != null && superClass.tsym != null) {\n\t\t\t\tClassSymbol clashingInnerClass = Util.findInnerClassDeclaration((ClassSymbol) superClass.tsym,\n\t\t\t\t\t\tclassdecl.name.toString());\n\t\t\t\tif (clashingInnerClass != null && !context.hasClassNameMapping(clashingInnerClass)) {\n\t\t\t\t\tcontext.addClassNameMapping(classdecl.sym,\n\t\t\t\t\t\t\t\"__\" + classdecl.sym.getEnclosingElement().getQualifiedName().toString().replace('.', '_')\n\t\t\t\t\t\t\t\t\t+ \"_\" + clashingInnerClass.getSimpleName());\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (classdecl.sym.getKind() == ElementKind.ANNOTATION_TYPE\n\t\t\t\t\t&& context.hasAnnotationType(classdecl.sym, JSweetConfig.ANNOTATION_DECORATOR)) {\n\t\t\t\tcontext.registerDecoratorAnnotation(classdecl);\n\t\t\t}\n\t\t}\n\n\t\tboolean globals = false;\n\t\tif (JSweetConfig.GLOBALS_CLASS_NAME.equals(classdecl.name.toString())) {\n\t\t\tglobals = true;\n\t\t}\n\n\t\tfor (JCTree def : classdecl.defs) {\n\t\t\tif (def instanceof JCVariableDecl) {\n\t\t\t\tJCVariableDecl var = (JCVariableDecl) def;\n\t\t\t\tif (getCompilationUnit().docComments.hasComment(var)) {\n\t\t\t\t\tcontext.docComments.put(var.sym, getCompilationUnit().docComments.getCommentText(var));\n\t\t\t\t}\n\n\t\t\t\tif (!context.hasFieldNameMapping(var.sym)) {\n\t\t\t\t\tVarSymbol clashingField = null;\n\t\t\t\t\tclashingField = Util.findFieldDeclaration((ClassSymbol) classdecl.sym.getSuperclass().tsym,\n\t\t\t\t\t\t\tvar.name);\n\t\t\t\t\tif (clashingField != null) {\n\t\t\t\t\t\tif (clashingField.isPrivate() && !context.hasFieldNameMapping(clashingField)) {\n\t\t\t\t\t\t\tcontext.addFieldNameMapping(var.sym, JSweetConfig.FIELD_METHOD_CLASH_RESOLVER_PREFIX\n\t\t\t\t\t\t\t\t\t+ classdecl.sym.toString().replace(\".\", \"_\") + \"_\" + var.name.toString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tMethodSymbol m = Util.findMethodDeclarationInType(context.types, classdecl.sym, var.name.toString(),\n\t\t\t\t\t\t\tnull);\n\t\t\t\t\tif (m != null) {\n\t\t\t\t\t\tcontext.addFieldNameMapping(var.sym,\n\t\t\t\t\t\t\t\tJSweetConfig.FIELD_METHOD_CLASH_RESOLVER_PREFIX + var.name.toString());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (var.getModifiers().getFlags().contains(Modifier.STATIC)) {\n\t\t\t\t\tif (!(var.getModifiers().getFlags().contains(Modifier.FINAL) && var.init != null\n\t\t\t\t\t\t\t&& var.init instanceof JCLiteral)) {\n\t\t\t\t\t\tlazyInitializedStaticCandidates.add(var);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else if (def instanceof JCBlock) {\n\t\t\t\tif (((JCBlock) def).isStatic()) {\n\t\t\t\t\tcontext.countStaticInitializer(classdecl.sym);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (globals && def instanceof JCMethodDecl) {\n\t\t\t\tif (((JCMethodDecl) def).sym.isStatic()) {\n\t\t\t\t\tcontext.registerGlobalMethod(classdecl, (JCMethodDecl) def);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tsuper.visitClassDef(classdecl);\n\t}\n\n\t@Override\n\tpublic void visitMethodDef(JCMethodDecl methodDecl) {\n\t\tif (getCompilationUnit().docComments.hasComment(methodDecl)) {\n\t\t\tcontext.docComments.put(methodDecl.sym, getCompilationUnit().docComments.getCommentText(methodDecl));\n\t\t}\n\n\t\tif (methodDecl.mods.getFlags().contains(Modifier.DEFAULT)) {\n\t\t\tgetContext().addDefaultMethod(compilationUnit, getParent(JCClassDecl.class), methodDecl);\n\t\t}\n\t\tif (!getContext().ignoreWildcardBounds) {\n\t\t\tscan(methodDecl.params);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void visitWildcard(JCWildcard wildcard) {\n\t\tSymbol container = null;\n\t\tJCMethodDecl method = getParent(JCMethodDecl.class);\n\t\tif (method != null) {\n\t\t\tcontainer = method.sym;\n\t\t}\n\t\tif (container != null) {\n\t\t\tgetContext().registerWildcard(container, wildcard);\n\t\t\tscan(wildcard.getBound());\n\t\t}\n\t}\n\n\tpublic void process(List<JCCompilationUnit> compilationUnits) {\n\t\tfor (JCCompilationUnit compilationUnit : compilationUnits) {\n\t\t\tscan(compilationUnit);\n\t\t}\n\t\tfor (JCVariableDecl var : lazyInitializedStaticCandidates) {\n\t\t\tif (context.getStaticInitializerCount(var.sym.enclClass()) == 0 && var.init == null\n\t\t\t\t\t|| Util.isLiteralExpression(var.init)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tcontext.lazyInitializedStatics.add(var.sym);\n\t\t}\n\t}\n\n}\n", "human_rating": 1.000920158, "metadata": {"project": "jsweet", "class": "org.jsweet.transpiler.GlobalBeforeTranslationScanner", "source_path": "Jsweet/sourcefiles/transpiler/src/main/java/org/jsweet/transpiler/GlobalBeforeTranslationScanner.java", "label_probabilities": {"readability": [0.0, 0.0, 0.000920079, 0.99908], "understandability": [0.0, 0.0, 5.59092e-13, 1.0], "complexity": [0.143674, 0.856326, 2.43863e-08, 0.0], "modularization": [0.0, 1.0, 3.68315e-07, 0.0], "overall": [0.0, 0.0, 0.984742, 0.0152579]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/org.jsweet.transpiler.JSweetTranspiler", "source": "/* \n * JSweet transpiler - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *  \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\npackage org.jsweet.transpiler;\n\nimport static java.util.Arrays.asList;\nimport static java.util.stream.Collectors.toList;\nimport static org.jsweet.transpiler.util.ProcessUtil.isVersionHighEnough;\nimport static org.jsweet.transpiler.util.Util.toJavaFileObjects;\n\nimport java.io.File;\nimport java.io.FileNotFoundException;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.io.UncheckedIOException;\nimport java.nio.charset.Charset;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.Comparator;\nimport java.util.HashSet;\nimport java.util.LinkedHashSet;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.Queue;\nimport java.util.Set;\nimport java.util.regex.Pattern;\nimport java.util.stream.Collectors;\nimport java.util.stream.Stream;\n\nimport javax.tools.JavaFileManager;\nimport javax.tools.JavaFileObject;\n\nimport org.apache.commons.io.FileUtils;\nimport org.apache.commons.lang3.ArrayUtils;\nimport org.apache.commons.lang3.StringUtils;\nimport org.apache.commons.lang3.SystemUtils;\nimport org.apache.log4j.Level;\nimport org.apache.log4j.LogManager;\nimport org.apache.log4j.Logger;\nimport org.jsweet.JSweetConfig;\nimport org.jsweet.transpiler.candy.CandyProcessor;\nimport org.jsweet.transpiler.eval.EvalOptions;\nimport org.jsweet.transpiler.eval.JavaEval;\nimport org.jsweet.transpiler.eval.JavaScriptEval;\nimport org.jsweet.transpiler.eval.JavaScriptEval.JavaScriptRuntime;\nimport org.jsweet.transpiler.extension.ExtensionManager;\nimport org.jsweet.transpiler.extension.PrinterAdapter;\nimport org.jsweet.transpiler.util.AbstractTreePrinter;\nimport org.jsweet.transpiler.util.DirectedGraph;\nimport org.jsweet.transpiler.util.DirectedGraph.Node;\nimport org.jsweet.transpiler.util.ErrorCountTranspilationHandler;\nimport org.jsweet.transpiler.util.EvaluationResult;\nimport org.jsweet.transpiler.util.Position;\nimport org.jsweet.transpiler.util.ProcessUtil;\nimport org.jsweet.transpiler.util.SourceMap;\nimport org.jsweet.transpiler.util.SourceMap.Entry;\nimport org.jsweet.transpiler.util.Util;\n\nimport com.google.debugging.sourcemap.FilePosition;\nimport com.google.debugging.sourcemap.SourceMapConsumerFactory;\nimport com.google.debugging.sourcemap.SourceMapFormat;\nimport com.google.debugging.sourcemap.SourceMapGenerator;\nimport com.google.debugging.sourcemap.SourceMapGeneratorFactory;\nimport com.google.debugging.sourcemap.SourceMapGeneratorV3;\nimport com.google.debugging.sourcemap.SourceMapping;\nimport com.google.debugging.sourcemap.proto.Mapping.OriginalMapping;\nimport com.google.gson.Gson;\nimport com.sun.tools.javac.code.Symbol;\nimport com.sun.tools.javac.code.Symbol.PackageSymbol;\nimport com.sun.tools.javac.comp.AttrContext;\nimport com.sun.tools.javac.comp.Env;\nimport com.sun.tools.javac.file.JavacFileManager;\nimport com.sun.tools.javac.main.JavaCompiler;\nimport com.sun.tools.javac.main.Option;\nimport com.sun.tools.javac.tree.JCTree;\nimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;\nimport com.sun.tools.javac.util.List;\nimport com.sun.tools.javac.util.Log;\nimport com.sun.tools.javac.util.Options;\n\n/**\n * The actual JSweet transpiler.\n * \n * <p>\n * Instantiate this class to transpile Java to TypeScript (phase 1), and\n * TypeScript to JavaScript (phase 2).\n * \n * <p>\n * There are 2 phases in JSweet transpilation:\n *\n * <ol>\n * <li>Java to TypeScript</li>\n * <li>TypeScript to JavaScript</li>\n * </ol>\n *\n * <p>\n * In phase 1, JSweet delegates to Javac and applies the\n * {@link Java2TypeScriptTranslator} AST visitor to print out the TypeScript\n * code. Before printing out the code, the transpiler first applies AST\n * visitors: {@link GlobalBeforeTranslationScanner},\n * {@link StaticInitilializerAnalyzer}, and {@link TypeChecker}. All external\n * referenced classes must be in the classpath for this phase to succeed. Note\n * that this generation is fully customizable with the\n * {@link org.jsweet.transpiler.extension} API.\n *\n * <p>\n * In phase 2, JSweet delegates to tsc (TypeScript). TypeScript needs to have a\n * TypeScript typing definition for all external classes. Existing JSweet\n * candies (http://www.jsweet.org/jsweet-candies/) are Maven artifacts that come\n * both with the compiled Java implementation/definition in a Jar, and the\n * associated TypeScript definitions for phase 2.\n * \n * @author Renaud Pawlak\n */\npublic class JSweetTranspiler implements JSweetOptions {\n\n\t/**\n\t * The TypeScript version to be installed/used with this version of JSweet\n\t * (WARNING: so far, having multiple JSweet versions for the same user account\n\t * may lead to performance issues - could be fixed if necessary).\n\t */\n\tpublic static final String TSC_VERSION = \"2.1\";\n\n\tstatic {\n\t\tif (!SystemUtils.IS_JAVA_1_8) {\n\t\t\tthrow new RuntimeException(\"JSweet is currently only supported for JDK8, please use JDK 8.\\n\" + //\n\t\t\t\t\t\"Please see this issue which asks for Java>8 support: https://github.com/cincheo/jsweet/issues/519\");\n\t\t}\n\n\t\tJSweetConfig.initClassPath(null);\n\t}\n\n\t/**\n\t * Gets the target version from a user-friendly descriptive string.\n\t */\n\tpublic static EcmaScriptComplianceLevel getEcmaTargetVersion(String targetVersion) {\n\t\ttry {\n\t\t\tEcmaScriptComplianceLevel ecmaScriptComplianceLevel = EcmaScriptComplianceLevel.valueOf(targetVersion);\n\t\t\treturn ecmaScriptComplianceLevel;\n\t\t} catch (IllegalArgumentException e) {\n\t\t\tthrow new RuntimeException(\"Invalid EcmaScript target version: \" + targetVersion);\n\t\t}\n\t}\n\n\t/**\n\t * The constant for the name of the directory that stores temporary files.\n\t */\n\tpublic static final String TMP_WORKING_DIR_NAME = \".jsweet\";\n\n\t/**\n\t * A constant that is used for exporting variables.\n\t * \n\t * @see TraceBasedEvaluationResult\n\t * @see #eval(TranspilationHandler, SourceFile...)\n\t */\n\tpublic static final String EXPORTED_VAR_BEGIN = \"EXPORT \";\n\t/**\n\t * A constant that is used for exporting variables.\n\t * \n\t * @see TraceBasedEvaluationResult\n\t * @see #eval(TranspilationHandler, SourceFile...)\n\t */\n\tpublic static final String EXPORTED_VAR_END = \";\";\n\tpublic static Pattern EXPORTED_VAR_REGEXP = Pattern.compile(EXPORTED_VAR_BEGIN + \"(\\\\w*)=(.*)\" + EXPORTED_VAR_END);\n\n\tprivate final static Logger logger = Logger.getLogger(JSweetTranspiler.class);\n\n\t/**\n\t * The name of the file generated in the root package to avoid the TypeScript\n\t * compiler to skip empty directories.\n\t * \n\t * @deprecated Use {@link TypeScript2JavaScriptWithTscTranspiler#TSCROOTFILE}\n\t *             instead\n\t */\n\tpublic final static String TSCROOTFILE = TypeScript2JavaScriptWithTscTranspiler.TSCROOTFILE;\n\n\tprivate JSweetFactory factory;\n\tprivate PrinterAdapter adapter;\n\tprivate long transpilationStartTimestamp;\n\n\tprivate JSweetContext context;\n\tprivate Options options;\n\tprivate JavaFileManager fileManager;\n\tprivate JavaCompiler compiler;\n\tprivate Log log;\n\tprivate CandyProcessor candiesProcessor;\n\tprivate boolean generateSourceMaps = false;\n\tprivate File workingDir;\n\tprivate File tsOutputDir;\n\tprivate File jsOutputDir;\n\tprivate String classPath;\n\tprivate boolean generateTsFiles = true;\n\tprivate boolean generateJsFiles = true;\n\tprivate boolean tscWatchMode = false;\n\tprivate final LinkedList<File> tsDefDirs = new LinkedList<>();\n\tprivate ModuleKind moduleKind = ModuleKind.none;\n\tprivate ModuleResolution moduleResolution = ModuleResolution.classic;\n\tprivate EcmaScriptComplianceLevel ecmaTargetVersion = EcmaScriptComplianceLevel.ES3;\n\tprivate boolean bundle = false;\n\tprivate String encoding = null;\n\tprivate boolean noRootDirectories = false;\n\tprivate boolean ignoreAssertions = true;\n\tprivate boolean ignoreJavaFileNameError = false;\n\tprivate boolean generateDeclarations = false;\n\tprivate File declarationsOutputDir;\n\tprivate boolean generateDefinitions = true;\n\tprivate ArrayList<File> jsLibFiles = new ArrayList<>();\n\tprivate File sourceRoot = null;\n\tprivate boolean ignoreTypeScriptErrors = false;\n\tprivate boolean ignoreJavaErrors = false;\n\tprivate boolean forceJavaRuntime = false;\n\tprivate boolean isUsingJavaRuntime = false;\n\tprivate File headerFile = null;\n\tprivate boolean debugMode = false;\n\tprivate boolean skipTypeScriptChecks = false;\n\tprivate boolean disableSingleFloatPrecision = false;\n\tprivate boolean ignoreCandiesTypeScriptDefinitions = false;\n\n\tprivate ArrayList<String> adapters = new ArrayList<>();\n\tprivate File configurationFile;\n\n\tprivate TypeScript2JavaScriptTranspiler ts2jsTranspiler = new TypeScript2JavaScriptWithTscTranspiler();\n\n\t/**\n\t * Manually sets the transpiler to use (or not use) a Java runtime.\n\t * \n\t * <p>\n\t * Calling this method is usually not needed since JSweet auto-detects the J4TS\n\t * candy. Use only to manually force the transpiler in a mode or another.\n\t */\n\tpublic void setUsingJavaRuntime(boolean usingJavaRuntime) {\n\t\tforceJavaRuntime = true;\n\t\tisUsingJavaRuntime = usingJavaRuntime;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"workingDir=\" + workingDir + \"\\ntsOutputDir=\" + tsOutputDir + \"\\njsOutputDir=\" + jsOutputDir\n\t\t\t\t+ \"\\nclassPath=\" + classPath + \"\\ngenerateJsFiles=\" + generateJsFiles + \"\\ntscWatchMode=\" + tscWatchMode\n\t\t\t\t+ \"\\ntsDefDirs=\" + tsDefDirs + \"\\nmoduleKind=\" + moduleKind + \"\\necmaTargertVersion=\"\n\t\t\t\t+ ecmaTargetVersion + \"\\nbundle=\" + bundle + \"\\nencoding=\" + encoding + \"\\nnoRootDirectories=\"\n\t\t\t\t+ noRootDirectories + \"\\nignoreAssertions=\" + ignoreAssertions + \"\\nignoreJavaFileNameError=\"\n\t\t\t\t+ ignoreJavaFileNameError + \"\\ngenerateDeclarations=\" + generateDeclarations\n\t\t\t\t+ \"\\ndeclarationsOutputDir=\" + declarationsOutputDir + \"\\ngenerateDefinitions=\" + generateDefinitions\n\t\t\t\t+ \"\\njsLibFiles=\" + jsLibFiles;\n\t}\n\n\t/**\n\t * Creates a JSweet transpiler, with the default values.\n\t * \n\t * <p>\n\t * TypeScript and JavaScript output directories are set to\n\t * <code>System.getProperty(\"java.io.tmpdir\")</code>. The classpath is set to\n\t * <code>System.getProperty(\"java.class.path\")</code>.\n\t * \n\t * @param factory the factory used to create the transpiler objects\n\t */\n\tpublic JSweetTranspiler(JSweetFactory factory) {\n\t\tthis(factory, new File(System.getProperty(\"java.io.tmpdir\")), null, null,\n\t\t\t\tSystem.getProperty(\"java.class.path\"));\n\t}\n\n\t/**\n\t * Creates a JSweet transpiler.\n\t * \n\t * @param factory                       the factory used to create the\n\t *                                      transpiler objects\n\t * @param tsOutputDir                   the directory where TypeScript files are\n\t *                                      written\n\t * @param jsOutputDir                   the directory where JavaScript files are\n\t *                                      written\n\t * @param extractedCandiesJavascriptDir see\n\t *                                      {@link #getExtractedCandyJavascriptDir()}\n\t * @param classPath                     the classpath as a string (check out\n\t *                                      system-specific requirements for Java\n\t *                                      classpathes)\n\t */\n\tpublic JSweetTranspiler(JSweetFactory factory, File tsOutputDir, File jsOutputDir,\n\t\t\tFile extractedCandiesJavascriptDir, String classPath) {\n\t\tthis(factory, null, tsOutputDir, jsOutputDir, extractedCandiesJavascriptDir, classPath);\n\t}\n\n\tprivate Map<String, Object> configuration;\n\n\tprivate File baseDirectory;\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate <T> T getMapValue(Map<String, Object> map, String key) {\n\t\treturn (T) map.get(key);\n\t}\n\n\t/**\n\t * Applies the current configuration map.\n\t */\n\tprivate void applyConfiguration() {\n\t\tif (configuration.containsKey(\"options\")) {\n\n\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\tMap<String, Object> options = (Map<String, Object>) configuration.get(\"options\");\n\n\t\t\tfor (String key : options.keySet()) {\n\t\t\t\tif (!ArrayUtils.contains(JSweetOptions.options, key)) {\n\t\t\t\t\tlogger.error(\"unsupported option: \" + key);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.bundle)) {\n\t\t\t\tsetBundle(getMapValue(options, JSweetOptions.bundle));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.noRootDirectories)) {\n\t\t\t\tsetNoRootDirectories(getMapValue(options, JSweetOptions.noRootDirectories));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.sourceMap)) {\n\t\t\t\tsetGenerateSourceMaps(getMapValue(options, JSweetOptions.sourceMap));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.module)) {\n\t\t\t\tsetModuleKind(ModuleKind.valueOf(getMapValue(options, JSweetOptions.module)));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.encoding)) {\n\t\t\t\tsetEncoding(getMapValue(options, JSweetOptions.encoding));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.enableAssertions)) {\n\t\t\t\tsetIgnoreAssertions(!(Boolean) getMapValue(options, JSweetOptions.enableAssertions));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.declaration)) {\n\t\t\t\tsetGenerateDeclarations(getMapValue(options, JSweetOptions.declaration));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.tsOnly)) {\n\t\t\t\tsetGenerateJsFiles(!(Boolean) getMapValue(options, JSweetOptions.tsOnly));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.ignoreDefinitions)) {\n\t\t\t\tsetGenerateDefinitions(!(Boolean) getMapValue(options, JSweetOptions.ignoreDefinitions));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.header)) {\n\t\t\t\tsetHeaderFile(new File((String) getMapValue(options, JSweetOptions.header)));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.disableSinglePrecisionFloats)) {\n\t\t\t\tsetDisableSinglePrecisionFloats(getMapValue(options, JSweetOptions.disableSinglePrecisionFloats));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.targetVersion)) {\n\t\t\t\tsetEcmaTargetVersion(\n\t\t\t\t\t\tJSweetTranspiler.getEcmaTargetVersion(getMapValue(options, JSweetOptions.targetVersion)));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.tsout)) {\n\t\t\t\tsetTsOutputDir(new File((String) getMapValue(options, JSweetOptions.tsout)));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.dtsout)) {\n\t\t\t\tsetDeclarationsOutputDir(new File((String) getMapValue(options, JSweetOptions.dtsout)));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.jsout)) {\n\t\t\t\tsetJsOutputDir(new File((String) getMapValue(options, JSweetOptions.jsout)));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.candiesJsOut)) {\n\t\t\t\tsetJsOutputDir(new File((String) getMapValue(options, JSweetOptions.candiesJsOut)));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.moduleResolution)) {\n\t\t\t\tsetModuleResolution(getMapValue(options, JSweetOptions.moduleResolution));\n\t\t\t}\n\t\t\tif (options.containsKey(JSweetOptions.extraSystemPath)) {\n\t\t\t\tProcessUtil.addExtraPath(extraSystemPath);\n\t\t\t}\n\t\t}\n\n\t}\n\n\t/**\n\t * Reads configuration from current configuration file.\n\t */\n\tprivate void readConfiguration() {\n\t\tFile confFile = configurationFile == null ? new File(baseDirectory, JSweetConfig.CONFIGURATION_FILE_NAME)\n\t\t\t\t: configurationFile;\n\t\tif (confFile.exists()) {\n\t\t\ttry {\n\t\t\t\tlogger.info(\"configuration file found: \" + confFile);\n\t\t\t\t@SuppressWarnings(\"unchecked\")\n\t\t\t\tMap<String, Object> fromJson = new Gson().fromJson(FileUtils.readFileToString(confFile), Map.class);\n\t\t\t\tconfiguration = fromJson;\n\t\t\t\tlogger.debug(\"configuration: \" + configuration);\n\t\t\t\tapplyConfiguration();\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.warn(\"error reading configuration file\", e);\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.info(\"no configuration file found at \" + confFile.getAbsolutePath());\n\t\t}\n\t}\n\n\t/**\n\t * Creates a JSweet transpiler.\n\t * \n\t * @param factory                       the factory used to create the\n\t *                                      transpiler objects\n\t * @param workingDir                    the working directory (uses default one\n\t *                                      if null)\n\t * @param tsOutputDir                   the directory where TypeScript files are\n\t *                                      written\n\t * @param jsOutputDir                   the directory where JavaScript files are\n\t *                                      written\n\t * @param extractedCandiesJavascriptDir see\n\t *                                      {@link #getExtractedCandyJavascriptDir()}\n\t * @param classPath                     the classpath as a string (check out\n\t *                                      system-specific requirements for Java\n\t *                                      classpaths)\n\t */\n\tpublic JSweetTranspiler(JSweetFactory factory, File workingDir, File tsOutputDir, File jsOutputDir,\n\t\t\tFile extractedCandiesJavascriptDir, String classPath) {\n\t\tthis(null, factory, workingDir, tsOutputDir, tsOutputDir, extractedCandiesJavascriptDir, classPath);\n\t}\n\n\t/**\n\t * Creates a JSweet transpiler.\n\t * \n\t * @param configurationFile             the configurationFile (uses default one\n\t *                                      if null)\n\t * @param factory                       the factory used to create the\n\t *                                      transpiler objects\n\t * @param workingDir                    the working directory (uses default one\n\t *                                      if null)\n\t * @param tsOutputDir                   the directory where TypeScript files are\n\t *                                      written\n\t * @param jsOutputDir                   the directory where JavaScript files are\n\t *                                      written\n\t * @param extractedCandiesJavascriptDir see\n\t *                                      {@link #getExtractedCandyJavascriptDir()}\n\t * @param classPath                     the classpath as a string (check out\n\t *                                      system-specific requirements for Java\n\t *                                      classpaths)\n\t */\n\tpublic JSweetTranspiler(File configurationFile, JSweetFactory factory, File workingDir, File tsOutputDir,\n\t\t\tFile jsOutputDir, File extractedCandiesJavascriptDir, String classPath) {\n\t\tthis(null, configurationFile, factory, workingDir, tsOutputDir, jsOutputDir, extractedCandiesJavascriptDir,\n\t\t\t\tclassPath);\n\t}\n\n\t/**\n\t * Creates a JSweet transpiler.\n\t * \n\t * @param configurationFile             the configurationFile (uses default one\n\t *                                      if null)\n\t * @param factory                       the factory used to create the\n\t *                                      transpiler objects\n\t * @param workingDir                    the working directory (uses default one\n\t *                                      if null)\n\t * @param tsOutputDir                   the directory where TypeScript files are\n\t *                                      written\n\t * @param jsOutputDir                   the directory where JavaScript files are\n\t *                                      written\n\t * @param extractedCandiesJavascriptDir see\n\t *                                      {@link #getExtractedCandyJavascriptDir()}\n\t * @param classPath                     the classpath as a string (check out\n\t *                                      system-specific requirements for Java\n\t *                                      classpaths)\n\t */\n\tpublic JSweetTranspiler(File baseDirectory, File configurationFile, JSweetFactory factory, File workingDir,\n\t\t\tFile tsOutputDir, File jsOutputDir, File extractedCandiesJavascriptDir, String classPath) {\n\t\tif (baseDirectory == null) {\n\t\t\tbaseDirectory = new File(\".\");\n\t\t}\n\t\tthis.baseDirectory = baseDirectory;\n\t\tthis.baseDirectory.mkdirs();\n\n\t\tthis.configurationFile = configurationFile;\n\t\tthis.factory = factory;\n\t\treadConfiguration();\n\t\tif (tsOutputDir == null) {\n\t\t\ttsOutputDir = new File(baseDirectory, \"target/ts\");\n\t\t}\n\t\tthis.workingDir = workingDir == null ? new File(baseDirectory, TMP_WORKING_DIR_NAME).getAbsoluteFile()\n\t\t\t\t: workingDir.getAbsoluteFile();\n\t\tthis.extractedCandyJavascriptDir = extractedCandiesJavascriptDir;\n\t\ttry {\n\t\t\ttsOutputDir.mkdirs();\n\t\t\tthis.tsOutputDir = tsOutputDir.getCanonicalFile();\n\t\t\tif (jsOutputDir != null && generateJsFiles) {\n\t\t\t\tjsOutputDir.mkdirs();\n\t\t\t\tthis.jsOutputDir = jsOutputDir.getCanonicalFile();\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new RuntimeException(\"cannot locate output dirs\", e);\n\t\t}\n\n\t\tFile extensionDirectory = new File(baseDirectory, JSweetConfig.EXTENSION_DIR);\n\n\t\tclassPath = classPath == null ? System.getProperty(\"java.class.path\") : classPath;\n\t\tclassPath = extensionDirectory.getAbsolutePath() + File.pathSeparator + classPath;\n\t\tthis.classPath = classPath;\n\n\t\tlogger.info(\"creating transpiler version \" + JSweetConfig.getVersionNumber() + \" (build date: \"\n\t\t\t\t+ JSweetConfig.getBuildDate() + \")\");\n\t\tlogger.info(\"current dir: \" + new File(\".\").getAbsolutePath());\n\t\tlogger.info(\"base directory: \" + this.baseDirectory.getAbsolutePath());\n\t\tlogger.info(\"working directory: \" + this.workingDir.getAbsolutePath());\n\t\tlogger.info(\"tsOut: \" + tsOutputDir + (tsOutputDir == null ? \"\" : \" - \" + tsOutputDir.getAbsolutePath()));\n\t\tlogger.info(\"jsOut: \" + jsOutputDir + (jsOutputDir == null ? \"\" : \" - \" + jsOutputDir.getAbsolutePath()));\n\t\tlogger.info(\"candyJsOut: \" + extractedCandiesJavascriptDir);\n\t\tlogger.info(\"factory: \" + factory);\n\t\tlogger.debug(\"compile classpath: \" + classPath);\n\t\tlogger.debug(\"runtime classpath: \" + System.getProperty(\"java.class.path\"));\n\t\tlogger.debug(\"extension directory: \" + extensionDirectory.getAbsolutePath());\n\t\tthis.candiesProcessor = new CandyProcessor(this.workingDir, classPath, extractedCandyJavascriptDir);\n\n\t\tnew ExtensionManager(extensionDirectory.getAbsolutePath()).checkAndCompileExtension(this.workingDir, classPath);\n\t}\n\n\t/**\n\t * Gets this transpiler working directory (where the temporary files are\n\t * stored).\n\t */\n\tpublic File getWorkingDirectory() {\n\t\treturn this.workingDir;\n\t}\n\n\tpublic void initNode(TranspilationHandler transpilationHandler) throws Exception {\n\t\tProcessUtil.initNode();\n\n\t\tFile initFile = new File(workingDir, \".node-init\");\n\t\tboolean initialized = initFile.exists();\n\t\tif (!initialized) {\n\t\t\tProcessUtil.runCommand(ProcessUtil.NODE_COMMAND, currentNodeVersion -> {\n\t\t\t\tlogger.info(\"node version: \" + currentNodeVersion);\n\n\t\t\t\tif (!isVersionHighEnough(currentNodeVersion, ProcessUtil.NODE_MINIMUM_VERSION)) {\n\t\t\t\t\ttranspilationHandler.report(JSweetProblem.NODE_OBSOLETE_VERSION, null,\n\t\t\t\t\t\t\tJSweetProblem.NODE_OBSOLETE_VERSION.getMessage(currentNodeVersion,\n\t\t\t\t\t\t\t\t\tProcessUtil.NODE_MINIMUM_VERSION));\n\t\t\t\t\t// throw new RuntimeException(\"node.js version is obsolete,\n\t\t\t\t\t// minimum version: \" + ProcessUtil.NODE_MINIMUM_VERSION);\n\t\t\t\t}\n\n\t\t\t}, () -> {\n\t\t\t\ttranspilationHandler.report(JSweetProblem.NODE_CANNOT_START, null,\n\t\t\t\t\t\tJSweetProblem.NODE_CANNOT_START.getMessage());\n\t\t\t\tthrow new RuntimeException(\"cannot find node.js\");\n\t\t\t}, \"--version\");\n\t\t\tinitFile.mkdirs();\n\t\t\tinitFile.createNewFile();\n\t\t}\n\n\t\tString v = \"\";\n\t\tFile tscVersionFile = new File(ProcessUtil.NPM_DIR, \"tsc-version\");\n\t\tif (tscVersionFile.exists()) {\n\t\t\tv = FileUtils.readFileToString(tscVersionFile);\n\t\t}\n\t\tif (!ProcessUtil.isInstalledWithNpm(\"tsc\") || !v.trim().startsWith(TSC_VERSION)) {\n\t\t\t// this will lead to performances issues if having multiple versions\n\t\t\t// of JSweet installed\n\t\t\tif (ProcessUtil.isInstalledWithNpm(\"tsc\")) {\n\t\t\t\tProcessUtil.uninstallNodePackage(\"typescript\", true);\n\t\t\t}\n\t\t\tProcessUtil.installNodePackage(\"typescript\", TSC_VERSION, true);\n\t\t\tFileUtils.writeStringToFile(tscVersionFile, TSC_VERSION);\n\t\t}\n\t}\n\n\t/**\n\t * Sets one or more directories that contain TypeScript definition files\n\t * (sub-directories are scanned recursively to find all .d.ts files).\n\t * \n\t * @param tsDefDirs a list of directories to scan for .d.ts files\n\t */\n\tpublic void setTsDefDirs(File... tsDefDirs) {\n\t\tclearTsDefDirs();\n\t\tthis.tsDefDirs.addAll(Arrays.asList(tsDefDirs));\n\t}\n\n\t/**\n\t * Adds a directory that contains TypeScript definition files (sub-directories\n\t * are scanned recursively to find all .d.ts files).\n\t * \n\t * @param tsDefDir a directory to scan for .d.ts files\n\t */\n\tpublic void addTsDefDir(File tsDefDir) {\n\t\tif (!tsDefDirs.contains(tsDefDir)) {\n\t\t\ttsDefDirs.add(tsDefDir);\n\t\t}\n\t}\n\n\t/**\n\t * Undo previous calls to {@link #setTsDefDirs(File...)} and\n\t * {@link #addTsDefDir(File)}.\n\t */\n\tpublic void clearTsDefDirs() {\n\t\ttsDefDirs.clear();\n\t}\n\n\tprivate void initJavac(final TranspilationHandler transpilationHandler) {\n\t\tcontext = factory.createContext(this);\n\t\tcontext.setUsingJavaRuntime(forceJavaRuntime ? isUsingJavaRuntime\n\t\t\t\t: (candiesProcessor == null ? false : candiesProcessor.isUsingJavaRuntime()));\n\t\tadapter = factory.createAdapter(context);\n\t\toptions = Options.instance(context);\n\t\tif (classPath != null) {\n\t\t\toptions.put(Option.CLASSPATH, classPath);\n\t\t\tfor (String s : classPath.split(File.pathSeparator)) {\n\t\t\t\tif (s.contains(JSweetConfig.MAVEN_JAVA_OVERRIDE_ARTIFACT)) {\n\t\t\t\t\tcontext.strictMode = true;\n\t\t\t\t\toptions.put(Option.BOOTCLASSPATH, s);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (encoding != null) {\n\t\t\toptions.put(Option.ENCODING, encoding);\n\t\t}\n\t\tlogger.debug(\"encoding: \" + options.get(Option.ENCODING));\n\t\t// this is too verbose for Travis...\n\t\t// logger.debug(\"classpath: \" + options.get(Option.CLASSPATH));\n\t\t// logger.debug(\"bootclasspath: \" + options.get(Option.BOOTCLASSPATH));\n\t\tlogger.debug(\"strict mode: \" + context.strictMode);\n\t\toptions.put(Option.XLINT, \"path\");\n\t\tJavacFileManager.preRegister(context);\n\t\tfileManager = context.get(JavaFileManager.class);\n\t\tcompiler = JavaCompiler.instance(context);\n\t\tcompiler.attrParseOnly = true;\n\t\tcompiler.verbose = false;\n\t\tcompiler.genEndPos = true;\n\t\tcompiler.keepComments = true;\n\t\tlog = Log.instance(context);\n\t\tlog.dumpOnError = false;\n\t\tlog.emitWarnings = false;\n\t\tlog.setWriters(new PrintWriter(new StringWriter() {\n\t\t\t@Override\n\t\t\tpublic void write(String str) {\n\t\t\t}\n\t\t}));\n\t\tlog.setDiagnosticFormatter(factory.createDiagnosticHandler(transpilationHandler, context));\n\t}\n\n\tprivate boolean areAllTranspiled(SourceFile... sourceFiles) {\n\t\tfor (SourceFile file : sourceFiles) {\n\t\t\tif (file.getJsFile() == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Evaluates the given Java source files with the default JavaScript engine\n\t * (Nashorn).\n\t * <p>\n\t * This function automatically transpile the source files if needed.\n\t * \n\t * @param transpilationHandler the transpilation handler\n\t * @param sourceFiles          the source files to be evaluated\n\t * @return an object that holds the evaluation result\n\t * @throws Exception when an internal error occurs\n\t */\n\tpublic EvaluationResult eval(TranspilationHandler transpilationHandler, SourceFile... sourceFiles)\n\t\t\tthrows Exception {\n\t\treturn eval(\"JavaScript\", transpilationHandler, sourceFiles);\n\t}\n\n\t/**\n\t * Evaluates the given source files with the given evaluation engine.\n\t * <p>\n\t * If given engine name is \"Java\", this function looks up for the classes in the\n\t * classpath and run the main methods when found.\n\t * \n\t * @param engineName           the engine name: either \"Java\" or any valid and\n\t *                             installed JavaScript engine.\n\t * @param transpilationHandler the log handler\n\t * @param sourceFiles          the source files to be evaluated (transpiled\n\t *                             first if needed)\n\t * @return the evaluation result\n\t * @throws Exception when an internal error occurs\n\t */\n\tpublic EvaluationResult eval(String engineName, TranspilationHandler transpilationHandler,\n\t\t\tSourceFile... sourceFiles) throws Exception {\n\t\tlogger.info(\"[\" + engineName + \" engine] eval files: \" + Arrays.asList(sourceFiles));\n\n\t\tEvalOptions options = new EvalOptions(isUsingModules(), workingDir);\n\n\t\tif (\"Java\".equals(engineName)) {\n\n\t\t\tJavaEval evaluator = new JavaEval(this, options);\n\t\t\treturn evaluator.performEval(sourceFiles);\n\t\t} else {\n\t\t\tif (!areAllTranspiled(sourceFiles)) {\n\t\t\t\tErrorCountTranspilationHandler errorHandler = new ErrorCountTranspilationHandler(transpilationHandler);\n\t\t\t\ttranspile(errorHandler, sourceFiles);\n\t\t\t\tif (errorHandler.getErrorCount() > 0) {\n\t\t\t\t\tthrow new Exception(\"unable to evaluate: transpilation errors remain\");\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\tCollection<File> jsFiles;\n\t\t\tif (context.useModules) {\n\t\t\t\tFile f = null;\n\t\t\t\tif (!context.entryFiles.isEmpty()) {\n\t\t\t\t\tf = context.entryFiles.get(0);\n\t\t\t\t\tfor (SourceFile sf : sourceFiles) {\n\t\t\t\t\t\tif (sf.getJavaFile().equals(f)) {\n\t\t\t\t\t\t\tf = sf.getJsFile();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (f == null) {\n\t\t\t\t\tf = sourceFiles[sourceFiles.length - 1].getJsFile();\n\t\t\t\t}\n\t\t\t\tjsFiles = asList(f);\n\t\t\t} else {\n\t\t\t\tjsFiles = Stream.of(sourceFiles).map(sourceFile -> sourceFile.getJsFile()).collect(toList());\n\t\t\t}\n\n\t\t\tJavaScriptEval evaluator = new JavaScriptEval(options, JavaScriptRuntime.NodeJs);\n\t\t\treturn evaluator.performEval(jsFiles);\n\t\t}\n\t}\n\n\tpublic List<JCCompilationUnit> setupCompiler(java.util.List<File> files,\n\t\t\tErrorCountTranspilationHandler transpilationHandler) throws IOException {\n\t\tinitJavac(transpilationHandler);\n\t\tList<JavaFileObject> fileObjects = toJavaFileObjects(fileManager, files);\n\n\t\tlogger.info(\"ENTER phase: \" + fileObjects);\n\t\ttranspilationHandler.setDisabled(isIgnoreJavaErrors());\n\n\t\tList<JCCompilationUnit> compilationUnits = compiler.enterTrees(compiler.parseFiles(fileObjects));\n\t\tif (transpilationHandler.getErrorCount() > 0) {\n\t\t\tlogger.warn(\"errors during parse tree\");\n\t\t\treturn null;\n\t\t}\n\t\tlogger.info(\"ATTRIBUTE phase\");\n\t\tQueue<Env<AttrContext>> todo = compiler.attribute(compiler.todo);\n\n\t\tlogger.info(\"FLOW phase\");\n\t\ttodo = compiler.flow(todo);\n\n\t\t// logger.info(\"DESUGAR phase\");\n\t\t// compiler.generate(compiler.desugar(todo));\n\n\t\tlogger.info(\"REPORT DEFERRED phase\");\n\t\tcompiler.reportDeferredDiagnostics();\n\n\t\t// logger.info(\"CLOSE phase\");\n\t\t// compiler.close(true);\n\n\t\ttranspilationHandler.setDisabled(false);\n\t\tcontext.compilationUnits = compilationUnits.toArray(new JCCompilationUnit[compilationUnits.size()]);\n\n\t\tif (transpilationHandler.getErrorCount() > 0) {\n\t\t\treturn null;\n\t\t}\n\t\tif (!generateTsFiles) {\n\t\t\treturn null;\n\t\t}\n\t\tcontext.useModules = isUsingModules();\n\t\tcontext.useRequireForModules = moduleKind != ModuleKind.es2015;\n\n\t\tif (context.useModules && bundle) {\n\t\t\ttranspilationHandler.report(JSweetProblem.BUNDLE_WITH_MODULE, null,\n\t\t\t\t\tJSweetProblem.BUNDLE_WITH_MODULE.getMessage());\n\t\t\treturn null;\n\t\t}\n\t\treturn compilationUnits;\n\t}\n\n\tprivate String ts2js(ErrorCountTranspilationHandler handler, String tsCode, String targetFileName)\n\t\t\tthrows IOException {\n\t\tSourceFile sf = new SourceFile(null);\n\t\tsf.setTsFile(File.createTempFile(targetFileName, \".ts\", tsOutputDir));\n\t\tsf.setJsFile(File.createTempFile(targetFileName, \".js\", jsOutputDir));\n\t\ttry {\n\t\t\tsf.tsFile.getParentFile().mkdirs();\n\t\t\tsf.tsFile.createNewFile();\n\t\t\tFiles.write(sf.tsFile.toPath(), Arrays.asList(tsCode));\n\t\t} catch (IOException ex) {\n\t\t\tthrow new UncheckedIOException(ex);\n\t\t}\n\n\t\tts2js(handler, new SourceFile[] { sf });\n\t\ttry {\n\t\t\treturn new String(Files.readAllBytes(sf.jsFile.toPath()));\n\t\t} catch (IOException ex) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Transpiles the given Java source files. When the transpiler is in watch mode\n\t * ({@link #setTscWatchMode(boolean)}), the first invocation to this method\n\t * determines the files to be watched by the Tsc process.\n\t * \n\t * @param transpilationHandler the log handler\n\t * @param files                the files to be transpiled\n\t * @throws IOException\n\t */\n\tsynchronized public void transpile(TranspilationHandler transpilationHandler, SourceFile... files)\n\t\t\tthrows IOException {\n\t\ttranspilationStartTimestamp = System.currentTimeMillis();\n\n\t\ttry {\n\t\t\tinitNode(transpilationHandler);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(e.getMessage(), e);\n\t\t\treturn;\n\t\t}\n\t\tcandiesProcessor.processCandies(transpilationHandler);\n\n\t\tif (!isIgnoreCandiesTypeScriptDefinitions()) {\n\t\t\taddTsDefDir(candiesProcessor.getCandiesTsdefsDir());\n\t\t}\n\n\t\tErrorCountTranspilationHandler errorHandler = new ErrorCountTranspilationHandler(transpilationHandler);\n\t\tCollection<SourceFile> jsweetSources = asList(files).stream() //\n\t\t\t\t.filter(source -> source.getJavaFile() != null).collect(toList());\n\n\t\tlong startJava2TsTimeNanos = System.nanoTime();\n\t\tjava2ts(errorHandler, jsweetSources.toArray(new SourceFile[0]));\n\t\tlong endJava2TsTimeNanos = System.nanoTime();\n\n\t\tlong startTs2JsTimeNanos = System.nanoTime();\n\t\tif (errorHandler.getErrorCount() == 0 && generateTsFiles && generateJsFiles) {\n\t\t\tts2js(errorHandler, files);\n\t\t}\n\t\tlong endTs2JsTimeNanos = System.nanoTime();\n\n\t\tif (!generateJsFiles || !generateTsFiles) {\n\t\t\ttranspilationHandler.onCompleted(this, !isTscWatchMode(), files);\n\t\t}\n\n\t\tlogger.info(\"transpilation process finished in \" + (System.currentTimeMillis() - transpilationStartTimestamp)\n\t\t\t\t+ \" ms \\n\" //\n\t\t\t\t+ \"> java2ts: \" + ((endJava2TsTimeNanos - startJava2TsTimeNanos) / 1e6) + \"ms\\n\" + \"> ts2js: \"\n\t\t\t\t+ ((endTs2JsTimeNanos - startTs2JsTimeNanos) / 1e6) + \"ms\\n\");\n\t}\n\n\tprivate void ts2js(ErrorCountTranspilationHandler transpilationHandler, SourceFile[] sourceFiles)\n\t\t\tthrows IOException {\n\n\t\tLinkedHashSet<SourceFile> tsSourceFiles = new LinkedHashSet<>();\n\t\tfor (SourceFile sourceFile : sourceFiles) {\n\t\t\tif (sourceFile.getTsFile() != null) {\n\t\t\t\ttsSourceFiles.add(sourceFile);\n\t\t\t}\n\t\t}\n\n\t\tlogger.info(\"ts2js on \" + ts2jsTranspiler + \" sourceFiles=\" + sourceFiles.length);\n\t\tts2jsTranspiler.ts2js(transpilationHandler, //\n\t\t\t\ttsSourceFiles, //\n\t\t\t\ttsDefDirs, //\n\t\t\t\tthis, //\n\t\t\t\tisIgnoreTypeScriptErrors(), //\n\t\t\t\tthis::onTsTranspilationCompleted);\n\t}\n\n\tpublic void setUseTsserver(boolean useTsserver) {\n\t\tif (useTsserver) {\n\t\t\tthis.ts2jsTranspiler = TypeScript2JavaScriptWithTsserverTranspiler.INSTANCE;\n\t\t} else {\n\t\t\tthis.ts2jsTranspiler = new TypeScript2JavaScriptWithTscTranspiler();\n\t\t}\n\t}\n\n\tprivate void java2ts(ErrorCountTranspilationHandler transpilationHandler, SourceFile[] files) throws IOException {\n\t\tList<JCCompilationUnit> compilationUnits = setupCompiler(Arrays.asList(SourceFile.toFiles(files)),\n\t\t\t\ttranspilationHandler);\n\t\tif (compilationUnits == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (candiesProcessor.hasDeprecatedCandy()) {\n\t\t\tcontext.deprecatedApply = true;\n\t\t\tlogger.warn(\"\\n\\n\\n*********************************************************************\\n\" //\n\t\t\t\t\t+ \"*********************************************************************\\n\" //\n\t\t\t\t\t+ \" YOUR CLASSPATH CONTAINS JSweet v1.x CANDIES \\n\" //\n\t\t\t\t\t+ \" This can lead to unexpected behaviors, please contribute to https://github.com/jsweet-candies \\n\" //\n\t\t\t\t\t+ \" to add your library's typings \\n\" //\n\t\t\t\t\t+ \"*********************************************************************\\n\" //\n\t\t\t\t\t+ \"*********************************************************************\\n\\n\");\n\t\t}\n\n\t\tcontext.sourceFiles = files;\n\t\tfactory.createBeforeTranslationScanner(transpilationHandler, context).process(compilationUnits);\n\n\t\tif (context.useModules) {\n\t\t\tgenerateTsFiles(transpilationHandler, files, compilationUnits);\n\t\t} else {\n\t\t\tif (bundle) {\n\t\t\t\tgenerateTsBundle(transpilationHandler, files, compilationUnits);\n\t\t\t} else {\n\t\t\t\tgenerateTsFiles(transpilationHandler, files, compilationUnits);\n\t\t\t}\n\t\t}\n\t\tlog.flush();\n\t}\n\n\tprivate void generateModuleDefs(JCCompilationUnit moduleDefs) throws IOException {\n\t\tStringBuilder out = new StringBuilder();\n\t\tfor (String line : FileUtils.readLines(new File(moduleDefs.getSourceFile().getName()))) {\n\t\t\tif (line.startsWith(\"///\")) {\n\t\t\t\tout.append(line.substring(3));\n\t\t\t}\n\t\t}\n\t\tFileUtils.write(new File(tsOutputDir, \"module_defs.d.ts\"), out, false);\n\t}\n\n\tprivate void generateTsFiles(ErrorCountTranspilationHandler transpilationHandler, SourceFile[] files,\n\t\t\tList<JCCompilationUnit> compilationUnits) throws IOException {\n\t\t// regular file-to-file generation\n\t\tnew OverloadScanner(transpilationHandler, context).process(compilationUnits);\n\n\t\tif (isVerbose()) {\n\t\t\tcontext.dumpOverloads(System.out);\n\t\t}\n\n\t\tString[] headerLines = getHeaderLines();\n\t\tfor (int i = 0; i < compilationUnits.length(); i++) {\n\t\t\ttry {\n\t\t\t\tJCCompilationUnit cu = compilationUnits.get(i);\n\t\t\t\tif (isModuleDefsFile(cu)) {\n\t\t\t\t\tif (context.useModules) {\n\t\t\t\t\t\tgenerateModuleDefs(cu);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlogger.info(\"scanning \" + cu.sourcefile.getName() + \"...\");\n\t\t\t\tAbstractTreePrinter printer = factory.createTranslator(adapter, transpilationHandler, context, cu,\n\t\t\t\t\t\tgenerateSourceMaps);\n\t\t\t\tprinter.print(cu);\n\t\t\t\tif (StringUtils.isWhitespace(printer.getResult())) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tString[] s = cu.getSourceFile().getName().split(File.separator.equals(\"\\\\\") ? \"\\\\\\\\\" : File.separator);\n\t\t\t\tString cuName = s[s.length - 1];\n\t\t\t\ts = cuName.split(\"\\\\.\");\n\t\t\t\tcuName = s[0];\n\t\t\t\tString javaSourceFileRelativeFullName = (cu.packge.getQualifiedName().toString().replace(\".\",\n\t\t\t\t\t\tFile.separator) + File.separator + cuName + \".java\");\n\t\t\t\tfiles[i].javaSourceDirRelativeFile = new File(javaSourceFileRelativeFullName);\n\t\t\t\tfiles[i].javaSourceDir = new File(cu.getSourceFile().getName().substring(0,\n\t\t\t\t\t\tcu.getSourceFile().getName().length() - javaSourceFileRelativeFullName.length()));\n\t\t\t\tString packageName = isNoRootDirectories() ? context.getRootRelativeJavaName(cu.packge)\n\t\t\t\t\t\t: cu.packge.getQualifiedName().toString();\n\t\t\t\tString outputFileRelativePathNoExt = packageName.replace(\".\", File.separator) + File.separator + cuName;\n\t\t\t\tString outputFileRelativePath = outputFileRelativePathNoExt\n\t\t\t\t\t\t+ (cu.packge.fullname.toString().startsWith(\"def.\") ? \".d.ts\" : \".ts\");\n\t\t\t\tlogger.info(\"output file: \" + outputFileRelativePath);\n\t\t\t\tFile outputFile = new File(tsOutputDir, outputFileRelativePath);\n\t\t\t\toutputFile.getParentFile().mkdirs();\n\t\t\t\tString outputFilePath = outputFile.getPath();\n\t\t\t\tPrintWriter out = new PrintWriter(outputFilePath);\n\t\t\t\tString headers = context.getHeaders();\n\t\t\t\tint headersLineCount = StringUtils.countMatches(headers, \"\\n\");\n\t\t\t\ttry {\n\t\t\t\t\tfor (String line : headerLines) {\n\t\t\t\t\t\tout.println(line);\n\t\t\t\t\t}\n\t\t\t\t\tout.print(headers);\n\t\t\t\t\tout.println(printer.getResult());\n\t\t\t\t\tout.print(context.getGlobalsMappingString());\n\t\t\t\t\tout.print(context.getFooterStatements());\n\t\t\t\t} finally {\n\t\t\t\t\tout.close();\n\t\t\t\t}\n\t\t\t\tfiles[i].tsFile = outputFile;\n\t\t\t\tfiles[i].javaFileLastTranspiled = files[i].getJavaFile().lastModified();\n\t\t\t\tprinter.sourceMap.shiftOutputPositions(headerLines.length + headersLineCount);\n\t\t\t\tfiles[i].setSourceMap(printer.sourceMap);\n\t\t\t\tif (generateSourceMaps && !generateJsFiles) {\n\t\t\t\t\tgenerateTypeScriptSourceMapFile(files[i]);\n\t\t\t\t}\n\t\t\t\tlogger.info(\"created \" + outputFilePath);\n\t\t\t} finally {\n\t\t\t\tcontext.clearHeaders();\n\t\t\t\tcontext.clearFooterStatements();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void generateTypeScriptSourceMapFile(SourceFile sourceFile) throws IOException {\n\t\tif (sourceFile.getSourceMap() == null) {\n\t\t\treturn;\n\t\t}\n\t\tSourceMapGenerator generator = SourceMapGeneratorFactory.getInstance(SourceMapFormat.V3);\n\t\tString javaSourceFilePath = sourceFile.getTsFile().getAbsoluteFile().getCanonicalFile().getParentFile().toPath()\n\t\t\t\t.relativize(sourceFile.getJavaFile().getAbsoluteFile().getCanonicalFile().toPath()).toString();\n\t\tfor (Entry entry : sourceFile.getSourceMap().getSortedEntries(new Comparator<SourceMap.Entry>() {\n\t\t\t@Override\n\t\t\tpublic int compare(Entry e1, Entry e2) {\n\t\t\t\treturn e1.getOutputPosition().compareTo(e2.getOutputPosition());\n\t\t\t}\n\t\t})) {\n\t\t\tgenerator.addMapping(javaSourceFilePath, null,\n\t\t\t\t\tnew FilePosition(entry.getInputPosition().getLine(), entry.getInputPosition().getColumn()),\n\t\t\t\t\tnew FilePosition(entry.getOutputPosition().getLine(), entry.getOutputPosition().getColumn()),\n\t\t\t\t\tnew FilePosition(entry.getOutputPosition().getLine(), entry.getOutputPosition().getColumn() + 1));\n\t\t}\n\t\tFile outputFile = new File(sourceFile.getTsFile().getPath() + \".map\");\n\t\ttry (FileWriter writer = new FileWriter(outputFile, false)) {\n\t\t\tgenerator.appendTo(writer, sourceFile.getTsFile().getName());\n\t\t} catch (Exception ex) {\n\t\t\tex.printStackTrace();\n\t\t}\n\n\t}\n\n\tprivate boolean isModuleDefsFile(JCCompilationUnit cu) {\n\t\treturn cu.getSourceFile().getName().equals(\"module_defs.java\")\n\t\t\t\t|| cu.getSourceFile().getName().endsWith(\"/module_defs.java\");\n\t}\n\n\tprivate void generateTsBundle(ErrorCountTranspilationHandler transpilationHandler, SourceFile[] files,\n\t\t\tList<JCCompilationUnit> compilationUnits) throws IOException {\n\t\tif (context.useModules) {\n\t\t\treturn;\n\t\t}\n\t\tStaticInitilializerAnalyzer analizer = new StaticInitilializerAnalyzer(context);\n\t\tanalizer.process(compilationUnits);\n\t\tArrayList<Node<JCCompilationUnit>> sourcesInCycle = new ArrayList<>();\n\t\tjava.util.List<JCCompilationUnit> orderedCompilationUnits = analizer.globalStaticInitializersDependencies\n\t\t\t\t.topologicalSort(n -> {\n\t\t\t\t\tsourcesInCycle.add(n);\n\t\t\t\t});\n\t\tif (!sourcesInCycle.isEmpty()) {\n\t\t\ttranspilationHandler.report(JSweetProblem.CYCLE_IN_STATIC_INITIALIZER_DEPENDENCIES, null,\n\t\t\t\t\tJSweetProblem.CYCLE_IN_STATIC_INITIALIZER_DEPENDENCIES.getMessage(sourcesInCycle.stream()\n\t\t\t\t\t\t\t.map(n -> n.element.sourcefile.getName()).collect(Collectors.toList())));\n\n\t\t\tDirectedGraph.dumpCycles(sourcesInCycle, u -> u.sourcefile.getName());\n\n\t\t\treturn;\n\t\t}\n\n\t\tnew OverloadScanner(transpilationHandler, context).process(orderedCompilationUnits);\n\n\t\tlogger.debug(\"ordered compilation units: \" + orderedCompilationUnits.stream().map(cu -> {\n\t\t\treturn cu.sourcefile.getName();\n\t\t}).collect(Collectors.toList()));\n\t\tlogger.debug(\n\t\t\t\t\"count: \" + compilationUnits.size() + \" (initial), \" + orderedCompilationUnits.size() + \" (ordered)\");\n\t\tint[] permutation = new int[orderedCompilationUnits.size()];\n\t\tStringBuilder permutationString = new StringBuilder();\n\t\tfor (int i = 0; i < orderedCompilationUnits.size(); i++) {\n\t\t\tpermutation[i] = compilationUnits.indexOf(orderedCompilationUnits.get(i));\n\t\t\tpermutationString.append(\"\" + i + \"=\" + permutation[i] + \";\");\n\t\t}\n\t\tlogger.debug(\"permutation: \" + permutationString.toString());\n\t\tcreateBundle(transpilationHandler, files, permutation, orderedCompilationUnits, false);\n\t\tif (isGenerateDefinitions()) {\n\t\t\tcreateBundle(transpilationHandler, files, permutation, orderedCompilationUnits, true);\n\t\t}\n\t}\n\n\tprivate void initSourceFileJavaPaths(SourceFile file, JCCompilationUnit cu) {\n\t\tString[] s = cu.getSourceFile().getName().split(File.separator.equals(\"\\\\\") ? \"\\\\\\\\\" : File.separator);\n\t\tString cuName = s[s.length - 1];\n\t\ts = cuName.split(\"\\\\.\");\n\t\tcuName = s[0];\n\n\t\tString javaSourceFileRelativeFullName = (cu.packge.getQualifiedName().toString().replace(\".\", File.separator)\n\t\t\t\t+ File.separator + cuName + \".java\");\n\t\tfile.javaSourceDirRelativeFile = new File(javaSourceFileRelativeFullName);\n\t\tfile.javaSourceDir = new File(cu.getSourceFile().getName().substring(0,\n\t\t\t\tcu.getSourceFile().getName().length() - javaSourceFileRelativeFullName.length()));\n\t}\n\n\tprivate void createBundle(ErrorCountTranspilationHandler transpilationHandler, SourceFile[] files,\n\t\t\tint[] permutation, java.util.List<JCCompilationUnit> orderedCompilationUnits, boolean definitionBundle)\n\t\t\tthrows FileNotFoundException {\n\t\tcontext.bundleMode = true;\n\t\tStringBuilder sb = new StringBuilder();\n\t\tint lineCount = 0;\n\t\tfor (String line : getHeaderLines()) {\n\t\t\tsb.append(line).append(\"\\n\");\n\t\t\tlineCount++;\n\t\t}\n\t\tfor (int i = 0; i < orderedCompilationUnits.size(); i++) {\n\t\t\tJCCompilationUnit cu = orderedCompilationUnits.get(i);\n\t\t\tif (isModuleDefsFile(cu)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (cu.packge.fullname.toString().startsWith(\"def.\")) {\n\t\t\t\tif (!definitionBundle) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (definitionBundle) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.info(\"scanning \" + cu.sourcefile.getName() + \"...\");\n\t\t\tAbstractTreePrinter printer = factory.createTranslator(adapter, transpilationHandler, context, cu,\n\t\t\t\t\tgenerateSourceMaps);\n\t\t\tprinter.print(cu);\n\t\t\tprinter.sourceMap.shiftOutputPositions(lineCount);\n\t\t\tfiles[permutation[i]].setSourceMap(printer.sourceMap);\n\n\t\t\tsb.append(printer.getOutput());\n\t\t\tlineCount += (printer.getCurrentLine() - 1);\n\n\t\t\tinitSourceFileJavaPaths(files[permutation[i]], cu);\n\t\t}\n\n\t\tcontext.bundleMode = false;\n\n\t\tFile bundleDirectory = tsOutputDir;\n\t\tif (!bundleDirectory.exists()) {\n\t\t\tbundleDirectory.mkdirs();\n\t\t}\n\t\tString bundleName = \"bundle\" + (definitionBundle ? \".d.ts\" : \".ts\");\n\n\t\tFile outputFile = new File(bundleDirectory, bundleName);\n\n\t\tlogger.info(\"creating bundle file: \" + outputFile);\n\t\toutputFile.getParentFile().mkdirs();\n\t\tString outputFilePath = outputFile.getPath();\n\t\tPrintWriter out = new PrintWriter(outputFilePath);\n\t\ttry {\n\t\t\tout.println(sb.toString());\n\t\t\tif (!definitionBundle) {\n\t\t\t\tout.print(context.getGlobalsMappingString());\n\t\t\t}\n\t\t\tout.print(context.getFooterStatements());\n\t\t\tcontext.clearFooterStatements();\n\t\t\tif (definitionBundle && context.getExportedElements() != null) {\n\t\t\t\tfor (java.util.Map.Entry<String, java.util.List<Symbol>> exportedElements : context\n\t\t\t\t\t\t.getExportedElements().entrySet()) {\n\t\t\t\t\tout.println();\n\t\t\t\t\tout.print(\"declare module \\\"\" + exportedElements.getKey() + \"\\\"\");\n\t\t\t\t\tboolean exported = false;\n\t\t\t\t\tfor (Symbol element : exportedElements.getValue()) {\n\t\t\t\t\t\tif (element instanceof PackageSymbol && !context.isRootPackage(element)) {\n\t\t\t\t\t\t\tout.print(\" {\");\n\t\t\t\t\t\t\tout.println();\n\t\t\t\t\t\t\tout.print(\"    export = \" + context.getExportedElementName(element) + \";\");\n\t\t\t\t\t\t\tout.println();\n\t\t\t\t\t\t\tout.print(\"}\");\n\t\t\t\t\t\t\texported = true;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (!exported) {\n\t\t\t\t\t\tout.print(\";\");\n\t\t\t\t\t}\n\t\t\t\t\tout.println();\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tout.close();\n\t\t}\n\t\tfor (int i = 0; i < orderedCompilationUnits.size(); i++) {\n\t\t\tJCCompilationUnit cu = orderedCompilationUnits.get(i);\n\t\t\tif (cu.packge.fullname.toString().startsWith(\"def.\")) {\n\t\t\t\tif (!definitionBundle) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (definitionBundle) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfiles[permutation[i]].tsFile = outputFile;\n\t\t\tfiles[permutation[i]].javaFileLastTranspiled = files[permutation[i]].getJavaFile().lastModified();\n\t\t}\n\t\tlogger.info(\"created \" + outputFilePath);\n\n\t}\n\n\tprivate File extractedCandyJavascriptDir;\n\n\t/**\n\t * Returns the watched files when the transpiler is in watch mode. See\n\t * {@link #setTscWatchMode(boolean)}. The watched file list corresponds to the\n\t * one given at the first invocation of\n\t * {@link #transpile(TranspilationHandler, SourceFile...)} after the transpiler\n\t * was set to watch mode. All subsequent invocations of\n\t * {@link #transpile(TranspilationHandler, SourceFile...)} will not change the\n\t * initial watched files. In order to change the watch files, invoke\n\t * {@link #resetTscWatchMode()} and call\n\t * {@link #transpile(TranspilationHandler, SourceFile...)} with a new file list.\n\t */\n\tsynchronized public SourceFile[] getWatchedFiles() {\n\t\t// TODO : watch mode isn't implemented with tsserver transpiler, either we\n\t\t// remove watch mode (only used for tests if I'm right), or provide a dummy\n\t\t// implementation for tsserver\n\t\treturn ((TypeScript2JavaScriptWithTscTranspiler) ts2jsTranspiler).getWatchedFiles().toArray(new SourceFile[0]);\n\t}\n\n\t/**\n\t * Gets the watched files that corresponds to the given Java file. See\n\t * {@link #setTscWatchMode(boolean)}.\n\t */\n\tsynchronized public SourceFile getWatchedFile(File javaFile) {\n\t\t// TODO : see #getWatchedFiles()\n\t\treturn ((TypeScript2JavaScriptWithTscTranspiler) ts2jsTranspiler).getWatchedFile(javaFile);\n\t}\n\n\t/**\n\t * Tells if this transpiler is using a Tsc watch process to automatically\n\t * regenerate the javascript when one of the source file changes.\n\t */\n\tsynchronized public boolean isTscWatchMode() {\n\t\treturn tscWatchMode;\n\t}\n\n\t/**\n\t * Enables or disable this transpiler watch mode. When watch mode is enabled,\n\t * the first invocation to\n\t * {@link #transpile(TranspilationHandler, SourceFile...)} will start the Tsc\n\t * watch process, which regenerates the JavaScript files when one of the input\n\t * file changes.\n\t * \n\t * @param tscWatchMode true: enables the watch mode (do nothing is already\n\t *                     enabled), false: disables the watch mode and stops the\n\t *                     current Tsc watching process\n\t * @see #getWatchedFile(File)\n\t */\n\tsynchronized public void setTscWatchMode(boolean tscWatchMode) {\n\t\tthis.tscWatchMode = tscWatchMode;\n\t\tif (!tscWatchMode) {\n\t\t\t// TODO : see #getWatchedFiles()\n\t\t\t((TypeScript2JavaScriptWithTscTranspiler) ts2jsTranspiler).stopWatch();\n\t\t}\n\t}\n\n\tprivate void onTsTranspilationCompleted(boolean fullPass, ErrorCountTranspilationHandler handler,\n\t\t\tCollection<SourceFile> files) {\n\t\ttry {\n\t\t\tif (isGenerateDeclarations()) {\n\t\t\t\tif (getDeclarationsOutputDir() != null) {\n\t\t\t\t\tlogger.info(\"moving d.ts files to \" + getDeclarationsOutputDir());\n\t\t\t\t\tLinkedList<File> dtsFiles = new LinkedList<File>();\n\t\t\t\t\tFile rootDir = jsOutputDir == null ? tsOutputDir : jsOutputDir;\n\t\t\t\t\tUtil.addFiles(\".d.ts\", rootDir, dtsFiles);\n\t\t\t\t\tfor (File dtsFile : dtsFiles) {\n\t\t\t\t\t\tString relativePath = Util.getRelativePath(rootDir.getAbsolutePath(),\n\t\t\t\t\t\t\t\tdtsFile.getAbsolutePath());\n\t\t\t\t\t\tFile targetFile = new File(getDeclarationsOutputDir(), relativePath);\n\t\t\t\t\t\tlogger.info(\"moving \" + dtsFile + \" to \" + targetFile);\n\t\t\t\t\t\tif (targetFile.exists()) {\n\t\t\t\t\t\t\tFileUtils.deleteQuietly(targetFile);\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tFileUtils.moveFile(dtsFile, targetFile);\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\tlogger.error(e.getMessage(), e);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (handler.getErrorCount() == 0) {\n\t\t\t\tSet<File> handledFiles = new HashSet<>();\n\t\t\t\tfor (SourceFile sourceFile : files) {\n\t\t\t\t\tif (!sourceFile.getTsFile().getAbsolutePath().startsWith(tsOutputDir.getAbsolutePath())) {\n\t\t\t\t\t\tthrow new RuntimeException(\"ts directory isn't configured properly, please use setTsDir: \"\n\t\t\t\t\t\t\t\t+ sourceFile.getTsFile().getAbsolutePath() + \" != \" + tsOutputDir.getAbsolutePath());\n\t\t\t\t\t}\n\t\t\t\t\tString outputFileRelativePath = sourceFile.getTsFile().getAbsolutePath()\n\t\t\t\t\t\t\t.substring(tsOutputDir.getAbsolutePath().length());\n\t\t\t\t\tFile outputFile = new File(jsOutputDir == null ? tsOutputDir : jsOutputDir,\n\t\t\t\t\t\t\tUtil.removeExtension(outputFileRelativePath) + \".js\");\n\t\t\t\t\tsourceFile.jsFile = outputFile;\n\t\t\t\t\tif (outputFile.lastModified() > sourceFile.jsFileLastTranspiled) {\n\t\t\t\t\t\tif (handledFiles.contains(outputFile)) {\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\thandledFiles.add(outputFile);\n\t\t\t\t\t\tlogger.info(\"js output file: \" + outputFile);\n\t\t\t\t\t\tFile mapFile = new File(outputFile.getAbsolutePath() + \".map\");\n\n\t\t\t\t\t\tif (mapFile.exists() && generateSourceMaps) {\n\n\t\t\t\t\t\t\tSourceMapGeneratorV3 generator = (SourceMapGeneratorV3) SourceMapGeneratorFactory\n\t\t\t\t\t\t\t\t\t.getInstance(SourceMapFormat.V3);\n\t\t\t\t\t\t\tPath javaSourcePath = sourceFile.javaSourceDir.getCanonicalFile().toPath();\n\t\t\t\t\t\t\tString sourceRoot = getSourceRoot() != null ? getSourceRoot().toString()\n\t\t\t\t\t\t\t\t\t: sourceFile.getJsFile().getParentFile().getCanonicalFile().toPath()\n\t\t\t\t\t\t\t\t\t\t\t.relativize(javaSourcePath) + \"/\";\n\t\t\t\t\t\t\tgenerator.setSourceRoot(sourceRoot);\n\n\t\t\t\t\t\t\tsourceFile.jsMapFile = mapFile;\n\t\t\t\t\t\t\tlogger.info(\"redirecting map file: \" + mapFile);\n\t\t\t\t\t\t\tString contents = FileUtils.readFileToString(mapFile);\n\t\t\t\t\t\t\tSourceMapping mapping = SourceMapConsumerFactory.parse(contents);\n\n\t\t\t\t\t\t\tint line = 1;\n\t\t\t\t\t\t\tint columnIndex = 0;\n\t\t\t\t\t\t\tfor (String lineContent : FileUtils.readLines(outputFile, (Charset) null)) {\n\t\t\t\t\t\t\t\tcolumnIndex = 0;\n\t\t\t\t\t\t\t\twhile (columnIndex < lineContent.length() && (lineContent.charAt(columnIndex) == ' '\n\t\t\t\t\t\t\t\t\t\t|| lineContent.charAt(columnIndex) == '\\t')) {\n\t\t\t\t\t\t\t\t\tcolumnIndex++;\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tOriginalMapping originalMapping = mapping.getMappingForLine(line, columnIndex + 1);\n\t\t\t\t\t\t\t\tif (originalMapping != null) {\n\t\t\t\t\t\t\t\t\t// TODO: this is quite slow and should be\n\t\t\t\t\t\t\t\t\t// optimized\n\t\t\t\t\t\t\t\t\tSourcePosition originPosition = SourceFile.findOriginPosition(new SourcePosition(\n\t\t\t\t\t\t\t\t\t\t\tsourceFile.tsFile, null, new Position(originalMapping.getLineNumber(),\n\t\t\t\t\t\t\t\t\t\t\t\t\toriginalMapping.getColumnPosition())),\n\t\t\t\t\t\t\t\t\t\t\tfiles);\n\t\t\t\t\t\t\t\t\tif (originPosition != null) {\n\t\t\t\t\t\t\t\t\t\t// as a first approximation, we only map\n\t\t\t\t\t\t\t\t\t\t// line numbers (ignore columns)\n\t\t\t\t\t\t\t\t\t\tgenerator.addMapping(\n\t\t\t\t\t\t\t\t\t\t\t\tjavaSourcePath\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.relativize(\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\toriginPosition.getFile().getCanonicalFile().toPath())\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t.toString(),\n\t\t\t\t\t\t\t\t\t\t\t\tnull, new FilePosition(originPosition.getStartLine() - 1, 0),\n\t\t\t\t\t\t\t\t\t\t\t\tnew FilePosition(line - 1, 0),\n\t\t\t\t\t\t\t\t\t\t\t\tnew FilePosition(line - 1, lineContent.length() - 1));\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tline++;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\ttry (FileWriter writer = new FileWriter(mapFile, false)) {\n\t\t\t\t\t\t\t\tgenerator.appendTo(writer, outputFile.getName());\n\t\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\t\tex.printStackTrace();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\thandler.onCompleted(this, fullPass, files.toArray(new SourceFile[0]));\n\t\t}\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#isPreserveSourceLineNumbers()\n\t */\n\t@Deprecated\n\t@Override\n\tpublic boolean isPreserveSourceLineNumbers() {\n\t\treturn generateSourceMaps;\n\t}\n\n\t@Override\n\tpublic boolean isGenerateSourceMaps() {\n\t\treturn generateSourceMaps;\n\t}\n\n\t/**\n\t * Sets the flag that tells if the transpiler preserves the generated TypeScript\n\t * source line numbers wrt the Java original source file (allows for Java\n\t * debugging through js.map files).\n\t * \n\t * @deprecated use {@link #setGenerateSourceMaps(boolean)} instead\n\t */\n\t@Deprecated\n\tpublic void setPreserveSourceLineNumbers(boolean preserveSourceLineNumbers) {\n\t\tthis.generateSourceMaps = preserveSourceLineNumbers;\n\t}\n\n\t/**\n\t * Sets the flag that tells if the transpiler allows for Java debugging through\n\t * js.map files.\n\t */\n\tpublic void setGenerateSourceMaps(boolean generateSourceMaps) {\n\t\tthis.generateSourceMaps = generateSourceMaps;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#getTsOutputDir()\n\t */\n\t@Override\n\tpublic File getTsOutputDir() {\n\t\treturn tsOutputDir;\n\t}\n\n\t/**\n\t * Sets the current TypeScript output directory.\n\t */\n\tpublic void setTsOutputDir(File tsOutputDir) {\n\t\tthis.tsOutputDir = tsOutputDir;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#getJsOutputDir()\n\t */\n\t@Override\n\tpublic File getJsOutputDir() {\n\t\treturn jsOutputDir;\n\t}\n\n\t/**\n\t * Sets the current JavaScript output directory.\n\t */\n\tpublic void setJsOutputDir(File jsOutputDir) {\n\t\tthis.jsOutputDir = jsOutputDir;\n\t}\n\n\t/**\n\t * Tells if the JavaScript generation is enabled/disabled.\n\t */\n\t@Override\n\tpublic boolean isGenerateJsFiles() {\n\t\treturn generateJsFiles;\n\t}\n\n\t/**\n\t * Sets the flag to enable/disable JavaScript generation.\n\t */\n\tpublic void setGenerateJsFiles(boolean generateJsFiles) {\n\t\tthis.generateJsFiles = generateJsFiles;\n\t}\n\n\t/**\n\t * Resets the watch mode (clears the watched files and restarts the Tsc process\n\t * on the next invocation of\n\t * {@link #transpile(TranspilationHandler, SourceFile...)}).\n\t */\n\tsynchronized public void resetTscWatchMode() {\n\t\tsetTscWatchMode(false);\n\t\tsetTscWatchMode(true);\n\t}\n\n\t/**\n\t * Gets the candies processor.\n\t */\n\tpublic CandyProcessor getCandiesProcessor() {\n\t\treturn candiesProcessor;\n\t}\n\n\t/**\n\t * Sets target ECMA script version for generated JavaScript\n\t * \n\t * @param ecmaTargetVersion The target version\n\t */\n\tpublic void setEcmaTargetVersion(EcmaScriptComplianceLevel ecmaTargetVersion) {\n\t\tthis.ecmaTargetVersion = ecmaTargetVersion;\n\t}\n\n\t@Override\n\tpublic EcmaScriptComplianceLevel getEcmaTargetVersion() {\n\t\treturn ecmaTargetVersion;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#getModuleKind()\n\t */\n\t@Override\n\tpublic ModuleKind getModuleKind() {\n\t\treturn moduleKind;\n\t}\n\n\t/**\n\t * Sets the module kind when transpiling to code using JavaScript modules.\n\t */\n\tpublic void setModuleKind(ModuleKind moduleKind) {\n\t\tthis.moduleKind = moduleKind;\n\t}\n\n\t@Override\n\tpublic ModuleResolution getModuleResolution() {\n\t\treturn moduleResolution;\n\t}\n\n\t/**\n\t * Sets the module strategy when transpiling to code using JavaScript modules.\n\t */\n\tpublic void setModuleResolution(ModuleResolution moduleResolution) {\n\t\tthis.moduleResolution = moduleResolution;\n\t}\n\n\t/**\n\t * Tells tsc to skip some checks in order to reduce load time, useful in unit\n\t * tests where transpiler is invoked many times\n\t */\n\tpublic void setSkipTypeScriptChecks(boolean skipTypeScriptChecks) {\n\t\tthis.skipTypeScriptChecks = skipTypeScriptChecks;\n\t}\n\n\t@Override\n\tpublic boolean isSkipTypeScriptChecks() {\n\t\treturn skipTypeScriptChecks;\n\t}\n\n\t/**\n\t * Tells if this transpiler transpiles to code using JavaScript modules.\n\t */\n\tpublic boolean isUsingModules() {\n\t\treturn moduleKind != null && moduleKind != ModuleKind.none;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#isBundle()\n\t */\n\t@Override\n\tpublic boolean isBundle() {\n\t\treturn bundle;\n\t}\n\n\t/**\n\t * Sets this transpiler to generate JavaScript bundles for running in a Web\n\t * browser.\n\t */\n\tpublic void setBundle(boolean bundle) {\n\t\tthis.bundle = bundle;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#getEncoding()\n\t */\n\t@Override\n\tpublic String getEncoding() {\n\t\treturn encoding;\n\t}\n\n\t/**\n\t * Sets the expected Java source code encoding.\n\t */\n\tpublic void setEncoding(String encoding) {\n\t\tthis.encoding = encoding;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#isNoRootDirectories()\n\t */\n\t@Override\n\tpublic boolean isNoRootDirectories() {\n\t\treturn noRootDirectories;\n\t}\n\n\t/**\n\t * Sets this transpiler to skip the root directories (packages annotated\n\t * with @jsweet.lang.Root) so that the generated file hierarchy starts at the\n\t * root directories rather than including the entire directory structure.\n\t */\n\tpublic void setNoRootDirectories(boolean noRootDirectories) {\n\t\tthis.noRootDirectories = noRootDirectories;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#isIgnoreAssertions()\n\t */\n\t@Override\n\tpublic boolean isIgnoreAssertions() {\n\t\treturn ignoreAssertions;\n\t}\n\n\t/**\n\t * Sets the transpiler to ignore the 'assert' statements or generate appropriate\n\t * code.\n\t */\n\tpublic void setIgnoreAssertions(boolean ignoreAssertions) {\n\t\tthis.ignoreAssertions = ignoreAssertions;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see org.jsweet.transpiler.JSweetOptions#isIgnoreJavaFileNameError()\n\t */\n\t@Override\n\tpublic boolean isIgnoreJavaFileNameError() {\n\t\treturn ignoreJavaFileNameError;\n\t}\n\n\tpublic void setIgnoreJavaFileNameError(boolean ignoreJavaFileNameError) {\n\t\tthis.ignoreJavaFileNameError = ignoreJavaFileNameError;\n\t}\n\n\t@Override\n\tpublic boolean isGenerateDeclarations() {\n\t\treturn generateDeclarations;\n\t}\n\n\tpublic void setGenerateDeclarations(boolean generateDeclarations) {\n\t\tthis.generateDeclarations = generateDeclarations;\n\t}\n\n\t@Override\n\tpublic File getDeclarationsOutputDir() {\n\t\treturn declarationsOutputDir;\n\t}\n\n\tpublic void setDeclarationsOutputDir(File declarationsOutputDir) {\n\t\tthis.declarationsOutputDir = declarationsOutputDir;\n\t}\n\n\t@Override\n\tpublic File getExtractedCandyJavascriptDir() {\n\t\treturn extractedCandyJavascriptDir;\n\t}\n\n\t/**\n\t * Add JavaScript libraries that are used for the JavaScript evaluation.\n\t * \n\t * @see #eval(TranspilationHandler, SourceFile...)\n\t */\n\tpublic void addJsLibFiles(File... files) {\n\t\tjsLibFiles.addAll(Arrays.asList(files));\n\t}\n\n\t/**\n\t * Clears JavaScript libraries that are used for the JavaScript evaluation.\n\t * \n\t * @see #eval(TranspilationHandler, SourceFile...)\n\t */\n\tpublic void clearJsLibFiles() {\n\t\tjsLibFiles.clear();\n\t}\n\n\t/**\n\t * Transpiles the given Java AST.\n\t * \n\t * @param transpilationHandler the log handler\n\t * @param tree                 the AST to be transpiled\n\t * @param targetFileName       the name of the file (without any extension)\n\t *                             where to put the transpilation output\n\t * @throws IOException\n\t */\n\tpublic String transpile(ErrorCountTranspilationHandler handler, JCTree tree, String targetFileName)\n\t\t\tthrows IOException {\n\t\tJava2TypeScriptTranslator translator = factory.createTranslator(adapter, handler, context, null, false);\n\t\ttranslator.enterScope();\n\t\ttranslator.scan(tree);\n\t\ttranslator.exitScope();\n\t\tString tsCode = translator.getResult();\n\t\treturn ts2js(handler, tsCode, targetFileName);\n\t}\n\n\t@Override\n\tpublic boolean isGenerateDefinitions() {\n\t\treturn generateDefinitions;\n\t}\n\n\tpublic void setGenerateDefinitions(boolean generateDefinitions) {\n\t\tthis.generateDefinitions = generateDefinitions;\n\t}\n\n\t@Override\n\tpublic File getSourceRoot() {\n\t\treturn sourceRoot;\n\t}\n\n\tpublic void setSourceRoot(File sourceRoot) {\n\t\tthis.sourceRoot = sourceRoot;\n\t}\n\n\t@Override\n\tpublic Map<String, Object> getConfiguration() {\n\t\treturn configuration;\n\t}\n\n\t@Override\n\tpublic boolean isIgnoreTypeScriptErrors() {\n\t\treturn ignoreTypeScriptErrors;\n\t}\n\n\tpublic void setIgnoreTypeScriptErrors(boolean ignoreTypeScriptErrors) {\n\t\tthis.ignoreTypeScriptErrors = ignoreTypeScriptErrors;\n\t}\n\n\t@Override\n\tpublic File getHeaderFile() {\n\t\treturn headerFile;\n\t}\n\n\tpublic void setHeaderFile(File headerFile) {\n\t\tthis.headerFile = headerFile;\n\t}\n\n\tprivate String[] getHeaderLines() {\n\t\tString[] headerLines = null;\n\t\tif (getHeaderFile() != null) {\n\t\t\ttry {\n\t\t\t\theaderLines = FileUtils.readLines(getHeaderFile(), getEncoding()).toArray(new String[0]);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\"cannot read header file: \" + getHeaderFile() + \" - using default header\");\n\t\t\t}\n\t\t}\n\t\tif (headerLines == null) {\n\t\t\theaderLines = new String[] { \"/* Generated from Java with JSweet \" + JSweetConfig.getVersionNumber()\n\t\t\t\t\t+ \" - http://www.jsweet.org */\" };\n\t\t}\n\t\tif (context.options.isDebugMode()) {\n\t\t\theaderLines = ArrayUtils.add(headerLines,\n\t\t\t\t\t\"declare function __debug_exec(className, functionName, argNames, target, args, generator);\");\n\t\t\theaderLines = ArrayUtils.add(headerLines, \"declare function __debug_result(expression);\");\n\t\t}\n\t\treturn headerLines;\n\t}\n\n\t@Override\n\tpublic boolean isGenerateTsFiles() {\n\t\treturn generateTsFiles;\n\t}\n\n\tpublic void setGenerateTsFiles(boolean generateTsFiles) {\n\t\tthis.generateTsFiles = generateTsFiles;\n\t}\n\n\t@Override\n\tpublic boolean isIgnoreJavaErrors() {\n\t\treturn ignoreJavaErrors;\n\t}\n\n\tpublic void setIgnoreJavaErrors(boolean ignoreJavaErrors) {\n\t\tthis.ignoreJavaErrors = ignoreJavaErrors;\n\t}\n\n\tpublic JSweetContext getContext() {\n\t\treturn context;\n\t}\n\n\tpublic Options getOptions() {\n\t\treturn options;\n\t}\n\n\t@Override\n\tpublic boolean isDebugMode() {\n\t\treturn debugMode;\n\t}\n\n\tpublic void setDebugMode(boolean debugMode) {\n\t\tthis.debugMode = debugMode;\n\t}\n\n\t@Override\n\tpublic boolean isVerbose() {\n\t\treturn LogManager.getLogger(\"org.jsweet\").getLevel() == Level.ALL;\n\t}\n\n\tpublic void setVerbose(boolean verbose) {\n\t\tLevel level = Level.WARN;\n\t\tif (verbose) {\n\t\t\tlevel = Level.ALL;\n\t\t}\n\t\tLogManager.getLogger(\"org.jsweet\").setLevel(level);\n\t}\n\n\t@Override\n\tpublic boolean isDisableSinglePrecisionFloats() {\n\t\treturn disableSingleFloatPrecision;\n\t}\n\n\tpublic void setDisableSinglePrecisionFloats(boolean disableSinglePrecisionFloats) {\n\t\tthis.disableSingleFloatPrecision = disableSinglePrecisionFloats;\n\t}\n\n\t// @SuppressWarnings(\"unchecked\")\n\t// private <T> T getConfigurationValue(String key) {\n\t// return (T) getConfiguration().get(key);\n\t// }\n\n\t@Override\n\tpublic java.util.List<String> getAdapters() {\n\t\treturn adapters;\n\t}\n\n\tpublic void setAdapters(java.util.List<String> adapters) {\n\t\tthis.adapters = new ArrayList<>(adapters);\n\t}\n\n\t@Override\n\tpublic File getConfigurationFile() {\n\t\treturn configurationFile;\n\t}\n\n\tpublic String getClassPath() {\n\t\treturn classPath;\n\t}\n\n\tpublic boolean isIgnoreCandiesTypeScriptDefinitions() {\n\t\treturn ignoreCandiesTypeScriptDefinitions;\n\t}\n\n\tpublic void setIgnoreCandiesTypeScriptDefinitions(boolean ignoreCandiesTypeScriptDefinitions) {\n\t\tthis.ignoreCandiesTypeScriptDefinitions = ignoreCandiesTypeScriptDefinitions;\n\t}\n}\n", "human_rating": 2.9813892014795, "metadata": {"project": "jsweet", "class": "org.jsweet.transpiler.JSweetTranspiler", "source_path": "Jsweet/sourcefiles/transpiler/src/main/java/org/jsweet/transpiler/JSweetTranspiler.java", "label_probabilities": {"readability": [0.0, 0.981389, 0.0186111, 1.4795e-09], "understandability": [2.48148e-06, 0.0519105, 0.948084, 2.57688e-06], "complexity": [0.302649, 0.697351, 0.0, 0.0], "modularization": [0.999998, 1.64669e-06, 0.0, 0.0], "overall": [0.0, 5.96013e-08, 0.116192, 0.883808]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/org.jsweet.transpiler.model.support.CompilationUnitElementSupport", "source": "/* \n * JSweet transpiler - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *  \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\npackage org.jsweet.transpiler.model.support;\n\nimport javax.lang.model.element.PackageElement;\n\nimport org.jsweet.transpiler.model.CompilationUnitElement;\n\nimport com.sun.tools.javac.tree.JCTree.JCCompilationUnit;\n\n/**\n * See {@link CompilationUnitElement}.\n * \n * @author Renaud Pawlak\n */\npublic class CompilationUnitElementSupport extends ExtendedElementSupport<JCCompilationUnit> implements CompilationUnitElement {\n\n\tpublic CompilationUnitElementSupport(JCCompilationUnit tree) {\n\t\tsuper(tree);\n\t}\n\n\t@Override\n\tpublic PackageElement getPackage() {\n\t\treturn tree.packge;\n\t}\n\n\t@Override\n\tpublic String getSourceFilePath() {\n\t\treturn tree.sourcefile.getName();\n\t}\n\t\n\t\n}\n", "human_rating": 3.927985835881085, "metadata": {"project": "jsweet", "class": "org.jsweet.transpiler.model.support.CompilationUnitElementSupport", "source_path": "Jsweet/sourcefiles/transpiler/src/main/java/org/jsweet/transpiler/model/support/CompilationUnitElementSupport.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/org.jsweet.transpiler.ModuleImportDescriptor", "source": "/* \n * JSweet transpiler - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *  \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\npackage org.jsweet.transpiler;\n\nimport javax.lang.model.element.PackageElement;\n\n/**\n * This class describes a module import.\n * \n * @author Renaud Pawlak\n */\npublic class ModuleImportDescriptor {\n\tpublic ModuleImportDescriptor(PackageElement targetPackage, String importedName, String pathToImportedClass) {\n\t\tsuper();\n\t\tthis.targetPackage = targetPackage;\n\t\tthis.importedName = importedName;\n\t\tthis.pathToImportedClass = pathToImportedClass;\n\t}\n\n\tprivate PackageElement targetPackage;\n\tprivate String importedName;\n\tprivate String pathToImportedClass;\n\n\t/**\n\t * Gets the package of the element being imported.\n\t */\n\tpublic PackageElement getTargetPackage() {\n\t\treturn targetPackage;\n\t}\n\n\t/**\n\t * Gets the name of the import.\n\t */\n\tpublic String getImportedName() {\n\t\treturn importedName;\n\t}\n\n\t/**\n\t * Gets the path to the imported class.\n\t */\n\tpublic String getPathToImportedClass() {\n\t\treturn pathToImportedClass;\n\t}\n}", "human_rating": 3.973538576000013, "metadata": {"project": "jsweet", "class": "org.jsweet.transpiler.ModuleImportDescriptor", "source_path": "Jsweet/sourcefiles/transpiler/src/main/java/org/jsweet/transpiler/ModuleImportDescriptor.java", "label_probabilities": {"readability": [0.97354, 0.0264578, 2.588e-06, 1.30881e-14], "understandability": [0.969643, 0.0303298, 2.68883e-05, 3.095e-17], "complexity": [2.1823e-16, 5.01846e-06, 0.0374895, 0.962505], "modularization": [3.5e-18, 5.55856e-05, 0.0339101, 0.966034], "overall": [0.990516, 0.00948377, 5.99246e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/jsweet/org.jsweet.transpiler.util.ErrorCountTranspilationHandler", "source": "/* \n * JSweet transpiler - http://www.jsweet.org\n * Copyright (C) 2015 CINCHEO SAS <renaud.pawlak@cincheo.fr>\n * \n * This program is free software; you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *  \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n */\npackage org.jsweet.transpiler.util;\n\nimport org.jsweet.transpiler.JSweetProblem;\nimport org.jsweet.transpiler.SourcePosition;\nimport org.jsweet.transpiler.TranspilationHandler;\n\n/**\n * An error count decorator for a transpilation handler.\n * \n * @author Renaud Pawlak\n */\npublic class ErrorCountTranspilationHandler extends AbstractDelegatedTranspilationHandler {\n\n\tprivate int errorCount = 0;\n\tprivate int warningCount = 0;\n\tprivate int problemCount = 0;\n\tprivate boolean disabled = false;\n\n\t/**\n\t * Decorates the given transpilation handler.\n\t */\n\tpublic ErrorCountTranspilationHandler(TranspilationHandler delegate) {\n\t\tsuper(delegate);\n\t}\n\n\t/**\n\t * Count the problems and delegates to the decorated transpilation handler.\n\t */\n\tpublic void report(JSweetProblem problem, SourcePosition sourcePosition, String message) {\n\t\tif (!disabled) {\n\t\t\tswitch (problem.getSeverity()) {\n\t\t\tcase ERROR:\n\t\t\t\tproblemCount++;\n\t\t\t\terrorCount++;\n\t\t\t\tbreak;\n\t\t\tcase WARNING:\n\t\t\t\tproblemCount++;\n\t\t\t\twarningCount++;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tproblemCount++;\n\t\t\t}\n\t\t}\n\t\tsuper.report(problem, sourcePosition, message);\n\t}\n\n\t/**\n\t * Returns the error count.\n\t */\n\tpublic int getErrorCount() {\n\t\treturn errorCount;\n\t}\n\n\t/**\n\t * Returns the warning count.\n\t */\n\tpublic int getWarningCount() {\n\t\treturn warningCount;\n\t}\n\n\t/**\n\t * Returns the problem count (error + warning count).\n\t */\n\tpublic int getProblemCount() {\n\t\treturn problemCount;\n\t}\n\n\t/**\n\t * Returns false if this handler actually counts anything.\n\t */\n\tpublic boolean isDisabled() {\n\t\treturn disabled;\n\t}\n\n\t/**\n\t * Enables/disables the counting.\n\t */\n\tpublic void setDisabled(boolean disabled) {\n\t\tthis.disabled = disabled;\n\t}\n\n}\n", "human_rating": 3.973538576000013, "metadata": {"project": "jsweet", "class": "org.jsweet.transpiler.util.ErrorCountTranspilationHandler", "source_path": "Jsweet/sourcefiles/transpiler/src/main/java/org/jsweet/transpiler/util/ErrorCountTranspilationHandler.java", "label_probabilities": {"readability": [0.97354, 0.0264578, 2.588e-06, 1.30881e-14], "understandability": [0.969643, 0.0303298, 2.68883e-05, 3.095e-17], "complexity": [2.1823e-16, 5.01846e-06, 0.0374895, 0.962505], "modularization": [3.5e-18, 5.55856e-05, 0.0339101, 0.966034], "overall": [0.990516, 0.00948377, 5.99246e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.extensions.RepeatedTest", "source": "package junit.extensions;\n\nimport junit.framework.Test;\nimport junit.framework.TestResult;\n\n/**\n * A Decorator that runs a test repeatedly.\n */\npublic class RepeatedTest extends TestDecorator {\n    private int fTimesRepeat;\n\n    public RepeatedTest(Test test, int repeat) {\n        super(test);\n        if (repeat < 0) {\n            throw new IllegalArgumentException(\"Repetition count must be >= 0\");\n        }\n        fTimesRepeat = repeat;\n    }\n\n    @Override\n    public int countTestCases() {\n        return super.countTestCases() * fTimesRepeat;\n    }\n\n    @Override\n    public void run(TestResult result) {\n        for (int i = 0; i < fTimesRepeat; i++) {\n            if (result.shouldStop()) {\n                break;\n            }\n            super.run(result);\n        }\n    }\n\n    @Override\n    public String toString() {\n        return super.toString() + \"(repeated)\";\n    }\n}", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "junit.extensions.RepeatedTest", "source_path": "junit4/sourcefiles/src/main/java/junit/extensions/RepeatedTest.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.extensions.TestDecorator", "source": "package junit.extensions;\n\nimport junit.framework.Assert;\nimport junit.framework.Test;\nimport junit.framework.TestResult;\n\n/**\n * A Decorator for Tests. Use TestDecorator as the base class for defining new\n * test decorators. Test decorator subclasses can be introduced to add behaviour\n * before or after a test is run.\n */\npublic class TestDecorator extends Assert implements Test {\n    protected Test fTest;\n\n    public TestDecorator(Test test) {\n        fTest = test;\n    }\n\n    /**\n     * The basic run behaviour.\n     */\n    public void basicRun(TestResult result) {\n        fTest.run(result);\n    }\n\n    public int countTestCases() {\n        return fTest.countTestCases();\n    }\n\n    public void run(TestResult result) {\n        basicRun(result);\n    }\n\n    @Override\n    public String toString() {\n        return fTest.toString();\n    }\n\n    public Test getTest() {\n        return fTest;\n    }\n}", "human_rating": 3.9678160391699997, "metadata": {"project": "junit4", "class": "junit.extensions.TestDecorator", "source_path": "junit4/sourcefiles/src/main/java/junit/extensions/TestDecorator.java", "label_probabilities": {"readability": [0.967815, 0.0321851, 3.69585e-07, 3.22e-17], "understandability": [0.968864, 0.0311358, 3.51835e-07, 2.27174e-15], "complexity": [1.02515e-15, 6.754e-06, 0.0614659, 0.938527], "modularization": [0.0, 4.96842e-10, 0.0753064, 0.924694], "overall": [0.98976, 0.0102397, 1.642e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.framework.Assert", "source": "package junit.framework;\n\n/**\n * A set of assert methods.  Messages are only displayed when an assert fails.\n *\n * @deprecated Please use {@link org.junit.Assert} instead.\n */\n@Deprecated\npublic class Assert {\n    /**\n     * Protect constructor since it is a static only class\n     */\n    protected Assert() {\n    }\n\n    /**\n     * Asserts that a condition is true. If it isn't it throws\n     * an AssertionFailedError with the given message.\n     */\n    static public void assertTrue(String message, boolean condition) {\n        if (!condition) {\n            fail(message);\n        }\n    }\n\n    /**\n     * Asserts that a condition is true. If it isn't it throws\n     * an AssertionFailedError.\n     */\n    static public void assertTrue(boolean condition) {\n        assertTrue(null, condition);\n    }\n\n    /**\n     * Asserts that a condition is false. If it isn't it throws\n     * an AssertionFailedError with the given message.\n     */\n    static public void assertFalse(String message, boolean condition) {\n        assertTrue(message, !condition);\n    }\n\n    /**\n     * Asserts that a condition is false. If it isn't it throws\n     * an AssertionFailedError.\n     */\n    static public void assertFalse(boolean condition) {\n        assertFalse(null, condition);\n    }\n\n    /**\n     * Fails a test with the given message.\n     */\n    static public void fail(String message) {\n        if (message == null) {\n            throw new AssertionFailedError();\n        }\n        throw new AssertionFailedError(message);\n    }\n\n    /**\n     * Fails a test with no message.\n     */\n    static public void fail() {\n        fail(null);\n    }\n\n    /**\n     * Asserts that two objects are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertEquals(String message, Object expected, Object actual) {\n        if (expected == null && actual == null) {\n            return;\n        }\n        if (expected != null && expected.equals(actual)) {\n            return;\n        }\n        failNotEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two objects are equal. If they are not\n     * an AssertionFailedError is thrown.\n     */\n    static public void assertEquals(Object expected, Object actual) {\n        assertEquals(null, expected, actual);\n    }\n\n    /**\n     * Asserts that two Strings are equal.\n     */\n    static public void assertEquals(String message, String expected, String actual) {\n        if (expected == null && actual == null) {\n            return;\n        }\n        if (expected != null && expected.equals(actual)) {\n            return;\n        }\n        String cleanMessage = message == null ? \"\" : message;\n        throw new ComparisonFailure(cleanMessage, expected, actual);\n    }\n\n    /**\n     * Asserts that two Strings are equal.\n     */\n    static public void assertEquals(String expected, String actual) {\n        assertEquals(null, expected, actual);\n    }\n\n    /**\n     * Asserts that two doubles are equal concerning a delta.  If they are not\n     * an AssertionFailedError is thrown with the given message.  If the expected\n     * value is infinity then the delta value is ignored.\n     */\n    static public void assertEquals(String message, double expected, double actual, double delta) {\n        if (Double.compare(expected, actual) == 0) {\n            return;\n        }\n        if (!(Math.abs(expected - actual) <= delta)) {\n            failNotEquals(message, new Double(expected), new Double(actual));\n        }\n    }\n\n    /**\n     * Asserts that two doubles are equal concerning a delta. If the expected\n     * value is infinity then the delta value is ignored.\n     */\n    static public void assertEquals(double expected, double actual, double delta) {\n        assertEquals(null, expected, actual, delta);\n    }\n\n    /**\n     * Asserts that two floats are equal concerning a positive delta. If they\n     * are not an AssertionFailedError is thrown with the given message. If the\n     * expected value is infinity then the delta value is ignored.\n     */\n    static public void assertEquals(String message, float expected, float actual, float delta) {\n        if (Float.compare(expected, actual) == 0) {\n            return;\n        }\n        if (!(Math.abs(expected - actual) <= delta)) {\n            failNotEquals(message, new Float(expected), new Float(actual));\n        }\n    }\n\n    /**\n     * Asserts that two floats are equal concerning a delta. If the expected\n     * value is infinity then the delta value is ignored.\n     */\n    static public void assertEquals(float expected, float actual, float delta) {\n        assertEquals(null, expected, actual, delta);\n    }\n\n    /**\n     * Asserts that two longs are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertEquals(String message, long expected, long actual) {\n        assertEquals(message, Long.valueOf(expected), Long.valueOf(actual));\n    }\n\n    /**\n     * Asserts that two longs are equal.\n     */\n    static public void assertEquals(long expected, long actual) {\n        assertEquals(null, expected, actual);\n    }\n\n    /**\n     * Asserts that two booleans are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertEquals(String message, boolean expected, boolean actual) {\n        assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual));\n    }\n\n    /**\n     * Asserts that two booleans are equal.\n     */\n    static public void assertEquals(boolean expected, boolean actual) {\n        assertEquals(null, expected, actual);\n    }\n\n    /**\n     * Asserts that two bytes are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertEquals(String message, byte expected, byte actual) {\n        assertEquals(message, Byte.valueOf(expected), Byte.valueOf(actual));\n    }\n\n    /**\n     * Asserts that two bytes are equal.\n     */\n    static public void assertEquals(byte expected, byte actual) {\n        assertEquals(null, expected, actual);\n    }\n\n    /**\n     * Asserts that two chars are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertEquals(String message, char expected, char actual) {\n        assertEquals(message, Character.valueOf(expected), Character.valueOf(actual));\n    }\n\n    /**\n     * Asserts that two chars are equal.\n     */\n    static public void assertEquals(char expected, char actual) {\n        assertEquals(null, expected, actual);\n    }\n\n    /**\n     * Asserts that two shorts are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertEquals(String message, short expected, short actual) {\n        assertEquals(message, Short.valueOf(expected), Short.valueOf(actual));\n    }\n\n    /**\n     * Asserts that two shorts are equal.\n     */\n    static public void assertEquals(short expected, short actual) {\n        assertEquals(null, expected, actual);\n    }\n\n    /**\n     * Asserts that two ints are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertEquals(String message, int expected, int actual) {\n        assertEquals(message, Integer.valueOf(expected), Integer.valueOf(actual));\n    }\n\n    /**\n     * Asserts that two ints are equal.\n     */\n    static public void assertEquals(int expected, int actual) {\n        assertEquals(null, expected, actual);\n    }\n\n    /**\n     * Asserts that an object isn't null.\n     */\n    static public void assertNotNull(Object object) {\n        assertNotNull(null, object);\n    }\n\n    /**\n     * Asserts that an object isn't null. If it is\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertNotNull(String message, Object object) {\n        assertTrue(message, object != null);\n    }\n\n    /**\n     * Asserts that an object is null. If it isn't an {@link AssertionError} is\n     * thrown.\n     * Message contains: Expected: <null> but was: object\n     *\n     * @param object Object to check or <code>null</code>\n     */\n    static public void assertNull(Object object) {\n        if (object != null) {\n            assertNull(\"Expected: <null> but was: \" + object.toString(), object);\n        }\n    }\n\n    /**\n     * Asserts that an object is null.  If it is not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertNull(String message, Object object) {\n        assertTrue(message, object == null);\n    }\n\n    /**\n     * Asserts that two objects refer to the same object. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    static public void assertSame(String message, Object expected, Object actual) {\n        if (expected == actual) {\n            return;\n        }\n        failNotSame(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two objects refer to the same object. If they are not\n     * the same an AssertionFailedError is thrown.\n     */\n    static public void assertSame(Object expected, Object actual) {\n        assertSame(null, expected, actual);\n    }\n\n    /**\n     * Asserts that two objects do not refer to the same object. If they do\n     * refer to the same object an AssertionFailedError is thrown with the\n     * given message.\n     */\n    static public void assertNotSame(String message, Object expected, Object actual) {\n        if (expected == actual) {\n            failSame(message);\n        }\n    }\n\n    /**\n     * Asserts that two objects do not refer to the same object. If they do\n     * refer to the same object an AssertionFailedError is thrown.\n     */\n    static public void assertNotSame(Object expected, Object actual) {\n        assertNotSame(null, expected, actual);\n    }\n\n    static public void failSame(String message) {\n        String formatted = (message != null) ? message + \" \" : \"\";\n        fail(formatted + \"expected not same\");\n    }\n\n    static public void failNotSame(String message, Object expected, Object actual) {\n        String formatted = (message != null) ? message + \" \" : \"\";\n        fail(formatted + \"expected same:<\" + expected + \"> was not:<\" + actual + \">\");\n    }\n\n    static public void failNotEquals(String message, Object expected, Object actual) {\n        fail(format(message, expected, actual));\n    }\n\n    public static String format(String message, Object expected, Object actual) {\n        String formatted = \"\";\n        if (message != null && message.length() > 0) {\n            formatted = message + \" \";\n        }\n        return formatted + \"expected:<\" + expected + \"> but was:<\" + actual + \">\";\n    }\n}\n", "human_rating": 3.9571827370002413, "metadata": {"project": "junit4", "class": "junit.framework.Assert", "source_path": "junit4/sourcefiles/src/main/java/junit/framework/Assert.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.framework.AssertionFailedError", "source": "package junit.framework;\n\n/**\n * Thrown when an assertion failed.\n */\npublic class AssertionFailedError extends AssertionError {\n\n    private static final long serialVersionUID = 1L;\n\n    public AssertionFailedError() {\n    }\n\n    public AssertionFailedError(String message) {\n        super(defaultString(message));\n    }\n\n    private static String defaultString(String message) {\n        return message == null ? \"\" : message;\n    }\n}", "human_rating": 3.99847319, "metadata": {"project": "junit4", "class": "junit.framework.AssertionFailedError", "source_path": "junit4/sourcefiles/src/main/java/junit/framework/AssertionFailedError.java", "label_probabilities": {"readability": [0.998474, 0.00152573, 0.0, 0.0], "understandability": [2.48894e-05, 0.999975, 1.45397e-11, 0.0], "complexity": [0.0, 0.0, 0.00243856, 0.997561], "modularization": [0.0, 0.0, 9e-20, 1.0], "overall": [1.0, 2.69749e-14, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.framework.ComparisonCompactor", "source": "package junit.framework;\n\npublic class ComparisonCompactor {\n\n    private static final String ELLIPSIS = \"...\";\n    private static final String DELTA_END = \"]\";\n    private static final String DELTA_START = \"[\";\n\n    private int fContextLength;\n    private String fExpected;\n    private String fActual;\n    private int fPrefix;\n    private int fSuffix;\n\n    public ComparisonCompactor(int contextLength, String expected, String actual) {\n        fContextLength = contextLength;\n        fExpected = expected;\n        fActual = actual;\n    }\n\n    public String compact(String message) {\n        if (fExpected == null || fActual == null || areStringsEqual()) {\n            return Assert.format(message, fExpected, fActual);\n        }\n\n        findCommonPrefix();\n        findCommonSuffix();\n        String expected = compactString(fExpected);\n        String actual = compactString(fActual);\n        return Assert.format(message, expected, actual);\n    }\n\n    private String compactString(String source) {\n        String result = DELTA_START + source.substring(fPrefix, source.length() - fSuffix + 1) + DELTA_END;\n        if (fPrefix > 0) {\n            result = computeCommonPrefix() + result;\n        }\n        if (fSuffix > 0) {\n            result = result + computeCommonSuffix();\n        }\n        return result;\n    }\n\n    private void findCommonPrefix() {\n        fPrefix = 0;\n        int end = Math.min(fExpected.length(), fActual.length());\n        for (; fPrefix < end; fPrefix++) {\n            if (fExpected.charAt(fPrefix) != fActual.charAt(fPrefix)) {\n                break;\n            }\n        }\n    }\n\n    private void findCommonSuffix() {\n        int expectedSuffix = fExpected.length() - 1;\n        int actualSuffix = fActual.length() - 1;\n        for (; actualSuffix >= fPrefix && expectedSuffix >= fPrefix; actualSuffix--, expectedSuffix--) {\n            if (fExpected.charAt(expectedSuffix) != fActual.charAt(actualSuffix)) {\n                break;\n            }\n        }\n        fSuffix = fExpected.length() - expectedSuffix;\n    }\n\n    private String computeCommonPrefix() {\n        return (fPrefix > fContextLength ? ELLIPSIS : \"\") + fExpected.substring(Math.max(0, fPrefix - fContextLength), fPrefix);\n    }\n\n    private String computeCommonSuffix() {\n        int end = Math.min(fExpected.length() - fSuffix + 1 + fContextLength, fExpected.length());\n        return fExpected.substring(fExpected.length() - fSuffix + 1, end) + (fExpected.length() - fSuffix + 1 < fExpected.length() - fContextLength ? ELLIPSIS : \"\");\n    }\n\n    private boolean areStringsEqual() {\n        return fExpected.equals(fActual);\n    }\n}\n", "human_rating": 3.0002079, "metadata": {"project": "junit4", "class": "junit.framework.ComparisonCompactor", "source_path": "junit4/sourcefiles/src/main/java/junit/framework/ComparisonCompactor.java", "label_probabilities": {"readability": [0.0420995, 0.930063, 0.0137837, 0.0140535], "understandability": [0.0431342, 0.943166, 0.0137002, 7.69729e-10], "complexity": [2.88337e-07, 0.00651462, 0.804444, 0.189041], "modularization": [2.209e-17, 6.29103e-05, 0.0339099, 0.966027], "overall": [0.0513299, 0.948668, 1.66176e-06, 6e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.framework.JUnit4TestAdapter", "source": "package junit.framework;\n\nimport java.util.List;\n\nimport org.junit.Ignore;\nimport org.junit.runner.Describable;\nimport org.junit.runner.Description;\nimport org.junit.runner.Request;\nimport org.junit.runner.Runner;\nimport org.junit.runner.manipulation.Filter;\nimport org.junit.runner.manipulation.Filterable;\nimport org.junit.runner.manipulation.NoTestsRemainException;\nimport org.junit.runner.manipulation.Sortable;\nimport org.junit.runner.manipulation.Sorter;\n\npublic class JUnit4TestAdapter implements Test, Filterable, Sortable, Describable {\n    private final Class<?> fNewTestClass;\n\n    private final Runner fRunner;\n\n    private final JUnit4TestAdapterCache fCache;\n\n    public JUnit4TestAdapter(Class<?> newTestClass) {\n        this(newTestClass, JUnit4TestAdapterCache.getDefault());\n    }\n\n    public JUnit4TestAdapter(final Class<?> newTestClass, JUnit4TestAdapterCache cache) {\n        fCache = cache;\n        fNewTestClass = newTestClass;\n        fRunner = Request.classWithoutSuiteMethod(newTestClass).getRunner();\n    }\n\n    public int countTestCases() {\n        return fRunner.testCount();\n    }\n\n    public void run(TestResult result) {\n        fRunner.run(fCache.getNotifier(result, this));\n    }\n\n    // reflective interface for Eclipse\n    public List<Test> getTests() {\n        return fCache.asTestList(getDescription());\n    }\n\n    // reflective interface for Eclipse\n    public Class<?> getTestClass() {\n        return fNewTestClass;\n    }\n\n    public Description getDescription() {\n        Description description = fRunner.getDescription();\n        return removeIgnored(description);\n    }\n\n    private Description removeIgnored(Description description) {\n        if (isIgnored(description)) {\n            return Description.EMPTY;\n        }\n        Description result = description.childlessCopy();\n        for (Description each : description.getChildren()) {\n            Description child = removeIgnored(each);\n            if (!child.isEmpty()) {\n                result.addChild(child);\n            }\n        }\n        return result;\n    }\n\n    private boolean isIgnored(Description description) {\n        return description.getAnnotation(Ignore.class) != null;\n    }\n\n    @Override\n    public String toString() {\n        return fNewTestClass.getName();\n    }\n\n    public void filter(Filter filter) throws NoTestsRemainException {\n        filter.apply(fRunner);\n    }\n\n    public void sort(Sorter sorter) {\n        sorter.apply(fRunner);\n    }\n}", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "junit.framework.JUnit4TestAdapter", "source_path": "junit4/sourcefiles/src/main/java/junit/framework/JUnit4TestAdapter.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.framework.JUnit4TestCaseFacade", "source": "package junit.framework;\n\nimport org.junit.runner.Describable;\nimport org.junit.runner.Description;\n\npublic class JUnit4TestCaseFacade implements Test, Describable {\n    private final Description fDescription;\n\n    JUnit4TestCaseFacade(Description description) {\n        fDescription = description;\n    }\n\n    @Override\n    public String toString() {\n        return getDescription().toString();\n    }\n\n    public int countTestCases() {\n        return 1;\n    }\n\n    public void run(TestResult result) {\n        throw new RuntimeException(\n                \"This test stub created only for informational purposes.\");\n    }\n\n    public Description getDescription() {\n        return fDescription;\n    }\n}", "human_rating": 3.949780154780024, "metadata": {"project": "junit4", "class": "junit.framework.JUnit4TestCaseFacade", "source_path": "junit4/sourcefiles/src/main/java/junit/framework/JUnit4TestCaseFacade.java", "label_probabilities": {"readability": [0.949787, 0.0502067, 6.02739e-06, 2.37972e-14], "understandability": [0.935149, 0.0647859, 6.51511e-05, 2.4182e-16], "complexity": [2.69749e-15, 1.35403e-05, 0.082906, 0.91708], "modularization": [2.895e-17, 8.9233e-05, 0.0388652, 0.961046], "overall": [0.979707, 0.0202933, 3.12146e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.framework.TestCase", "source": "package junit.framework;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\n\n/**\n * A test case defines the fixture to run multiple tests. To define a test case<br/>\n * <ol>\n *   <li>implement a subclass of <code>TestCase</code></li>\n *   <li>define instance variables that store the state of the fixture</li>\n *   <li>initialize the fixture state by overriding {@link #setUp()}</li>\n *   <li>clean-up after a test by overriding {@link #tearDown()}.</li>\n * </ol>\n * Each test runs in its own fixture so there\n * can be no side effects among test runs.\n * Here is an example:\n * <pre>\n * public class MathTest extends TestCase {\n *    protected double fValue1;\n *    protected double fValue2;\n *\n *    protected void setUp() {\n *       fValue1= 2.0;\n *       fValue2= 3.0;\n *    }\n * }\n * </pre>\n *\n * For each test implement a method which interacts\n * with the fixture. Verify the expected results with assertions specified\n * by calling {@link junit.framework.Assert#assertTrue(String, boolean)} with a boolean.\n * <pre>\n *    public void testAdd() {\n *       double result= fValue1 + fValue2;\n *       assertTrue(result == 5.0);\n *    }\n * </pre>\n *\n * Once the methods are defined you can run them. The framework supports\n * both a static type safe and more dynamic way to run a test.\n * In the static way you override the runTest method and define the method to\n * be invoked. A convenient way to do so is with an anonymous inner class.\n * <pre>\n * TestCase test= new MathTest(\"add\") {\n *    public void runTest() {\n *       testAdd();\n *    }\n * };\n * test.run();\n * </pre>\n * The dynamic way uses reflection to implement {@link #runTest()}. It dynamically finds\n * and invokes a method.\n * In this case the name of the test case has to correspond to the test method\n * to be run.\n * <pre>\n * TestCase test= new MathTest(\"testAdd\");\n * test.run();\n * </pre>\n *\n * The tests to be run can be collected into a TestSuite. JUnit provides\n * different <i>test runners</i> which can run a test suite and collect the results.\n * A test runner either expects a static method <code>suite</code> as the entry\n * point to get a test to run or it will extract the suite automatically.\n * <pre>\n * public static Test suite() {\n *    suite.addTest(new MathTest(\"testAdd\"));\n *    suite.addTest(new MathTest(\"testDivideByZero\"));\n *    return suite;\n * }\n * </pre>\n *\n * @see TestResult\n * @see TestSuite\n */\npublic abstract class TestCase extends Assert implements Test {\n    /**\n     * the name of the test case\n     */\n    private String fName;\n\n    /**\n     * No-arg constructor to enable serialization. This method\n     * is not intended to be used by mere mortals without calling setName().\n     */\n    public TestCase() {\n        fName = null;\n    }\n\n    /**\n     * Constructs a test case with the given name.\n     */\n    public TestCase(String name) {\n        fName = name;\n    }\n\n    /**\n     * Counts the number of test cases executed by run(TestResult result).\n     */\n    public int countTestCases() {\n        return 1;\n    }\n\n    /**\n     * Creates a default TestResult object\n     *\n     * @see TestResult\n     */\n    protected TestResult createResult() {\n        return new TestResult();\n    }\n\n    /**\n     * A convenience method to run this test, collecting the results with a\n     * default TestResult object.\n     *\n     * @see TestResult\n     */\n    public TestResult run() {\n        TestResult result = createResult();\n        run(result);\n        return result;\n    }\n\n    /**\n     * Runs the test case and collects the results in TestResult.\n     */\n    public void run(TestResult result) {\n        result.run(this);\n    }\n\n    /**\n     * Runs the bare test sequence.\n     *\n     * @throws Throwable if any exception is thrown\n     */\n    public void runBare() throws Throwable {\n        Throwable exception = null;\n        setUp();\n        try {\n            runTest();\n        } catch (Throwable running) {\n            exception = running;\n        } finally {\n            try {\n                tearDown();\n            } catch (Throwable tearingDown) {\n                if (exception == null) exception = tearingDown;\n            }\n        }\n        if (exception != null) throw exception;\n    }\n\n    /**\n     * Override to run the test and assert its state.\n     *\n     * @throws Throwable if any exception is thrown\n     */\n    protected void runTest() throws Throwable {\n        assertNotNull(\"TestCase.fName cannot be null\", fName); // Some VMs crash when calling getMethod(null,null);\n        Method runMethod = null;\n        try {\n            // use getMethod to get all public inherited\n            // methods. getDeclaredMethods returns all\n            // methods of this class but excludes the\n            // inherited ones.\n            runMethod = getClass().getMethod(fName, (Class[]) null);\n        } catch (NoSuchMethodException e) {\n            fail(\"Method \\\"\" + fName + \"\\\" not found\");\n        }\n        if (!Modifier.isPublic(runMethod.getModifiers())) {\n            fail(\"Method \\\"\" + fName + \"\\\" should be public\");\n        }\n\n        try {\n            runMethod.invoke(this);\n        } catch (InvocationTargetException e) {\n            e.fillInStackTrace();\n            throw e.getTargetException();\n        } catch (IllegalAccessException e) {\n            e.fillInStackTrace();\n            throw e;\n        }\n    }\n\n    /**\n     * Asserts that a condition is true. If it isn't it throws\n     * an AssertionFailedError with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertTrue(String message, boolean condition) {\n        Assert.assertTrue(message, condition);\n    }\n\n    /**\n     * Asserts that a condition is true. If it isn't it throws\n     * an AssertionFailedError.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertTrue(boolean condition) {\n        Assert.assertTrue(condition);\n    }\n\n    /**\n     * Asserts that a condition is false. If it isn't it throws\n     * an AssertionFailedError with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertFalse(String message, boolean condition) {\n        Assert.assertFalse(message, condition);\n    }\n\n    /**\n     * Asserts that a condition is false. If it isn't it throws\n     * an AssertionFailedError.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertFalse(boolean condition) {\n        Assert.assertFalse(condition);\n    }\n\n    /**\n     * Fails a test with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void fail(String message) {\n        Assert.fail(message);\n    }\n\n    /**\n     * Fails a test with no message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void fail() {\n        Assert.fail();\n    }\n\n    /**\n     * Asserts that two objects are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, Object expected, Object actual) {\n        Assert.assertEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two objects are equal. If they are not\n     * an AssertionFailedError is thrown.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(Object expected, Object actual) {\n        Assert.assertEquals(expected, actual);\n    }\n\n    /**\n     * Asserts that two Strings are equal.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, String expected, String actual) {\n        Assert.assertEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two Strings are equal.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String expected, String actual) {\n        Assert.assertEquals(expected, actual);\n    }\n\n    /**\n     * Asserts that two doubles are equal concerning a delta.  If they are not\n     * an AssertionFailedError is thrown with the given message.  If the expected\n     * value is infinity then the delta value is ignored.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, double expected, double actual, double delta) {\n        Assert.assertEquals(message, expected, actual, delta);\n    }\n\n    /**\n     * Asserts that two doubles are equal concerning a delta. If the expected\n     * value is infinity then the delta value is ignored.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(double expected, double actual, double delta) {\n        Assert.assertEquals(expected, actual, delta);\n    }\n\n    /**\n     * Asserts that two floats are equal concerning a positive delta. If they\n     * are not an AssertionFailedError is thrown with the given message. If the\n     * expected value is infinity then the delta value is ignored.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, float expected, float actual, float delta) {\n        Assert.assertEquals(message, expected, actual, delta);\n    }\n\n    /**\n     * Asserts that two floats are equal concerning a delta. If the expected\n     * value is infinity then the delta value is ignored.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(float expected, float actual, float delta) {\n        Assert.assertEquals(expected, actual, delta);\n    }\n\n    /**\n     * Asserts that two longs are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, long expected, long actual) {\n        Assert.assertEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two longs are equal.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(long expected, long actual) {\n        Assert.assertEquals(expected, actual);\n    }\n\n    /**\n     * Asserts that two booleans are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, boolean expected, boolean actual) {\n        Assert.assertEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two booleans are equal.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(boolean expected, boolean actual) {\n        Assert.assertEquals(expected, actual);\n    }\n\n    /**\n     * Asserts that two bytes are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, byte expected, byte actual) {\n        Assert.assertEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two bytes are equal.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(byte expected, byte actual) {\n        Assert.assertEquals(expected, actual);\n    }\n\n    /**\n     * Asserts that two chars are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, char expected, char actual) {\n        Assert.assertEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two chars are equal.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(char expected, char actual) {\n        Assert.assertEquals(expected, actual);\n    }\n\n    /**\n     * Asserts that two shorts are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, short expected, short actual) {\n        Assert.assertEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two shorts are equal.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(short expected, short actual) {\n        Assert.assertEquals(expected, actual);\n    }\n\n    /**\n     * Asserts that two ints are equal. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(String message, int expected, int actual) {\n        Assert.assertEquals(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two ints are equal.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertEquals(int expected, int actual) {\n        Assert.assertEquals(expected, actual);\n    }\n\n    /**\n     * Asserts that an object isn't null.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertNotNull(Object object) {\n        Assert.assertNotNull(object);\n    }\n\n    /**\n     * Asserts that an object isn't null. If it is\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertNotNull(String message, Object object) {\n        Assert.assertNotNull(message, object);\n    }\n\n    /**\n     * Asserts that an object is null. If it isn't an {@link AssertionError} is\n     * thrown.\n     * Message contains: Expected: <null> but was: object\n     *\n     * @param object Object to check or <code>null</code>\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertNull(Object object) {\n        Assert.assertNull(object);\n    }\n\n    /**\n     * Asserts that an object is null.  If it is not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertNull(String message, Object object) {\n        Assert.assertNull(message, object);\n    }\n\n    /**\n     * Asserts that two objects refer to the same object. If they are not\n     * an AssertionFailedError is thrown with the given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertSame(String message, Object expected, Object actual) {\n        Assert.assertSame(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two objects refer to the same object. If they are not\n     * the same an AssertionFailedError is thrown.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertSame(Object expected, Object actual) {\n        Assert.assertSame(expected, actual);\n    }\n\n    /**\n     * Asserts that two objects do not refer to the same object. If they do\n     * refer to the same object an AssertionFailedError is thrown with the\n     * given message.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertNotSame(String message, Object expected, Object actual) {\n        Assert.assertNotSame(message, expected, actual);\n    }\n\n    /**\n     * Asserts that two objects do not refer to the same object. If they do\n     * refer to the same object an AssertionFailedError is thrown.\n     */\n    @SuppressWarnings(\"deprecation\")\n    public static void assertNotSame(Object expected, Object actual) {\n        Assert.assertNotSame(expected, actual);\n    }\n\n    @SuppressWarnings(\"deprecation\")\n    public static void failSame(String message) {\n        Assert.failSame(message);\n    }\n\n    @SuppressWarnings(\"deprecation\")\n    public static void failNotSame(String message, Object expected, Object actual) {\n        Assert.failNotSame(message, expected, actual);\n    }\n\n    @SuppressWarnings(\"deprecation\")\n    public static void failNotEquals(String message, Object expected, Object actual) {\n        Assert.failNotEquals(message, expected, actual);\n    }\n\n    @SuppressWarnings(\"deprecation\")\n    public static String format(String message, Object expected, Object actual) {\n        return Assert.format(message, expected, actual);\n    }\n\n    /**\n     * Sets up the fixture, for example, open a network connection.\n     * This method is called before a test is executed.\n     */\n    protected void setUp() throws Exception {\n    }\n\n    /**\n     * Tears down the fixture, for example, close a network connection.\n     * This method is called after a test is executed.\n     */\n    protected void tearDown() throws Exception {\n    }\n\n    /**\n     * Returns a string representation of the test case\n     */\n    @Override\n    public String toString() {\n        return getName() + \"(\" + getClass().getName() + \")\";\n    }\n\n    /**\n     * Gets the name of a TestCase\n     *\n     * @return the name of the TestCase\n     */\n    public String getName() {\n        return fName;\n    }\n\n    /**\n     * Sets the name of a TestCase\n     *\n     * @param name the name to set\n     */\n    public void setName(String name) {\n        fName = name;\n    }\n}\n", "human_rating": 3.9582949010401, "metadata": {"project": "junit4", "class": "junit.framework.TestCase", "source_path": "junit4/sourcefiles/src/main/java/junit/framework/TestCase.java", "label_probabilities": {"readability": [0.958295, 0.0417043, 1.00052e-06, 9.98987e-14], "understandability": [0.968477, 0.0315224, 4.69583e-07, 1.31449e-13], "complexity": [3.78658e-13, 0.00216642, 0.962878, 0.0349552], "modularization": [0.0, 4.84987e-11, 0.0203369, 0.979663], "overall": [0.994958, 0.00504182, 1.47754e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.framework.TestResult", "source": "package junit.framework;\n\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Enumeration;\nimport java.util.List;\n\n/**\n * A <code>TestResult</code> collects the results of executing\n * a test case. It is an instance of the Collecting Parameter pattern.\n * The test framework distinguishes between <i>failures</i> and <i>errors</i>.\n * A failure is anticipated and checked for with assertions. Errors are\n * unanticipated problems like an {@link ArrayIndexOutOfBoundsException}.\n *\n * @see Test\n */\npublic class TestResult {\n    protected List<TestFailure> fFailures;\n    protected List<TestFailure> fErrors;\n    protected List<TestListener> fListeners;\n    protected int fRunTests;\n    private boolean fStop;\n\n    public TestResult() {\n        fFailures = new ArrayList<TestFailure>();\n        fErrors = new ArrayList<TestFailure>();\n        fListeners = new ArrayList<TestListener>();\n        fRunTests = 0;\n        fStop = false;\n    }\n\n    /**\n     * Adds an error to the list of errors. The passed in exception\n     * caused the error.\n     */\n    public synchronized void addError(Test test, Throwable e) {\n        fErrors.add(new TestFailure(test, e));\n        for (TestListener each : cloneListeners()) {\n            each.addError(test, e);\n        }\n    }\n\n    /**\n     * Adds a failure to the list of failures. The passed in exception\n     * caused the failure.\n     */\n    public synchronized void addFailure(Test test, AssertionFailedError e) {\n        fFailures.add(new TestFailure(test, e));\n        for (TestListener each : cloneListeners()) {\n            each.addFailure(test, e);\n        }\n    }\n\n    /**\n     * Registers a TestListener\n     */\n    public synchronized void addListener(TestListener listener) {\n        fListeners.add(listener);\n    }\n\n    /**\n     * Unregisters a TestListener\n     */\n    public synchronized void removeListener(TestListener listener) {\n        fListeners.remove(listener);\n    }\n\n    /**\n     * Returns a copy of the listeners.\n     */\n    private synchronized List<TestListener> cloneListeners() {\n        List<TestListener> result = new ArrayList<TestListener>();\n        result.addAll(fListeners);\n        return result;\n    }\n\n    /**\n     * Informs the result that a test was completed.\n     */\n    public void endTest(Test test) {\n        for (TestListener each : cloneListeners()) {\n            each.endTest(test);\n        }\n    }\n\n    /**\n     * Gets the number of detected errors.\n     */\n    public synchronized int errorCount() {\n        return fErrors.size();\n    }\n\n    /**\n     * Returns an Enumeration for the errors\n     */\n    public synchronized Enumeration<TestFailure> errors() {\n        return Collections.enumeration(fErrors);\n    }\n\n\n    /**\n     * Gets the number of detected failures.\n     */\n    public synchronized int failureCount() {\n        return fFailures.size();\n    }\n\n    /**\n     * Returns an Enumeration for the failures\n     */\n    public synchronized Enumeration<TestFailure> failures() {\n        return Collections.enumeration(fFailures);\n    }\n\n    /**\n     * Runs a TestCase.\n     */\n    protected void run(final TestCase test) {\n        startTest(test);\n        Protectable p = new Protectable() {\n            public void protect() throws Throwable {\n                test.runBare();\n            }\n        };\n        runProtected(test, p);\n\n        endTest(test);\n    }\n\n    /**\n     * Gets the number of run tests.\n     */\n    public synchronized int runCount() {\n        return fRunTests;\n    }\n\n    /**\n     * Runs a TestCase.\n     */\n    public void runProtected(final Test test, Protectable p) {\n        try {\n            p.protect();\n        } catch (AssertionFailedError e) {\n            addFailure(test, e);\n        } catch (ThreadDeath e) { // don't catch ThreadDeath by accident\n            throw e;\n        } catch (Throwable e) {\n            addError(test, e);\n        }\n    }\n\n    /**\n     * Checks whether the test run should stop\n     */\n    public synchronized boolean shouldStop() {\n        return fStop;\n    }\n\n    /**\n     * Informs the result that a test will be started.\n     */\n    public void startTest(Test test) {\n        final int count = test.countTestCases();\n        synchronized (this) {\n            fRunTests += count;\n        }\n        for (TestListener each : cloneListeners()) {\n            each.startTest(test);\n        }\n    }\n\n    /**\n     * Marks that the test run should stop.\n     */\n    public synchronized void stop() {\n        fStop = true;\n    }\n\n    /**\n     * Returns whether the entire test was successful or not.\n     */\n    public synchronized boolean wasSuccessful() {\n        return failureCount() == 0 && errorCount() == 0;\n    }\n}\n", "human_rating": 3.927985835881085, "metadata": {"project": "junit4", "class": "junit.framework.TestResult", "source_path": "junit4/sourcefiles/src/main/java/junit/framework/TestResult.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/junit.textui.TestRunner", "source": "package junit.textui;\n\n\nimport java.io.PrintStream;\n\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestResult;\nimport junit.framework.TestSuite;\nimport junit.runner.BaseTestRunner;\nimport junit.runner.Version;\n\n/**\n * A command line based tool to run tests.\n * <pre>\n * java junit.textui.TestRunner [-wait] TestCaseClass\n * </pre>\n * <p>\n * TestRunner expects the name of a TestCase class as argument.\n * If this class defines a static <code>suite</code> method it\n * will be invoked and the returned test is run. Otherwise all\n * the methods starting with \"test\" having no arguments are run.\n * <p>\n * When the wait command line argument is given TestRunner\n * waits until the users types RETURN.\n * <p>\n * TestRunner prints a trace as the tests are executed followed by a\n * summary at the end.\n */\npublic class TestRunner extends BaseTestRunner {\n    private ResultPrinter fPrinter;\n\n    public static final int SUCCESS_EXIT = 0;\n    public static final int FAILURE_EXIT = 1;\n    public static final int EXCEPTION_EXIT = 2;\n\n    /**\n     * Constructs a TestRunner.\n     */\n    public TestRunner() {\n        this(System.out);\n    }\n\n    /**\n     * Constructs a TestRunner using the given stream for all the output\n     */\n    public TestRunner(PrintStream writer) {\n        this(new ResultPrinter(writer));\n    }\n\n    /**\n     * Constructs a TestRunner using the given ResultPrinter all the output\n     */\n    public TestRunner(ResultPrinter printer) {\n        fPrinter = printer;\n    }\n\n    /**\n     * Runs a suite extracted from a TestCase subclass.\n     */\n    static public void run(Class<? extends TestCase> testClass) {\n        run(new TestSuite(testClass));\n    }\n\n    /**\n     * Runs a single test and collects its results.\n     * This method can be used to start a test run\n     * from your program.\n     * <pre>\n     * public static void main (String[] args) {\n     *    test.textui.TestRunner.run(suite());\n     * }\n     * </pre>\n     */\n    static public TestResult run(Test test) {\n        TestRunner runner = new TestRunner();\n        return runner.doRun(test);\n    }\n\n    /**\n     * Runs a single test and waits until the user\n     * types RETURN.\n     */\n    static public void runAndWait(Test suite) {\n        TestRunner aTestRunner = new TestRunner();\n        aTestRunner.doRun(suite, true);\n    }\n\n    @Override\n    public void testFailed(int status, Test test, Throwable e) {\n    }\n\n    @Override\n    public void testStarted(String testName) {\n    }\n\n    @Override\n    public void testEnded(String testName) {\n    }\n\n    /**\n     * Creates the TestResult to be used for the test run.\n     */\n    protected TestResult createTestResult() {\n        return new TestResult();\n    }\n\n    public TestResult doRun(Test test) {\n        return doRun(test, false);\n    }\n\n    public TestResult doRun(Test suite, boolean wait) {\n        TestResult result = createTestResult();\n        result.addListener(fPrinter);\n        long startTime = System.currentTimeMillis();\n        suite.run(result);\n        long endTime = System.currentTimeMillis();\n        long runTime = endTime - startTime;\n        fPrinter.print(result, runTime);\n\n        pause(wait);\n        return result;\n    }\n\n    protected void pause(boolean wait) {\n        if (!wait) return;\n        fPrinter.printWaitPrompt();\n        try {\n            System.in.read();\n        } catch (Exception e) {\n        }\n    }\n\n    public static void main(String args[]) {\n        TestRunner aTestRunner = new TestRunner();\n        try {\n            TestResult r = aTestRunner.start(args);\n            if (!r.wasSuccessful()) {\n                System.exit(FAILURE_EXIT);\n            }\n            System.exit(SUCCESS_EXIT);\n        } catch (Exception e) {\n            System.err.println(e.getMessage());\n            System.exit(EXCEPTION_EXIT);\n        }\n    }\n\n    /**\n     * Starts a test run. Analyzes the command line arguments and runs the given\n     * test suite.\n     */\n    public TestResult start(String args[]) throws Exception {\n        String testCase = \"\";\n        String method = \"\";\n        boolean wait = false;\n\n        for (int i = 0; i < args.length; i++) {\n            if (args[i].equals(\"-wait\")) {\n                wait = true;\n            } else if (args[i].equals(\"-c\")) {\n                testCase = extractClassName(args[++i]);\n            } else if (args[i].equals(\"-m\")) {\n                String arg = args[++i];\n                int lastIndex = arg.lastIndexOf('.');\n                testCase = arg.substring(0, lastIndex);\n                method = arg.substring(lastIndex + 1);\n            } else if (args[i].equals(\"-v\")) {\n                System.err.println(\"JUnit \" + Version.id() + \" by Kent Beck and Erich Gamma\");\n            } else {\n                testCase = args[i];\n            }\n        }\n\n        if (testCase.equals(\"\")) {\n            throw new Exception(\"Usage: TestRunner [-wait] testCaseName, where name is the name of the TestCase class\");\n        }\n\n        try {\n            if (!method.equals(\"\")) {\n                return runSingleMethod(testCase, method, wait);\n            }\n            Test suite = getTest(testCase);\n            return doRun(suite, wait);\n        } catch (Exception e) {\n            throw new Exception(\"Could not create and run test suite: \" + e);\n        }\n    }\n\n    protected TestResult runSingleMethod(String testCase, String method, boolean wait) throws Exception {\n        Class<? extends TestCase> testClass = loadSuiteClass(testCase).asSubclass(TestCase.class);\n        Test test = TestSuite.createTest(testClass, method);\n        return doRun(test, wait);\n    }\n\n    @Override\n    protected void runFailed(String message) {\n        System.err.println(message);\n        System.exit(FAILURE_EXIT);\n    }\n\n    public void setPrinter(ResultPrinter printer) {\n        fPrinter = printer;\n    }\n\n\n}", "human_rating": 4.000000000030692, "metadata": {"project": "junit4", "class": "junit.textui.TestRunner", "source_path": "junit4/sourcefiles/src/main/java/junit/textui/TestRunner.java", "label_probabilities": {"readability": [1.0, 1.02307e-11, 0.0, 0.0], "understandability": [1.0, 1.99865e-07, 0.0, 0.0], "complexity": [0.0, 0.0, 2.54161e-05, 0.999975], "modularization": [0.0, 0.0, 0.0, 1.0], "overall": [0.999999, 7.99459e-07, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.Assume", "source": "package org.junit;\n\nimport static java.util.Arrays.asList;\nimport static org.hamcrest.CoreMatchers.everyItem;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.CoreMatchers.notNullValue;\nimport static org.hamcrest.CoreMatchers.nullValue;\n\nimport org.hamcrest.Matcher;\n\n/**\n * A set of methods useful for stating assumptions about the conditions in which a test is meaningful.\n * A failed assumption does not mean the code is broken, but that the test provides no useful information.\n * The default JUnit runner treats tests with failing assumptions as ignored.  Custom runners may behave differently.\n *\n * For example:\n * <pre>\n * // only provides information if database is reachable.\n * &#064;Test public void calculateTotalSalary() {\n *    DBConnection dbc = Database.connect();\n *    assumeNotNull(dbc);\n *    // ...\n * }\n * </pre>\n * These methods can be used directly: <code>Assume.assumeTrue(...)</code>, however, they\n * read better if they are referenced through static import:<br/>\n * <pre>\n * import static org.junit.Assume.*;\n *    ...\n *    assumeTrue(...);\n * </pre>\n *\n * @since 4.4\n */\npublic class Assume {\n    /**\n     * If called with an expression evaluating to {@code false}, the test will halt and be ignored.\n     */\n    public static void assumeTrue(boolean b) {\n        assumeThat(b, is(true));\n    }\n\n    /**\n     * The inverse of {@link #assumeTrue(boolean)}.\n     */\n    public static void assumeFalse(boolean b) {\n        assumeTrue(!b);\n    }\n\n    /**\n     * If called with an expression evaluating to {@code false}, the test will halt and be ignored.\n     *\n     * @param b If <code>false</code>, the method will attempt to stop the test and ignore it by\n     * throwing {@link AssumptionViolatedException}.\n     * @param message A message to pass to {@link AssumptionViolatedException}.\n     */\n    public static void assumeTrue(String message, boolean b) {\n        if (!b) throw new AssumptionViolatedException(message);\n    }\n\n    /**\n     * The inverse of {@link #assumeTrue(String, boolean)}.\n     */\n    public static void assumeFalse(String message, boolean b) {\n        assumeTrue(message, !b);\n    }\n\n    /**\n     * If called with one or more null elements in <code>objects</code>, the test will halt and be ignored.\n     */\n    public static void assumeNotNull(Object... objects) {\n        assumeThat(asList(objects), everyItem(notNullValue()));\n    }\n\n    /**\n     * Call to assume that <code>actual</code> satisfies the condition specified by <code>matcher</code>.\n     * If not, the test halts and is ignored.\n     * Example:\n     * <pre>:\n     *   assumeThat(1, is(1)); // passes\n     *   foo(); // will execute\n     *   assumeThat(0, is(1)); // assumption failure! test halts\n     *   int x = 1 / 0; // will never execute\n     * </pre>\n     *\n     * @param <T> the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is(\"a\"))}\n     * @param actual the computed value being compared\n     * @param matcher an expression, built of {@link Matcher}s, specifying allowed values\n     * @see org.hamcrest.CoreMatchers\n     * @see org.junit.matchers.JUnitMatchers\n     */\n    public static <T> void assumeThat(T actual, Matcher<T> matcher) {\n        if (!matcher.matches(actual)) {\n            throw new AssumptionViolatedException(actual, matcher);\n        }\n    }\n\n    /**\n     * Call to assume that <code>actual</code> satisfies the condition specified by <code>matcher</code>.\n     * If not, the test halts and is ignored.\n     * Example:\n     * <pre>:\n     *   assumeThat(1, is(1)); // passes\n     *   foo(); // will execute\n     *   assumeThat(0, is(1)); // assumption failure! test halts\n     *   int x = 1 / 0; // will never execute\n     * </pre>\n     *\n     * @param <T> the static type accepted by the matcher (this can flag obvious compile-time problems such as {@code assumeThat(1, is(\"a\"))}\n     * @param actual the computed value being compared\n     * @param matcher an expression, built of {@link Matcher}s, specifying allowed values\n     * @see org.hamcrest.CoreMatchers\n     * @see org.junit.matchers.JUnitMatchers\n     */\n    public static <T> void assumeThat(String message, T actual, Matcher<T> matcher) {\n        if (!matcher.matches(actual)) {\n            throw new AssumptionViolatedException(message, actual, matcher);\n        }\n    }\n\n    /**\n     * Use to assume that an operation completes normally.  If {@code e} is non-null, the test will halt and be ignored.\n     *\n     * For example:\n     * <pre>\n     * \\@Test public void parseDataFile() {\n     *   DataFile file;\n     *   try {\n     *     file = DataFile.open(\"sampledata.txt\");\n     *   } catch (IOException e) {\n     *     // stop test and ignore if data can't be opened\n     *     assumeNoException(e);\n     *   }\n     *   // ...\n     * }\n     * </pre>\n     *\n     * @param e if non-null, the offending exception\n     */\n    public static void assumeNoException(Throwable e) {\n        assumeThat(e, nullValue());\n    }\n\n    /**\n     * Attempts to halt the test and ignore it if Throwable <code>e</code> is\n     * not <code>null</code>. Similar to {@link #assumeNoException(Throwable)},\n     * but provides an additional message that can explain the details\n     * concerning the assumption.\n     *\n     * @param e if non-null, the offending exception\n     * @param message Additional message to pass to {@link AssumptionViolatedException}.\n     * @see #assumeNoException(Throwable)\n     */\n    public static void assumeNoException(String message, Throwable e) {\n        assumeThat(message, e, nullValue());\n    }\n}\n", "human_rating": 3.9571827370002413, "metadata": {"project": "junit4", "class": "org.junit.Assume", "source_path": "junit4/sourcefiles/src/main/java/org/junit/Assume.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.ComparisonFailure", "source": "package org.junit;\n\n/**\n * Thrown when an {@link org.junit.Assert#assertEquals(Object, Object) assertEquals(String, String)} fails. Create and throw\n * a <code>ComparisonFailure</code> manually if you want to show users the difference between two complex\n * strings.\n *\n * Inspired by a patch from Alex Chaffee (alex@purpletech.com)\n *\n * @since 4.0\n */\npublic class ComparisonFailure extends AssertionError {\n    /**\n     * The maximum length for expected and actual strings. If it is exceeded, the strings should be shortened.\n     *\n     * @see ComparisonCompactor\n     */\n    private static final int MAX_CONTEXT_LENGTH = 20;\n    private static final long serialVersionUID = 1L;\n\n    private String expected;\n    private String actual;\n\n    /**\n     * Constructs a comparison failure.\n     *\n     * @param message the identifying message or null\n     * @param expected the expected string value\n     * @param actual the actual string value\n     */\n    public ComparisonFailure(String message, String expected, String actual) {\n        super(message);\n        this.expected = expected;\n        this.actual = actual;\n    }\n\n    /**\n     * Returns \"...\" in place of common prefix and \"...\" in\n     * place of common suffix between expected and actual.\n     *\n     * @see Throwable#getMessage()\n     */\n    @Override\n    public String getMessage() {\n        return new ComparisonCompactor(MAX_CONTEXT_LENGTH, expected, actual).compact(super.getMessage());\n    }\n\n    /**\n     * Returns the actual string value\n     *\n     * @return the actual string value\n     */\n    public String getActual() {\n        return actual;\n    }\n\n    /**\n     * Returns the expected string value\n     *\n     * @return the expected string value\n     */\n    public String getExpected() {\n        return expected;\n    }\n\n    private static class ComparisonCompactor {\n        private static final String ELLIPSIS = \"...\";\n        private static final String DELTA_END = \"]\";\n        private static final String DELTA_START = \"[\";\n\n        /**\n         * The maximum length for <code>expected</code> and <code>actual</code> strings to show. When <code>contextLength</code>\n         * is exceeded, the Strings are shortened.\n         */\n        private int contextLength;\n        \n        private String expected;\n        private String actual;\n        \n        /**\n         * The length of the shared prefix / suffix of the expected and actual strings.\n         * Equals to zero if the strings do not share a common prefix/suffix.\n         */\n        private int prefix;\n        private int suffix;\n\n        /**\n         * @param contextLength the maximum length for <code>expected</code> and <code>actual</code> strings. When contextLength\n         * is exceeded, the Strings are shortened.\n         * @param expected the expected string value\n         * @param actual the actual string value\n         */\n        public ComparisonCompactor(int contextLength, String expected, String actual) {\n            this.contextLength = contextLength;\n            this.expected = expected;\n            this.actual = actual;\n        }\n\n        private String compact(String message) {\n            if (expected == null || actual == null || areStringsEqual()) {\n                return Assert.format(message, expected, actual);\n            }\n\n            findCommonPrefix();\n            findCommonSuffix();\n            String expected = compactString(this.expected);\n            String actual = compactString(this.actual);\n            return Assert.format(message, expected, actual);\n        }\n\n        private String compactString(String source) {\n            String result = DELTA_START + source.substring(prefix, source.length() - suffix) + DELTA_END;\n            if (prefix > 0) {\n                result = computeCommonPrefix() + result;\n            }\n            if (suffix > 0) {\n                result = result + computeCommonSuffix();\n            }\n            return result;\n        }\n\n        private void findCommonPrefix() {\n            prefix = 0;\n            int end = Math.min(expected.length(), actual.length());\n            for (; prefix < end; prefix++) {\n                if (expected.charAt(prefix) != actual.charAt(prefix)) {\n                    break;\n                }\n            }\n        }\n\n        private void findCommonSuffix() {\n            int expectedSuffix = expected.length() - 1;\n            int actualSuffix = actual.length() - 1;\n            for (; actualSuffix >= prefix && expectedSuffix >= prefix; actualSuffix--, expectedSuffix--) {\n                if (expected.charAt(expectedSuffix) != actual.charAt(actualSuffix)) {\n                    break;\n                }\n            }\n            suffix = expected.length() - expectedSuffix - 1;\n        }\n\n        private String computeCommonPrefix() {\n            return (prefix > contextLength ? ELLIPSIS : \"\") + expected.substring(Math.max(0, prefix - contextLength), prefix);\n        }\n\n        private String computeCommonSuffix() {\n            int end = Math.min(expected.length() - suffix + contextLength, expected.length());\n            return expected.substring(expected.length() - suffix, end) + (expected.length() - suffix < expected.length() - contextLength ? ELLIPSIS : \"\");\n        }\n\n        private boolean areStringsEqual() {\n            return expected.equals(actual);\n        }\n    }\n}", "human_rating": 3.7543581356027556, "metadata": {"project": "junit4", "class": "org.junit.ComparisonFailure", "source_path": "junit4/sourcefiles/src/main/java/org/junit/ComparisonFailure.java", "label_probabilities": {"readability": [0.754403, 0.245552, 4.50678e-05, 2.75536e-12], "understandability": [0.825915, 0.173218, 0.000867019, 9.57171e-12], "complexity": [0.000223985, 0.00908973, 0.726575, 0.264111], "modularization": [2.1878e-07, 0.000424501, 0.15506, 0.844516], "overall": [0.439977, 0.560021, 1.7413e-06, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.categories.Categories", "source": "package org.junit.experimental.categories;\n\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.util.Collections;\nimport java.util.HashSet;\nimport java.util.Set;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.manipulation.Filter;\nimport org.junit.runner.manipulation.NoTestsRemainException;\nimport org.junit.runners.Suite;\nimport org.junit.runners.model.InitializationError;\nimport org.junit.runners.model.RunnerBuilder;\n\n/**\n * From a given set of test classes, runs only the classes and methods that are\n * annotated with either the category given with the @IncludeCategory\n * annotation, or a subtype of that category.\n * <p>\n * Note that, for now, annotating suites with {@code @Category} has no effect.\n * Categories must be annotated on the direct method or class.\n * <p>\n * Example:\n * <pre>\n * public interface FastTests {\n * }\n *\n * public interface SlowTests {\n * }\n *\n * public interface SmokeTests\n * }\n *\n * public static class A {\n *     &#064;Test\n *     public void a() {\n *         fail();\n *     }\n *\n *     &#064;Category(SlowTests.class)\n *     &#064;Test\n *     public void b() {\n *     }\n *\n *     &#064;Category({FastTests.class, SmokeTests.class})\n *     &#064;Test\n *     public void c() {\n *     }\n * }\n *\n * &#064;Category({SlowTests.class, FastTests.class})\n * public static class B {\n *     &#064;Test\n *     public void d() {\n *     }\n * }\n *\n * &#064;RunWith(Categories.class)\n * &#064;IncludeCategory(SlowTests.class)\n * &#064;SuiteClasses({A.class, B.class})\n * // Note that Categories is a kind of Suite\n * public static class SlowTestSuite {\n *     // Will run A.b and B.d, but not A.a and A.c\n * }\n * </pre>\n * <p>\n * Example to run multiple categories:\n * <pre>\n * &#064;RunWith(Categories.class)\n * &#064;IncludeCategory({FastTests.class, SmokeTests.class})\n * &#064;SuiteClasses({A.class, B.class})\n * public static class FastOrSmokeTestSuite {\n *     // Will run A.c and B.d, but not A.b because it is not any of FastTests or SmokeTests\n * }\n * </pre>\n *\n * @version 4.12\n * @see <a href=\"https://github.com/junit-team/junit/wiki/Categories\">Categories at JUnit wiki</a>\n */\npublic class Categories extends Suite {\n    // the way filters are implemented makes this unnecessarily complicated,\n    // buggy, and difficult to specify.  A new way of handling filters could\n    // someday enable a better new implementation.\n    // https://github.com/junit-team/junit/issues/issue/172\n\n    @Retention(RetentionPolicy.RUNTIME)\n    public @interface IncludeCategory {\n        /**\n         * Determines the tests to run that are annotated with categories specified in\n         * the value of this annotation or their subtypes unless excluded with {@link ExcludeCategory}.\n         */\n        public Class<?>[] value() default {};\n\n        /**\n         * If <tt>true</tt>, runs tests annotated with <em>any</em> of the categories in\n         * {@link IncludeCategory#value()}. Otherwise, runs tests only if annotated with <em>all</em> of the categories.\n         */\n        public boolean matchAny() default true;\n    }\n\n    @Retention(RetentionPolicy.RUNTIME)\n    public @interface ExcludeCategory {\n        /**\n         * Determines the tests which do not run if they are annotated with categories specified in the\n         * value of this annotation or their subtypes regardless of being included in {@link IncludeCategory#value()}.\n         */\n        public Class<?>[] value() default {};\n\n        /**\n         * If <tt>true</tt>, the tests annotated with <em>any</em> of the categories in {@link ExcludeCategory#value()}\n         * do not run. Otherwise, the tests do not run if and only if annotated with <em>all</em> categories.\n         */\n        public boolean matchAny() default true;\n    }\n\n    public static class CategoryFilter extends Filter {\n        private final Set<Class<?>> fIncluded;\n        private final Set<Class<?>> fExcluded;\n        private final boolean fIncludedAny;\n        private final boolean fExcludedAny;\n\n        public static CategoryFilter include(boolean matchAny, Class<?>... categories) {\n            if (hasNull(categories)) {\n                throw new NullPointerException(\"has null category\");\n            }\n            return categoryFilter(matchAny, createSet(categories), true, null);\n        }\n\n        public static CategoryFilter include(Class<?> category) {\n            return include(true, category);\n        }\n\n        public static CategoryFilter include(Class<?>... categories) {\n            return include(true, categories);\n        }\n\n        public static CategoryFilter exclude(boolean matchAny, Class<?>... categories) {\n            if (hasNull(categories)) {\n                throw new NullPointerException(\"has null category\");\n            }\n            return categoryFilter(true, null, matchAny, createSet(categories));\n        }\n\n        public static CategoryFilter exclude(Class<?> category) {\n            return exclude(true, category);\n        }\n\n        public static CategoryFilter exclude(Class<?>... categories) {\n            return exclude(true, categories);\n        }\n\n        public static CategoryFilter categoryFilter(boolean matchAnyInclusions, Set<Class<?>> inclusions,\n                                                    boolean matchAnyExclusions, Set<Class<?>> exclusions) {\n            return new CategoryFilter(matchAnyInclusions, inclusions, matchAnyExclusions, exclusions);\n        }\n\n        protected CategoryFilter(boolean matchAnyIncludes, Set<Class<?>> includes,\n                               boolean matchAnyExcludes, Set<Class<?>> excludes) {\n            fIncludedAny= matchAnyIncludes;\n            fExcludedAny= matchAnyExcludes;\n            fIncluded= copyAndRefine(includes);\n            fExcluded= copyAndRefine(excludes);\n        }\n\n        /**\n         * @see #toString()\n         */\n        @Override\n        public String describe() {\n            return toString();\n        }\n\n        /**\n         * Returns string in the form <tt>&quot;[included categories] - [excluded categories]&quot;</tt>, where both\n         * sets have comma separated names of categories.\n         *\n         * @return string representation for the relative complement of excluded categories set\n         * in the set of included categories. Examples:\n         * <ul>\n         *  <li> <tt>&quot;categories [all]&quot;</tt> for all included categories and no excluded ones;\n         *  <li> <tt>&quot;categories [all] - [A, B]&quot;</tt> for all included categories and given excluded ones;\n         *  <li> <tt>&quot;categories [A, B] - [C, D]&quot;</tt> for given included categories and given excluded ones.\n         * </ul>\n         * @see Class#toString() name of category\n         */\n        @Override public String toString() {\n            StringBuilder description= new StringBuilder(\"categories \")\n                .append(fIncluded.isEmpty() ? \"[all]\" : fIncluded);\n            if (!fExcluded.isEmpty()) {\n                description.append(\" - \").append(fExcluded);\n            }\n            return description.toString();\n        }\n\n        @Override\n        public boolean shouldRun(Description description) {\n            if (hasCorrectCategoryAnnotation(description)) {\n                return true;\n            }\n\n            for (Description each : description.getChildren()) {\n                if (shouldRun(each)) {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n\n        private boolean hasCorrectCategoryAnnotation(Description description) {\n            final Set<Class<?>> childCategories= categories(description);\n\n            // If a child has no categories, immediately return.\n            if (childCategories.isEmpty()) {\n                return fIncluded.isEmpty();\n            }\n\n            if (!fExcluded.isEmpty()) {\n                if (fExcludedAny) {\n                    if (matchesAnyParentCategories(childCategories, fExcluded)) {\n                        return false;\n                    }\n                } else {\n                    if (matchesAllParentCategories(childCategories, fExcluded)) {\n                        return false;\n                    }\n                }\n            }\n\n            if (fIncluded.isEmpty()) {\n                // Couldn't be excluded, and with no suite's included categories treated as should run.\n                return true;\n            } else {\n                if (fIncludedAny) {\n                    return matchesAnyParentCategories(childCategories, fIncluded);\n                } else {\n                    return matchesAllParentCategories(childCategories, fIncluded);\n                }\n            }\n        }\n\n        /**\n         * @return <tt>true</tt> if at least one (any) parent category match a child, otherwise <tt>false</tt>.\n         * If empty <tt>parentCategories</tt>, returns <tt>false</tt>.\n         */\n        private boolean matchesAnyParentCategories(Set<Class<?>> childCategories, Set<Class<?>> parentCategories) {\n            for (Class<?> parentCategory : parentCategories) {\n                if (hasAssignableTo(childCategories, parentCategory)) {\n                    return true;\n                }\n            }\n            return false;\n        }\n\n        /**\n         * @return <tt>false</tt> if at least one parent category does not match children, otherwise <tt>true</tt>.\n         * If empty <tt>parentCategories</tt>, returns <tt>true</tt>.\n         */\n        private boolean matchesAllParentCategories(Set<Class<?>> childCategories, Set<Class<?>> parentCategories) {\n            for (Class<?> parentCategory : parentCategories) {\n                if (!hasAssignableTo(childCategories, parentCategory)) {\n                    return false;\n                }\n            }\n            return true;\n        }\n\n        private static Set<Class<?>> categories(Description description) {\n            Set<Class<?>> categories= new HashSet<Class<?>>();\n            Collections.addAll(categories, directCategories(description));\n            Collections.addAll(categories, directCategories(parentDescription(description)));\n            return categories;\n        }\n\n        private static Description parentDescription(Description description) {\n            Class<?> testClass= description.getTestClass();\n            return testClass == null ? null : Description.createSuiteDescription(testClass);\n        }\n\n        private static Class<?>[] directCategories(Description description) {\n            if (description == null) {\n                return new Class<?>[0];\n            }\n\n            Category annotation= description.getAnnotation(Category.class);\n            return annotation == null ? new Class<?>[0] : annotation.value();\n        }\n\n        private static Set<Class<?>> copyAndRefine(Set<Class<?>> classes) {\n            HashSet<Class<?>> c= new HashSet<Class<?>>();\n            if (classes != null) {\n                c.addAll(classes);\n            }\n            c.remove(null);\n            return c;\n        }\n\n        private static boolean hasNull(Class<?>... classes) {\n            if (classes == null) return false;\n            for (Class<?> clazz : classes) {\n                if (clazz == null) {\n                    return true;\n                }\n            }\n            return false;\n        }\n    }\n\n    public Categories(Class<?> klass, RunnerBuilder builder) throws InitializationError {\n        super(klass, builder);\n        try {\n            Set<Class<?>> included= getIncludedCategory(klass);\n            Set<Class<?>> excluded= getExcludedCategory(klass);\n            boolean isAnyIncluded= isAnyIncluded(klass);\n            boolean isAnyExcluded= isAnyExcluded(klass);\n\n            filter(CategoryFilter.categoryFilter(isAnyIncluded, included, isAnyExcluded, excluded));\n        } catch (NoTestsRemainException e) {\n            throw new InitializationError(e);\n        }\n        assertNoCategorizedDescendentsOfUncategorizeableParents(getDescription());\n    }\n\n    private static Set<Class<?>> getIncludedCategory(Class<?> klass) {\n        IncludeCategory annotation= klass.getAnnotation(IncludeCategory.class);\n        return createSet(annotation == null ? null : annotation.value());\n    }\n\n    private static boolean isAnyIncluded(Class<?> klass) {\n        IncludeCategory annotation= klass.getAnnotation(IncludeCategory.class);\n        return annotation == null || annotation.matchAny();\n    }\n\n    private static Set<Class<?>> getExcludedCategory(Class<?> klass) {\n        ExcludeCategory annotation= klass.getAnnotation(ExcludeCategory.class);\n        return createSet(annotation == null ? null : annotation.value());\n    }\n\n    private static boolean isAnyExcluded(Class<?> klass) {\n        ExcludeCategory annotation= klass.getAnnotation(ExcludeCategory.class);\n        return annotation == null || annotation.matchAny();\n    }\n\n    private static void assertNoCategorizedDescendentsOfUncategorizeableParents(Description description) throws InitializationError {\n        if (!canHaveCategorizedChildren(description)) {\n            assertNoDescendantsHaveCategoryAnnotations(description);\n        }\n        for (Description each : description.getChildren()) {\n            assertNoCategorizedDescendentsOfUncategorizeableParents(each);\n        }\n    }\n\n    private static void assertNoDescendantsHaveCategoryAnnotations(Description description) throws InitializationError {\n        for (Description each : description.getChildren()) {\n            if (each.getAnnotation(Category.class) != null) {\n                throw new InitializationError(\"Category annotations on Parameterized classes are not supported on individual methods.\");\n            }\n            assertNoDescendantsHaveCategoryAnnotations(each);\n        }\n    }\n\n    // If children have names like [0], our current magical category code can't determine their parentage.\n    private static boolean canHaveCategorizedChildren(Description description) {\n        for (Description each : description.getChildren()) {\n            if (each.getTestClass() == null) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private static boolean hasAssignableTo(Set<Class<?>> assigns, Class<?> to) {\n        for (final Class<?> from : assigns) {\n            if (to.isAssignableFrom(from)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    private static Set<Class<?>> createSet(Class<?>... t) {\n        final Set<Class<?>> set= new HashSet<Class<?>>();\n        if (t != null) {\n            Collections.addAll(set, t);\n        }\n        return set;\n    }\n}\n", "human_rating": 2.8411790712899996, "metadata": {"project": "junit4", "class": "org.junit.experimental.categories.Categories", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/categories/Categories.java", "label_probabilities": {"readability": [0.00199723, 0.837187, 0.160814, 1.15129e-06], "understandability": [0.00557706, 0.764828, 0.229391, 0.00020356], "complexity": [2.8541e-16, 0.00168144, 0.997322, 0.000996955], "modularization": [7.909e-17, 0.765115, 0.234885, 1.00087e-11], "overall": [8.36774e-11, 0.929813, 0.0701866, 2.77757e-12]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.categories.CategoryFilterFactory", "source": "package org.junit.experimental.categories;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.internal.Classes;\nimport org.junit.runner.FilterFactory;\nimport org.junit.runner.FilterFactoryParams;\nimport org.junit.runner.manipulation.Filter;\n\n/**\n * Implementation of FilterFactory for Category filtering.\n */\nabstract class CategoryFilterFactory implements FilterFactory {\n    /**\n     * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given a\n     * {@link FilterFactoryParams} argument.\n     *\n     * @param params Parameters needed to create the {@link Filter}\n     * @throws FilterNotCreatedException\n     */\n    public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException {\n        try {\n            return createFilter(parseCategories(params.getArgs()));\n        } catch (ClassNotFoundException e) {\n            throw new FilterNotCreatedException(e);\n        }\n    }\n\n    /**\n     * Creates a {@link org.junit.experimental.categories.Categories.CategoryFilter} given an array of classes.\n     *\n     * @param categories Category classes.\n     */\n    protected abstract Filter createFilter(List<Class<?>> categories);\n\n    private List<Class<?>> parseCategories(String categories) throws ClassNotFoundException {\n        List<Class<?>> categoryClasses = new ArrayList<Class<?>>();\n\n        for (String category : categories.split(\",\")) {\n            Class<?> categoryClass = Classes.getClass(category);\n\n            categoryClasses.add(categoryClass);\n        }\n\n        return categoryClasses;\n    }\n}\n", "human_rating": 3.927985835881085, "metadata": {"project": "junit4", "class": "org.junit.experimental.categories.CategoryFilterFactory", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/categories/CategoryFilterFactory.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.categories.CategoryValidator", "source": "package org.junit.experimental.categories;\n\nimport static java.util.Arrays.asList;\nimport static java.util.Collections.unmodifiableList;\nimport static java.util.Collections.unmodifiableSet;\n\nimport java.lang.annotation.Annotation;\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.junit.After;\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.validator.AnnotationValidator;\n\n/**\n * Validates that there are no errors in the use of the {@code Category}\n * annotation. If there is, a {@code Throwable} object will be added to the list\n * of errors.\n *\n * @since 4.12\n */\npublic final class CategoryValidator extends AnnotationValidator {\n\n    @SuppressWarnings(\"unchecked\")\n    private static final Set<Class<? extends Annotation>> INCOMPATIBLE_ANNOTATIONS = unmodifiableSet(new HashSet<Class<? extends Annotation>>(\n            asList(BeforeClass.class, AfterClass.class, Before.class, After.class)));\n\n    /**\n     * Adds to {@code errors} a throwable for each problem detected. Looks for\n     * {@code BeforeClass}, {@code AfterClass}, {@code Before} and {@code After}\n     * annotations.\n     *\n     * @param method the method that is being validated\n     * @return A list of exceptions detected\n     *\n     * @since 4.12\n     */\n    @Override\n    public List<Exception> validateAnnotatedMethod(FrameworkMethod method) {\n        List<Exception> errors = new ArrayList<Exception>();\n        Annotation[] annotations = method.getAnnotations();\n        for (Annotation annotation : annotations) {\n            for (Class<?> clazz : INCOMPATIBLE_ANNOTATIONS) {\n                if (annotation.annotationType().isAssignableFrom(clazz)) {\n                    addErrorMessage(errors, clazz);\n                }\n            }\n        }\n        return unmodifiableList(errors);\n    }\n\n    private void addErrorMessage(List<Exception> errors, Class<?> clazz) {\n        String message = String.format(\"@%s can not be combined with @Category\",\n                clazz.getSimpleName());\n        errors.add(new Exception(message));\n    }\n}\n", "human_rating": 3.949780154780024, "metadata": {"project": "junit4", "class": "org.junit.experimental.categories.CategoryValidator", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/categories/CategoryValidator.java", "label_probabilities": {"readability": [0.949787, 0.0502067, 6.02739e-06, 2.37972e-14], "understandability": [0.935149, 0.0647859, 6.51511e-05, 2.4182e-16], "complexity": [2.69749e-15, 1.35403e-05, 0.082906, 0.91708], "modularization": [2.895e-17, 8.9233e-05, 0.0388652, 0.961046], "overall": [0.979707, 0.0202933, 3.12146e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.max.CouldNotReadCoreException", "source": "package org.junit.experimental.max;\n\n/**\n * Thrown when Max cannot read the MaxCore serialization\n */\npublic class CouldNotReadCoreException extends Exception {\n    private static final long serialVersionUID = 1L;\n\n    /**\n     * Constructs\n     */\n    public CouldNotReadCoreException(Throwable e) {\n        super(e);\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.experimental.max.CouldNotReadCoreException", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/max/CouldNotReadCoreException.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.max.MaxCore", "source": "package org.junit.experimental.max;\n\nimport java.io.File;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nimport junit.framework.TestSuite;\nimport org.junit.internal.requests.SortingRequest;\nimport org.junit.internal.runners.ErrorReportingRunner;\nimport org.junit.internal.runners.JUnit38ClassRunner;\nimport org.junit.runner.Description;\nimport org.junit.runner.JUnitCore;\nimport org.junit.runner.Request;\nimport org.junit.runner.Result;\nimport org.junit.runner.Runner;\nimport org.junit.runners.Suite;\nimport org.junit.runners.model.InitializationError;\n\n/**\n * A replacement for JUnitCore, which keeps track of runtime and failure history, and reorders tests\n * to maximize the chances that a failing test occurs early in the test run.\n *\n * The rules for sorting are:\n * <ol>\n * <li> Never-run tests first, in arbitrary order\n * <li> Group remaining tests by the date at which they most recently failed.\n * <li> Sort groups such that the most recent failure date is first, and never-failing tests are at the end.\n * <li> Within a group, run the fastest tests first.\n * </ol>\n */\npublic class MaxCore {\n    private static final String MALFORMED_JUNIT_3_TEST_CLASS_PREFIX = \"malformed JUnit 3 test class: \";\n\n    /**\n     * Create a new MaxCore from a serialized file stored at storedResults\n     *\n     * @deprecated use storedLocally()\n     */\n    @Deprecated\n    public static MaxCore forFolder(String folderName) {\n        return storedLocally(new File(folderName));\n    }\n\n    /**\n     * Create a new MaxCore from a serialized file stored at storedResults\n     */\n    public static MaxCore storedLocally(File storedResults) {\n        return new MaxCore(storedResults);\n    }\n\n    private final MaxHistory fHistory;\n\n    private MaxCore(File storedResults) {\n        fHistory = MaxHistory.forFolder(storedResults);\n    }\n\n    /**\n     * Run all the tests in <code>class</code>.\n     *\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public Result run(Class<?> testClass) {\n        return run(Request.aClass(testClass));\n    }\n\n    /**\n     * Run all the tests contained in <code>request</code>.\n     *\n     * @param request the request describing tests\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public Result run(Request request) {\n        return run(request, new JUnitCore());\n    }\n\n    /**\n     * Run all the tests contained in <code>request</code>.\n     *\n     * This variant should be used if {@code core} has attached listeners that this\n     * run should notify.\n     *\n     * @param request the request describing tests\n     * @param core a JUnitCore to delegate to.\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public Result run(Request request, JUnitCore core) {\n        core.addListener(fHistory.listener());\n        return core.run(sortRequest(request).getRunner());\n    }\n\n    /**\n     * @return a new Request, which contains all of the same tests, but in a new order.\n     */\n    public Request sortRequest(Request request) {\n        if (request instanceof SortingRequest) {\n            // We'll pay big karma points for this\n            return request;\n        }\n        List<Description> leaves = findLeaves(request);\n        Collections.sort(leaves, fHistory.testComparator());\n        return constructLeafRequest(leaves);\n    }\n\n    private Request constructLeafRequest(List<Description> leaves) {\n        final List<Runner> runners = new ArrayList<Runner>();\n        for (Description each : leaves) {\n            runners.add(buildRunner(each));\n        }\n        return new Request() {\n            @Override\n            public Runner getRunner() {\n                try {\n                    return new Suite((Class<?>) null, runners) {\n                    };\n                } catch (InitializationError e) {\n                    return new ErrorReportingRunner(null, e);\n                }\n            }\n        };\n    }\n\n    private Runner buildRunner(Description each) {\n        if (each.toString().equals(\"TestSuite with 0 tests\")) {\n            return Suite.emptySuite();\n        }\n        if (each.toString().startsWith(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX)) {\n            // This is cheating, because it runs the whole class\n            // to get the warning for this method, but we can't do better,\n            // because JUnit 3.8's\n            // thrown away which method the warning is for.\n            return new JUnit38ClassRunner(new TestSuite(getMalformedTestClass(each)));\n        }\n        Class<?> type = each.getTestClass();\n        if (type == null) {\n            throw new RuntimeException(\"Can't build a runner from description [\" + each + \"]\");\n        }\n        String methodName = each.getMethodName();\n        if (methodName == null) {\n            return Request.aClass(type).getRunner();\n        }\n        return Request.method(type, methodName).getRunner();\n    }\n\n    private Class<?> getMalformedTestClass(Description each) {\n        try {\n            return Class.forName(each.toString().replace(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX, \"\"));\n        } catch (ClassNotFoundException e) {\n            return null;\n        }\n    }\n\n    /**\n     * @param request a request to run\n     * @return a list of method-level tests to run, sorted in the order\n     *         specified in the class comment.\n     */\n    public List<Description> sortedLeavesForTest(Request request) {\n        return findLeaves(sortRequest(request));\n    }\n\n    private List<Description> findLeaves(Request request) {\n        List<Description> results = new ArrayList<Description>();\n        findLeaves(null, request.getRunner().getDescription(), results);\n        return results;\n    }\n\n    private void findLeaves(Description parent, Description description, List<Description> results) {\n        if (description.getChildren().isEmpty()) {\n            if (description.toString().equals(\"warning(junit.framework.TestSuite$1)\")) {\n                results.add(Description.createSuiteDescription(MALFORMED_JUNIT_3_TEST_CLASS_PREFIX + parent));\n            } else {\n                results.add(description);\n            }\n        } else {\n            for (Description each : description.getChildren()) {\n                findLeaves(description, each, results);\n            }\n        }\n    }\n}", "human_rating": 3.788647502651985, "metadata": {"project": "junit4", "class": "org.junit.experimental.max.MaxCore", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/max/MaxCore.java", "label_probabilities": {"readability": [0.788656, 0.211336, 7.75132e-06, 1.19846e-11], "understandability": [0.307977, 0.68612, 0.0059027, 3.93822e-11], "complexity": [1.66225e-07, 0.000676127, 0.0373025, 0.962021], "modularization": [2.47902e-06, 0.161017, 0.838981, 5.11241e-08], "overall": [0.0721647, 0.927832, 3.72261e-06, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.max.MaxHistory", "source": "package org.junit.experimental.max;\n\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.Comparator;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunListener;\n\n/**\n * Stores a subset of the history of each test:\n * <ul>\n * <li>Last failure timestamp\n * <li>Duration of last execution\n * </ul>\n */\npublic class MaxHistory implements Serializable {\n    private static final long serialVersionUID = 1L;\n\n    /**\n     * Loads a {@link MaxHistory} from {@code file}, or generates a new one that\n     * will be saved to {@code file}.\n     */\n    public static MaxHistory forFolder(File file) {\n        if (file.exists()) {\n            try {\n                return readHistory(file);\n            } catch (CouldNotReadCoreException e) {\n                e.printStackTrace();\n                file.delete();\n            }\n        }\n        return new MaxHistory(file);\n    }\n\n    private static MaxHistory readHistory(File storedResults)\n            throws CouldNotReadCoreException {\n        try {\n            FileInputStream file = new FileInputStream(storedResults);\n            try {\n                ObjectInputStream stream = new ObjectInputStream(file);\n                try {\n                    return (MaxHistory) stream.readObject();\n                } finally {\n                    stream.close();\n                }\n            } finally {\n                file.close();\n            }\n        } catch (Exception e) {\n            throw new CouldNotReadCoreException(e);\n        }\n    }\n\n    private final Map<String, Long> fDurations = new HashMap<String, Long>();\n\n    private final Map<String, Long> fFailureTimestamps = new HashMap<String, Long>();\n\n    private final File fHistoryStore;\n\n    private MaxHistory(File storedResults) {\n        fHistoryStore = storedResults;\n    }\n\n    private void save() throws IOException {\n        ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(\n                fHistoryStore));\n        stream.writeObject(this);\n        stream.close();\n    }\n\n    Long getFailureTimestamp(Description key) {\n        return fFailureTimestamps.get(key.toString());\n    }\n\n    void putTestFailureTimestamp(Description key, long end) {\n        fFailureTimestamps.put(key.toString(), end);\n    }\n\n    boolean isNewTest(Description key) {\n        return !fDurations.containsKey(key.toString());\n    }\n\n    Long getTestDuration(Description key) {\n        return fDurations.get(key.toString());\n    }\n\n    void putTestDuration(Description description, long duration) {\n        fDurations.put(description.toString(), duration);\n    }\n\n    private final class RememberingListener extends RunListener {\n        private long overallStart = System.currentTimeMillis();\n\n        private Map<Description, Long> starts = new HashMap<Description, Long>();\n\n        @Override\n        public void testStarted(Description description) throws Exception {\n            starts.put(description, System.nanoTime()); // Get most accurate\n            // possible time\n        }\n\n        @Override\n        public void testFinished(Description description) throws Exception {\n            long end = System.nanoTime();\n            long start = starts.get(description);\n            putTestDuration(description, end - start);\n        }\n\n        @Override\n        public void testFailure(Failure failure) throws Exception {\n            putTestFailureTimestamp(failure.getDescription(), overallStart);\n        }\n\n        @Override\n        public void testRunFinished(Result result) throws Exception {\n            save();\n        }\n    }\n\n    private class TestComparator implements Comparator<Description> {\n        public int compare(Description o1, Description o2) {\n            // Always prefer new tests\n            if (isNewTest(o1)) {\n                return -1;\n            }\n            if (isNewTest(o2)) {\n                return 1;\n            }\n            // Then most recently failed first\n            int result = getFailure(o2).compareTo(getFailure(o1));\n            return result != 0 ? result\n                    // Then shorter tests first\n                    : getTestDuration(o1).compareTo(getTestDuration(o2));\n        }\n\n        private Long getFailure(Description key) {\n            Long result = getFailureTimestamp(key);\n            if (result == null) {\n                return 0L; // 0 = \"never failed (that I know about)\"\n            }\n            return result;\n        }\n    }\n\n    /**\n     * @return a listener that will update this history based on the test\n     *         results reported.\n     */\n    public RunListener listener() {\n        return new RememberingListener();\n    }\n\n    /**\n     * @return a comparator that ranks tests based on the JUnit Max sorting\n     *         rules, as described in the {@link MaxCore} class comment.\n     */\n    public Comparator<Description> testComparator() {\n        return new TestComparator();\n    }\n}\n", "human_rating": 3.999857996, "metadata": {"project": "junit4", "class": "org.junit.experimental.max.MaxHistory", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/max/MaxHistory.java", "label_probabilities": {"readability": [0.999857, 0.000143332, 3e-20, 0.0], "understandability": [0.130569, 0.869431, 4.69627e-08, 2e-20], "complexity": [3.40449e-15, 0.000914646, 0.991692, 0.0073929], "modularization": [0.0, 9.50088e-08, 0.651912, 0.348088], "overall": [0.812592, 0.187408, 2.11045e-08, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.results.PrintableResult", "source": "package org.junit.experimental.results;\n\nimport java.io.ByteArrayOutputStream;\nimport java.io.PrintStream;\nimport java.util.List;\n\nimport org.junit.internal.TextListener;\nimport org.junit.runner.JUnitCore;\nimport org.junit.runner.Request;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\n/**\n * A test result that prints nicely in error messages.\n * This is only intended to be used in JUnit self-tests.\n * For example:\n *\n * <pre>\n *    assertThat(testResult(HasExpectedException.class), isSuccessful());\n * </pre>\n */\npublic class PrintableResult {\n    private Result result;\n\n    /**\n     * The result of running JUnit on {@code type}\n     */\n    public static PrintableResult testResult(Class<?> type) {\n        return testResult(Request.aClass(type));\n    }\n\n    /**\n     * The result of running JUnit on Request {@code request}\n     */\n    public static PrintableResult testResult(Request request) {\n        return new PrintableResult(new JUnitCore().run(request));\n    }\n\n    /**\n     * A result that includes the given {@code failures}\n     */\n    public PrintableResult(List<Failure> failures) {\n        this(new FailureList(failures).result());\n    }\n\n    private PrintableResult(Result result) {\n        this.result = result;\n    }\n\n    /**\n     * Returns the number of failures in this result.\n     */\n    public int failureCount() {\n        return result.getFailures().size();\n    }\n\n    @Override\n    public String toString() {\n        ByteArrayOutputStream stream = new ByteArrayOutputStream();\n        new TextListener(new PrintStream(stream)).testRunFinished(result);\n        return stream.toString();\n    }\n}", "human_rating": 3.9684204944362738, "metadata": {"project": "junit4", "class": "org.junit.experimental.results.PrintableResult", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/results/PrintableResult.java", "label_probabilities": {"readability": [0.968421, 0.0315788, 4.7218e-08, 2.73951e-13], "understandability": [0.964244, 0.0357549, 8.31796e-07, 1.83488e-12], "complexity": [0.0, 6.52016e-14, 0.00844262, 0.991557], "modularization": [0.0, 6.59152e-11, 0.0412797, 0.95872], "overall": [0.99052, 0.00947958, 1.13886e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.results.ResultMatchers", "source": "package org.junit.experimental.results;\n\nimport org.hamcrest.BaseMatcher;\nimport org.hamcrest.Description;\nimport org.hamcrest.Matcher;\nimport org.hamcrest.TypeSafeMatcher;\n\n/**\n * Matchers on a PrintableResult, to enable JUnit self-tests.\n * For example:\n *\n * <pre>\n * assertThat(testResult(HasExpectedException.class), isSuccessful());\n * </pre>\n */\npublic class ResultMatchers {\n    /**\n     * Matches if the tests are all successful\n     */\n    public static Matcher<PrintableResult> isSuccessful() {\n        return failureCountIs(0);\n    }\n\n    /**\n     * Matches if there are {@code count} failures\n     */\n    public static Matcher<PrintableResult> failureCountIs(final int count) {\n        return new TypeSafeMatcher<PrintableResult>() {\n            public void describeTo(Description description) {\n                description.appendText(\"has \" + count + \" failures\");\n            }\n\n            @Override\n            public boolean matchesSafely(PrintableResult item) {\n                return item.failureCount() == count;\n            }\n        };\n    }\n\n    /**\n     * Matches if the result has exactly one failure, and it contains {@code string}\n     */\n    public static Matcher<Object> hasSingleFailureContaining(final String string) {\n        return new BaseMatcher<Object>() {\n            public boolean matches(Object item) {\n                return item.toString().contains(string) && failureCountIs(1).matches(item);\n            }\n\n            public void describeTo(Description description) {\n                description.appendText(\"has single failure containing \" + string);\n            }\n        };\n    }\n\n    /**\n     * Matches if the result has one or more failures, and at least one of them\n     * contains {@code string}\n     */\n    public static Matcher<PrintableResult> hasFailureContaining(final String string) {\n        return new BaseMatcher<PrintableResult>() {\n            public boolean matches(Object item) {\n                return item.toString().contains(string);\n            }\n\n            public void describeTo(Description description) {\n                description.appendText(\"has failure containing \" + string);\n            }\n        };\n    }\n}\n", "human_rating": 3.749074436883183, "metadata": {"project": "junit4", "class": "org.junit.experimental.results.ResultMatchers", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/results/ResultMatchers.java", "label_probabilities": {"readability": [0.749083, 0.250909, 7.71844e-06, 3.18328e-12], "understandability": [0.747781, 0.252216, 2.74166e-06, 6.316e-17], "complexity": [2.14989e-15, 0.000878599, 0.646987, 0.352135], "modularization": [0.0, 6.37162e-11, 0.0233194, 0.976681], "overall": [0.992541, 0.00745936, 8.36718e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.runners.Enclosed", "source": "package org.junit.experimental.runners;\n\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.runners.Suite;\nimport org.junit.runners.model.RunnerBuilder;\n\n/**\n * If you put tests in inner classes, Ant, for example, won't find them. By running the outer class\n * with Enclosed, the tests in the inner classes will be run. You might put tests in inner classes\n * to group them for convenience or to share constants. Abstract inner classes are ignored.\n * <p>\n * So, for example:\n * <pre>\n * &#064;RunWith(Enclosed.class)\n * public class ListTests {\n *     ...useful shared stuff...\n *     public static class OneKindOfListTest {...}\n *     public static class AnotherKind {...}\n *     abstract public static class Ignored {...}\n * }\n * </pre>\n */\npublic class Enclosed extends Suite {\n    /**\n     * Only called reflectively. Do not use programmatically.\n     */\n    public Enclosed(Class<?> klass, RunnerBuilder builder) throws Throwable {\n        super(builder, klass, filterAbstractClasses(klass.getClasses()));\n    }\n    \n    private static Class<?>[] filterAbstractClasses(final Class<?>[] classes) {     \n        final List<Class<?>> filteredList= new ArrayList<Class<?>>(classes.length);\n\n        for (final Class<?> clazz : classes) {\n            if (!Modifier.isAbstract(clazz.getModifiers())) {\n                filteredList.add(clazz);\n            }\n        }\n        \n        return filteredList.toArray(new Class<?>[filteredList.size()]);\n    }   \n}\n", "human_rating": 3.9153708844086172, "metadata": {"project": "junit4", "class": "org.junit.experimental.runners.Enclosed", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/runners/Enclosed.java", "label_probabilities": {"readability": [0.915374, 0.0846228, 3.242e-06, 4.08617e-10], "understandability": [0.395983, 0.588832, 0.0151843, 2.15109e-07], "complexity": [3.52432e-07, 0.00152765, 0.0530604, 0.945412], "modularization": [1.6961e-07, 0.000303995, 0.137422, 0.862274], "overall": [0.962865, 0.0371344, 9.40623e-07, 4.1813e-16]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.theories.internal.AllMembersSupplier", "source": "package org.junit.experimental.theories.internal;\n\nimport java.lang.reflect.Array;\nimport java.lang.reflect.Field;\nimport java.util.ArrayList;\nimport java.util.Collection;\nimport java.util.Iterator;\nimport java.util.List;\n\nimport org.junit.Assume;\nimport org.junit.experimental.theories.DataPoint;\nimport org.junit.experimental.theories.DataPoints;\nimport org.junit.experimental.theories.ParameterSignature;\nimport org.junit.experimental.theories.ParameterSupplier;\nimport org.junit.experimental.theories.PotentialAssignment;\nimport org.junit.runners.model.FrameworkField;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.TestClass;\n\n/**\n * Supplies Theory parameters based on all public members of the target class.\n */\npublic class AllMembersSupplier extends ParameterSupplier {\n    static class MethodParameterValue extends PotentialAssignment {\n        private final FrameworkMethod fMethod;\n\n        private MethodParameterValue(FrameworkMethod dataPointMethod) {\n            fMethod = dataPointMethod;\n        }\n\n        @Override\n        public Object getValue() throws CouldNotGenerateValueException {\n            try {\n                return fMethod.invokeExplosively(null);\n            } catch (IllegalArgumentException e) {\n                throw new RuntimeException(\n                        \"unexpected: argument length is checked\");\n            } catch (IllegalAccessException e) {\n                throw new RuntimeException(\n                        \"unexpected: getMethods returned an inaccessible method\");\n            } catch (Throwable throwable) {\n                DataPoint annotation = fMethod.getAnnotation(DataPoint.class);\n                Assume.assumeTrue(annotation == null || !isAssignableToAnyOf(annotation.ignoredExceptions(), throwable));\n                \n                throw new CouldNotGenerateValueException(throwable);\n            }\n        }\n\n        @Override\n        public String getDescription() throws CouldNotGenerateValueException {\n            return fMethod.getName();\n        }\n    }\n    \n    private final TestClass fClass;\n\n    /**\n     * Constructs a new supplier for {@code type}\n     */\n    public AllMembersSupplier(TestClass type) {\n        fClass = type;\n    }\n\n    @Override\n    public List<PotentialAssignment> getValueSources(ParameterSignature sig) throws Throwable {\n        List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();\n\n        addSinglePointFields(sig, list);\n        addMultiPointFields(sig, list);\n        addSinglePointMethods(sig, list);\n        addMultiPointMethods(sig, list);\n\n        return list;\n    }\n\n    private void addMultiPointMethods(ParameterSignature sig, List<PotentialAssignment> list) throws Throwable {\n        for (FrameworkMethod dataPointsMethod : getDataPointsMethods(sig)) {\n            Class<?> returnType = dataPointsMethod.getReturnType();\n            \n            if ((returnType.isArray() && sig.canPotentiallyAcceptType(returnType.getComponentType())) ||\n                    Iterable.class.isAssignableFrom(returnType)) {\n                try {\n                    addDataPointsValues(returnType, sig, dataPointsMethod.getName(), list, \n                            dataPointsMethod.invokeExplosively(null));\n                } catch (Throwable throwable) {\n                    DataPoints annotation = dataPointsMethod.getAnnotation(DataPoints.class);\n                    if (annotation != null && isAssignableToAnyOf(annotation.ignoredExceptions(), throwable)) {\n                        return;\n                    } else {\n                        throw throwable;\n                    }\n                }\n            }\n        }\n    }\n\n    private void addSinglePointMethods(ParameterSignature sig, List<PotentialAssignment> list) {\n        for (FrameworkMethod dataPointMethod : getSingleDataPointMethods(sig)) {\n            if (sig.canAcceptType(dataPointMethod.getType())) {\n                list.add(new MethodParameterValue(dataPointMethod));\n            }\n        }\n    }\n    \n    private void addMultiPointFields(ParameterSignature sig, List<PotentialAssignment> list) {\n        for (final Field field : getDataPointsFields(sig)) {\n            Class<?> type = field.getType();\n            addDataPointsValues(type, sig, field.getName(), list, getStaticFieldValue(field));\n        }\n    }\n\n    private void addSinglePointFields(ParameterSignature sig, List<PotentialAssignment> list) {\n        for (final Field field : getSingleDataPointFields(sig)) {\n            Object value = getStaticFieldValue(field);\n            \n            if (sig.canAcceptValue(value)) {\n                list.add(PotentialAssignment.forValue(field.getName(), value));\n            }\n        }\n    }\n    \n    private void addDataPointsValues(Class<?> type, ParameterSignature sig, String name, \n            List<PotentialAssignment> list, Object value) {\n        if (type.isArray()) {\n            addArrayValues(sig, name, list, value);\n        }\n        else if (Iterable.class.isAssignableFrom(type)) {\n            addIterableValues(sig, name, list, (Iterable<?>) value);\n        }\n    }\n\n    private void addArrayValues(ParameterSignature sig, String name, List<PotentialAssignment> list, Object array) {\n        for (int i = 0; i < Array.getLength(array); i++) {\n            Object value = Array.get(array, i);\n            if (sig.canAcceptValue(value)) {\n                list.add(PotentialAssignment.forValue(name + \"[\" + i + \"]\", value));\n            }\n        }\n    }\n    \n    private void addIterableValues(ParameterSignature sig, String name, List<PotentialAssignment> list, Iterable<?> iterable) {\n        Iterator<?> iterator = iterable.iterator();\n        int i = 0;\n        while (iterator.hasNext()) {\n            Object value = iterator.next();\n            if (sig.canAcceptValue(value)) {\n                list.add(PotentialAssignment.forValue(name + \"[\" + i + \"]\", value));\n            }\n            i += 1;\n        }\n    }\n\n    private Object getStaticFieldValue(final Field field) {\n        try {\n            return field.get(null);\n        } catch (IllegalArgumentException e) {\n            throw new RuntimeException(\n                    \"unexpected: field from getClass doesn't exist on object\");\n        } catch (IllegalAccessException e) {\n            throw new RuntimeException(\n                    \"unexpected: getFields returned an inaccessible field\");\n        }\n    }\n    \n    private static boolean isAssignableToAnyOf(Class<?>[] typeArray, Object target) {\n        for (Class<?> type : typeArray) {\n            if (type.isAssignableFrom(target.getClass())) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    protected Collection<FrameworkMethod> getDataPointsMethods(ParameterSignature sig) {\n        return fClass.getAnnotatedMethods(DataPoints.class);        \n    }\n    \n    protected Collection<Field> getSingleDataPointFields(ParameterSignature sig) {\n        List<FrameworkField> fields = fClass.getAnnotatedFields(DataPoint.class);\n        Collection<Field> validFields = new ArrayList<Field>();\n\n        for (FrameworkField frameworkField : fields) {\n            validFields.add(frameworkField.getField());\n        }\n\n        return validFields;\n    }\n    \n    protected Collection<Field> getDataPointsFields(ParameterSignature sig) {\n        List<FrameworkField> fields = fClass.getAnnotatedFields(DataPoints.class);\n        Collection<Field> validFields = new ArrayList<Field>();\n\n        for (FrameworkField frameworkField : fields) {\n            validFields.add(frameworkField.getField());\n        }\n\n        return validFields;\n    }\n    \n    protected Collection<FrameworkMethod> getSingleDataPointMethods(ParameterSignature sig) {\n        return fClass.getAnnotatedMethods(DataPoint.class);\n    }\n\n}", "human_rating": 3.171347499024584, "metadata": {"project": "junit4", "class": "org.junit.experimental.theories.internal.AllMembersSupplier", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/theories/internal/AllMembersSupplier.java", "label_probabilities": {"readability": [0.171444, 0.828459, 9.72495e-05, 2.45839e-11], "understandability": [0.00110444, 0.809873, 0.188941, 8.16806e-05], "complexity": [1.236e-17, 0.0686571, 0.931336, 6.59853e-06], "modularization": [0.0, 3.09823e-06, 0.137574, 0.862423], "overall": [0.000146546, 0.997944, 0.00190921, 5.54126e-14]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.theories.internal.BooleanSupplier", "source": "package org.junit.experimental.theories.internal;\n\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.junit.experimental.theories.ParameterSignature;\nimport org.junit.experimental.theories.ParameterSupplier;\nimport org.junit.experimental.theories.PotentialAssignment;\n\npublic class BooleanSupplier extends ParameterSupplier {\n\n    @Override\n    public List<PotentialAssignment> getValueSources(ParameterSignature sig) {\n        return Arrays.asList(PotentialAssignment.forValue(\"true\", true),\n                             PotentialAssignment.forValue(\"false\", false));\n    }\n\n}\n", "human_rating": 3.9012051926, "metadata": {"project": "junit4", "class": "org.junit.experimental.theories.internal.BooleanSupplier", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/theories/internal/BooleanSupplier.java", "label_probabilities": {"readability": [0.90125, 0.0987045, 4.58463e-05, 0.0], "understandability": [0.846574, 0.153426, 2.38823e-07, 0.0], "complexity": [0.0, 2.22841e-10, 0.0583091, 0.941691], "modularization": [0.0, 0.00146691, 0.0712498, 0.927283], "overall": [0.977677, 0.0223232, 1.81181e-08, 1.5e-19]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.theories.ParameterSignature", "source": "package org.junit.experimental.theories;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.Map;\n\npublic class ParameterSignature {\n    \n    private static final Map<Class<?>, Class<?>> CONVERTABLE_TYPES_MAP = buildConvertableTypesMap();\n    \n    private static Map<Class<?>, Class<?>> buildConvertableTypesMap() {\n        Map<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>();\n\n        putSymmetrically(map, boolean.class, Boolean.class);\n        putSymmetrically(map, byte.class, Byte.class);\n        putSymmetrically(map, short.class, Short.class);\n        putSymmetrically(map, char.class, Character.class);\n        putSymmetrically(map, int.class, Integer.class);\n        putSymmetrically(map, long.class, Long.class);\n        putSymmetrically(map, float.class, Float.class);\n        putSymmetrically(map, double.class, Double.class);\n\n        return Collections.unmodifiableMap(map);\n    }\n    \n    private static <T> void putSymmetrically(Map<T, T> map, T a, T b) {\n        map.put(a, b);\n        map.put(b, a);\n    }\n    \n    public static ArrayList<ParameterSignature> signatures(Method method) {\n        return signatures(method.getParameterTypes(), method\n                .getParameterAnnotations());\n    }\n\n    public static List<ParameterSignature> signatures(Constructor<?> constructor) {\n        return signatures(constructor.getParameterTypes(), constructor\n                .getParameterAnnotations());\n    }\n\n    private static ArrayList<ParameterSignature> signatures(\n            Class<?>[] parameterTypes, Annotation[][] parameterAnnotations) {\n        ArrayList<ParameterSignature> sigs = new ArrayList<ParameterSignature>();\n        for (int i = 0; i < parameterTypes.length; i++) {\n            sigs.add(new ParameterSignature(parameterTypes[i],\n                    parameterAnnotations[i]));\n        }\n        return sigs;\n    }\n\n    private final Class<?> type;\n\n    private final Annotation[] annotations;\n\n    private ParameterSignature(Class<?> type, Annotation[] annotations) {\n        this.type = type;\n        this.annotations = annotations;\n    }\n\n    public boolean canAcceptValue(Object candidate) {\n        return (candidate == null) ? !type.isPrimitive() : canAcceptType(candidate.getClass());\n    }\n\n    public boolean canAcceptType(Class<?> candidate) {\n        return type.isAssignableFrom(candidate) ||\n                isAssignableViaTypeConversion(type, candidate);\n    }\n    \n    public boolean canPotentiallyAcceptType(Class<?> candidate) {\n        return candidate.isAssignableFrom(type) ||\n                isAssignableViaTypeConversion(candidate, type) ||\n                canAcceptType(candidate);\n    }\n\n    private boolean isAssignableViaTypeConversion(Class<?> targetType, Class<?> candidate) {\n        if (CONVERTABLE_TYPES_MAP.containsKey(candidate)) {\n            Class<?> wrapperClass = CONVERTABLE_TYPES_MAP.get(candidate);\n            return targetType.isAssignableFrom(wrapperClass);\n        } else {\n            return false;\n        }\n    }\n\n    public Class<?> getType() {\n        return type;\n    }\n\n    public List<Annotation> getAnnotations() {\n        return Arrays.asList(annotations);\n    }\n\n    public boolean hasAnnotation(Class<? extends Annotation> type) {\n        return getAnnotation(type) != null;\n    }\n\n    public <T extends Annotation> T findDeepAnnotation(Class<T> annotationType) {\n        Annotation[] annotations2 = annotations;\n        return findDeepAnnotation(annotations2, annotationType, 3);\n    }\n\n    private <T extends Annotation> T findDeepAnnotation(\n            Annotation[] annotations, Class<T> annotationType, int depth) {\n        if (depth == 0) {\n            return null;\n        }\n        for (Annotation each : annotations) {\n            if (annotationType.isInstance(each)) {\n                return annotationType.cast(each);\n            }\n            Annotation candidate = findDeepAnnotation(each.annotationType()\n                    .getAnnotations(), annotationType, depth - 1);\n            if (candidate != null) {\n                return annotationType.cast(candidate);\n            }\n        }\n\n        return null;\n    }\n\n    public <T extends Annotation> T getAnnotation(Class<T> annotationType) {\n        for (Annotation each : getAnnotations()) {\n            if (annotationType.isInstance(each)) {\n                return annotationType.cast(each);\n            }\n        }\n        return null;\n    }\n}", "human_rating": 3.9953152075018, "metadata": {"project": "junit4", "class": "org.junit.experimental.theories.ParameterSignature", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/theories/ParameterSignature.java", "label_probabilities": {"readability": [0.99543, 0.00445485, 0.000115312, 3.35018e-08], "understandability": [8.80485e-08, 1.0, 2.89862e-07, 0.0], "complexity": [5.6965e-10, 0.0107475, 0.989252, 5.09251e-07], "modularization": [1.5194e-16, 0.00155836, 0.402911, 0.595531], "overall": [0.875669, 0.124331, 2.52926e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.theories.suppliers.TestedOnSupplier", "source": "package org.junit.experimental.theories.suppliers;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.experimental.theories.ParameterSignature;\nimport org.junit.experimental.theories.ParameterSupplier;\nimport org.junit.experimental.theories.PotentialAssignment;\n\npublic class TestedOnSupplier extends ParameterSupplier {\n    @Override\n    public List<PotentialAssignment> getValueSources(ParameterSignature sig) {\n        List<PotentialAssignment> list = new ArrayList<PotentialAssignment>();\n        TestedOn testedOn = sig.getAnnotation(TestedOn.class);\n        int[] ints = testedOn.ints();\n        for (final int i : ints) {\n            list.add(PotentialAssignment.forValue(\"ints\", i));\n        }\n        return list;\n    }\n}\n", "human_rating": 3.840554615446389, "metadata": {"project": "junit4", "class": "org.junit.experimental.theories.suppliers.TestedOnSupplier", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/theories/suppliers/TestedOnSupplier.java", "label_probabilities": {"readability": [0.840643, 0.15927, 8.63073e-05, 8.46389e-10], "understandability": [0.914078, 0.0859007, 2.17136e-05, 7.56453e-12], "complexity": [0.0, 4.33136e-13, 0.0051493, 0.994851], "modularization": [0.0, 2.22454e-10, 0.0464159, 0.953584], "overall": [0.990092, 0.00990813, 3.63122e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.experimental.theories.Theories", "source": "package org.junit.experimental.theories;\n\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.lang.reflect.Modifier;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.Assert;\nimport org.junit.Assume;\nimport org.junit.experimental.theories.internal.Assignments;\nimport org.junit.experimental.theories.internal.ParameterizedAssertionError;\nimport org.junit.internal.AssumptionViolatedException;\nimport org.junit.runners.BlockJUnit4ClassRunner;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.InitializationError;\nimport org.junit.runners.model.Statement;\nimport org.junit.runners.model.TestClass;\n\npublic class Theories extends BlockJUnit4ClassRunner {\n    public Theories(Class<?> klass) throws InitializationError {\n        super(klass);\n    }\n\n    @Override\n    protected void collectInitializationErrors(List<Throwable> errors) {\n        super.collectInitializationErrors(errors);\n        validateDataPointFields(errors);\n        validateDataPointMethods(errors);\n    }\n\n    private void validateDataPointFields(List<Throwable> errors) {\n        Field[] fields = getTestClass().getJavaClass().getDeclaredFields();\n\n        for (Field field : fields) {\n            if (field.getAnnotation(DataPoint.class) == null && field.getAnnotation(DataPoints.class) == null) {\n                continue;\n            }\n            if (!Modifier.isStatic(field.getModifiers())) {\n                errors.add(new Error(\"DataPoint field \" + field.getName() + \" must be static\"));\n            }\n            if (!Modifier.isPublic(field.getModifiers())) {\n                errors.add(new Error(\"DataPoint field \" + field.getName() + \" must be public\"));\n            }\n        }\n    }\n\n    private void validateDataPointMethods(List<Throwable> errors) {\n        Method[] methods = getTestClass().getJavaClass().getDeclaredMethods();\n        \n        for (Method method : methods) {\n            if (method.getAnnotation(DataPoint.class) == null && method.getAnnotation(DataPoints.class) == null) {\n                continue;\n            }\n            if (!Modifier.isStatic(method.getModifiers())) {\n                errors.add(new Error(\"DataPoint method \" + method.getName() + \" must be static\"));\n            }\n            if (!Modifier.isPublic(method.getModifiers())) {\n                errors.add(new Error(\"DataPoint method \" + method.getName() + \" must be public\"));\n            }\n        }\n    }\n\n    @Override\n    protected void validateConstructor(List<Throwable> errors) {\n        validateOnlyOneConstructor(errors);\n    }\n\n    @Override\n    protected void validateTestMethods(List<Throwable> errors) {\n        for (FrameworkMethod each : computeTestMethods()) {\n            if (each.getAnnotation(Theory.class) != null) {\n                each.validatePublicVoid(false, errors);\n                each.validateNoTypeParametersOnArgs(errors);\n            } else {\n                each.validatePublicVoidNoArg(false, errors);\n            }\n            \n            for (ParameterSignature signature : ParameterSignature.signatures(each.getMethod())) {\n                ParametersSuppliedBy annotation = signature.findDeepAnnotation(ParametersSuppliedBy.class);\n                if (annotation != null) {\n                    validateParameterSupplier(annotation.value(), errors);\n                }\n            }\n        }\n    }\n\n    private void validateParameterSupplier(Class<? extends ParameterSupplier> supplierClass, List<Throwable> errors) {\n        Constructor<?>[] constructors = supplierClass.getConstructors();\n        \n        if (constructors.length != 1) {\n            errors.add(new Error(\"ParameterSupplier \" + supplierClass.getName() + \n                                 \" must have only one constructor (either empty or taking only a TestClass)\"));\n        } else {\n            Class<?>[] paramTypes = constructors[0].getParameterTypes();\n            if (!(paramTypes.length == 0) && !paramTypes[0].equals(TestClass.class)) {\n                errors.add(new Error(\"ParameterSupplier \" + supplierClass.getName() + \n                                     \" constructor must take either nothing or a single TestClass instance\"));\n            }\n        }\n    }\n\n    @Override\n    protected List<FrameworkMethod> computeTestMethods() {\n        List<FrameworkMethod> testMethods = new ArrayList<FrameworkMethod>(super.computeTestMethods());\n        List<FrameworkMethod> theoryMethods = getTestClass().getAnnotatedMethods(Theory.class);\n        testMethods.removeAll(theoryMethods);\n        testMethods.addAll(theoryMethods);\n        return testMethods;\n    }\n\n    @Override\n    public Statement methodBlock(final FrameworkMethod method) {\n        return new TheoryAnchor(method, getTestClass());\n    }\n\n    public static class TheoryAnchor extends Statement {\n        private int successes = 0;\n\n        private FrameworkMethod fTestMethod;\n        private TestClass fTestClass;\n\n        private List<AssumptionViolatedException> fInvalidParameters = new ArrayList<AssumptionViolatedException>();\n\n        public TheoryAnchor(FrameworkMethod method, TestClass testClass) {\n            fTestMethod = method;\n            fTestClass = testClass;\n        }\n\n        private TestClass getTestClass() {\n            return fTestClass;\n        }\n\n        @Override\n        public void evaluate() throws Throwable {\n            runWithAssignment(Assignments.allUnassigned(\n                    fTestMethod.getMethod(), getTestClass()));\n            \n            //if this test method is not annotated with Theory, then no successes is a valid case\n            boolean hasTheoryAnnotation = fTestMethod.getAnnotation(Theory.class) != null;\n            if (successes == 0 && hasTheoryAnnotation) {\n                Assert\n                        .fail(\"Never found parameters that satisfied method assumptions.  Violated assumptions: \"\n                                + fInvalidParameters);\n            }\n        }\n\n        protected void runWithAssignment(Assignments parameterAssignment)\n                throws Throwable {\n            if (!parameterAssignment.isComplete()) {\n                runWithIncompleteAssignment(parameterAssignment);\n            } else {\n                runWithCompleteAssignment(parameterAssignment);\n            }\n        }\n\n        protected void runWithIncompleteAssignment(Assignments incomplete)\n                throws Throwable {\n            for (PotentialAssignment source : incomplete\n                    .potentialsForNextUnassigned()) {\n                runWithAssignment(incomplete.assignNext(source));\n            }\n        }\n\n        protected void runWithCompleteAssignment(final Assignments complete)\n                throws Throwable {\n            new BlockJUnit4ClassRunner(getTestClass().getJavaClass()) {\n                @Override\n                protected void collectInitializationErrors(\n                        List<Throwable> errors) {\n                    // do nothing\n                }\n\n                @Override\n                public Statement methodBlock(FrameworkMethod method) {\n                    final Statement statement = super.methodBlock(method);\n                    return new Statement() {\n                        @Override\n                        public void evaluate() throws Throwable {\n                            try {\n                                statement.evaluate();\n                                handleDataPointSuccess();\n                            } catch (AssumptionViolatedException e) {\n                                handleAssumptionViolation(e);\n                            } catch (Throwable e) {\n                                reportParameterizedError(e, complete\n                                        .getArgumentStrings(nullsOk()));\n                            }\n                        }\n\n                    };\n                }\n\n                @Override\n                protected Statement methodInvoker(FrameworkMethod method, Object test) {\n                    return methodCompletesWithParameters(method, complete, test);\n                }\n\n                @Override\n                public Object createTest() throws Exception {\n                    Object[] params = complete.getConstructorArguments();\n                    \n                    if (!nullsOk()) {\n                        Assume.assumeNotNull(params);\n                    }\n                    \n                    return getTestClass().getOnlyConstructor().newInstance(params);\n                }\n            }.methodBlock(fTestMethod).evaluate();\n        }\n\n        private Statement methodCompletesWithParameters(\n                final FrameworkMethod method, final Assignments complete, final Object freshInstance) {\n            return new Statement() {\n                @Override\n                public void evaluate() throws Throwable {\n                    final Object[] values = complete.getMethodArguments();\n                    \n                    if (!nullsOk()) {\n                        Assume.assumeNotNull(values);\n                    }\n                    \n                    method.invokeExplosively(freshInstance, values);\n                }\n            };\n        }\n\n        protected void handleAssumptionViolation(AssumptionViolatedException e) {\n            fInvalidParameters.add(e);\n        }\n\n        protected void reportParameterizedError(Throwable e, Object... params)\n                throws Throwable {\n            if (params.length == 0) {\n                throw e;\n            }\n            throw new ParameterizedAssertionError(e, fTestMethod.getName(),\n                    params);\n        }\n\n        private boolean nullsOk() {\n            Theory annotation = fTestMethod.getMethod().getAnnotation(\n                    Theory.class);\n            if (annotation == null) {\n                return false;\n            }\n            return annotation.nullsAccepted();\n        }\n\n        protected void handleDataPointSuccess() {\n            successes++;\n        }\n    }\n}\n", "human_rating": 2.009964520059, "metadata": {"project": "junit4", "class": "org.junit.experimental.theories.Theories", "source_path": "junit4/sourcefiles/src/main/java/org/junit/experimental/theories/Theories.java", "label_probabilities": {"readability": [4.82e-18, 0.00996481, 0.990035, 9.0059e-08], "understandability": [3.16037e-06, 0.0237012, 0.529331, 0.446965], "complexity": [0.110679, 0.77885, 0.11047, 7.24601e-15], "modularization": [0.000847181, 0.401659, 0.597494, 3.33261e-09], "overall": [1.991e-05, 0.0994961, 0.900481, 2.80133e-06]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.ArrayComparisonFailure", "source": "package org.junit.internal;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.Assert;\n\n/**\n * Thrown when two array elements differ\n *\n * @see Assert#assertArrayEquals(String, Object[], Object[])\n */\npublic class ArrayComparisonFailure extends AssertionError {\n\n    private static final long serialVersionUID = 1L;\n\n    private List<Integer> fIndices = new ArrayList<Integer>();\n    private final String fMessage;\n\n    /**\n     * Construct a new <code>ArrayComparisonFailure</code> with an error text and the array's\n     * dimension that was not equal\n     *\n     * @param cause the exception that caused the array's content to fail the assertion test\n     * @param index the array position of the objects that are not equal.\n     * @see Assert#assertArrayEquals(String, Object[], Object[])\n     */\n    public ArrayComparisonFailure(String message, AssertionError cause, int index) {\n        fMessage = message;\n        initCause(cause);\n        addDimension(index);\n    }\n\n    public void addDimension(int index) {\n        fIndices.add(0, index);\n    }\n\n    @Override\n    public String getMessage() {\n        StringBuilder sb = new StringBuilder();\n        if (fMessage != null) {\n            sb.append(fMessage);\n        }\n        sb.append(\"arrays first differed at element \");\n        for (int each : fIndices) {\n            sb.append(\"[\");\n            sb.append(each);\n            sb.append(\"]\");\n        }\n        sb.append(\"; \");\n        sb.append(getCause().getMessage());\n        return sb.toString();\n    }\n\n    /**\n     * {@inheritDoc}\n     */\n    @Override\n    public String toString() {\n        return getMessage();\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.internal.ArrayComparisonFailure", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/ArrayComparisonFailure.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.AssumptionViolatedException", "source": "package org.junit.internal;\n\nimport org.hamcrest.Description;\nimport org.hamcrest.Matcher;\nimport org.hamcrest.SelfDescribing;\nimport org.hamcrest.StringDescription;\n\n/**\n * An exception class used to implement <i>assumptions</i> (state in which a given test\n * is meaningful and should or should not be executed). A test for which an assumption\n * fails should not generate a test case failure.\n *\n * @see org.junit.Assume\n *\n * @deprecated Please use {@link org.junit.AssumptionViolatedException} instead.\n */\n@Deprecated\npublic class AssumptionViolatedException extends RuntimeException implements SelfDescribing {\n    private static final long serialVersionUID = 2L;\n\n    private final String fAssumption;\n\n    private final boolean fValueMatcher;\n    private final Object fValue;\n\n    private final Matcher<?> fMatcher;\n\n    public AssumptionViolatedException(String assumption, boolean valueMatcher, Object value, Matcher<?> matcher) {\n        super(value instanceof Throwable ? (Throwable) value : null);\n        fAssumption = assumption;\n        fValue = value;\n        fMatcher = matcher;\n        fValueMatcher = valueMatcher;\n    }\n\n    /**\n     * An assumption exception with the given <i>value</i> (String or\n     * Throwable) and an additional failing {@link Matcher}.\n     */\n    public AssumptionViolatedException(Object value, Matcher<?> matcher) {\n        this(null, true, value, matcher);\n    }\n\n    /**\n     * An assumption exception with the given <i>value</i> (String or\n     * Throwable) and an additional failing {@link Matcher}.\n     */\n    public AssumptionViolatedException(String assumption, Object value, Matcher<?> matcher) {\n        this(assumption, true, value, matcher);\n    }\n\n    /**\n     * An assumption exception with the given message only.\n     */\n    public AssumptionViolatedException(String assumption) {\n        this(assumption, false, null, null);\n    }\n\n    /**\n     * An assumption exception with the given message and a cause.\n     */\n    public AssumptionViolatedException(String assumption, Throwable e) {\n        this(assumption, false, e, null);\n    }\n\n    @Override\n    public String getMessage() {\n        return StringDescription.asString(this);\n    }\n\n    public void describeTo(Description description) {\n        if (fAssumption != null) {\n            description.appendText(fAssumption);\n        }\n\n        if (fValueMatcher) {\n            if (fAssumption != null) {\n                description.appendText(\": \");\n            }\n\n            description.appendText(\"got: \");\n            description.appendValue(fValue);\n\n            if (fMatcher != null) {\n                description.appendText(\", expected: \");\n                description.appendDescriptionOf(fMatcher);\n            }\n        }\n    }\n}", "human_rating": 3.999340626, "metadata": {"project": "junit4", "class": "org.junit.internal.AssumptionViolatedException", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/AssumptionViolatedException.java", "label_probabilities": {"readability": [0.999342, 0.000657542, 0.0, 0.0], "understandability": [9.73133e-07, 0.999999, 6.42599e-12, 0.0], "complexity": [0.0, 3.30576e-13, 0.189223, 0.810777], "modularization": [0.0, 1.07076e-15, 2.17978e-08, 1.0], "overall": [1.0, 2.19266e-07, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.builders.AnnotatedBuilder", "source": "package org.junit.internal.builders;\n\nimport org.junit.runner.RunWith;\nimport org.junit.runner.Runner;\nimport org.junit.runners.model.InitializationError;\nimport org.junit.runners.model.RunnerBuilder;\n\npublic class AnnotatedBuilder extends RunnerBuilder {\n    private static final String CONSTRUCTOR_ERROR_FORMAT = \"Custom runner class %s should have a public constructor with signature %s(Class testClass)\";\n\n    private final RunnerBuilder fSuiteBuilder;\n\n    public AnnotatedBuilder(RunnerBuilder suiteBuilder) {\n        fSuiteBuilder = suiteBuilder;\n    }\n\n    @Override\n    public Runner runnerForClass(Class<?> testClass) throws Exception {\n        RunWith annotation = testClass.getAnnotation(RunWith.class);\n        if (annotation != null) {\n            return buildRunner(annotation.value(), testClass);\n        }\n        return null;\n    }\n\n    public Runner buildRunner(Class<? extends Runner> runnerClass,\n            Class<?> testClass) throws Exception {\n        try {\n            return runnerClass.getConstructor(Class.class).newInstance(testClass);\n        } catch (NoSuchMethodException e) {\n            try {\n                return runnerClass.getConstructor(Class.class,\n                        RunnerBuilder.class).newInstance(testClass, fSuiteBuilder);\n            } catch (NoSuchMethodException e2) {\n                String simpleName = runnerClass.getSimpleName();\n                throw new InitializationError(String.format(\n                        CONSTRUCTOR_ERROR_FORMAT, simpleName, simpleName));\n            }\n        }\n    }\n}", "human_rating": 3.8707873388799996, "metadata": {"project": "junit4", "class": "org.junit.internal.builders.AnnotatedBuilder", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/builders/AnnotatedBuilder.java", "label_probabilities": {"readability": [0.870871, 0.129047, 8.0319e-05, 1.70088e-06], "understandability": [0.47913, 0.518994, 0.00187543, 1.13074e-09], "complexity": [1.46726e-08, 0.0544014, 0.942615, 0.00298321], "modularization": [0.0, 2.63917e-10, 0.0263247, 0.973675], "overall": [0.988667, 0.0113334, 2.46646e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.builders.IgnoredBuilder", "source": "package org.junit.internal.builders;\n\nimport org.junit.Ignore;\nimport org.junit.runner.Runner;\nimport org.junit.runners.model.RunnerBuilder;\n\npublic class IgnoredBuilder extends RunnerBuilder {\n    @Override\n    public Runner runnerForClass(Class<?> testClass) {\n        if (testClass.getAnnotation(Ignore.class) != null) {\n            return new IgnoredClassRunner(testClass);\n        }\n        return null;\n    }\n}", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.internal.builders.IgnoredBuilder", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/builders/IgnoredBuilder.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.builders.IgnoredClassRunner", "source": "package org.junit.internal.builders;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Runner;\nimport org.junit.runner.notification.RunNotifier;\n\npublic class IgnoredClassRunner extends Runner {\n    private final Class<?> fTestClass;\n\n    public IgnoredClassRunner(Class<?> testClass) {\n        fTestClass = testClass;\n    }\n\n    @Override\n    public void run(RunNotifier notifier) {\n        notifier.fireTestIgnored(getDescription());\n    }\n\n    @Override\n    public Description getDescription() {\n        return Description.createSuiteDescription(fTestClass);\n    }\n}", "human_rating": 3.9571827370002413, "metadata": {"project": "junit4", "class": "org.junit.internal.builders.IgnoredClassRunner", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/builders/IgnoredClassRunner.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [2.16921e-08, 0.000702627, 0.120956, 0.878342], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.builders.JUnit3Builder", "source": "package org.junit.internal.builders;\n\nimport org.junit.internal.runners.JUnit38ClassRunner;\nimport org.junit.runner.Runner;\nimport org.junit.runners.model.RunnerBuilder;\n\npublic class JUnit3Builder extends RunnerBuilder {\n    @Override\n    public Runner runnerForClass(Class<?> testClass) throws Throwable {\n        if (isPre4Test(testClass)) {\n            return new JUnit38ClassRunner(testClass);\n        }\n        return null;\n    }\n\n    boolean isPre4Test(Class<?> testClass) {\n        return junit.framework.TestCase.class.isAssignableFrom(testClass);\n    }\n}", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.internal.builders.JUnit3Builder", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/builders/JUnit3Builder.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.builders.JUnit4Builder", "source": "package org.junit.internal.builders;\n\nimport org.junit.runner.Runner;\nimport org.junit.runners.BlockJUnit4ClassRunner;\nimport org.junit.runners.model.RunnerBuilder;\n\npublic class JUnit4Builder extends RunnerBuilder {\n    @Override\n    public Runner runnerForClass(Class<?> testClass) throws Throwable {\n        return new BlockJUnit4ClassRunner(testClass);\n    }\n}", "human_rating": 3.8707873388799996, "metadata": {"project": "junit4", "class": "org.junit.internal.builders.JUnit4Builder", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/builders/JUnit4Builder.java", "label_probabilities": {"readability": [0.870871, 0.129047, 8.0319e-05, 1.70088e-06], "understandability": [0.931635, 0.0683612, 3.47957e-06, 1.74392e-10], "complexity": [3.29649e-12, 3.50398e-06, 0.0360278, 0.963969], "modularization": [0.0, 2.63917e-10, 0.0263247, 0.973675], "overall": [0.988667, 0.0113334, 2.46646e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.builders.SuiteMethodBuilder", "source": "package org.junit.internal.builders;\n\nimport org.junit.internal.runners.SuiteMethod;\nimport org.junit.runner.Runner;\nimport org.junit.runners.model.RunnerBuilder;\n\npublic class SuiteMethodBuilder extends RunnerBuilder {\n    @Override\n    public Runner runnerForClass(Class<?> each) throws Throwable {\n        if (hasSuiteMethod(each)) {\n            return new SuiteMethod(each);\n        }\n        return null;\n    }\n\n    public boolean hasSuiteMethod(Class<?> testClass) {\n        try {\n            testClass.getMethod(\"suite\");\n        } catch (NoSuchMethodException e) {\n            return false;\n        }\n        return true;\n    }\n}", "human_rating": 3.99828239, "metadata": {"project": "junit4", "class": "org.junit.internal.builders.SuiteMethodBuilder", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/builders/SuiteMethodBuilder.java", "label_probabilities": {"readability": [0.998282, 0.00171813, 2e-20, 0.0], "understandability": [1.0, 5.11525e-15, 0.0, 0.0], "complexity": [0.0, 0.0, 2.69157e-05, 0.999973], "modularization": [0.0, 1.09432e-14, 3.34553e-08, 1.0], "overall": [1.0, 1.68746e-09, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.Classes", "source": "package org.junit.internal;\n\nimport static java.lang.Thread.currentThread;\n\n/**\n * Miscellaneous functions dealing with classes.\n */\npublic class Classes {\n    /**\n     * Returns Class.forName for {@code className} using the current thread's class loader.\n     *\n     * @param className Name of the class.\n     * @throws ClassNotFoundException\n     */\n    public static Class<?> getClass(String className) throws ClassNotFoundException {\n        return Class.forName(className, true, currentThread().getContextClassLoader());\n    }\n}\n", "human_rating": 2.6169718, "metadata": {"project": "junit4", "class": "org.junit.internal.Classes", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/Classes.java", "label_probabilities": {"readability": [0.002444, 0.627544, 0.354552, 0.0154598], "understandability": [1.17486e-14, 5.07011e-05, 0.552469, 0.44748], "complexity": [0.0, 0.0, 2.40634e-10, 1.0], "modularization": [1.79e-18, 3.22372e-10, 0.0346899, 0.96531], "overall": [0.000172097, 0.999828, 8.33689e-08, 3.49408e-14]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.ExactComparisonCriteria", "source": "package org.junit.internal;\n\nimport org.junit.Assert;\n\npublic class ExactComparisonCriteria extends ComparisonCriteria {\n    @Override\n    protected void assertElementsEqual(Object expected, Object actual) {\n        Assert.assertEquals(expected, actual);\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.internal.ExactComparisonCriteria", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/ExactComparisonCriteria.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.MethodSorter", "source": "package org.junit.internal;\n\nimport java.lang.reflect.Method;\nimport java.util.Arrays;\nimport java.util.Comparator;\n\nimport org.junit.FixMethodOrder;\n\npublic class MethodSorter {\n    /**\n     * DEFAULT sort order\n     */\n    public static final Comparator<Method> DEFAULT = new Comparator<Method>() {\n        public int compare(Method m1, Method m2) {\n            int i1 = m1.getName().hashCode();\n            int i2 = m2.getName().hashCode();\n            if (i1 != i2) {\n                return i1 < i2 ? -1 : 1;\n            }\n            return NAME_ASCENDING.compare(m1, m2);\n        }\n    };\n\n    /**\n     * Method name ascending lexicographic sort order, with {@link Method#toString()} as a tiebreaker\n     */\n    public static final Comparator<Method> NAME_ASCENDING = new Comparator<Method>() {\n        public int compare(Method m1, Method m2) {\n            final int comparison = m1.getName().compareTo(m2.getName());\n            if (comparison != 0) {\n                return comparison;\n            }\n            return m1.toString().compareTo(m2.toString());\n        }\n    };\n\n    /**\n     * Gets declared methods of a class in a predictable order, unless @FixMethodOrder(MethodSorters.JVM) is specified.\n     *\n     * Using the JVM order is unwise since the Java platform does not\n     * specify any particular order, and in fact JDK 7 returns a more or less\n     * random order; well-written test code would not assume any order, but some\n     * does, and a predictable failure is better than a random failure on\n     * certain platforms. By default, uses an unspecified but deterministic order.\n     *\n     * @param clazz a class\n     * @return same as {@link Class#getDeclaredMethods} but sorted\n     * @see <a href=\"http://bugs.sun.com/view_bug.do?bug_id=7023180\">JDK\n     *      (non-)bug #7023180</a>\n     */\n    public static Method[] getDeclaredMethods(Class<?> clazz) {\n        Comparator<Method> comparator = getSorter(clazz.getAnnotation(FixMethodOrder.class));\n\n        Method[] methods = clazz.getDeclaredMethods();\n        if (comparator != null) {\n            Arrays.sort(methods, comparator);\n        }\n\n        return methods;\n    }\n\n    private MethodSorter() {\n    }\n\n    private static Comparator<Method> getSorter(FixMethodOrder fixMethodOrder) {\n        if (fixMethodOrder == null) {\n            return DEFAULT;\n        }\n\n        return fixMethodOrder.value().getComparator();\n    }\n}\n", "human_rating": 3.9999830754, "metadata": {"project": "junit4", "class": "org.junit.internal.MethodSorter", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/MethodSorter.java", "label_probabilities": {"readability": [0.999984, 1.56918e-05, 0.0, 0.0], "understandability": [0.99999, 9.81703e-06, 5.9735e-16, 0.0], "complexity": [2.23e-18, 0.000159206, 0.346872, 0.652969], "modularization": [0.0, 1.59768e-13, 0.0558775, 0.944122], "overall": [0.911176, 0.0888221, 2.33299e-06, 1.229e-17]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.InitializationError", "source": "package org.junit.internal.runners;\n\nimport java.util.Arrays;\nimport java.util.List;\n\n/**\n * Use the published version: {@link org.junit.runners.InitializationError}\n * This may disappear as soon as 1 April 2009\n */\n@Deprecated\npublic class InitializationError extends Exception {\n    private static final long serialVersionUID = 1L;\n    private final List<Throwable> fErrors;\n\n    public InitializationError(List<Throwable> errors) {\n        fErrors = errors;\n    }\n\n    public InitializationError(Throwable... errors) {\n        this(Arrays.asList(errors));\n    }\n\n    public InitializationError(String string) {\n        this(new Exception(string));\n    }\n\n    public List<Throwable> getCauses() {\n        return fErrors;\n    }\n}\n", "human_rating": 4.0, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.InitializationError", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/InitializationError.java", "label_probabilities": {"readability": [1.0, 0.0, 0.0, 0.0], "understandability": [0.971532, 0.0284684, 4.04094e-09, 0.0], "complexity": [0.0, 0.0, 0.0948371, 0.905163], "modularization": [0.0, 0.0, 0.599703, 0.400297], "overall": [0.999896, 0.000103873, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.JUnit38ClassRunner", "source": "package org.junit.internal.runners;\n\nimport junit.extensions.TestDecorator;\nimport junit.framework.AssertionFailedError;\nimport junit.framework.Test;\nimport junit.framework.TestCase;\nimport junit.framework.TestListener;\nimport junit.framework.TestResult;\nimport junit.framework.TestSuite;\nimport org.junit.runner.Describable;\nimport org.junit.runner.Description;\nimport org.junit.runner.Runner;\nimport org.junit.runner.manipulation.Filter;\nimport org.junit.runner.manipulation.Filterable;\nimport org.junit.runner.manipulation.NoTestsRemainException;\nimport org.junit.runner.manipulation.Sortable;\nimport org.junit.runner.manipulation.Sorter;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunNotifier;\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Method;\n\npublic class JUnit38ClassRunner extends Runner implements Filterable, Sortable {\n    private static final class OldTestClassAdaptingListener implements\n            TestListener {\n        private final RunNotifier fNotifier;\n\n        private OldTestClassAdaptingListener(RunNotifier notifier) {\n            fNotifier = notifier;\n        }\n\n        public void endTest(Test test) {\n            fNotifier.fireTestFinished(asDescription(test));\n        }\n\n        public void startTest(Test test) {\n            fNotifier.fireTestStarted(asDescription(test));\n        }\n\n        // Implement junit.framework.TestListener\n        public void addError(Test test, Throwable e) {\n            Failure failure = new Failure(asDescription(test), e);\n            fNotifier.fireTestFailure(failure);\n        }\n\n        private Description asDescription(Test test) {\n            if (test instanceof Describable) {\n                Describable facade = (Describable) test;\n                return facade.getDescription();\n            }\n            return Description.createTestDescription(getEffectiveClass(test), getName(test));\n        }\n\n        private Class<? extends Test> getEffectiveClass(Test test) {\n            return test.getClass();\n        }\n\n        private String getName(Test test) {\n            if (test instanceof TestCase) {\n                return ((TestCase) test).getName();\n            } else {\n                return test.toString();\n            }\n        }\n\n        public void addFailure(Test test, AssertionFailedError t) {\n            addError(test, t);\n        }\n    }\n\n    private volatile Test fTest;\n\n    public JUnit38ClassRunner(Class<?> klass) {\n        this(new TestSuite(klass.asSubclass(TestCase.class)));\n    }\n\n    public JUnit38ClassRunner(Test test) {\n        super();\n        setTest(test);\n    }\n\n    @Override\n    public void run(RunNotifier notifier) {\n        TestResult result = new TestResult();\n        result.addListener(createAdaptingListener(notifier));\n        getTest().run(result);\n    }\n\n    public TestListener createAdaptingListener(final RunNotifier notifier) {\n        return new OldTestClassAdaptingListener(notifier);\n    }\n\n    @Override\n    public Description getDescription() {\n        return makeDescription(getTest());\n    }\n\n    private static Description makeDescription(Test test) {\n        if (test instanceof TestCase) {\n            TestCase tc = (TestCase) test;\n            return Description.createTestDescription(tc.getClass(), tc.getName(),\n                    getAnnotations(tc));\n        } else if (test instanceof TestSuite) {\n            TestSuite ts = (TestSuite) test;\n            String name = ts.getName() == null ? createSuiteDescription(ts) : ts.getName();\n            Description description = Description.createSuiteDescription(name);\n            int n = ts.testCount();\n            for (int i = 0; i < n; i++) {\n                Description made = makeDescription(ts.testAt(i));\n                description.addChild(made);\n            }\n            return description;\n        } else if (test instanceof Describable) {\n            Describable adapter = (Describable) test;\n            return adapter.getDescription();\n        } else if (test instanceof TestDecorator) {\n            TestDecorator decorator = (TestDecorator) test;\n            return makeDescription(decorator.getTest());\n        } else {\n            // This is the best we can do in this case\n            return Description.createSuiteDescription(test.getClass());\n        }\n    }\n\n    /**\n     * Get the annotations associated with given TestCase.\n     * @param test the TestCase.\n     */\n    private static Annotation[] getAnnotations(TestCase test) {\n        try {\n            Method m = test.getClass().getMethod(test.getName());\n            return m.getDeclaredAnnotations();\n        } catch (SecurityException e) {\n        } catch (NoSuchMethodException e) {\n        }\n        return new Annotation[0];\n    }\n\n    private static String createSuiteDescription(TestSuite ts) {\n        int count = ts.countTestCases();\n        String example = count == 0 ? \"\" : String.format(\" [example: %s]\", ts.testAt(0));\n        return String.format(\"TestSuite with %s tests%s\", count, example);\n    }\n\n    public void filter(Filter filter) throws NoTestsRemainException {\n        if (getTest() instanceof Filterable) {\n            Filterable adapter = (Filterable) getTest();\n            adapter.filter(filter);\n        } else if (getTest() instanceof TestSuite) {\n            TestSuite suite = (TestSuite) getTest();\n            TestSuite filtered = new TestSuite(suite.getName());\n            int n = suite.testCount();\n            for (int i = 0; i < n; i++) {\n                Test test = suite.testAt(i);\n                if (filter.shouldRun(makeDescription(test))) {\n                    filtered.addTest(test);\n                }\n            }\n            setTest(filtered);\n            if (filtered.testCount() == 0) {\n                throw new NoTestsRemainException();\n            }\n        }\n    }\n\n    public void sort(Sorter sorter) {\n        if (getTest() instanceof Sortable) {\n            Sortable adapter = (Sortable) getTest();\n            adapter.sort(sorter);\n        }\n    }\n\n    private void setTest(Test test) {\n        fTest = test;\n    }\n\n    private Test getTest() {\n        return fTest;\n    }\n}\n", "human_rating": 3.7232818688736997, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.JUnit38ClassRunner", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/JUnit38ClassRunner.java", "label_probabilities": {"readability": [0.723334, 0.276612, 5.49283e-05, 1.22737e-08], "understandability": [0.102245, 0.819608, 0.0779164, 0.000230168], "complexity": [1.80012e-09, 0.00519946, 0.993945, 0.000855442], "modularization": [1.13894e-15, 0.00064639, 0.438859, 0.560494], "overall": [0.0226191, 0.97737, 1.09094e-05, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.MethodRoadie", "source": "package org.junit.internal.runners;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.List;\nimport java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.Future;\nimport java.util.concurrent.TimeUnit;\nimport java.util.concurrent.TimeoutException;\n\nimport org.junit.internal.AssumptionViolatedException;\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunNotifier;\nimport org.junit.runners.BlockJUnit4ClassRunner;\nimport org.junit.runners.model.TestTimedOutException;\n\n/**\n * @deprecated Included for backwards compatibility with JUnit 4.4. Will be\n *             removed in the next release. Please use\n *             {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}.\n */\n@Deprecated\npublic class MethodRoadie {\n    private final Object fTest;\n    private final RunNotifier fNotifier;\n    private final Description fDescription;\n    private TestMethod fTestMethod;\n\n    public MethodRoadie(Object test, TestMethod method, RunNotifier notifier, Description description) {\n        fTest = test;\n        fNotifier = notifier;\n        fDescription = description;\n        fTestMethod = method;\n    }\n\n    public void run() {\n        if (fTestMethod.isIgnored()) {\n            fNotifier.fireTestIgnored(fDescription);\n            return;\n        }\n        fNotifier.fireTestStarted(fDescription);\n        try {\n            long timeout = fTestMethod.getTimeout();\n            if (timeout > 0) {\n                runWithTimeout(timeout);\n            } else {\n                runTest();\n            }\n        } finally {\n            fNotifier.fireTestFinished(fDescription);\n        }\n    }\n\n    private void runWithTimeout(final long timeout) {\n        runBeforesThenTestThenAfters(new Runnable() {\n\n            public void run() {\n                ExecutorService service = Executors.newSingleThreadExecutor();\n                Callable<Object> callable = new Callable<Object>() {\n                    public Object call() throws Exception {\n                        runTestMethod();\n                        return null;\n                    }\n                };\n                Future<Object> result = service.submit(callable);\n                service.shutdown();\n                try {\n                    boolean terminated = service.awaitTermination(timeout,\n                            TimeUnit.MILLISECONDS);\n                    if (!terminated) {\n                        service.shutdownNow();\n                    }\n                    result.get(0, TimeUnit.MILLISECONDS); // throws the exception if one occurred during the invocation\n                } catch (TimeoutException e) {\n                    addFailure(new TestTimedOutException(timeout, TimeUnit.MILLISECONDS));\n                } catch (Exception e) {\n                    addFailure(e);\n                }\n            }\n        });\n    }\n\n    public void runTest() {\n        runBeforesThenTestThenAfters(new Runnable() {\n            public void run() {\n                runTestMethod();\n            }\n        });\n    }\n\n    public void runBeforesThenTestThenAfters(Runnable test) {\n        try {\n            runBefores();\n            test.run();\n        } catch (FailedBefore e) {\n        } catch (Exception e) {\n            throw new RuntimeException(\"test should never throw an exception to this level\");\n        } finally {\n            runAfters();\n        }\n    }\n\n    protected void runTestMethod() {\n        try {\n            fTestMethod.invoke(fTest);\n            if (fTestMethod.expectsException()) {\n                addFailure(new AssertionError(\"Expected exception: \" + fTestMethod.getExpectedException().getName()));\n            }\n        } catch (InvocationTargetException e) {\n            Throwable actual = e.getTargetException();\n            if (actual instanceof AssumptionViolatedException) {\n                return;\n            } else if (!fTestMethod.expectsException()) {\n                addFailure(actual);\n            } else if (fTestMethod.isUnexpected(actual)) {\n                String message = \"Unexpected exception, expected<\" + fTestMethod.getExpectedException().getName() + \"> but was<\"\n                        + actual.getClass().getName() + \">\";\n                addFailure(new Exception(message, actual));\n            }\n        } catch (Throwable e) {\n            addFailure(e);\n        }\n    }\n\n    private void runBefores() throws FailedBefore {\n        try {\n            try {\n                List<Method> befores = fTestMethod.getBefores();\n                for (Method before : befores) {\n                    before.invoke(fTest);\n                }\n            } catch (InvocationTargetException e) {\n                throw e.getTargetException();\n            }\n        } catch (AssumptionViolatedException e) {\n            throw new FailedBefore();\n        } catch (Throwable e) {\n            addFailure(e);\n            throw new FailedBefore();\n        }\n    }\n\n    private void runAfters() {\n        List<Method> afters = fTestMethod.getAfters();\n        for (Method after : afters) {\n            try {\n                after.invoke(fTest);\n            } catch (InvocationTargetException e) {\n                addFailure(e.getTargetException());\n            } catch (Throwable e) {\n                addFailure(e); // Untested, but seems impossible\n            }\n        }\n    }\n\n    protected void addFailure(Throwable e) {\n        fNotifier.fireTestFailure(new Failure(fDescription, e));\n    }\n}\n\n", "human_rating": 2.2308700927665197, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.MethodRoadie", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/MethodRoadie.java", "label_probabilities": {"readability": [1.89398e-09, 0.23087, 0.76913, 8.51906e-08], "understandability": [0.270327, 0.721304, 0.00836896, 2.76098e-10], "complexity": [0.0504081, 0.754762, 0.19483, 9.32982e-09], "modularization": [0.0, 2.65974e-09, 0.0958948, 0.904105], "overall": [0.157794, 0.842188, 1.8479e-05, 1.21e-18]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.model.MultipleFailureException", "source": "package org.junit.internal.runners.model;\n\nimport java.util.List;\n\n@Deprecated\npublic class MultipleFailureException extends org.junit.runners.model.MultipleFailureException {\n    private static final long serialVersionUID = 1L;\n\n    public MultipleFailureException(List<Throwable> errors) {\n        super(errors);\n    }\n}\n", "human_rating": 3.9582949010401, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.model.MultipleFailureException", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/model/MultipleFailureException.java", "label_probabilities": {"readability": [0.958295, 0.0417043, 1.00052e-06, 9.98987e-14], "understandability": [0.968477, 0.0315224, 4.69583e-07, 1.31449e-13], "complexity": [2.5e-19, 1.88871e-07, 0.0258059, 0.974194], "modularization": [0.0, 4.84987e-11, 0.0203369, 0.979663], "overall": [0.994958, 0.00504182, 1.47754e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.statements.ExpectException", "source": "package org.junit.internal.runners.statements;\n\nimport org.junit.internal.AssumptionViolatedException;\nimport org.junit.runners.model.Statement;\n\npublic class ExpectException extends Statement {\n    private Statement fNext;\n    private final Class<? extends Throwable> fExpected;\n\n    public ExpectException(Statement next, Class<? extends Throwable> expected) {\n        fNext = next;\n        fExpected = expected;\n    }\n\n    @Override\n    public void evaluate() throws Exception {\n        boolean complete = false;\n        try {\n            fNext.evaluate();\n            complete = true;\n        } catch (AssumptionViolatedException e) {\n            throw e;\n        } catch (Throwable e) {\n            if (!fExpected.isAssignableFrom(e.getClass())) {\n                String message = \"Unexpected exception, expected<\"\n                        + fExpected.getName() + \"> but was<\"\n                        + e.getClass().getName() + \">\";\n                throw new Exception(message, e);\n            }\n        }\n        if (complete) {\n            throw new AssertionError(\"Expected exception: \"\n                    + fExpected.getName());\n        }\n    }\n}", "human_rating": 3.961635758076289, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.statements.ExpectException", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/statements/ExpectException.java", "label_probabilities": {"readability": [0.961645, 0.0383463, 8.42896e-06, 1.56289e-10], "understandability": [0.0740967, 0.918248, 0.00765495, 9.10424e-11], "complexity": [8.3154e-16, 0.00304558, 0.90385, 0.0931046], "modularization": [2.209e-17, 6.29103e-05, 0.0339099, 0.966027], "overall": [0.935888, 0.0641119, 6.7219e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.statements.Fail", "source": "package org.junit.internal.runners.statements;\n\nimport org.junit.runners.model.Statement;\n\npublic class Fail extends Statement {\n    private final Throwable fError;\n\n    public Fail(Throwable e) {\n        fError = e;\n    }\n\n    @Override\n    public void evaluate() throws Throwable {\n        throw fError;\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.statements.Fail", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/statements/Fail.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.statements.InvokeMethod", "source": "package org.junit.internal.runners.statements;\n\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.Statement;\n\npublic class InvokeMethod extends Statement {\n    private final FrameworkMethod fTestMethod;\n    private Object fTarget;\n\n    public InvokeMethod(FrameworkMethod testMethod, Object target) {\n        fTestMethod = testMethod;\n        fTarget = target;\n    }\n\n    @Override\n    public void evaluate() throws Throwable {\n        fTestMethod.invokeExplosively(fTarget);\n    }\n}", "human_rating": 3.927985835881085, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.statements.InvokeMethod", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/statements/InvokeMethod.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.statements.RunAfters", "source": "package org.junit.internal.runners.statements;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.MultipleFailureException;\nimport org.junit.runners.model.Statement;\n\npublic class RunAfters extends Statement {\n    private final Statement fNext;\n\n    private final Object fTarget;\n\n    private final List<FrameworkMethod> fAfters;\n\n    public RunAfters(Statement next, List<FrameworkMethod> afters, Object target) {\n        fNext = next;\n        fAfters = afters;\n        fTarget = target;\n    }\n\n    @Override\n    public void evaluate() throws Throwable {\n        List<Throwable> errors = new ArrayList<Throwable>();\n        try {\n            fNext.evaluate();\n        } catch (Throwable e) {\n            errors.add(e);\n        } finally {\n            for (FrameworkMethod each : fAfters) {\n                try {\n                    each.invokeExplosively(fTarget);\n                } catch (Throwable e) {\n                    errors.add(e);\n                }\n            }\n        }\n        MultipleFailureException.assertEmpty(errors);\n    }\n}", "human_rating": 3.98870211224896, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.statements.RunAfters", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/statements/RunAfters.java", "label_probabilities": {"readability": [0.988703, 0.0112967, 6.12448e-09, 1.241e-17], "understandability": [0.873623, 0.126312, 6.5331e-05, 2.4111e-16], "complexity": [3.848e-17, 3.79839e-05, 0.940262, 0.0597003], "modularization": [0.0, 3.62898e-11, 0.0360272, 0.963973], "overall": [0.897545, 0.102455, 2.52756e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.TestClass", "source": "package org.junit.internal.runners;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Constructor;\nimport java.lang.reflect.Method;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\nimport org.junit.AfterClass;\nimport org.junit.Before;\nimport org.junit.BeforeClass;\nimport org.junit.Test;\nimport org.junit.internal.MethodSorter;\nimport org.junit.runners.BlockJUnit4ClassRunner;\n\n/**\n * @deprecated Included for backwards compatibility with JUnit 4.4. Will be\n *             removed in the next release. Please use\n *             {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}.\n */\n@Deprecated\npublic class TestClass {\n    private final Class<?> fClass;\n\n    public TestClass(Class<?> klass) {\n        fClass = klass;\n    }\n\n    public List<Method> getTestMethods() {\n        return getAnnotatedMethods(Test.class);\n    }\n\n    List<Method> getBefores() {\n        return getAnnotatedMethods(BeforeClass.class);\n    }\n\n    List<Method> getAfters() {\n        return getAnnotatedMethods(AfterClass.class);\n    }\n\n    public List<Method> getAnnotatedMethods(Class<? extends Annotation> annotationClass) {\n        List<Method> results = new ArrayList<Method>();\n        for (Class<?> eachClass : getSuperClasses(fClass)) {\n            Method[] methods = MethodSorter.getDeclaredMethods(eachClass);\n            for (Method eachMethod : methods) {\n                Annotation annotation = eachMethod.getAnnotation(annotationClass);\n                if (annotation != null && !isShadowed(eachMethod, results)) {\n                    results.add(eachMethod);\n                }\n            }\n        }\n        if (runsTopToBottom(annotationClass)) {\n            Collections.reverse(results);\n        }\n        return results;\n    }\n\n    private boolean runsTopToBottom(Class<? extends Annotation> annotation) {\n        return annotation.equals(Before.class) || annotation.equals(BeforeClass.class);\n    }\n\n    private boolean isShadowed(Method method, List<Method> results) {\n        for (Method each : results) {\n            if (isShadowed(method, each)) {\n                return true;\n            }\n        }\n        return false;\n    }\n\n    private boolean isShadowed(Method current, Method previous) {\n        if (!previous.getName().equals(current.getName())) {\n            return false;\n        }\n        if (previous.getParameterTypes().length != current.getParameterTypes().length) {\n            return false;\n        }\n        for (int i = 0; i < previous.getParameterTypes().length; i++) {\n            if (!previous.getParameterTypes()[i].equals(current.getParameterTypes()[i])) {\n                return false;\n            }\n        }\n        return true;\n    }\n\n    private List<Class<?>> getSuperClasses(Class<?> testClass) {\n        ArrayList<Class<?>> results = new ArrayList<Class<?>>();\n        Class<?> current = testClass;\n        while (current != null) {\n            results.add(current);\n            current = current.getSuperclass();\n        }\n        return results;\n    }\n\n    public Constructor<?> getConstructor() throws SecurityException, NoSuchMethodException {\n        return fClass.getConstructor();\n    }\n\n    public Class<?> getJavaClass() {\n        return fClass;\n    }\n\n    public String getName() {\n        return fClass.getName();\n    }\n\n}\n", "human_rating": 3.9781143555700544, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.TestClass", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/TestClass.java", "label_probabilities": {"readability": [0.978115, 0.0218845, 4.27785e-07, 5.47111e-14], "understandability": [0.647933, 0.350683, 0.00138393, 3.42806e-12], "complexity": [1.48375e-15, 6.43073e-05, 0.292145, 0.70779], "modularization": [0.0, 9.14978e-10, 0.257771, 0.742229], "overall": [0.911815, 0.0881854, 7.19003e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.runners.TestMethod", "source": "package org.junit.internal.runners;\n\nimport java.lang.reflect.InvocationTargetException;\nimport java.lang.reflect.Method;\nimport java.util.List;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Ignore;\nimport org.junit.Test;\nimport org.junit.Test.None;\nimport org.junit.runners.BlockJUnit4ClassRunner;\n\n/**\n * @deprecated Included for backwards compatibility with JUnit 4.4. Will be\n *             removed in the next release. Please use\n *             {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}.\n */\n@Deprecated\npublic class TestMethod {\n    private final Method fMethod;\n    private TestClass fTestClass;\n\n    public TestMethod(Method method, TestClass testClass) {\n        fMethod = method;\n        fTestClass = testClass;\n    }\n\n    public boolean isIgnored() {\n        return fMethod.getAnnotation(Ignore.class) != null;\n    }\n\n    public long getTimeout() {\n        Test annotation = fMethod.getAnnotation(Test.class);\n        if (annotation == null) {\n            return 0;\n        }\n        long timeout = annotation.timeout();\n        return timeout;\n    }\n\n    protected Class<? extends Throwable> getExpectedException() {\n        Test annotation = fMethod.getAnnotation(Test.class);\n        if (annotation == null || annotation.expected() == None.class) {\n            return null;\n        } else {\n            return annotation.expected();\n        }\n    }\n\n    boolean isUnexpected(Throwable exception) {\n        return !getExpectedException().isAssignableFrom(exception.getClass());\n    }\n\n    boolean expectsException() {\n        return getExpectedException() != null;\n    }\n\n    List<Method> getBefores() {\n        return fTestClass.getAnnotatedMethods(Before.class);\n    }\n\n    List<Method> getAfters() {\n        return fTestClass.getAnnotatedMethods(After.class);\n    }\n\n    public void invoke(Object test) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n        fMethod.invoke(test);\n    }\n\n}\n", "human_rating": 3.9742539077162005, "metadata": {"project": "junit4", "class": "org.junit.internal.runners.TestMethod", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/runners/TestMethod.java", "label_probabilities": {"readability": [0.974253, 0.0257473, 3.8581e-09, 0.0], "understandability": [0.974756, 0.0252436, 2.56536e-07, 2.31961e-14], "complexity": [0.0, 3.10479e-08, 0.00953374, 0.990466], "modularization": [0.0, 3.91269e-12, 0.0181125, 0.981888], "overall": [0.998277, 0.00172309, 2.71389e-13, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.internal.TextListener", "source": "package org.junit.internal;\n\nimport java.io.PrintStream;\nimport java.text.NumberFormat;\nimport java.util.List;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\nimport org.junit.runner.notification.RunListener;\n\npublic class TextListener extends RunListener {\n\n    private final PrintStream fWriter;\n\n    public TextListener(JUnitSystem system) {\n        this(system.out());\n    }\n\n    public TextListener(PrintStream writer) {\n        this.fWriter = writer;\n    }\n\n    @Override\n    public void testRunFinished(Result result) {\n        printHeader(result.getRunTime());\n        printFailures(result);\n        printFooter(result);\n    }\n\n    @Override\n    public void testStarted(Description description) {\n        fWriter.append('.');\n    }\n\n    @Override\n    public void testFailure(Failure failure) {\n        fWriter.append('E');\n    }\n\n    @Override\n    public void testIgnored(Description description) {\n        fWriter.append('I');\n    }\n\n    /*\n      * Internal methods\n      */\n\n    private PrintStream getWriter() {\n        return fWriter;\n    }\n\n    protected void printHeader(long runTime) {\n        getWriter().println();\n        getWriter().println(\"Time: \" + elapsedTimeAsString(runTime));\n    }\n\n    protected void printFailures(Result result) {\n        List<Failure> failures = result.getFailures();\n        if (failures.size() == 0) {\n            return;\n        }\n        if (failures.size() == 1) {\n            getWriter().println(\"There was \" + failures.size() + \" failure:\");\n        } else {\n            getWriter().println(\"There were \" + failures.size() + \" failures:\");\n        }\n        int i = 1;\n        for (Failure each : failures) {\n            printFailure(each, \"\" + i++);\n        }\n    }\n\n    protected void printFailure(Failure each, String prefix) {\n        getWriter().println(prefix + \") \" + each.getTestHeader());\n        getWriter().print(each.getTrace());\n    }\n\n    protected void printFooter(Result result) {\n        if (result.wasSuccessful()) {\n            getWriter().println();\n            getWriter().print(\"OK\");\n            getWriter().println(\" (\" + result.getRunCount() + \" test\" + (result.getRunCount() == 1 ? \"\" : \"s\") + \")\");\n\n        } else {\n            getWriter().println();\n            getWriter().println(\"FAILURES!!!\");\n            getWriter().println(\"Tests run: \" + result.getRunCount() + \",  Failures: \" + result.getFailureCount());\n        }\n        getWriter().println();\n    }\n\n    /**\n     * Returns the formatted string of the elapsed time. Duplicated from\n     * BaseTestRunner. Fix it.\n     */\n    protected String elapsedTimeAsString(long runTime) {\n        return NumberFormat.getInstance().format((double) runTime / 1000);\n    }\n}\n", "human_rating": 3.9582949010401, "metadata": {"project": "junit4", "class": "org.junit.internal.TextListener", "source_path": "junit4/sourcefiles/src/main/java/org/junit/internal/TextListener.java", "label_probabilities": {"readability": [0.958295, 0.0417043, 1.00052e-06, 9.98987e-14], "understandability": [0.0551397, 0.943649, 0.00120605, 5.04827e-06], "complexity": [2.5e-19, 1.88871e-07, 0.0258059, 0.974194], "modularization": [0.0, 4.84987e-11, 0.0203369, 0.979663], "overall": [0.994958, 0.00504182, 1.47754e-12, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.rules.ExternalResource", "source": "package org.junit.rules;\n\nimport org.junit.runner.Description;\nimport org.junit.runners.model.Statement;\n\n/**\n * A base class for Rules (like TemporaryFolder) that set up an external\n * resource before a test (a file, socket, server, database connection, etc.),\n * and guarantee to tear it down afterward:\n *\n * <pre>\n * public static class UsesExternalResource {\n *  Server myServer= new Server();\n *\n *  &#064;Rule\n *  public ExternalResource resource= new ExternalResource() {\n *      &#064;Override\n *      protected void before() throws Throwable {\n *          myServer.connect();\n *         };\n *\n *      &#064;Override\n *      protected void after() {\n *          myServer.disconnect();\n *         };\n *     };\n *\n *  &#064;Test\n *  public void testFoo() {\n *      new Client().run(myServer);\n *     }\n * }\n * </pre>\n *\n * @since 4.7\n */\npublic abstract class ExternalResource implements TestRule {\n    public Statement apply(Statement base, Description description) {\n        return statement(base);\n    }\n\n    private Statement statement(final Statement base) {\n        return new Statement() {\n            @Override\n            public void evaluate() throws Throwable {\n                before();\n                try {\n                    base.evaluate();\n                } finally {\n                    after();\n                }\n            }\n        };\n    }\n\n    /**\n     * Override to set up your specific external resource.\n     *\n     * @throws if setup fails (which will disable {@code after}\n     */\n    protected void before() throws Throwable {\n        // do nothing\n    }\n\n    /**\n     * Override to tear down your specific external resource.\n     */\n    protected void after() {\n        // do nothing\n    }\n}\n", "human_rating": 3.4609380083695718, "metadata": {"project": "junit4", "class": "org.junit.rules.ExternalResource", "source_path": "junit4/sourcefiles/src/main/java/org/junit/rules/ExternalResource.java", "label_probabilities": {"readability": [0.46101, 0.538918, 7.20041e-05, 1.69572e-10], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.rules.Stopwatch", "source": "package org.junit.rules;\n\nimport org.junit.internal.AssumptionViolatedException;\nimport org.junit.runner.Description;\n\nimport java.util.concurrent.TimeUnit;\n\n/**\n * The Stopwatch Rule notifies one of its own protected methods of the time spent by a test.<p/>\n * Override them to get the time in nanoseconds. For example, this class will keep logging the\n * time spent by each passed, failed, skipped, and finished test:\n *\n * <pre>\n * public static class StopwatchTest {\n *     private static final Logger logger= Logger.getLogger(&quot;&quot;);\n *\n *     private static void logInfo(String testName, String status, long nanos) {\n *         logger.info(String.format(&quot;Test %s %s, spent %d microseconds&quot;,\n *                                     testName, status, Stopwatch.toMicros(nanos)));\n *     }\n *\n *     &#064;Rule\n *     public Stopwatch stopwatch= new Stopwatch() {\n *         &#064;Override\n *         protected void succeeded(long nanos, Description description) {\n *             logInfo(description.getMethodName(), &quot;succeeded&quot;, nanos);\n *         }\n *\n *         &#064;Override\n *         protected void failed(long nanos, Throwable e, Description description) {\n *             logInfo(description.getMethodName(), &quot;failed&quot;, nanos);\n *         }\n *\n *         &#064;Override\n *         protected void skipped(long nanos, AssumptionViolatedException e, Description description) {\n *             logInfo(description.getMethodName(), &quot;skipped&quot;, nanos);\n *         }\n *\n *         &#064;Override\n *         protected void finished(long nanos, Description description) {\n *             logInfo(description.getMethodName(), &quot;finished&quot;, nanos);\n *         }\n *     };\n *\n *     &#064;Test\n *     public void succeeds() {\n *     }\n *\n *     &#064;Test\n *     public void fails() {\n *         fail();\n *     }\n *\n *     &#064;Test\n *     public void skips() {\n *         assumeTrue(false);\n *     }\n * }\n * </pre>\n *\n * An example to assert runtime:\n * <pre>\n * &#064;Test\n * public void performanceTest() throws InterruptedException {\n *     long delta= 30;\n *     Thread.sleep(300L);\n *     assertEquals(300d, stopwatch.runtime(MILLISECONDS), delta);\n *     Thread.sleep(500L);\n *     assertEquals(800d, stopwatch.runtime(MILLISECONDS), delta);\n * }\n * </pre>\n *\n * @author tibor17\n * @since 4.12\n */\npublic class Stopwatch extends TestWatcher {\n    private long fStartNanos;\n    private long fEndNanos;\n\n    /**\n     * @param unit time unit for returned runtime\n     * @return runtime measured during the test\n     */\n    public long runtime(TimeUnit unit) {\n        return unit.convert(currentNanoTime() - fStartNanos, TimeUnit.NANOSECONDS);\n    }\n\n    /**\n     * Invoked when a test succeeds\n     */\n    protected void succeeded(long nanos, Description description) {\n    }\n\n    /**\n     * Invoked when a test fails\n     */\n    protected void failed(long nanos, Throwable e, Description description) {\n    }\n\n    /**\n     * Invoked when a test is skipped due to a failed assumption.\n     */\n    protected void skipped(long nanos, AssumptionViolatedException e, Description description) {\n    }\n\n    /**\n     * Invoked when a test method finishes (whether passing or failing)\n     */\n    protected void finished(long nanos, Description description) {\n    }\n\n    /**\n     * @param nanos time in nanoseconds\n     * @return time converted to microseconds\n     */\n    public static long toMicros(long nanos) {\n        return TimeUnit.NANOSECONDS.toMicros(nanos);\n    }\n\n    /**\n     * @param nanos time in nanoseconds\n     * @return time converted to milliseconds\n     */\n    public static long toMillis(long nanos) {\n        return TimeUnit.NANOSECONDS.toMillis(nanos);\n    }\n\n    /**\n     * @param nanos time in nanoseconds\n     * @return time converted to seconds\n     */\n    public static long toSeconds(long nanos) {\n        return TimeUnit.NANOSECONDS.toSeconds(nanos);\n    }\n\n    private long getNanos() {\n        return fEndNanos - fStartNanos;\n    }\n\n    private void starting() {\n        fStartNanos= currentNanoTime();\n    }\n\n    private void stopping() {\n        fEndNanos= currentNanoTime();\n    }\n\n    private long currentNanoTime() {\n        return System.nanoTime();\n    }\n\n    @Override final protected void succeeded(Description description) {\n        stopping();\n        succeeded(getNanos(), description);\n    }\n\n    @Override final protected void failed(Throwable e, Description description) {\n        stopping();\n        failed(getNanos(), e, description);\n    }\n\n    @Override final protected void skipped(AssumptionViolatedException e, Description description) {\n        stopping();\n        skipped(getNanos(), e, description);\n    }\n\n    @Override final protected void starting(Description description) {\n        starting();\n    }\n\n    @Override final protected void finished(Description description) {\n        finished(getNanos(), description);\n    }\n}\n", "human_rating": 3.4609380083695718, "metadata": {"project": "junit4", "class": "org.junit.rules.Stopwatch", "source_path": "junit4/sourcefiles/src/main/java/org/junit/rules/Stopwatch.java", "label_probabilities": {"readability": [0.46101, 0.538918, 7.20041e-05, 1.69572e-10], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.rules.TemporaryFolder", "source": "package org.junit.rules;\n\nimport java.io.File;\nimport java.io.IOException;\n\nimport org.junit.Rule;\n\n/**\n * The TemporaryFolder Rule allows creation of files and folders that are\n * guaranteed to be deleted when the test method finishes (whether it passes or\n * fails):\n *\n * <pre>\n * public static class HasTempFolder {\n *  &#064;Rule\n *  public TemporaryFolder folder= new TemporaryFolder();\n *\n *  &#064;Test\n *  public void testUsingTempFolder() throws IOException {\n *      File createdFile= folder.newFile(&quot;myfile.txt&quot;);\n *      File createdFolder= folder.newFolder(&quot;subfolder&quot;);\n *      // ...\n *     }\n * }\n * </pre>\n *\n * @since 4.7\n */\npublic class TemporaryFolder extends ExternalResource {\n    private final File parentFolder;\n    private File folder;\n\n    public TemporaryFolder() {\n        this(null);\n    }\n\n    public TemporaryFolder(File parentFolder) {\n        this.parentFolder = parentFolder;\n    }\n\n    @Override\n    protected void before() throws Throwable {\n        create();\n    }\n\n    @Override\n    protected void after() {\n        delete();\n    }\n\n    // testing purposes only\n\n    /**\n     * for testing purposes only. Do not use.\n     */\n    public void create() throws IOException {\n        folder = createTemporaryFolderIn(parentFolder);\n    }\n\n    /**\n     * Returns a new fresh file with the given name under the temporary folder.\n     */\n    public File newFile(String fileName) throws IOException {\n        File file = new File(getRoot(), fileName);\n        if (!file.createNewFile()) {\n            throw new IOException(\n                    \"a file with the name \\'\" + fileName + \"\\' already exists in the test folder\");\n        }\n        return file;\n    }\n\n    /**\n     * Returns a new fresh file with a random name under the temporary folder.\n     */\n    public File newFile() throws IOException {\n        return File.createTempFile(\"junit\", null, getRoot());\n    }\n\n    /**\n     * Returns a new fresh folder with the given name under the temporary\n     * folder.\n     */\n    public File newFolder(String folder) throws IOException {\n        return newFolder(new String[]{folder});\n    }\n\n    /**\n     * Returns a new fresh folder with the given name(s) under the temporary\n     * folder.\n     */\n    public File newFolder(String... folderNames) throws IOException {\n        File file = getRoot();\n        for (int i = 0; i < folderNames.length; i++) {\n            String folderName = folderNames[i];\n            file = new File(file, folderName);\n            if (!file.mkdir() && isLastElementInArray(i, folderNames)) {\n                throw new IOException(\n                        \"a folder with the name \\'\" + folderName + \"\\' already exists\");\n            }\n        }\n        return file;\n    }\n\n    private boolean isLastElementInArray(int index, String[] array) {\n        return index == array.length - 1;\n    }\n\n    /**\n     * Returns a new fresh folder with a random name under the temporary folder.\n     */\n    public File newFolder() throws IOException {\n        return createTemporaryFolderIn(getRoot());\n    }\n\n    private File createTemporaryFolderIn(File parentFolder) throws IOException {\n        File createdFolder = File.createTempFile(\"junit\", \"\", parentFolder);\n        createdFolder.delete();\n        createdFolder.mkdir();\n        return createdFolder;\n    }\n\n    /**\n     * @return the location of this temporary folder.\n     */\n    public File getRoot() {\n        if (folder == null) {\n            throw new IllegalStateException(\n                    \"the temporary folder has not yet been created\");\n        }\n        return folder;\n    }\n\n    /**\n     * Delete all files and folders under the temporary folder. Usually not\n     * called directly, since it is automatically applied by the {@link Rule}\n     */\n    public void delete() {\n        if (folder != null) {\n            recursiveDelete(folder);\n        }\n    }\n\n    private void recursiveDelete(File file) {\n        File[] files = file.listFiles();\n        if (files != null) {\n            for (File each : files) {\n                recursiveDelete(each);\n            }\n        }\n        file.delete();\n    }\n}\n", "human_rating": 3.9000431234099997, "metadata": {"project": "junit4", "class": "org.junit.rules.TemporaryFolder", "source_path": "junit4/sourcefiles/src/main/java/org/junit/rules/TemporaryFolder.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.446229, 0.550663, 0.00310751, 1.47645e-08], "complexity": [0.0077364, 0.392712, 0.599551, 6.74932e-08], "modularization": [0.0, 0.000823008, 0.842166, 0.157011], "overall": [0.528004, 0.471994, 2.85194e-06, 2e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.rules.TestName", "source": "package org.junit.rules;\n\nimport org.junit.runner.Description;\n\n/**\n * The TestName Rule makes the current test name available inside test methods:\n *\n * <pre>\n * public class TestNameTest {\n *  &#064;Rule\n *  public TestName name= new TestName();\n *\n *  &#064;Test\n *  public void testA() {\n *      assertEquals(&quot;testA&quot;, name.getMethodName());\n *     }\n *\n *  &#064;Test\n *  public void testB() {\n *      assertEquals(&quot;testB&quot;, name.getMethodName());\n *     }\n * }\n * </pre>\n *\n * @since 4.7\n */\npublic class TestName extends TestWatcher {\n    private String fName;\n\n    @Override\n    protected void starting(Description d) {\n        fName = d.getMethodName();\n    }\n\n    /**\n     * @return the name of the currently-running test method\n     */\n    public String getMethodName() {\n        return fName;\n    }\n}\n", "human_rating": 3.9440344499600917, "metadata": {"project": "junit4", "class": "org.junit.rules.TestName", "source_path": "junit4/sourcefiles/src/main/java/org/junit/rules/TestName.java", "label_probabilities": {"readability": [0.944041, 0.055952, 7.22498e-06, 9.12649e-14], "understandability": [0.895116, 0.104659, 0.000224743, 4.29014e-14], "complexity": [2.91311e-11, 0.000733943, 0.192302, 0.806964], "modularization": [2.80447e-08, 0.000983402, 0.136793, 0.862224], "overall": [0.93662, 0.0633799, 7.22746e-08, 2e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.rules.TestWatcher", "source": "package org.junit.rules;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.internal.AssumptionViolatedException;\nimport org.junit.runner.Description;\nimport org.junit.runners.model.MultipleFailureException;\nimport org.junit.runners.model.Statement;\n\n/**\n * TestWatcher is a base class for Rules that take note of the testing\n * action, without modifying it. For example, this class will keep a log of each\n * passing and failing test:\n *\n * <pre>\n * public static class WatchmanTest {\n *  private static String watchedLog;\n *\n *  &#064;Rule\n *  public TestWatcher watchman= new TestWatcher() {\n *      &#064;Override\n *      protected void failed(Throwable e, Description description) {\n *          watchedLog+= description + &quot;\\n&quot;;\n *      }\n *\n *      &#064;Override\n *      protected void succeeded(Description description) {\n *          watchedLog+= description + &quot; &quot; + &quot;success!\\n&quot;;\n *         }\n *     };\n *\n *  &#064;Test\n *  public void fails() {\n *      fail();\n *  }\n *\n *  &#064;Test\n *  public void succeeds() {\n *     }\n * }\n * </pre>\n *\n * @since 4.9\n */\npublic abstract class TestWatcher implements TestRule {\n    public Statement apply(final Statement base, final Description description) {\n        return new Statement() {\n            @Override\n            public void evaluate() throws Throwable {\n                List<Throwable> errors = new ArrayList<Throwable>();\n\n                startingQuietly(description, errors);\n                try {\n                    base.evaluate();\n                    succeededQuietly(description, errors);\n                } catch (AssumptionViolatedException e) {\n                    errors.add(e);\n                    skippedQuietly(e, description, errors);\n                } catch (Throwable e) {\n                    errors.add(e);\n                    failedQuietly(e, description, errors);\n                } finally {\n                    finishedQuietly(description, errors);\n                }\n\n                MultipleFailureException.assertEmpty(errors);\n            }\n        };\n    }\n\n    private void succeededQuietly(Description description,\n            List<Throwable> errors) {\n        try {\n            succeeded(description);\n        } catch (Throwable e) {\n            errors.add(e);\n        }\n    }\n\n    private void failedQuietly(Throwable e, Description description,\n            List<Throwable> errors) {\n        try {\n            failed(e, description);\n        } catch (Throwable e1) {\n            errors.add(e1);\n        }\n    }\n\n    private void skippedQuietly(AssumptionViolatedException e, Description description,\n            List<Throwable> errors) {\n        try {\n            skipped(e, description);\n        } catch (Throwable e1) {\n            errors.add(e1);\n        }\n    }\n\n    private void startingQuietly(Description description,\n            List<Throwable> errors) {\n        try {\n            starting(description);\n        } catch (Throwable e) {\n            errors.add(e);\n        }\n    }\n\n    private void finishedQuietly(Description description,\n            List<Throwable> errors) {\n        try {\n            finished(description);\n        } catch (Throwable e) {\n            errors.add(e);\n        }\n    }\n\n    /**\n     * Invoked when a test succeeds\n     */\n    protected void succeeded(Description description) {\n    }\n\n    /**\n     * Invoked when a test fails\n     */\n    protected void failed(Throwable e, Description description) {\n    }\n\n    /**\n     * Invoked when a test is skipped due to a failed assumption.\n     */\n    protected void skipped(AssumptionViolatedException e, Description description) {\n    }\n\n    /**\n     * Invoked when a test is about to start\n     */\n    protected void starting(Description description) {\n    }\n\n    /**\n     * Invoked when a test method finishes (whether passing or failing)\n     */\n    protected void finished(Description description) {\n    }\n}\n", "human_rating": 4.000000083892, "metadata": {"project": "junit4", "class": "org.junit.rules.TestWatcher", "source_path": "junit4/sourcefiles/src/main/java/org/junit/rules/TestWatcher.java", "label_probabilities": {"readability": [1.0, 2.7964e-08, 0.0, 0.0], "understandability": [0.00223055, 0.744274, 0.253474, 2.12105e-05], "complexity": [0.0, 0.00028033, 0.202545, 0.797175], "modularization": [0.0, 3.68396e-11, 0.136927, 0.863073], "overall": [0.856512, 0.143488, 1.12074e-14, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.Description", "source": "package org.junit.runner;\n\nimport java.io.Serializable;\nimport java.lang.annotation.Annotation;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.Collection;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\n/**\n * A <code>Description</code> describes a test which is to be run or has been run. <code>Descriptions</code>\n * can be atomic (a single test) or compound (containing children tests). <code>Descriptions</code> are used\n * to provide feedback about the tests that are about to run (for example, the tree view\n * visible in many IDEs) or tests that have been run (for example, the failures view).\n * <p>\n * <code>Descriptions</code> are implemented as a single class rather than a Composite because\n * they are entirely informational. They contain no logic aside from counting their tests.\n * <p>\n * In the past, we used the raw {@link junit.framework.TestCase}s and {@link junit.framework.TestSuite}s\n * to display the tree of tests. This was no longer viable in JUnit 4 because atomic tests no longer have\n * a superclass below {@link Object}. We needed a way to pass a class and name together. Description\n * emerged from this.\n *\n * @see org.junit.runner.Request\n * @see org.junit.runner.Runner\n * @since 4.0\n */\npublic class Description implements Serializable {\n    private static final long serialVersionUID = 1L;\n\n    private static final Pattern METHOD_AND_CLASS_NAME_PATTERN = Pattern\n            .compile(\"(.*)\\\\((.*)\\\\)\");\n\n    /**\n     * Create a <code>Description</code> named <code>name</code>.\n     * Generally, you will add children to this <code>Description</code>.\n     *\n     * @param name the name of the <code>Description</code>\n     * @param annotations meta-data about the test, for downstream interpreters\n     * @return a <code>Description</code> named <code>name</code>\n     */\n    public static Description createSuiteDescription(String name, Annotation... annotations) {\n        return new Description(null, name, annotations);\n    }\n\n    /**\n     * Create a <code>Description</code> named <code>name</code>.\n     * Generally, you will add children to this <code>Description</code>.\n     *\n     * @param name the name of the <code>Description</code>\n     * @param uniqueId an arbitrary object used to define uniqueness (in {@link #equals(Object)}\n     * @param annotations meta-data about the test, for downstream interpreters\n     * @return a <code>Description</code> named <code>name</code>\n     */\n    public static Description createSuiteDescription(String name, Serializable uniqueId, Annotation... annotations) {\n        return new Description(null, name, uniqueId, annotations);\n    }\n\n    /**\n     * Create a <code>Description</code> of a single test named <code>name</code> in the 'class' named\n     * <code>className</code>. Generally, this will be a leaf <code>Description</code>. This method is a better choice\n     * than {@link #createTestDescription(Class, String, Annotation...)} for test runners whose test cases are not\n     * defined in an actual Java <code>Class</code>.\n     *\n     * @param className the class name of the test\n     * @param name the name of the test (a method name for test annotated with {@link org.junit.Test})\n     * @param annotations meta-data about the test, for downstream interpreters\n     * @return a <code>Description</code> named <code>name</code>\n     */\n    public static Description createTestDescription(String className, String name, Annotation... annotations) {\n        return new Description(null, formatDisplayName(name, className), annotations);\n    }\n\n    /**\n     * Create a <code>Description</code> of a single test named <code>name</code> in the class <code>clazz</code>.\n     * Generally, this will be a leaf <code>Description</code>.\n     *\n     * @param clazz the class of the test\n     * @param name the name of the test (a method name for test annotated with {@link org.junit.Test})\n     * @param annotations meta-data about the test, for downstream interpreters\n     * @return a <code>Description</code> named <code>name</code>\n     */\n    public static Description createTestDescription(Class<?> clazz, String name, Annotation... annotations) {\n        return new Description(clazz, formatDisplayName(name, clazz.getName()), annotations);\n    }\n\n    /**\n     * Create a <code>Description</code> of a single test named <code>name</code> in the class <code>clazz</code>.\n     * Generally, this will be a leaf <code>Description</code>.\n     * (This remains for binary compatibility with clients of JUnit 4.3)\n     *\n     * @param clazz the class of the test\n     * @param name the name of the test (a method name for test annotated with {@link org.junit.Test})\n     * @return a <code>Description</code> named <code>name</code>\n     */\n    public static Description createTestDescription(Class<?> clazz, String name) {\n        return new Description(clazz, formatDisplayName(name, clazz.getName()));\n    }\n\n    /**\n     * Create a <code>Description</code> of a single test named <code>name</code> in the class <code>clazz</code>.\n     * Generally, this will be a leaf <code>Description</code>.\n     *\n     * @param name the name of the test (a method name for test annotated with {@link org.junit.Test})\n     * @return a <code>Description</code> named <code>name</code>\n     */\n    public static Description createTestDescription(String className, String name, Serializable uniqueId) {\n        return new Description(null, formatDisplayName(name, className), uniqueId);\n    }\n\n    private static String formatDisplayName(String name, String className) {\n        return String.format(\"%s(%s)\", name, className);\n    }\n\n    /**\n     * Create a <code>Description</code> named after <code>testClass</code>\n     *\n     * @param testClass A {@link Class} containing tests\n     * @return a <code>Description</code> of <code>testClass</code>\n     */\n    public static Description createSuiteDescription(Class<?> testClass) {\n        return new Description(testClass, testClass.getName(), testClass.getAnnotations());\n    }\n\n    /**\n     * Describes a Runner which runs no tests\n     */\n    public static final Description EMPTY = new Description(null, \"No Tests\");\n\n    /**\n     * Describes a step in the test-running mechanism that goes so wrong no\n     * other description can be used (for example, an exception thrown from a Runner's\n     * constructor\n     */\n    public static final Description TEST_MECHANISM = new Description(null, \"Test mechanism\");\n\n    private final Collection<Description> fChildren = new ConcurrentLinkedQueue<Description>();\n    private final String fDisplayName;\n    private final Serializable fUniqueId;\n    private final Annotation[] fAnnotations;\n    private volatile /* write-once */ Class<?> fTestClass;\n\n    private Description(Class<?> clazz, String displayName, Annotation... annotations) {\n        this(clazz, displayName, displayName, annotations);\n    }\n\n    private Description(Class<?> clazz, String displayName, Serializable uniqueId, Annotation... annotations) {\n        if ((displayName == null) || (displayName.length() == 0)) {\n            throw new IllegalArgumentException(\n                    \"The display name must not be empty.\");\n        }\n        if ((uniqueId == null)) {\n            throw new IllegalArgumentException(\n                    \"The unique id must not be null.\");\n        }\n        fTestClass = clazz;\n        fDisplayName = displayName;\n        fUniqueId = uniqueId;\n        fAnnotations = annotations;\n    }\n\n    /**\n     * @return a user-understandable label\n     */\n    public String getDisplayName() {\n        return fDisplayName;\n    }\n\n    /**\n     * Add <code>Description</code> as a child of the receiver.\n     *\n     * @param description the soon-to-be child.\n     */\n    public void addChild(Description description) {\n        fChildren.add(description);\n    }\n\n    /**\n     * Gets the copy of the children of this {@code Description}.\n     * Returns an empty list if there are no children.\n     */\n    public ArrayList<Description> getChildren() {\n        return new ArrayList<Description>(fChildren);\n    }\n\n    /**\n     * @return <code>true</code> if the receiver is a suite\n     */\n    public boolean isSuite() {\n        return !isTest();\n    }\n\n    /**\n     * @return <code>true</code> if the receiver is an atomic test\n     */\n    public boolean isTest() {\n        return fChildren.isEmpty();\n    }\n\n    /**\n     * @return the total number of atomic tests in the receiver\n     */\n    public int testCount() {\n        if (isTest()) {\n            return 1;\n        }\n        int result = 0;\n        for (Description child : fChildren) {\n            result += child.testCount();\n        }\n        return result;\n    }\n\n    @Override\n    public int hashCode() {\n        return fUniqueId.hashCode();\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (!(obj instanceof Description)) {\n            return false;\n        }\n        Description d = (Description) obj;\n        return fUniqueId.equals(d.fUniqueId);\n    }\n\n    @Override\n    public String toString() {\n        return getDisplayName();\n    }\n\n    /**\n     * @return true if this is a description of a Runner that runs no tests\n     */\n    public boolean isEmpty() {\n        return equals(EMPTY);\n    }\n\n    /**\n     * @return a copy of this description, with no children (on the assumption that some of the\n     *         children will be added back)\n     */\n    public Description childlessCopy() {\n        return new Description(fTestClass, fDisplayName, fAnnotations);\n    }\n\n    /**\n     * @return the annotation of type annotationType that is attached to this description node,\n     *         or null if none exists\n     */\n    public <T extends Annotation> T getAnnotation(Class<T> annotationType) {\n        for (Annotation each : fAnnotations) {\n            if (each.annotationType().equals(annotationType)) {\n                return annotationType.cast(each);\n            }\n        }\n        return null;\n    }\n\n    /**\n     * @return all of the annotations attached to this description node\n     */\n    public Collection<Annotation> getAnnotations() {\n        return Arrays.asList(fAnnotations);\n    }\n\n    /**\n     * @return If this describes a method invocation,\n     *         the class of the test instance.\n     */\n    public Class<?> getTestClass() {\n        if (fTestClass != null) {\n            return fTestClass;\n        }\n        String name = getClassName();\n        if (name == null) {\n            return null;\n        }\n        try {\n            fTestClass = Class.forName(name, false, getClass().getClassLoader());\n            return fTestClass;\n        } catch (ClassNotFoundException e) {\n            return null;\n        }\n    }\n\n    /**\n     * @return If this describes a method invocation,\n     *         the name of the class of the test instance\n     */\n    public String getClassName() {\n        return fTestClass != null ? fTestClass.getName() : methodAndClassNamePatternGroupOrDefault(2, toString());\n    }\n\n    /**\n     * @return If this describes a method invocation,\n     *         the name of the method (or null if not)\n     */\n    public String getMethodName() {\n        return methodAndClassNamePatternGroupOrDefault(1, null);\n    }\n\n    private String methodAndClassNamePatternGroupOrDefault(int group,\n            String defaultString) {\n        Matcher matcher = METHOD_AND_CLASS_NAME_PATTERN.matcher(toString());\n        return matcher.matches() ? matcher.group(group) : defaultString;\n    }\n}", "human_rating": 3.9999195092, "metadata": {"project": "junit4", "class": "org.junit.runner.Description", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/Description.java", "label_probabilities": {"readability": [0.99992, 7.98364e-05, 7e-20, 0.0], "understandability": [0.988202, 0.0117975, 3.20667e-10, 0.0], "complexity": [0.0, 2.39144e-06, 0.0525442, 0.947453], "modularization": [1.75e-18, 0.000115693, 0.055379, 0.944505], "overall": [0.989259, 0.0107414, 6.3263e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.FilterFactories", "source": "package org.junit.runner;\n\nimport org.junit.internal.Classes;\nimport org.junit.runner.manipulation.Filter;\n\nimport static org.junit.runner.FilterFactory.FilterNotCreatedException;\n\n/**\n * Utility class whose methods create a {@link FilterFactory}.\n */\npublic class FilterFactories {\n    /**\n     * Creates a {@link Filter}.\n     *\n     * A filter specification is of the form \"package.of.FilterFactory=args-to-filter-factory\" or\n     * \"package.of.FilterFactory\".\n     *\n     * @param filterSpec The filter specification\n     * @throws org.junit.runner.FilterFactory.FilterNotCreatedException\n     */\n    public static Filter createFilterFromFilterSpec(Description description, String filterSpec)\n            throws FilterFactory.FilterNotCreatedException {\n        String[] tuple;\n\n        if (filterSpec.contains(\"=\")) {\n            tuple = filterSpec.split(\"=\", 2);\n        } else {\n            tuple = new String[]{ filterSpec, \"\" };\n        }\n\n        return createFilter(tuple[0], new FilterFactoryParams(tuple[1]));\n    }\n\n    /**\n     * Creates a {@link Filter}.\n     *\n     * @param filterFactoryFqcn The fully qualified class name of the {@link FilterFactory}\n     * @param params The arguments to the {@link FilterFactory}\n     * @throws org.junit.runner.FilterFactory.FilterNotCreatedException\n     */\n    public static Filter createFilter(String filterFactoryFqcn, FilterFactoryParams params)\n            throws FilterFactory.FilterNotCreatedException {\n        FilterFactory filterFactory = createFilterFactory(filterFactoryFqcn);\n\n        return filterFactory.createFilter(params);\n    }\n\n    /**\n     * Creates a {@link Filter}.\n     *\n     * @param filterFactoryClass The class of the {@link FilterFactory}\n     * @param params             The arguments to the {@link FilterFactory}\n     * @throws org.junit.runner.FilterFactory.FilterNotCreatedException\n     *\n     */\n    public static Filter createFilter(Class<? extends FilterFactory> filterFactoryClass, FilterFactoryParams params)\n            throws FilterFactory.FilterNotCreatedException {\n        FilterFactory filterFactory = createFilterFactory(filterFactoryClass);\n\n        return filterFactory.createFilter(params);\n    }\n\n    static FilterFactory createFilterFactory(String filterFactoryFqcn) throws FilterNotCreatedException {\n        Class<? extends FilterFactory> filterFactoryClass;\n\n        try {\n            filterFactoryClass = Classes.getClass(filterFactoryFqcn).asSubclass(FilterFactory.class);\n        } catch (Exception e) {\n            throw new FilterNotCreatedException(e);\n        }\n\n        return createFilterFactory(filterFactoryClass);\n    }\n\n    static FilterFactory createFilterFactory(Class<? extends FilterFactory> filterFactoryClass)\n            throws FilterNotCreatedException {\n        try {\n            return filterFactoryClass.getConstructor().newInstance();\n        } catch (Exception e) {\n            throw new FilterNotCreatedException(e);\n        }\n    }\n}\n", "human_rating": 3.2954938659999997, "metadata": {"project": "junit4", "class": "org.junit.runner.FilterFactories", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/FilterFactories.java", "label_probabilities": {"readability": [0.296371, 0.703125, 0.000131296, 0.000372274], "understandability": [0.351538, 0.641288, 0.00717371, 1.57216e-09], "complexity": [1.56314e-07, 0.00387251, 0.725796, 0.270331], "modularization": [0.0, 3.02134e-11, 0.0140928, 0.985907], "overall": [0.785156, 0.214844, 1.75105e-08, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.FilterFactoryParams", "source": "package org.junit.runner;\n\npublic final class FilterFactoryParams {\n    private final String args;\n\n    public FilterFactoryParams(String args) {\n        if (args == null) {\n            throw new NullPointerException();\n        }\n\n        this.args = args;\n    }\n\n    public String getArgs() {\n        return args;\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.runner.FilterFactoryParams", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/FilterFactoryParams.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.JUnitCore", "source": "package org.junit.runner;\n\nimport junit.runner.Version;\nimport org.junit.internal.JUnitSystem;\nimport org.junit.internal.RealSystem;\nimport org.junit.internal.TextListener;\nimport org.junit.internal.runners.JUnit38ClassRunner;\nimport org.junit.runner.notification.RunListener;\nimport org.junit.runner.notification.RunNotifier;\n\n/**\n * <code>JUnitCore</code> is a facade for running tests. It supports running JUnit 4 tests,\n * JUnit 3.8.x tests, and mixtures. To run tests from the command line, run\n * <code>java org.junit.runner.JUnitCore TestClass1 TestClass2 ...</code>.\n * For one-shot test runs, use the static method {@link #runClasses(Class[])}.\n * If you want to add special listeners,\n * create an instance of {@link org.junit.runner.JUnitCore} first and use it to run the tests.\n *\n * @see org.junit.runner.Result\n * @see org.junit.runner.notification.RunListener\n * @see org.junit.runner.Request\n * @since 4.0\n */\npublic class JUnitCore {\n    private final RunNotifier fNotifier = new RunNotifier();\n\n    /**\n     * Run the tests contained in the classes named in the <code>args</code>.\n     * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1.\n     * Write feedback while tests are running and write\n     * stack traces for all failed tests after the tests all complete.\n     *\n     * @param args names of classes in which to find tests to run\n     */\n    public static void main(String... args) {\n        Result result = new JUnitCore().runMain(new RealSystem(), args);\n        System.exit(result.wasSuccessful() ? 0 : 1);\n    }\n\n    /**\n     * Run the tests contained in <code>classes</code>. Write feedback while the tests\n     * are running and write stack traces for all failed tests after all tests complete. This is\n     * similar to {@link #main(String[])}, but intended to be used programmatically.\n     *\n     * @param classes Classes in which to find tests\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public static Result runClasses(Class<?>... classes) {\n        return runClasses(defaultComputer(), classes);\n    }\n\n    /**\n     * Run the tests contained in <code>classes</code>. Write feedback while the tests\n     * are running and write stack traces for all failed tests after all tests complete. This is\n     * similar to {@link #main(String[])}, but intended to be used programmatically.\n     *\n     * @param computer Helps construct Runners from classes\n     * @param classes  Classes in which to find tests\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public static Result runClasses(Computer computer, Class<?>... classes) {\n        return new JUnitCore().run(computer, classes);\n    }\n\n    /**\n     * @param system\n     * @param args from main()\n     */\n    Result runMain(JUnitSystem system, String... args) {\n        system.out().println(\"JUnit version \" + Version.id());\n\n        JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args);\n\n        RunListener listener = new TextListener(system);\n        addListener(listener);\n\n        return run(jUnitCommandLineParseResult.createRequest(defaultComputer()));\n    }\n\n    /**\n     * @return the version number of this release\n     */\n    public String getVersion() {\n        return Version.id();\n    }\n\n    /**\n     * Run all the tests in <code>classes</code>.\n     *\n     * @param classes the classes containing tests\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public Result run(Class<?>... classes) {\n        return run(defaultComputer(), classes);\n    }\n\n    /**\n     * Run all the tests in <code>classes</code>.\n     *\n     * @param computer Helps construct Runners from classes\n     * @param classes the classes containing tests\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public Result run(Computer computer, Class<?>... classes) {\n        return run(Request.classes(computer, classes));\n    }\n\n    /**\n     * Run all the tests contained in <code>request</code>.\n     *\n     * @param request the request describing tests\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public Result run(Request request) {\n        return run(request.getRunner());\n    }\n\n    /**\n     * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility.\n     *\n     * @param test the old-style test\n     * @return a {@link Result} describing the details of the test run and the failed tests.\n     */\n    public Result run(junit.framework.Test test) {\n        return run(new JUnit38ClassRunner(test));\n    }\n\n    /**\n     * Do not use. Testing purposes only.\n     */\n    public Result run(Runner runner) {\n        Result result = new Result();\n        RunListener listener = result.createListener();\n        fNotifier.addFirstListener(listener);\n        try {\n            fNotifier.fireTestRunStarted(runner.getDescription());\n            runner.run(fNotifier);\n            fNotifier.fireTestRunFinished(result);\n        } finally {\n            removeListener(listener);\n        }\n        return result;\n    }\n\n    /**\n     * Add a listener to be notified as the tests run.\n     *\n     * @param listener the listener to add\n     * @see org.junit.runner.notification.RunListener\n     */\n    public void addListener(RunListener listener) {\n        fNotifier.addListener(listener);\n    }\n\n    /**\n     * Remove a listener.\n     *\n     * @param listener the listener to remove\n     */\n    public void removeListener(RunListener listener) {\n        fNotifier.removeListener(listener);\n    }\n\n    static Computer defaultComputer() {\n        return new Computer();\n    }\n}\n", "human_rating": 3.9000431234099997, "metadata": {"project": "junit4", "class": "org.junit.runner.JUnitCore", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/JUnitCore.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.922848, 0.0771458, 6.1322e-06, 2.42194e-09], "complexity": [5.61592e-08, 0.000555821, 0.163575, 0.83587], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.978809, 0.021191, 1.89057e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.manipulation.Filter", "source": "package org.junit.runner.manipulation;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Request;\n\n/**\n * The canonical case of filtering is when you want to run a single test method in a class. Rather\n * than introduce runner API just for that one case, JUnit provides a general filtering mechanism.\n * If you want to filter the tests to be run, extend <code>Filter</code> and apply an instance of\n * your filter to the {@link org.junit.runner.Request} before running it (see\n * {@link org.junit.runner.JUnitCore#run(Request)}. Alternatively, apply a <code>Filter</code> to\n * a {@link org.junit.runner.Runner} before running tests (for example, in conjunction with\n * {@link org.junit.runner.RunWith}.\n *\n * @since 4.0\n */\npublic abstract class Filter {\n    /**\n     * A null <code>Filter</code> that passes all tests through.\n     */\n    public static final Filter ALL = new Filter() {\n        @Override\n        public boolean shouldRun(Description description) {\n            return true;\n        }\n\n        @Override\n        public String describe() {\n            return \"all tests\";\n        }\n\n        @Override\n        public void apply(Object child) throws NoTestsRemainException {\n            // do nothing\n        }\n\n        @Override\n        public Filter intersect(Filter second) {\n            return second;\n        }\n    };\n\n    /**\n     * Returns a {@code Filter} that only runs the single method described by\n     * {@code desiredDescription}\n     */\n    public static Filter matchMethodDescription(final Description desiredDescription) {\n        return new Filter() {\n            @Override\n            public boolean shouldRun(Description description) {\n                if (description.isTest()) {\n                    return desiredDescription.equals(description);\n                }\n\n                // explicitly check if any children want to run\n                for (Description each : description.getChildren()) {\n                    if (shouldRun(each)) {\n                        return true;\n                    }\n                }\n                return false;\n            }\n\n            @Override\n            public String describe() {\n                return String.format(\"Method %s\", desiredDescription.getDisplayName());\n            }\n        };\n    }\n\n\n    /**\n     * @param description the description of the test to be run\n     * @return <code>true</code> if the test should be run\n     */\n    public abstract boolean shouldRun(Description description);\n\n    /**\n     * Returns a textual description of this Filter\n     *\n     * @return a textual description of this Filter\n     */\n    public abstract String describe();\n\n    /**\n     * Invoke with a {@link org.junit.runner.Runner} to cause all tests it intends to run\n     * to first be checked with the filter. Only those that pass the filter will be run.\n     *\n     * @param child the runner to be filtered by the receiver\n     * @throws NoTestsRemainException if the receiver removes all tests\n     */\n    public void apply(Object child) throws NoTestsRemainException {\n        if (!(child instanceof Filterable)) {\n            return;\n        }\n        Filterable filterable = (Filterable) child;\n        filterable.filter(this);\n    }\n\n    /**\n     * Returns a new Filter that accepts the intersection of the tests accepted\n     * by this Filter and {@code second}\n     */\n    public Filter intersect(final Filter second) {\n        if (second == this || second == ALL) {\n            return this;\n        }\n        final Filter first = this;\n        return new Filter() {\n            @Override\n            public boolean shouldRun(Description description) {\n                return first.shouldRun(description)\n                        && second.shouldRun(description);\n            }\n\n            @Override\n            public String describe() {\n                return first.describe() + \" and \" + second.describe();\n            }\n        };\n    }\n}\n", "human_rating": 3.9000431234099997, "metadata": {"project": "junit4", "class": "org.junit.runner.manipulation.Filter", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/manipulation/Filter.java", "label_probabilities": {"readability": [0.900057, 0.0999342, 3.8766e-06, 4.77021e-06], "understandability": [0.108338, 0.889523, 0.00213871, 1.35596e-07], "complexity": [8.40574e-09, 0.000734785, 0.962835, 0.0364301], "modularization": [0.0, 3.56449e-10, 0.0530996, 0.9469], "overall": [0.191239, 0.808751, 9.92388e-06, 9e-20]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.manipulation.Sorter", "source": "package org.junit.runner.manipulation;\n\nimport java.util.Comparator;\n\nimport org.junit.runner.Description;\n\n/**\n * A <code>Sorter</code> orders tests. In general you will not need\n * to use a <code>Sorter</code> directly. Instead, use {@link org.junit.runner.Request#sortWith(Comparator)}.\n *\n * @since 4.0\n */\npublic class Sorter implements Comparator<Description> {\n    /**\n     * NULL is a <code>Sorter</code> that leaves elements in an undefined order\n     */\n    public static final Sorter NULL = new Sorter(new Comparator<Description>() {\n        public int compare(Description o1, Description o2) {\n            return 0;\n        }\n    });\n\n    private final Comparator<Description> fComparator;\n\n    /**\n     * Creates a <code>Sorter</code> that uses <code>comparator</code>\n     * to sort tests\n     *\n     * @param comparator the {@link Comparator} to use when sorting tests\n     */\n    public Sorter(Comparator<Description> comparator) {\n        fComparator = comparator;\n    }\n\n    /**\n     * Sorts the test in <code>runner</code> using <code>comparator</code>\n     */\n    public void apply(Object object) {\n        if (object instanceof Sortable) {\n            Sortable sortable = (Sortable) object;\n            sortable.sort(this);\n        }\n    }\n\n    public int compare(Description o1, Description o2) {\n        return fComparator.compare(o1, o2);\n    }\n}\n", "human_rating": 3.7295051619999997, "metadata": {"project": "junit4", "class": "org.junit.runner.manipulation.Sorter", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/manipulation/Sorter.java", "label_probabilities": {"readability": [0.729612, 0.270281, 0.000107081, 0.0], "understandability": [0.447608, 0.552392, 2.51088e-07, 0.0], "complexity": [0.0, 1.05275e-10, 0.0810204, 0.91898], "modularization": [0.0, 3.6178e-12, 0.0131584, 0.986842], "overall": [0.97476, 0.02524, 1.90946e-08, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.notification.RunListener", "source": "package org.junit.runner.notification;\n\nimport java.lang.annotation.Documented;\nimport java.lang.annotation.ElementType;\nimport java.lang.annotation.Retention;\nimport java.lang.annotation.RetentionPolicy;\nimport java.lang.annotation.Target;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Result;\n\n/**\n * Register an instance of this class with {@link RunNotifier} to be notified\n * of events that occur during a test run. All of the methods in this class\n * are abstract and have no implementation; override one or more methods to\n * receive events.\n * <p>\n * For example, suppose you have a <code>Cowbell</code>\n * class that you want to make a noise whenever a test fails. You could write:\n * <pre>\n * public class RingingListener extends RunListener {\n *    public void testFailure(Failure failure) {\n *       Cowbell.ring();\n *    }\n * }\n * </pre>\n * <p>\n * To invoke your listener, you need to run your tests through <code>JUnitCore</code>.\n * <pre>\n * public void main(String... args) {\n *    JUnitCore core= new JUnitCore();\n *    core.addListener(new RingingListener());\n *    core.run(MyTestClass.class);\n * }\n * </pre>\n * <p>\n * If a listener throws an exception for a test event, the other listeners will\n * have their {@link RunListener#testFailure(Failure)} called with a {@code Description}\n * of {@link Description#TEST_MECHANISM} to indicate the failure.\n * <p>\n * By default, JUnit will synchronize calls to your listener. If your listener\n * is thread-safe and you want to allow JUnit to call your listener from\n * multiple threads when tests are run in parallel, you can annotate your\n * test class with {@link RunListener.ThreadSafe}.\n * <p>\n * Listener methods will be called from the same thread as is running\n * the test, unless otherwise indicated by the method Javadoc\n *\n * @see org.junit.runner.JUnitCore\n * @since 4.0\n */\npublic class RunListener {\n\n    /**\n     * Called before any tests have been run. This may be called on an\n     * arbitrary thread.\n     *\n     * @param description describes the tests to be run\n     */\n    public void testRunStarted(Description description) throws Exception {\n    }\n\n    /**\n     * Called when all tests have finished. This may be called on an\n     * arbitrary thread.\n     *\n     * @param result the summary of the test run, including all the tests that failed\n     */\n    public void testRunFinished(Result result) throws Exception {\n    }\n\n    /**\n     * Called when an atomic test is about to be started.\n     *\n     * @param description the description of the test that is about to be run\n     * (generally a class and method name)\n     */\n    public void testStarted(Description description) throws Exception {\n    }\n\n    /**\n     * Called when an atomic test has finished, whether the test succeeds or fails.\n     *\n     * @param description the description of the test that just ran\n     */\n    public void testFinished(Description description) throws Exception {\n    }\n\n    /**\n     * Called when an atomic test fails, or when a listener throws an exception.\n     *\n     * <p>In the case of a failure of an atomic test, this method will be called\n     * with the same {@code Description} passed to\n     * {@link #testStarted(Description)}, from the same thread that called\n     * {@link #testStarted(Description)}.\n     *\n     * <p>In the case of a listener throwing an exception, this will be called with\n     * a {@code Description} of {@link Description#TEST_MECHANISM}, and may be called\n     * on an arbitrary thread.\n     *\n     * @param failure describes the test that failed and the exception that was thrown\n     */\n    public void testFailure(Failure failure) throws Exception {\n    }\n\n    /**\n     * Called when an atomic test flags that it assumes a condition that is\n     * false\n     *\n     * @param failure describes the test that failed and the\n     * {@link org.junit.AssumptionViolatedException} that was thrown\n     */\n    public void testAssumptionFailure(Failure failure) {\n    }\n\n    /**\n     * Called when a test will not be run, generally because a test method is annotated\n     * with {@link org.junit.Ignore}.\n     *\n     * @param description describes the test that will not be run\n     */\n    public void testIgnored(Description description) throws Exception {\n    }\n\n\n    /**\n     * Indicates a {@code RunListener} that can have its methods called\n     * concurrently. This implies that the class is thread-safe (i.e. no set of\n     * listener calls can put the listener into an invalid state, even if those\n     * listener calls are being made by multiple threads without\n     * synchronization).\n     *\n     * @since 4.12\n     */\n    @Documented\n    @Target(ElementType.TYPE)\n    @Retention(RetentionPolicy.RUNTIME)\n    public @interface ThreadSafe {\n    }\n}\n", "human_rating": 3.999857996, "metadata": {"project": "junit4", "class": "org.junit.runner.notification.RunListener", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/notification/RunListener.java", "label_probabilities": {"readability": [0.999857, 0.000143332, 3e-20, 0.0], "understandability": [0.991929, 0.00807099, 1.14236e-11, 0.0], "complexity": [0.0, 5.25867e-06, 0.0904313, 0.909563], "modularization": [0.0, 1.39e-18, 0.0139355, 0.986064], "overall": [0.997895, 0.00210509, 3.344e-17, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.notification.RunNotifier", "source": "package org.junit.runner.notification;\n\nimport static java.util.Arrays.asList;\n\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.concurrent.CopyOnWriteArrayList;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Result;\n\n/**\n * If you write custom runners, you may need to notify JUnit of your progress running tests.\n * Do this by invoking the <code>RunNotifier</code> passed to your implementation of\n * {@link org.junit.runner.Runner#run(RunNotifier)}. Future evolution of this class is likely to\n * move {@link #fireTestRunStarted(Description)} and {@link #fireTestRunFinished(Result)}\n * to a separate class since they should only be called once per run.\n *\n * @since 4.0\n */\npublic class RunNotifier {\n    private final List<RunListener> fListeners = new CopyOnWriteArrayList<RunListener>();\n    private volatile boolean fPleaseStop = false;\n\n    /**\n     * Internal use only\n     */\n    public void addListener(RunListener listener) {\n        if (listener == null) {\n            throw new NullPointerException(\"Cannot add a null listener\");\n        }\n        fListeners.add(wrapIfNotThreadSafe(listener));\n    }\n\n    /**\n     * Internal use only\n     */\n    public void removeListener(RunListener listener) {\n        if (listener == null) {\n            throw new NullPointerException(\"Cannot remove a null listener\");\n        }\n        fListeners.remove(wrapIfNotThreadSafe(listener));\n    }\n\n    /**\n     * Wraps the given listener with {@link SynchronizedRunListener} if\n     * it is not annotated with {@link RunListener.ThreadSafe}.\n     */\n    RunListener wrapIfNotThreadSafe(RunListener listener) {\n        return listener.getClass().isAnnotationPresent(RunListener.ThreadSafe.class) ?\n                listener : new SynchronizedRunListener(listener, this);\n    }\n\n\n    private abstract class SafeNotifier {\n        private final List<RunListener> fCurrentListeners;\n\n        SafeNotifier() {\n            this(fListeners);\n        }\n\n        SafeNotifier(List<RunListener> currentListeners) {\n            fCurrentListeners = currentListeners;\n        }\n\n        void run() {\n            int capacity = fCurrentListeners.size();\n            ArrayList<RunListener> safeListeners = new ArrayList<RunListener>(capacity);\n            ArrayList<Failure> failures = new ArrayList<Failure>(capacity);\n            for (RunListener listener : fCurrentListeners) {\n                try {\n                    notifyListener(listener);\n                    safeListeners.add(listener);\n                } catch (Exception e) {\n                    failures.add(new Failure(Description.TEST_MECHANISM, e));\n                }\n            }\n            fireTestFailures(safeListeners, failures);\n        }\n\n        abstract protected void notifyListener(RunListener each) throws Exception;\n    }\n\n    /**\n     * Do not invoke.\n     */\n    public void fireTestRunStarted(final Description description) {\n        new SafeNotifier() {\n            @Override\n            protected void notifyListener(RunListener each) throws Exception {\n                each.testRunStarted(description);\n            }\n        }.run();\n    }\n\n    /**\n     * Do not invoke.\n     */\n    public void fireTestRunFinished(final Result result) {\n        new SafeNotifier() {\n            @Override\n            protected void notifyListener(RunListener each) throws Exception {\n                each.testRunFinished(result);\n            }\n        }.run();\n    }\n\n    /**\n     * Invoke to tell listeners that an atomic test is about to start.\n     *\n     * @param description the description of the atomic test (generally a class and method name)\n     * @throws StoppedByUserException thrown if a user has requested that the test run stop\n     */\n    public void fireTestStarted(final Description description) throws StoppedByUserException {\n        if (fPleaseStop) {\n            throw new StoppedByUserException();\n        }\n        new SafeNotifier() {\n            @Override\n            protected void notifyListener(RunListener each) throws Exception {\n                each.testStarted(description);\n            }\n        }.run();\n    }\n\n    /**\n     * Invoke to tell listeners that an atomic test failed.\n     *\n     * @param failure the description of the test that failed and the exception thrown\n     */\n    public void fireTestFailure(Failure failure) {\n        fireTestFailures(fListeners, asList(failure));\n    }\n\n    private void fireTestFailures(List<RunListener> listeners,\n            final List<Failure> failures) {\n        if (!failures.isEmpty()) {\n            new SafeNotifier(listeners) {\n                @Override\n                protected void notifyListener(RunListener listener) throws Exception {\n                    for (Failure each : failures) {\n                        listener.testFailure(each);\n                    }\n                }\n            }.run();\n        }\n    }\n\n    /**\n     * Invoke to tell listeners that an atomic test flagged that it assumed\n     * something false.\n     *\n     * @param failure the description of the test that failed and the\n     * {@link org.junit.AssumptionViolatedException} thrown\n     */\n    public void fireTestAssumptionFailed(final Failure failure) {\n        new SafeNotifier() {\n            @Override\n            protected void notifyListener(RunListener each) throws Exception {\n                each.testAssumptionFailure(failure);\n            }\n        }.run();\n    }\n\n    /**\n     * Invoke to tell listeners that an atomic test was ignored.\n     *\n     * @param description the description of the ignored test\n     */\n    public void fireTestIgnored(final Description description) {\n        new SafeNotifier() {\n            @Override\n            protected void notifyListener(RunListener each) throws Exception {\n                each.testIgnored(description);\n            }\n        }.run();\n    }\n\n    /**\n     * Invoke to tell listeners that an atomic test finished. Always invoke\n     * this method if you invoke {@link #fireTestStarted(Description)}\n     * as listeners are likely to expect them to come in pairs.\n     *\n     * @param description the description of the test that finished\n     */\n    public void fireTestFinished(final Description description) {\n        new SafeNotifier() {\n            @Override\n            protected void notifyListener(RunListener each) throws Exception {\n                each.testFinished(description);\n            }\n        }.run();\n    }\n\n    /**\n     * Ask that the tests run stop before starting the next test. Phrased politely because\n     * the test currently running will not be interrupted. It seems a little odd to put this\n     * functionality here, but the <code>RunNotifier</code> is the only object guaranteed\n     * to be shared amongst the many runners involved.\n     */\n    public void pleaseStop() {\n        fPleaseStop = true;\n    }\n\n    /**\n     * Internal use only. The Result's listener must be first.\n     */\n    public void addFirstListener(RunListener listener) {\n        if (listener == null) {\n            throw new NullPointerException(\"Cannot add a null listener\");\n        }\n        fListeners.add(0, wrapIfNotThreadSafe(listener));\n    }\n}\n", "human_rating": 3.89545004433997, "metadata": {"project": "junit4", "class": "org.junit.runner.notification.RunNotifier", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/notification/RunNotifier.java", "label_probabilities": {"readability": [0.897868, 0.0997139, 0.00241817, 4.33997e-09], "understandability": [0.000411319, 0.048375, 0.539944, 0.41127], "complexity": [2.93668e-08, 0.0184371, 0.881474, 0.100089], "modularization": [0.00286971, 0.865937, 0.131193, 3.67801e-10], "overall": [0.00133611, 0.890109, 0.0788705, 0.0296839]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.notification.StoppedByUserException", "source": "package org.junit.runner.notification;\n\n/**\n * Thrown when a user has requested that the test run stop. Writers of\n * test running GUIs should be prepared to catch a <code>StoppedByUserException</code>.\n *\n * @see org.junit.runner.notification.RunNotifier\n * @since 4.0\n */\npublic class StoppedByUserException extends RuntimeException {\n    private static final long serialVersionUID = 1L;\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.runner.notification.StoppedByUserException", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/notification/StoppedByUserException.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.notification.SynchronizedRunListener", "source": "package org.junit.runner.notification;\n\nimport org.junit.runner.Description;\nimport org.junit.runner.Result;\n\n/**\n * Thread-safe decorator for {@link RunListener} implementations that synchronizes\n * calls to the delegate.\n *\n * <p>This class synchronizes all listener calls on a RunNotifier instance. This is done because\n * prior to JUnit 4.12, all listeners were called in a synchronized block in RunNotifier,\n * so no two listeners were ever called concurrently. If we instead made the methods here\n * sychronized, clients that added multiple listeners that called common code might see\n * issues due to the reduced synchronization.\n *\n * @author Tibor Digana (tibor17)\n * @author Kevin Cooney (kcooney)\n * @since 4.12\n *\n * @see RunNotifier\n */\n@RunListener.ThreadSafe\nfinal class SynchronizedRunListener extends RunListener {\n    private final RunListener fListener;\n    private final Object fMonitor;\n\n    SynchronizedRunListener(RunListener listener, Object monitor) {\n        fListener = listener;\n        fMonitor = monitor;\n    }\n\n    @Override\n    public void testRunStarted(Description description) throws Exception {\n        synchronized (fMonitor) {\n            fListener.testRunStarted(description);\n        }\n    }\n\n    @Override\n    public void testRunFinished(Result result) throws Exception {\n        synchronized (fMonitor) {\n            fListener.testRunFinished(result);\n        }\n    }\n\n    @Override\n    public void testStarted(Description description) throws Exception {\n        synchronized (fMonitor) {\n            fListener.testStarted(description);\n        }\n    }\n\n    @Override\n    public void testFinished(Description description) throws Exception {\n        synchronized (fMonitor) {\n            fListener.testFinished(description);\n        }\n    }\n\n    @Override\n    public void testFailure(Failure failure) throws Exception {\n        synchronized (fMonitor) {\n            fListener.testFailure(failure);\n        }\n    }\n\n    @Override\n    public void testAssumptionFailure(Failure failure) {\n        synchronized (fMonitor) {\n            fListener.testAssumptionFailure(failure);\n        }\n    }\n\n    @Override\n    public void testIgnored(Description description) throws Exception {\n        synchronized (fMonitor) {\n            fListener.testIgnored(description);\n        }\n    }\n\n    @Override\n    public int hashCode() {\n        return fListener.hashCode();\n    }\n\n    @Override\n    public boolean equals(Object other) {\n        if (this == other) {\n            return true;\n        }\n        if (!(other instanceof SynchronizedRunListener)) {\n            return false;\n        }\n        SynchronizedRunListener that = (SynchronizedRunListener) other;\n        \n        return fListener.equals(that.fListener);\n    }\n\n    @Override\n    public String toString() {\n        return fListener.toString() + \" (with synchronization wrapper)\";\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.runner.notification.SynchronizedRunListener", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/notification/SynchronizedRunListener.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runner.Runner", "source": "package org.junit.runner;\n\nimport org.junit.runner.notification.RunNotifier;\n\n/**\n * A <code>Runner</code> runs tests and notifies a {@link org.junit.runner.notification.RunNotifier}\n * of significant events as it does so. You will need to subclass <code>Runner</code>\n * when using {@link org.junit.runner.RunWith} to invoke a custom runner. When creating\n * a custom runner, in addition to implementing the abstract methods here you must\n * also provide a constructor that takes as an argument the {@link Class} containing\n * the tests.\n * <p/>\n * The default runner implementation guarantees that the instances of the test case\n * class will be constructed immediately before running the test and that the runner\n * will retain no reference to the test case instances, generally making them\n * available for garbage collection.\n *\n * @see org.junit.runner.Description\n * @see org.junit.runner.RunWith\n * @since 4.0\n */\npublic abstract class Runner implements Describable {\n    /*\n     * (non-Javadoc)\n     * @see org.junit.runner.Describable#getDescription()\n     */\n    public abstract Description getDescription();\n\n    /**\n     * Run the tests for this runner.\n     *\n     * @param notifier will be notified of events while tests are being run--tests being\n     * started, finishing, and failing\n     */\n    public abstract void run(RunNotifier notifier);\n\n    /**\n     * @return the number of tests to be run by the receiver\n     */\n    public int testCount() {\n        return getDescription().testCount();\n    }\n}", "human_rating": 3.927985835881085, "metadata": {"project": "junit4", "class": "org.junit.runner.Runner", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runner/Runner.java", "label_probabilities": {"readability": [0.928004, 0.071977, 1.94178e-05, 2.81085e-10], "understandability": [0.893849, 0.105851, 0.000299652, 2.47987e-12], "complexity": [7.76097e-15, 2.23481e-05, 0.0879109, 0.912067], "modularization": [1.829e-16, 0.000100991, 0.0388647, 0.961034], "overall": [0.967919, 0.0320814, 6.68577e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runners.BlockJUnit4ClassRunner", "source": "package org.junit.runners;\n\nimport static org.junit.internal.runners.rules.RuleFieldValidator.RULE_METHOD_VALIDATOR;\nimport static org.junit.internal.runners.rules.RuleFieldValidator.RULE_VALIDATOR;\n\nimport java.util.List;\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Ignore;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.Test.None;\nimport org.junit.internal.runners.model.ReflectiveCallable;\nimport org.junit.internal.runners.statements.ExpectException;\nimport org.junit.internal.runners.statements.Fail;\nimport org.junit.internal.runners.statements.FailOnTimeout;\nimport org.junit.internal.runners.statements.InvokeMethod;\nimport org.junit.internal.runners.statements.RunAfters;\nimport org.junit.internal.runners.statements.RunBefores;\nimport org.junit.rules.RunRules;\nimport org.junit.rules.TestRule;\nimport org.junit.runner.Description;\nimport org.junit.runner.notification.RunNotifier;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.InitializationError;\nimport org.junit.runners.model.MultipleFailureException;\nimport org.junit.runners.model.Statement;\n\n/**\n * Implements the JUnit 4 standard test case class model, as defined by the\n * annotations in the org.junit package. Many users will never notice this\n * class: it is now the default test class runner, but it should have exactly\n * the same behavior as the old test class runner ({@code JUnit4ClassRunner}).\n * <p>\n * BlockJUnit4ClassRunner has advantages for writers of custom JUnit runners\n * that are slight changes to the default behavior, however:\n *\n * <ul>\n * <li>It has a much simpler implementation based on {@link Statement}s,\n * allowing new operations to be inserted into the appropriate point in the\n * execution flow.\n *\n * <li>It is published, and extension and reuse are encouraged, whereas {@code\n * JUnit4ClassRunner} was in an internal package, and is now deprecated.\n * </ul>\n * <p>\n * In turn, in 2009 we introduced {@link Rule}s.  In many cases where extending\n * BlockJUnit4ClassRunner was necessary to add new behavior, {@link Rule}s can\n * be used, which makes the extension more reusable and composable.\n *\n * @since 4.5\n */\npublic class BlockJUnit4ClassRunner extends ParentRunner<FrameworkMethod> {\n    private final ConcurrentHashMap<FrameworkMethod, Description> fMethodDescriptions = new ConcurrentHashMap<FrameworkMethod, Description>();\n    /**\n     * Creates a BlockJUnit4ClassRunner to run {@code klass}\n     *\n     * @throws InitializationError if the test class is malformed.\n     */\n    public BlockJUnit4ClassRunner(Class<?> klass) throws InitializationError {\n        super(klass);\n    }\n\n    //\n    // Implementation of ParentRunner\n    //\n\n    @Override\n    protected void runChild(final FrameworkMethod method, RunNotifier notifier) {\n        Description description = describeChild(method);\n        if (isIgnored(method)) {\n            notifier.fireTestIgnored(description);\n        } else {\n            runLeaf(methodBlock(method), description, notifier);\n        }\n    }\n    \n    /**\n     * Evaluates whether {@link FrameworkMethod}s are ignored based on the\n     * {@link Ignore} annotation.\n     */\n    @Override\n    protected boolean isIgnored(FrameworkMethod child) {\n        return child.getAnnotation(Ignore.class) != null;\n    }\n\n    @Override\n    protected Description describeChild(FrameworkMethod method) {\n        Description description = fMethodDescriptions.get(method);\n\n        if (description == null) {\n            description = Description.createTestDescription(getTestClass().getJavaClass(),\n                    testName(method), method.getAnnotations());\n            fMethodDescriptions.putIfAbsent(method, description);\n        }\n\n        return description;\n    }\n\n    @Override\n    protected List<FrameworkMethod> getChildren() {\n        return computeTestMethods();\n    }\n\n    //\n    // Override in subclasses\n    //\n\n    /**\n     * Returns the methods that run tests. Default implementation returns all\n     * methods annotated with {@code @Test} on this class and superclasses that\n     * are not overridden.\n     */\n    protected List<FrameworkMethod> computeTestMethods() {\n        return getTestClass().getAnnotatedMethods(Test.class);\n    }\n\n    @Override\n    protected void collectInitializationErrors(List<Throwable> errors) {\n        super.collectInitializationErrors(errors);\n\n        validateNoNonStaticInnerClass(errors);\n        validateConstructor(errors);\n        validateInstanceMethods(errors);\n        validateFields(errors);\n        validateMethods(errors);\n    }\n\n    protected void validateNoNonStaticInnerClass(List<Throwable> errors) {\n        if (getTestClass().isANonStaticInnerClass()) {\n            String gripe = \"The inner class \" + getTestClass().getName()\n                    + \" is not static.\";\n            errors.add(new Exception(gripe));\n        }\n    }\n\n    /**\n     * Adds to {@code errors} if the test class has more than one constructor,\n     * or if the constructor takes parameters. Override if a subclass requires\n     * different validation rules.\n     */\n    protected void validateConstructor(List<Throwable> errors) {\n        validateOnlyOneConstructor(errors);\n        validateZeroArgConstructor(errors);\n    }\n\n    /**\n     * Adds to {@code errors} if the test class has more than one constructor\n     * (do not override)\n     */\n    protected void validateOnlyOneConstructor(List<Throwable> errors) {\n        if (!hasOneConstructor()) {\n            String gripe = \"Test class should have exactly one public constructor\";\n            errors.add(new Exception(gripe));\n        }\n    }\n\n    /**\n     * Adds to {@code errors} if the test class's single constructor takes\n     * parameters (do not override)\n     */\n    protected void validateZeroArgConstructor(List<Throwable> errors) {\n        if (!getTestClass().isANonStaticInnerClass()\n                && hasOneConstructor()\n                && (getTestClass().getOnlyConstructor().getParameterTypes().length != 0)) {\n            String gripe = \"Test class should have exactly one public zero-argument constructor\";\n            errors.add(new Exception(gripe));\n        }\n    }\n\n    private boolean hasOneConstructor() {\n        return getTestClass().getJavaClass().getConstructors().length == 1;\n    }\n\n    /**\n     * Adds to {@code errors} for each method annotated with {@code @Test},\n     * {@code @Before}, or {@code @After} that is not a public, void instance\n     * method with no arguments.\n     */\n    @Deprecated\n    protected void validateInstanceMethods(List<Throwable> errors) {\n        validatePublicVoidNoArgMethods(After.class, false, errors);\n        validatePublicVoidNoArgMethods(Before.class, false, errors);\n        validateTestMethods(errors);\n\n        if (computeTestMethods().size() == 0) {\n            errors.add(new Exception(\"No runnable methods\"));\n        }\n    }\n\n    protected void validateFields(List<Throwable> errors) {\n        RULE_VALIDATOR.validate(getTestClass(), errors);\n    }\n\n    private void validateMethods(List<Throwable> errors) {\n        RULE_METHOD_VALIDATOR.validate(getTestClass(), errors);\n    }\n\n    /**\n     * Adds to {@code errors} for each method annotated with {@code @Test}that\n     * is not a public, void instance method with no arguments.\n     */\n    protected void validateTestMethods(List<Throwable> errors) {\n        validatePublicVoidNoArgMethods(Test.class, false, errors);\n    }\n\n    /**\n     * Returns a new fixture for running a test. Default implementation executes\n     * the test class's no-argument constructor (validation should have ensured\n     * one exists).\n     */\n    protected Object createTest() throws Exception {\n        return getTestClass().getOnlyConstructor().newInstance();\n    }\n\n    /**\n     * Returns the name that describes {@code method} for {@link Description}s.\n     * Default implementation is the method's name\n     */\n    protected String testName(FrameworkMethod method) {\n        return method.getName();\n    }\n\n    /**\n     * Returns a Statement that, when executed, either returns normally if\n     * {@code method} passes, or throws an exception if {@code method} fails.\n     *\n     * Here is an outline of the default implementation:\n     *\n     * <ul>\n     * <li>Invoke {@code method} on the result of {@code createTest()}, and\n     * throw any exceptions thrown by either operation.\n     * <li>HOWEVER, if {@code method}'s {@code @Test} annotation has the {@code\n     * expecting} attribute, return normally only if the previous step threw an\n     * exception of the correct type, and throw an exception otherwise.\n     * <li>HOWEVER, if {@code method}'s {@code @Test} annotation has the {@code\n     * timeout} attribute, throw an exception if the previous step takes more\n     * than the specified number of milliseconds.\n     * <li>ALWAYS run all non-overridden {@code @Before} methods on this class\n     * and superclasses before any of the previous steps; if any throws an\n     * Exception, stop execution and pass the exception on.\n     * <li>ALWAYS run all non-overridden {@code @After} methods on this class\n     * and superclasses after any of the previous steps; all After methods are\n     * always executed: exceptions thrown by previous steps are combined, if\n     * necessary, with exceptions from After methods into a\n     * {@link MultipleFailureException}.\n     * <li>ALWAYS allow {@code @Rule} fields to modify the execution of the\n     * above steps. A {@code Rule} may prevent all execution of the above steps,\n     * or add additional behavior before and after, or modify thrown exceptions.\n     * For more information, see {@link TestRule}\n     * </ul>\n     *\n     * This can be overridden in subclasses, either by overriding this method,\n     * or the implementations creating each sub-statement.\n     */\n    protected Statement methodBlock(FrameworkMethod method) {\n        Object test;\n        try {\n            test = new ReflectiveCallable() {\n                @Override\n                protected Object runReflectiveCall() throws Throwable {\n                    return createTest();\n                }\n            }.run();\n        } catch (Throwable e) {\n            return new Fail(e);\n        }\n\n        Statement statement = methodInvoker(method, test);\n        statement = possiblyExpectingExceptions(method, test, statement);\n        statement = withPotentialTimeout(method, test, statement);\n        statement = withBefores(method, test, statement);\n        statement = withAfters(method, test, statement);\n        statement = withRules(method, test, statement);\n        return statement;\n    }\n\n    //\n    // Statement builders\n    //\n\n    /**\n     * Returns a {@link Statement} that invokes {@code method} on {@code test}\n     */\n    protected Statement methodInvoker(FrameworkMethod method, Object test) {\n        return new InvokeMethod(method, test);\n    }\n\n    /**\n     * Returns a {@link Statement}: if {@code method}'s {@code @Test} annotation\n     * has the {@code expecting} attribute, return normally only if {@code next}\n     * throws an exception of the correct type, and throw an exception\n     * otherwise.\n     */\n    protected Statement possiblyExpectingExceptions(FrameworkMethod method,\n            Object test, Statement next) {\n        Test annotation = method.getAnnotation(Test.class);\n        return expectsException(annotation) ? new ExpectException(next,\n                getExpectedException(annotation)) : next;\n    }\n\n    /**\n     * Returns a {@link Statement}: if {@code method}'s {@code @Test} annotation\n     * has the {@code timeout} attribute, throw an exception if {@code next}\n     * takes more than the specified number of milliseconds.\n     */\n    @Deprecated\n    protected Statement withPotentialTimeout(FrameworkMethod method,\n            Object test, Statement next) {\n        long timeout = getTimeout(method.getAnnotation(Test.class));\n        return timeout > 0 ? new FailOnTimeout(next, timeout) : next;\n    }\n\n    /**\n     * Returns a {@link Statement}: run all non-overridden {@code @Before}\n     * methods on this class and superclasses before running {@code next}; if\n     * any throws an Exception, stop execution and pass the exception on.\n     */\n    protected Statement withBefores(FrameworkMethod method, Object target,\n            Statement statement) {\n        List<FrameworkMethod> befores = getTestClass().getAnnotatedMethods(\n                Before.class);\n        return befores.isEmpty() ? statement : new RunBefores(statement,\n                befores, target);\n    }\n\n    /**\n     * Returns a {@link Statement}: run all non-overridden {@code @After}\n     * methods on this class and superclasses before running {@code next}; all\n     * After methods are always executed: exceptions thrown by previous steps\n     * are combined, if necessary, with exceptions from After methods into a\n     * {@link MultipleFailureException}.\n     */\n    protected Statement withAfters(FrameworkMethod method, Object target,\n            Statement statement) {\n        List<FrameworkMethod> afters = getTestClass().getAnnotatedMethods(\n                After.class);\n        return afters.isEmpty() ? statement : new RunAfters(statement, afters,\n                target);\n    }\n\n    private Statement withRules(FrameworkMethod method, Object target,\n            Statement statement) {\n        List<TestRule> testRules = getTestRules(target);\n        Statement result = statement;\n        result = withMethodRules(method, testRules, target, result);\n        result = withTestRules(method, testRules, result);\n\n        return result;\n    }\n\n    private Statement withMethodRules(FrameworkMethod method, List<TestRule> testRules,\n            Object target, Statement result) {\n        for (org.junit.rules.MethodRule each : getMethodRules(target)) {\n            if (!testRules.contains(each)) {\n                result = each.apply(result, method, target);\n            }\n        }\n        return result;\n    }\n\n    private List<org.junit.rules.MethodRule> getMethodRules(Object target) {\n        return rules(target);\n    }\n\n    /**\n     * @param target the test case instance\n     * @return a list of MethodRules that should be applied when executing this\n     *         test\n     */\n    protected List<org.junit.rules.MethodRule> rules(Object target) {\n        return getTestClass().getAnnotatedFieldValues(target, Rule.class,\n                org.junit.rules.MethodRule.class);\n    }\n\n    /**\n     * Returns a {@link Statement}: apply all non-static {@link Value} fields\n     * annotated with {@link Rule}.\n     *\n     * @param statement The base statement\n     * @return a RunRules statement if any class-level {@link Rule}s are\n     *         found, or the base statement\n     */\n    private Statement withTestRules(FrameworkMethod method, List<TestRule> testRules,\n            Statement statement) {\n        return testRules.isEmpty() ? statement :\n                new RunRules(statement, testRules, describeChild(method));\n    }\n\n    /**\n     * @param target the test case instance\n     * @return a list of TestRules that should be applied when executing this\n     *         test\n     */\n    protected List<TestRule> getTestRules(Object target) {\n        List<TestRule> result = getTestClass().getAnnotatedMethodValues(target,\n                Rule.class, TestRule.class);\n\n        result.addAll(getTestClass().getAnnotatedFieldValues(target,\n                Rule.class, TestRule.class));\n\n        return result;\n    }\n\n    private Class<? extends Throwable> getExpectedException(Test annotation) {\n        if (annotation == null || annotation.expected() == None.class) {\n            return null;\n        } else {\n            return annotation.expected();\n        }\n    }\n\n    private boolean expectsException(Test annotation) {\n        return getExpectedException(annotation) != null;\n    }\n\n    private long getTimeout(Test annotation) {\n        if (annotation == null) {\n            return 0;\n        }\n        return annotation.timeout();\n    }\n}\n", "human_rating": 3.9582949010401, "metadata": {"project": "junit4", "class": "org.junit.runners.BlockJUnit4ClassRunner", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runners/BlockJUnit4ClassRunner.java", "label_probabilities": {"readability": [0.958295, 0.0417043, 1.00052e-06, 9.98987e-14], "understandability": [0.675225, 0.324432, 0.000343115, 1.15543e-12], "complexity": [2.5e-19, 1.88871e-07, 0.0258059, 0.974194], "modularization": [3.32239e-12, 0.0669728, 0.926458, 0.00656935], "overall": [0.603184, 0.396816, 2.72584e-07, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runners.model.FrameworkField", "source": "package org.junit.runners.model;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\n\nimport org.junit.runners.BlockJUnit4ClassRunner;\n\n/**\n * Represents a field on a test class (currently used only for Rules in\n * {@link BlockJUnit4ClassRunner}, but custom runners can make other uses)\n *\n * @since 4.7\n */\npublic class FrameworkField extends FrameworkMember<FrameworkField> {\n    private final Field fField;\n\n    FrameworkField(Field field) {\n        if (field == null) {\n            throw new NullPointerException(\n                    \"FrameworkField cannot be created without an underlying field.\");\n        }\n        fField = field;\n    }\n\n    @Override\n    public String getName() {\n        return getField().getName();\n    }\n\n    public Annotation[] getAnnotations() {\n        return fField.getAnnotations();\n    }\n\n    @Override\n    public boolean isShadowedBy(FrameworkField otherMember) {\n        return otherMember.getName().equals(getName());\n    }\n\n    @Override\n    protected int getModifiers() {\n        return fField.getModifiers();\n    }\n\n    /**\n     * @return the underlying java Field\n     */\n    public Field getField() {\n        return fField;\n    }\n\n    /**\n     * @return the underlying Java Field type\n     * @see java.lang.reflect.Field#getType()\n     */\n    @Override\n    public Class<?> getType() {\n        return fField.getType();\n    }\n    \n    @Override\n    public Class<?> getDeclaringClass() {\n        return fField.getDeclaringClass();\n    }\n\n    /**\n     * Attempts to retrieve the value of this field on {@code target}\n     */\n    public Object get(Object target) throws IllegalArgumentException, IllegalAccessException {\n        return fField.get(target);\n    }\n\n    @Override\n    public String toString() {\n        return fField.toString();\n    }\n}\n", "human_rating": 3.953471301100384, "metadata": {"project": "junit4", "class": "org.junit.runners.model.FrameworkField", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runners/model/FrameworkField.java", "label_probabilities": {"readability": [0.953474, 0.0465243, 1.20055e-06, 3.83515e-13], "understandability": [0.947926, 0.052072, 1.65639e-06, 2.38462e-11], "complexity": [2.95365e-15, 1.11632e-05, 0.0652689, 0.93472], "modularization": [0.0, 5.62316e-10, 0.0753064, 0.924694], "overall": [0.983715, 0.0162848, 3.53805e-10, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runners.model.RunnerBuilder", "source": "package org.junit.runners.model;\n\nimport java.util.ArrayList;\nimport java.util.HashSet;\nimport java.util.List;\nimport java.util.Set;\n\nimport org.junit.internal.runners.ErrorReportingRunner;\nimport org.junit.runner.Runner;\n\n/**\n * A RunnerBuilder is a strategy for constructing runners for classes.\n *\n * Only writers of custom runners should use <code>RunnerBuilder</code>s.  A custom runner class with a constructor taking\n * a <code>RunnerBuilder</code> parameter will be passed the instance of <code>RunnerBuilder</code> used to build that runner itself.\n * For example,\n * imagine a custom runner that builds suites based on a list of classes in a text file:\n *\n * <pre>\n * \\@RunWith(TextFileSuite.class)\n * \\@SuiteSpecFile(\"mysuite.txt\")\n * class MySuite {}\n * </pre>\n *\n * The implementation of TextFileSuite might include:\n *\n * <pre>\n * public TextFileSuite(Class testClass, RunnerBuilder builder) {\n *   // ...\n *   for (String className : readClassNames())\n *     addRunner(builder.runnerForClass(Class.forName(className)));\n *   // ...\n * }\n * </pre>\n *\n * @see org.junit.runners.Suite\n * @since 4.5\n */\npublic abstract class RunnerBuilder {\n    private final Set<Class<?>> parents = new HashSet<Class<?>>();\n\n    /**\n     * Override to calculate the correct runner for a test class at runtime.\n     *\n     * @param testClass class to be run\n     * @return a Runner\n     * @throws Throwable if a runner cannot be constructed\n     */\n    public abstract Runner runnerForClass(Class<?> testClass) throws Throwable;\n\n    /**\n     * Always returns a runner, even if it is just one that prints an error instead of running tests.\n     *\n     * @param testClass class to be run\n     * @return a Runner\n     */\n    public Runner safeRunnerForClass(Class<?> testClass) {\n        try {\n            return runnerForClass(testClass);\n        } catch (Throwable e) {\n            return new ErrorReportingRunner(testClass, e);\n        }\n    }\n\n    Class<?> addParent(Class<?> parent) throws InitializationError {\n        if (!parents.add(parent)) {\n            throw new InitializationError(String.format(\"class '%s' (possibly indirectly) contains itself as a SuiteClass\", parent.getName()));\n        }\n        return parent;\n    }\n\n    void removeParent(Class<?> klass) {\n        parents.remove(klass);\n    }\n\n    /**\n     * Constructs and returns a list of Runners, one for each child class in\n     * {@code children}.  Care is taken to avoid infinite recursion:\n     * this builder will throw an exception if it is requested for another\n     * runner for {@code parent} before this call completes.\n     */\n    public List<Runner> runners(Class<?> parent, Class<?>[] children)\n            throws InitializationError {\n        addParent(parent);\n\n        try {\n            return runners(children);\n        } finally {\n            removeParent(parent);\n        }\n    }\n\n    public List<Runner> runners(Class<?> parent, List<Class<?>> children)\n            throws InitializationError {\n        return runners(parent, children.toArray(new Class<?>[0]));\n    }\n\n    private List<Runner> runners(Class<?>[] children) {\n        ArrayList<Runner> runners = new ArrayList<Runner>();\n        for (Class<?> each : children) {\n            Runner childRunner = safeRunnerForClass(each);\n            if (childRunner != null) {\n                runners.add(childRunner);\n            }\n        }\n        return runners;\n    }\n}\n", "human_rating": 3.9755259290762104, "metadata": {"project": "junit4", "class": "org.junit.runners.model.RunnerBuilder", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runners/model/RunnerBuilder.java", "label_probabilities": {"readability": [0.975527, 0.0244723, 5.14538e-07, 2.10541e-13], "understandability": [0.975798, 0.0242017, 6.78669e-07, 3.02962e-12], "complexity": [2.3646e-16, 4.09431e-06, 0.0292064, 0.970789], "modularization": [0.0, 3.51971e-10, 0.0660224, 0.933978], "overall": [0.992406, 0.00759391, 6.77744e-11, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runners.model.TestTimedOutException", "source": "package org.junit.runners.model;\n\nimport java.util.concurrent.TimeUnit;\n\n/**\n * Exception thrown when a test fails on timeout.\n * \n * @since 4.12\n * \n */\npublic class TestTimedOutException extends Exception {\n\n    private static final long serialVersionUID = 31935685163547539L;\n\n    private final TimeUnit fTimeUnit;\n    private final long fTimeout;\n\n    /**\n     * Creates exception with a standard message \"test timed out after [timeout] [timeUnit]\"\n     * \n     * @param timeout the amount of time passed before the test was interrupted\n     * @param timeUnit the time unit for the timeout value\n     */\n    public TestTimedOutException(long timeout, TimeUnit timeUnit) {\n        super(String.format(\"test timed out after %d %s\", \n                timeout, timeUnit.name().toLowerCase()));\n        fTimeUnit = timeUnit;\n        fTimeout = timeout;\n    }\n\n    /**\n     * Gets the time passed before the test was interrupted\n     */\n    public long getTimeout() {\n        return fTimeout;\n    }\n\n    /**\n     * Gets the time unit for the timeout value\n     */\n    public TimeUnit getTimeUnit() {\n        return fTimeUnit;\n    }\n}\n", "human_rating": 4.0, "metadata": {"project": "junit4", "class": "org.junit.runners.model.TestTimedOutException", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runners/model/TestTimedOutException.java", "label_probabilities": {"readability": [1.0, 4e-20, 0.0, 0.0], "understandability": [0.998067, 0.00193271, 2.87795e-10, 0.0], "complexity": [0.0, 4.9529e-14, 0.27181, 0.72819], "modularization": [0.0, 0.0, 0.0138884, 0.986112], "overall": [0.999521, 0.000479311, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters", "source": "package org.junit.runners.parameterized;\n\nimport java.lang.annotation.Annotation;\nimport java.lang.reflect.Field;\nimport java.util.List;\n\nimport org.junit.runner.notification.RunNotifier;\nimport org.junit.runners.BlockJUnit4ClassRunner;\nimport org.junit.runners.Parameterized.Parameter;\nimport org.junit.runners.model.FrameworkField;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.InitializationError;\nimport org.junit.runners.model.Statement;\n\n/**\n * A {@link BlockJUnit4ClassRunner} with parameters support. Parameters can be\n * injected via constructor or into annotated fields.\n */\npublic class BlockJUnit4ClassRunnerWithParameters extends\n        BlockJUnit4ClassRunner {\n    private final Object[] fParameters;\n\n    private final String fName;\n\n    public BlockJUnit4ClassRunnerWithParameters(TestWithParameters test)\n            throws InitializationError {\n        super(test.getTestClass().getJavaClass());\n        fParameters = test.getParameters().toArray(\n                new Object[test.getParameters().size()]);\n        fName = test.getName();\n    }\n\n    @Override\n    public Object createTest() throws Exception {\n        if (fieldsAreAnnotated()) {\n            return createTestUsingFieldInjection();\n        } else {\n            return createTestUsingConstructorInjection();\n        }\n    }\n\n    private Object createTestUsingConstructorInjection() throws Exception {\n        return getTestClass().getOnlyConstructor().newInstance(fParameters);\n    }\n\n    private Object createTestUsingFieldInjection() throws Exception {\n        List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();\n        if (annotatedFieldsByParameter.size() != fParameters.length) {\n            throw new Exception(\n                    \"Wrong number of parameters and @Parameter fields.\"\n                            + \" @Parameter fields counted: \"\n                            + annotatedFieldsByParameter.size()\n                            + \", available parameters: \" + fParameters.length\n                            + \".\");\n        }\n        Object testClassInstance = getTestClass().getJavaClass().newInstance();\n        for (FrameworkField each : annotatedFieldsByParameter) {\n            Field field = each.getField();\n            Parameter annotation = field.getAnnotation(Parameter.class);\n            int index = annotation.value();\n            try {\n                field.set(testClassInstance, fParameters[index]);\n            } catch (IllegalArgumentException iare) {\n                throw new Exception(getTestClass().getName()\n                        + \": Trying to set \" + field.getName()\n                        + \" with the value \" + fParameters[index]\n                        + \" that is not the right type (\"\n                        + fParameters[index].getClass().getSimpleName()\n                        + \" instead of \" + field.getType().getSimpleName()\n                        + \").\", iare);\n            }\n        }\n        return testClassInstance;\n    }\n\n    @Override\n    protected String getName() {\n        return fName;\n    }\n\n    @Override\n    protected String testName(FrameworkMethod method) {\n        return method.getName() + getName();\n    }\n\n    @Override\n    protected void validateConstructor(List<Throwable> errors) {\n        validateOnlyOneConstructor(errors);\n        if (fieldsAreAnnotated()) {\n            validateZeroArgConstructor(errors);\n        }\n    }\n\n    @Override\n    protected void validateFields(List<Throwable> errors) {\n        super.validateFields(errors);\n        if (fieldsAreAnnotated()) {\n            List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();\n            int[] usedIndices = new int[annotatedFieldsByParameter.size()];\n            for (FrameworkField each : annotatedFieldsByParameter) {\n                int index = each.getField().getAnnotation(Parameter.class)\n                        .value();\n                if (index < 0 || index > annotatedFieldsByParameter.size() - 1) {\n                    errors.add(new Exception(\"Invalid @Parameter value: \"\n                            + index + \". @Parameter fields counted: \"\n                            + annotatedFieldsByParameter.size()\n                            + \". Please use an index between 0 and \"\n                            + (annotatedFieldsByParameter.size() - 1) + \".\"));\n                } else {\n                    usedIndices[index]++;\n                }\n            }\n            for (int index = 0; index < usedIndices.length; index++) {\n                int numberOfUse = usedIndices[index];\n                if (numberOfUse == 0) {\n                    errors.add(new Exception(\"@Parameter(\" + index\n                            + \") is never used.\"));\n                } else if (numberOfUse > 1) {\n                    errors.add(new Exception(\"@Parameter(\" + index\n                            + \") is used more than once (\" + numberOfUse + \").\"));\n                }\n            }\n        }\n    }\n\n    @Override\n    protected Statement classBlock(RunNotifier notifier) {\n        return childrenInvoker(notifier);\n    }\n\n    @Override\n    protected Annotation[] getRunnerAnnotations() {\n        return new Annotation[0];\n    }\n\n    private List<FrameworkField> getAnnotatedFieldsByParameter() {\n        return getTestClass().getAnnotatedFields(Parameter.class);\n    }\n\n    private boolean fieldsAreAnnotated() {\n        return !getAnnotatedFieldsByParameter().isEmpty();\n    }\n}\n", "human_rating": 2.7153838, "metadata": {"project": "junit4", "class": "org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParameters.java", "label_probabilities": {"readability": [0.019358, 0.676805, 0.3037, 0.0001368], "understandability": [0.0111266, 0.821677, 0.167103, 9.39152e-05], "complexity": [0.000741807, 0.17182, 0.430005, 0.397433], "modularization": [3.0863e-05, 0.0453484, 0.909886, 0.0447346], "overall": [0.0114379, 0.91303, 0.075532, 1.20478e-07]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory", "source": "package org.junit.runners.parameterized;\n\nimport org.junit.runner.Runner;\nimport org.junit.runners.model.InitializationError;\n\n/**\n * A {@link ParametersRunnerFactory} that creates\n * {@link BlockJUnit4ClassRunnerWithParameters}.\n * \n * @since 4.12\n */\npublic class BlockJUnit4ClassRunnerWithParametersFactory implements\n        ParametersRunnerFactory {\n    public Runner createRunnerForTestWithParameters(TestWithParameters test)\n            throws InitializationError {\n        return new BlockJUnit4ClassRunnerWithParameters(test);\n    }\n}\n", "human_rating": 3.9571827370002413, "metadata": {"project": "junit4", "class": "org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParametersFactory", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runners/parameterized/BlockJUnit4ClassRunnerWithParametersFactory.java", "label_probabilities": {"readability": [0.957194, 0.0427955, 1.01182e-05, 6.00241e-10], "understandability": [0.916827, 0.0827324, 0.000440876, 5.81851e-11], "complexity": [7.25228e-12, 0.000480204, 0.0986215, 0.900898], "modularization": [3.69542e-06, 0.00354894, 0.392319, 0.604128], "overall": [0.952335, 0.0476649, 3.02513e-07, 2.01474e-15]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.runners.parameterized.TestWithParameters", "source": "package org.junit.runners.parameterized;\n\nimport static java.util.Collections.unmodifiableList;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport org.junit.runners.model.TestClass;\n\n/**\n * A {@code TestWithParameters} keeps the data together that are needed for\n * creating a runner for a single data set of a parameterized test. It has a\n * name, the test class and a list of parameters.\n * \n * @since 4.12\n */\npublic class TestWithParameters {\n    private final String fName;\n\n    private final TestClass fTestClass;\n\n    private final List<Object> fParameters;\n\n    public TestWithParameters(String name, TestClass testClass,\n            List<Object> parameters) {\n        notNull(name, \"The name is missing.\");\n        notNull(testClass, \"The test class is missing.\");\n        notNull(parameters, \"The parameters are missing.\");\n        fName = name;\n        fTestClass = testClass;\n        fParameters = unmodifiableList(new ArrayList<Object>(parameters));\n    }\n\n    public String getName() {\n        return fName;\n    }\n\n    public TestClass getTestClass() {\n        return fTestClass;\n    }\n\n    public List<Object> getParameters() {\n        return fParameters;\n    }\n\n    @Override\n    public int hashCode() {\n        int prime = 14747;\n        int result = prime + fName.hashCode();\n        result = prime * result + fTestClass.hashCode();\n        return prime * result + fParameters.hashCode();\n    }\n\n    @Override\n    public boolean equals(Object obj) {\n        if (this == obj) {\n            return true;\n        }\n        if (obj == null) {\n            return false;\n        }\n        if (getClass() != obj.getClass()) {\n            return false;\n        }\n        TestWithParameters other = (TestWithParameters) obj;\n        return fName.equals(other.fName)\n                && fParameters.equals(other.fParameters)\n                && fTestClass.equals(other.fTestClass);\n    }\n\n    @Override\n    public String toString() {\n        return fTestClass.getName() + \" '\" + fName + \"' with parameters \"\n                + fParameters;\n    }\n\n    private static void notNull(Object value, String message) {\n        if (value == null) {\n            throw new NullPointerException(message);\n        }\n    }\n}\n", "human_rating": 3.9696838001344767, "metadata": {"project": "junit4", "class": "org.junit.runners.parameterized.TestWithParameters", "source_path": "junit4/sourcefiles/src/main/java/org/junit/runners/parameterized/TestWithParameters.java", "label_probabilities": {"readability": [0.969685, 0.0303146, 6.72384e-11, 0.0], "understandability": [0.989089, 0.0109114, 4.04073e-11, 0.0], "complexity": [0.0, 0.0, 1.38803e-06, 0.999999], "modularization": [1.98354e-13, 0.0034714, 0.0144196, 0.982109], "overall": [0.970269, 0.0297314, 2.20163e-09, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.validator.AnnotationsValidator", "source": "package org.junit.validator;\n\nimport static java.util.Collections.singletonList;\n\nimport java.lang.annotation.Annotation;\nimport java.util.ArrayList;\nimport java.util.Arrays;\nimport java.util.List;\n\nimport org.junit.runners.model.Annotatable;\nimport org.junit.runners.model.FrameworkField;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.TestClass;\n\n/**\n * An {@code AnnotationsValidator} validates all annotations of a test class,\n * including its annotated fields and methods.\n * \n * @since 4.12\n */\npublic final class AnnotationsValidator implements TestClassValidator {\n    private static final List<AnnotatableValidator<?>> VALIDATORS = Arrays.<AnnotatableValidator<?>>asList(\n            new ClassValidator(), new MethodValidator(), new FieldValidator());\n\n    /**\n     * Validate all annotations of the specified test class that are be\n     * annotated with {@link ValidateWith}.\n     * \n     * @param testClass\n     *            the {@link TestClass} that is validated.\n     * @return the errors found by the validator.\n     */\n    public List<Exception> validateTestClass(TestClass testClass) {\n        List<Exception> validationErrors= new ArrayList<Exception>();\n        for (AnnotatableValidator<?> validator : VALIDATORS) {\n            List<Exception> additionalErrors= validator\n                    .validateTestClass(testClass);\n            validationErrors.addAll(additionalErrors);\n        }\n        return validationErrors;\n    }\n\n    private static abstract class AnnotatableValidator<T extends Annotatable> {\n        private static final AnnotationValidatorFactory ANNOTATION_VALIDATOR_FACTORY = new AnnotationValidatorFactory();\n\n        abstract Iterable<T> getAnnotatablesForTestClass(TestClass testClass);\n\n        abstract List<Exception> validateAnnotatable(\n                AnnotationValidator validator, T annotatable);\n\n        public List<Exception> validateTestClass(TestClass testClass) {\n            List<Exception> validationErrors= new ArrayList<Exception>();\n            for (T annotatable : getAnnotatablesForTestClass(testClass)) {\n                List<Exception> additionalErrors= validateAnnotatable(annotatable);\n                validationErrors.addAll(additionalErrors);\n            }\n            return validationErrors;\n        }\n\n        private List<Exception> validateAnnotatable(T annotatable) {\n            List<Exception> validationErrors= new ArrayList<Exception>();\n            for (Annotation annotation : annotatable.getAnnotations()) {\n                Class<? extends Annotation> annotationType = annotation\n                        .annotationType();\n                ValidateWith validateWith = annotationType\n                        .getAnnotation(ValidateWith.class);\n                if (validateWith != null) {\n                    AnnotationValidator annotationValidator = ANNOTATION_VALIDATOR_FACTORY\n                            .createAnnotationValidator(validateWith);\n                    List<Exception> errors= validateAnnotatable(\n                            annotationValidator, annotatable);\n                    validationErrors.addAll(errors);\n                }\n            }\n            return validationErrors;\n        }\n    }\n\n    private static class ClassValidator extends AnnotatableValidator<TestClass> {\n        @Override\n        Iterable<TestClass> getAnnotatablesForTestClass(TestClass testClass) {\n            return singletonList(testClass);\n        }\n\n        @Override\n        List<Exception> validateAnnotatable(\n                AnnotationValidator validator, TestClass testClass) {\n            return validator.validateAnnotatedClass(testClass);\n        }\n    }\n\n    private static class MethodValidator extends\n            AnnotatableValidator<FrameworkMethod> {\n        @Override\n        Iterable<FrameworkMethod> getAnnotatablesForTestClass(\n                TestClass testClass) {\n            return testClass.getAnnotatedMethods();\n        }\n\n        @Override\n        List<Exception> validateAnnotatable(\n                AnnotationValidator validator, FrameworkMethod method) {\n            return validator.validateAnnotatedMethod(method);\n        }\n    }\n\n    private static class FieldValidator extends\n            AnnotatableValidator<FrameworkField> {\n        @Override\n        Iterable<FrameworkField> getAnnotatablesForTestClass(TestClass testClass) {\n            return testClass.getAnnotatedFields();\n        }\n\n        @Override\n        List<Exception> validateAnnotatable(\n                AnnotationValidator validator, FrameworkField field) {\n            return validator.validateAnnotatedField(field);\n        }\n    };\n}\n", "human_rating": 3.1983780602538237, "metadata": {"project": "junit4", "class": "org.junit.validator.AnnotationsValidator", "source_path": "junit4/sourcefiles/src/main/java/org/junit/validator/AnnotationsValidator.java", "label_probabilities": {"readability": [0.201472, 0.795434, 0.00309403, 2.53824e-10], "understandability": [0.00267324, 0.690416, 0.306889, 2.1857e-05], "complexity": [8.10501e-15, 0.017544, 0.982293, 0.000163134], "modularization": [1.01946e-13, 0.013168, 0.82727, 0.159562], "overall": [0.00331022, 0.987217, 0.00947288, 7.43778e-14]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}, {"task_id": "Schnappinger/junit4/org.junit.validator.AnnotationValidator", "source": "package org.junit.validator;\n\nimport org.junit.runners.model.FrameworkField;\nimport org.junit.runners.model.FrameworkMethod;\nimport org.junit.runners.model.TestClass;\n\nimport static java.util.Collections.emptyList;\n\nimport java.util.List;\n\n/**\n * Validates annotations on classes and methods. To be validated,\n * an annotation should be annotated with {@link ValidateWith}\n *\n * Instances of this class are shared by multiple test runners, so they should\n * be immutable and thread-safe.\n *\n * @since 4.12\n */\npublic abstract class AnnotationValidator {\n\n    private static final List<Exception> NO_VALIDATION_ERRORS = emptyList();\n\n    /**\n     * Validates annotation on the given class.\n     *\n     * @param testClass that is being validated\n     * @return A list of exceptions. Default behavior is to return an empty list.\n     *\n     * @since 4.12\n     */\n    public List<Exception> validateAnnotatedClass(TestClass testClass) {\n        return NO_VALIDATION_ERRORS;\n    }\n\n    /**\n     * Validates annotation on the given field.\n     *\n     * @param field that is being validated\n     * @return A list of exceptions. Default behavior is to return an empty list.\n     *\n     * @since 4.12\n     */\n    public List<Exception> validateAnnotatedField(FrameworkField field) {\n        return NO_VALIDATION_ERRORS;\n\n    }\n\n    /**\n     * Validates annotation on the given method.\n     *\n     * @param method that is being validated\n     * @return A list of exceptions. Default behavior is to return an empty list.\n     *\n     * @since 4.12\n     */\n    public List<Exception> validateAnnotatedMethod(FrameworkMethod method) {\n        return NO_VALIDATION_ERRORS;\n    }\n}\n", "human_rating": 4.000000000006059, "metadata": {"project": "junit4", "class": "org.junit.validator.AnnotationValidator", "source_path": "junit4/sourcefiles/src/main/java/org/junit/validator/AnnotationValidator.java", "label_probabilities": {"readability": [1.0, 2.01984e-12, 0.0, 0.0], "understandability": [1.0, 3.18587e-10, 0.0, 0.0], "complexity": [0.0, 0.0, 0.000110132, 0.99989], "modularization": [0.0, 0.0, 0.0, 1.0], "overall": [1.0, 7e-20, 0.0, 0.0]}, "readability_scale": "expected Likert score; 4=easy to read, 1=hard to read"}}]}