/**
   * Checks every node if it is essential for the network to be connected (i.e., the node is a
   * failure node). In each step, the network is prepared by setting all removed nodes (incl. the
   * one that is currently examined) to be iteration-path blocking and the iteration is then started
   * with a node that is known exist. All nodes that have their essentiality flag switched on are
   * then added to an array that is returned.
   *
   * @param removeArrayIndices An ArrayList of Integers (indices of the {@link nodeIndices} array)
   *     that should be considered as removed from the network, i.e. are not transversible by {@link
   *     iterateNetwork()}. An empty list can also be supplied and means that no nodes are removed.
   * @return An array of node indices that were determined to be failure points.
   */
  public int[] getFailureNodes(ArrayList<Integer> removeArrayIndices) {
    // array to capture whether node at nodeIndices[i] is essential or not
    boolean nodeEssential[] = new boolean[nodeIndices.length];

    // loop through nodes that are not removed with removeNodeIndices
    for (int curArrayIndex = 0; curArrayIndex < nodeIndices.length; curArrayIndex++) {
      if (removeArrayIndices.contains((Integer) curArrayIndex)) {
        continue;
      }
      // set current and all nodes in removeNodeIndices to visited
      boolean nodeReachable[] = new boolean[nodeIndices.length];
      nodeReachable[curArrayIndex] = true;
      for (int arrayIdx : removeArrayIndices) {
        nodeReachable[arrayIdx] = true;
      }
      // start iteration at a non-visited node and check if all were reached
      iterateNetwork(ArrayUtils.indexOf(nodeReachable, false), nodeReachable);
      nodeEssential[curArrayIndex] = ArrayUtils.indexOf(nodeReachable, false) != -1;
    }

    // return array with node indices that are essential (=failure points)
    ArrayList failureNodes = new ArrayList<Integer>();
    for (int curArrayIndex = 0; curArrayIndex < nodeEssential.length; curArrayIndex++) {
      if (nodeEssential[curArrayIndex] == true) {
        failureNodes.add(a2nIdx(curArrayIndex));
      }
    }
    return list2array(failureNodes);
  }
  public static Integer findIdColumn(String[] headings) {
    int idCol = -1;

    idCol = ArrayUtils.indexOf(headings, "local_id");
    if (idCol > -1) {
      return idCol;
    }

    idCol = ArrayUtils.indexOf(headings, "mrb_id");
    if (idCol > -1) {
      return idCol;
    }

    idCol = ArrayUtils.indexOf(headings, "waterid");
    if (idCol > -1) {
      return idCol;
    }

    idCol = ArrayUtils.indexOf(headings, "reach");
    if (idCol > -1) {
      return idCol;
    }

    return -1;
  }
 @SuppressWarnings("unchecked")
 public boolean onPreUpdate(PreUpdateEvent event) {
   Object entity = event.getEntity();
   boolean evict = false;
   if (preUpdateEventListener != null) {
     evict = preUpdateEventListener.call(entity);
     synchronizePersisterState(entity, event.getPersister(), event.getState());
   }
   if (lastUpdatedProperty != null && shouldTimestamp) {
     Object now =
         DefaultGroovyMethods.newInstance(
             lastUpdatedProperty.getType(), new Object[] {System.currentTimeMillis()});
     event
             .getState()[
             ArrayUtils.indexOf(
                 event.getPersister().getPropertyNames(),
                 GrailsDomainClassProperty.LAST_UPDATED)] =
         now;
     lastUpdatedProperty.setProperty(entity, now);
   }
   if (!AbstractSavePersistentMethod.isAutoValidationDisabled(entity)
       && !DefaultTypeTransformation.castToBoolean(
           validateMethod.invoke(entity, new Object[] {validateParams}))) {
     evict = true;
     if (failOnErrorEnabled) {
       Errors errors = (Errors) errorsProperty.getProperty(entity);
       throw new ValidationException(
           "Validation error whilst flushing entity [" + entity.getClass().getName() + "]",
           errors);
     }
   }
   return evict;
 }
 /**
  * this method can be used to modify the state of particular property.
  *
  * @param currentState array of property values
  * @param propertyNames array of property names
  * @param propertyToSet property to be modified
  * @param value newValue to set
  */
 public static void setValue(
     Object[] currentState, String[] propertyNames, String propertyToSet, Object value) {
   int index = ArrayUtils.indexOf(propertyNames, propertyToSet);
   if (index >= 0) {
     currentState[index] = value;
   }
 }
 /**
  * Reads the network structure from Cytoscape and creates an array with node indices as well as
  * the plugin GUI upon clicking on the menu entry. Performs sanity checks on the network data.
  *
  * @param actionEvent The unused click-event on the menu entry.
  */
 @Override
 public void actionPerformed(ActionEvent e) {
   // initialise network and node indices
   net = Cytoscape.getCurrentNetwork();
   netView = Cytoscape.getCurrentNetworkView();
   nodeIndices = net.getNodeIndicesArray();
   // create PluginGUI panel inside frame and display
   JFrame pluginFrame = new JFrame();
   JPanel pluginPanel = new MainPanel(myPlugin, nodeIndices.length, net.getEdgeCount());
   pluginFrame.setTitle("Network Failure Plugin");
   pluginFrame.add(pluginPanel);
   pluginFrame.pack();
   pluginFrame.setResizable(false);
   pluginFrame.setVisible(true);
   // check if netword contains nodes
   if (nodeIndices.length < 3) {
     final String msg = "No network loaded or netword contains under 3 nodes";
     JOptionPane.showMessageDialog(pluginFrame, msg, "Error", JOptionPane.ERROR_MESSAGE);
     pluginFrame.dispose();
     return;
   }
   // check if network is not already split
   boolean nodeReachable[] = new boolean[nodeIndices.length];
   iterateNetwork(0, nodeReachable);
   if (ArrayUtils.indexOf(nodeReachable, false) != -1) {
     final String msg =
         "Need a functional network to analyse, this one is already split.\n"
             + "You may remove isolated subnetworks and re-run the plugin.";
     JOptionPane.showMessageDialog(pluginFrame, msg, "Error", JOptionPane.ERROR_MESSAGE);
     pluginFrame.dispose();
     return;
   }
 }
Esempio n. 6
0
 public static int[] removeZeroFromChord(int[] chord) {
   int[] tempChord = chord;
   while (ArrayUtils.contains(tempChord, ZERO)) {
     int index = ArrayUtils.indexOf(tempChord, ZERO);
     tempChord = ArrayUtils.remove(tempChord, index);
   }
   return tempChord;
 }
Esempio n. 7
0
 @Test
 public void checkSetPeriodIndexGetMean() {
   double mag = 5.0;
   double rJB = 10.0;
   double rake = 0.0;
   double period = 1.0;
   int iper = ArrayUtils.indexOf(ToroEtAl2002Constants.PERIOD, period);
   toro2002SHARE.getParameter(MagParam.NAME).setValue(mag);
   toro2002SHARE.getParameter(DistanceJBParameter.NAME).setValue(rJB);
   toro2002SHARE.getParameter(RakeParam.NAME).setValue(rake);
   toro2002SHARE.getParameter(PeriodParam.NAME).setValue(period);
   toro2002SHARE.setIntensityMeasure(SA_Param.NAME);
   assertTrue(toro2002SHARE.getMean() == toro2002SHARE.getMean(iper, mag, rJB, rake));
 }
Esempio n. 8
0
 /** Check SA at T = 4 s */
 @Test
 public final void sa4s() {
   double mag = 5.0;
   double rJB = 10.0;
   double rake = 0.0;
   double period = 4.0;
   String stdDevType = StdDevTypeParam.STD_DEV_TYPE_TOTAL;
   int iper = ArrayUtils.indexOf(ToroEtAl2002Constants.PERIOD, period);
   toro2002SHARE.getParameter(MagParam.NAME).setValue(mag);
   toro2002SHARE.getParameter(DistanceJBParameter.NAME).setValue(rJB);
   toro2002SHARE.getParameter(RakeParam.NAME).setValue(rake);
   toro2002SHARE.getParameter(PeriodParam.NAME).setValue(period);
   toro2002SHARE.getParameter(StdDevTypeParam.NAME).setValue(stdDevType);
   toro2002SHARE.setIntensityMeasure(SA_Param.NAME);
   assertTrue(toro2002SHARE.getStdDev() == toro2002SHARE.getStdDev(iper, mag, rJB, stdDevType));
 }
 @SuppressWarnings("unchecked")
 private static void accessProperty(
     InputStream input,
     OutputStream output,
     String[] keys,
     PropertyOperation operation,
     boolean autoclose)
     throws IOException {
   List<String> lines = new ArrayList<String>();
   List<String> result = new ArrayList<String>();
   try {
     lines = IOUtils.readLines(input);
   } finally {
     if (autoclose) {
       IOUtils.closeQuietly(input);
     }
   }
   try {
     for (String line : lines) {
       int offset = line.indexOf("=");
       if (line.trim().length() > 0 && offset > -1) {
         String originalKey = line.substring(0, offset).trim();
         String originalValue = line.substring(++offset);
         int index = ArrayUtils.indexOf(keys, originalKey);
         if (index > -1) {
           String outputLine = operation.process(line, originalKey, originalValue);
           if (outputLine != null) {
             result.add(outputLine);
           }
         } else {
           result.add(line);
         }
       } else {
         result.add(line);
       }
     }
     if (output != null) {
       IOUtils.writeLines(result, null, output);
     }
   } finally {
     if (autoclose) {
       IOUtils.closeQuietly(output);
     }
   }
 }
Esempio n. 10
0
  public TblColRef findPKByFK(TblColRef fk, String joinType) {
    assert isFactTable(fk.getTable());

    TblColRef candidate = null;

    for (LookupDesc dim : lookups) {
      JoinDesc join = dim.getJoin();
      if (join == null) continue;

      if (joinType != null && !joinType.equals(join.getType())) continue;

      int find = ArrayUtils.indexOf(join.getForeignKeyColumns(), fk);
      if (find >= 0) {
        candidate = join.getPrimaryKeyColumns()[find];
        if (join.getForeignKeyColumns().length == 1) { // is single
          // column join?
          break;
        }
      }
    }
    return candidate;
  }
  public void changeLocale(final Activity activity) {
    // Get the index of the current locale
    final int currentIndex = ArrayUtils.indexOf(mLocaleCodes, mLocaleCode);

    // Populate and show the language menu
    Builder builder = new Builder(activity);
    builder.setTitle(R.string.menuItem_localeOverride);
    builder.setSingleChoiceItems(
        mLocaleNames,
        currentIndex,
        new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            if (which >= 0 && which != currentIndex) {
              mPreferences.edit().putString(KEY_LOCALE_OVERRIDE, mLocaleCodes[which]).commit();
              ActivityHelper.restartActivity(activity);
            }
          }
        });
    builder.create().show();
  }
Esempio n. 12
0
  @Override
  public DecResult decode(DecContext ctx) {
    byte[] bytes = ctx.getDecBytes();
    Object ret = null;

    int index = ArrayUtils.indexOf(bytes, (byte) 0x00);
    if (-1 == index) {
      String errmsg = "CStyleString: could not found \\0 for string terminated.";
      if (null != ctx.getField()) {
        errmsg += "/ cause field is [" + ctx.getField() + "]";
      }
      logger.error(errmsg);
      throw new RuntimeException(errmsg);
    }

    try {
      byte[] tmp = ArrayUtils.subarray(bytes, 0, index);
      ret = new String(tmp, XIP_STR_CHARSET);
    } catch (UnsupportedEncodingException e) {
      logger.error("CStyleString", e);
    }

    return new DecResult(ret, ArrayUtils.subarray(bytes, index + 1, bytes.length));
  }
Esempio n. 13
0
 /**
  * Converts a node index to a nodeIndices array index.
  *
  * @param arrayIndex A given node index.
  * @return The corresponding array index.
  */
 private int n2aIdx(int nodeIndex) {
   return ArrayUtils.indexOf(nodeIndices, nodeIndex);
 }
Esempio n. 14
0
  /**
   * @brief 数组工具
   * @details 详细说明
   * @warning 注意事项
   * @date 2014-7-11 上午11:25:18
   */
  @Test
  public void array() {
    // 追加元素到数组尾部
    int[] array1 = {1, 2};
    array1 = ArrayUtils.add(array1, 3); // => [1, 2, 3]

    System.out.println(array1.length); // 3
    System.out.println(array1[2]); // 3

    // 删除指定位置的元素
    int[] array2 = {1, 2, 3};
    array2 = ArrayUtils.remove(array2, 2); // => [1, 2]

    System.out.println(array2.length); // 2

    // 截取部分元素
    int[] array3 = {1, 2, 3, 4};
    array3 = ArrayUtils.subarray(array3, 1, 3); // => [2, 3]

    System.out.println(array3.length); // 2

    // 数组拷贝
    String[] array4 = {"aaa", "bbb", "ccc"};
    String[] copied = (String[]) ArrayUtils.clone(array4); // => {"aaa", "bbb", "ccc"}

    System.out.println(copied.length); // 3

    // 判断是否包含某元素
    String[] array5 = {"aaa", "bbb", "ccc", "bbb"};
    boolean result1 = ArrayUtils.contains(array5, "bbb"); // => true
    System.out.println(result1); // true

    // 判断某元素在数组中出现的位置(从前往后,没有返回-1)
    int result2 = ArrayUtils.indexOf(array5, "bbb"); // => 1
    System.out.println(result2); // 1

    // 判断某元素在数组中出现的位置(从后往前,没有返回-1)
    int result3 = ArrayUtils.lastIndexOf(array5, "bbb"); // => 3
    System.out.println(result3); // 3

    // 数组转Map
    Map<Object, Object> map =
        ArrayUtils.toMap(
            new String[][] {
              {"key1", "value1"},
              {"key2", "value2"}
            });
    System.out.println(map.get("key1")); // "value1"
    System.out.println(map.get("key2")); // "value2"

    // 判断数组是否为空
    Object[] array61 = new Object[0];
    Object[] array62 = null;
    Object[] array63 = new Object[] {"aaa"};

    System.out.println(ArrayUtils.isEmpty(array61)); // true
    System.out.println(ArrayUtils.isEmpty(array62)); // true

    // 判断数组长度是否相等
    Object[] array71 = new Object[] {"aa", "bb", "cc"};
    Object[] array72 = new Object[] {"dd", "ee", "ff"};

    System.out.println(ArrayUtils.isSameLength(array71, array72)); // true

    // 判断数组元素内容是否相等
    Object[] array81 = new Object[] {"aa", "bb", "cc"};
    Object[] array82 = new Object[] {"aa", "bb", "cc"};

    System.out.println(ArrayUtils.isEquals(array81, array82));

    // Integer[] 转化为 int[]
    Integer[] array9 = new Integer[] {1, 2};
    int[] result = ArrayUtils.toPrimitive(array9);

    System.out.println(result.length); // 2
    System.out.println(result[0]); // 1

    // int[] 转化为 Integer[]
    int[] array10 = new int[] {1, 2};
    Integer[] result10 = ArrayUtils.toObject(array10);

    System.out.println(result.length); // 2
    System.out.println(result10[0].intValue()); // 1
  }
  /**
   * load the Element's parameters to EMF Model
   *
   * @param elemParam
   * @param paType
   */
  public static void loadElementParameters(
      Element elemParam, ParametersType paType, String repParamName) {
    if (paType == null || elemParam == null) {
      return;
    }
    EList listParamType = paType.getElementParameter();
    ElementParameterType repositoryParam = null;
    if (repParamName != null && !repParamName.equals("")) {
      repositoryParam = findElementParameterType(paType, repParamName);
    } else {
      repositoryParam =
          findElementParameterType(
              paType,
              EParameterName.PROPERTY_TYPE.getName()
                  + ":"
                  + EParameterName.PROPERTY_TYPE.getName());
    }

    IElementParameter statsDBType = null;
    IElementParameter implicitDBType = null;
    IElementParameter statsDBVersion = null;
    IElementParameter implicitDBVersion = null;

    for (int j = 0; j < listParamType.size(); j++) {
      ElementParameterType pType = (ElementParameterType) listParamType.get(j);
      if (pType != null) {
        String pTypeName = pType.getName();
        if (pTypeName != null && !"".equals(pTypeName)) {
          IElementParameter param = elemParam.getElementParameter(pTypeName);
          if (pTypeName.equals("DB_TYPE")) { // $NON-NLS-1$
            statsDBType = param;
          } else if (pTypeName.equals("DB_VERSION")) { // $NON-NLS-1$
            statsDBVersion = param;
          } else if (pTypeName.equals("DB_TYPE_IMPLICIT_CONTEXT")) { // $NON-NLS-1$
            implicitDBType = param;
          } else if (pTypeName.equals("DB_VERSION_IMPLICIT_CONTEXT")) { // $NON-NLS-1$
            implicitDBVersion = param;
          }
          if (param != null) {
            String name = param.getName();
            param.setContextMode(pType.isContextMode());
            if (param.isReadOnly()
                && !(EParameterName.UNIQUE_NAME.getName().equals(name)
                    || EParameterName.VERSION.getName().equals(name))) {
              continue; // if the parameter is read only, don't load
              // it (this will prevent to overwrite the
              // value)
            }
            String value = null;
            if ("STATANDLOG_USE_PROJECT_SETTINGS".equals(name) // $NON-NLS-1$
                || "IMPLICITCONTEXT_USE_PROJECT_SETTINGS".equals(name)) { // $NON-NLS-1$
              Object value2 = param.getValue();
              if (value2 != null) {
                value = value2.toString();
              }
            } else {
              value = pType.getValue();
            }
            if (param.getFieldType().equals(EParameterFieldType.CHECK)
                || param.getFieldType().equals(EParameterFieldType.RADIO)) {
              if (Boolean.FALSE.toString().equalsIgnoreCase(value)
                  || Boolean.TRUE.toString().equalsIgnoreCase(value)
                  || !pType.isContextMode()) {
                Boolean boolean1 = new Boolean(value);
                elemParam.setPropertyValue(pTypeName, boolean1);
              } else {
                elemParam.setPropertyValue(pTypeName, value);
              }
              // if (EParameterName.ACTIVATE.getName().equals(param.getName())) {
              // if ((elemParam instanceof Node) && !boolean1) {
              // ((Node) elemParam).setDummy(!boolean1);
              // }
              // }
            } else if (param.getFieldType().equals(EParameterFieldType.CLOSED_LIST)) {
              boolean valueSet = false;
              if (!ArrayUtils.contains(param.getListItemsValue(), value)) {
                if (ArrayUtils.contains(param.getListItemsDisplayName(), value)) {
                  valueSet = true;
                  int index = ArrayUtils.indexOf(param.getListItemsDisplayName(), value);
                  if (index > -1) {
                    elemParam.setPropertyValue(pTypeName, param.getListItemsValue()[index]);
                  }
                } else if (value.equals("")
                    && name != null
                    && (name.equals("LOAD_NEW_VARIABLE") || name.equals("NOT_LOAD_OLD_VARIABLE"))) {
                  valueSet = true;
                  elemParam.setPropertyValue(pTypeName, param.getListItemsValue()[1]);
                }
              }
              if (!valueSet) {
                elemParam.setPropertyValue(pTypeName, value);
              }
            } else if (param.getFieldType().equals(EParameterFieldType.TABLE)) {
              List<Map<String, Object>> tableValues = new ArrayList<Map<String, Object>>();
              String[] codeList = param.getListItemsDisplayCodeName();
              Map<String, Object> lineValues = null;
              for (ElementValueType elementValue :
                  (List<ElementValueType>) pType.getElementValue()) {
                boolean found = false;
                int length = codeList.length;
                if (length > 0) {
                  for (int i = 0; i < length && !found; i++) {
                    if (codeList[i].equals(elementValue.getElementRef())) {
                      found = true;
                    }
                  }
                }
                IElementParameter tmpParam = null;
                for (Object o : param.getListItemsValue()) {
                  if (o instanceof IElementParameter) {
                    IElementParameter tableParam = (IElementParameter) o;
                    if (tableParam.getName().equals(elementValue.getElementRef())) {
                      tmpParam = tableParam;
                      break;
                    }
                  }
                }
                if (found) {
                  if ((lineValues == null)
                      || (lineValues.get(elementValue.getElementRef()) != null)) {
                    lineValues = new HashMap<String, Object>();
                    tableValues.add(lineValues);
                  }
                  String elemValue = elementValue.getValue();
                  if (tmpParam != null
                      && EParameterFieldType.PASSWORD.equals(tmpParam.getFieldType())) {
                    elemValue = elementValue.getRawValue();
                  }
                  lineValues.put(elementValue.getElementRef(), elemValue);
                  if (elementValue.getType() != null) {
                    lineValues.put(
                        elementValue.getElementRef() + IEbcdicConstant.REF_TYPE,
                        elementValue.getType());
                  }
                }
              }
              elemParam.setPropertyValue(pTypeName, tableValues);
            } else if (param.getFieldType().equals(EParameterFieldType.PASSWORD)) {
              param.setValue(pType.getRawValue());
            } else if (param.getFieldType().equals(EParameterFieldType.ENCODING_TYPE)) {
              // fix for bug 2193
              boolean setToCustom = false;
              if (EmfComponent.REPOSITORY.equals(
                      elemParam.getPropertyValue(EParameterName.PROPERTY_TYPE.getName()))
                  && param.getRepositoryValue() != null
                  && param.getRepositoryValue().equals("ENCODING")) { // $NON-NLS-1$
                setToCustom = true;
              }
              String tempValue = null;
              IElementParameter iElementParameter = null;
              Map<String, IElementParameter> childParameters = param.getChildParameters();
              if (childParameters != null) {
                iElementParameter = childParameters.get(EParameterName.ENCODING_TYPE.getName());
                if (iElementParameter != null) {
                  tempValue = (String) iElementParameter.getValue();
                }
              }
              if (tempValue != null && !tempValue.equals(EmfComponent.ENCODING_TYPE_CUSTOM)) {
                tempValue = tempValue.replaceAll("'", ""); // $NON-NLS-1$ //$NON-NLS-2$
                tempValue = tempValue.replaceAll("\"", ""); // $NON-NLS-1$ //$NON-NLS-2$
                tempValue = TalendTextUtils.addQuotes(tempValue);
                if (!tempValue.equals(value)) {
                  setToCustom = true;
                }
              }

              if (iElementParameter != null && setToCustom) {
                iElementParameter.setValue(EmfComponent.ENCODING_TYPE_CUSTOM);
              }
              elemParam.setPropertyValue(pTypeName, value);
              // end of fix for bug 2193
            } else if (!param.getFieldType().equals(EParameterFieldType.SCHEMA_TYPE)) {
              if (param.getRepositoryValue() != null
                  && !param.getFieldType().equals(EParameterFieldType.PROPERTY_TYPE)) {
                if (repositoryParam != null
                    && EmfComponent.REPOSITORY.equals(repositoryParam.getValue())) {
                  param.setRepositoryValueUsed(true);
                } else {
                  param.setRepositoryValueUsed(false);
                }
              }
              elemParam.setPropertyValue(pTypeName, value);
            }
          } else if (UpdateTheJobsActionsOnTable.isClear
              && "CLEAR_TABLE".equals(pTypeName) // $NON-NLS-1$
              && "true".equals(pType.getValue()) // $NON-NLS-1$
              && "NONE"
                  .equals(
                      elemParam
                          .getElementParameter(Process.TABLE_ACTION)
                          .getValue())) { //$NON-NLS-1$
            elemParam.setPropertyValue(Process.TABLE_ACTION, "CLEAR"); // $NON-NLS-1$
            UpdateTheJobsActionsOnTable.isClear = false;
          }
        }
      }
    }

    // update combo list for dbversion
    if (statsDBType != null && statsDBVersion != null) {
      JobSettingVersionUtil.setDbVersion(
          statsDBVersion,
          String.valueOf(statsDBType.getValue()),
          String.valueOf(statsDBVersion.getValue()));
    }
    if (implicitDBType != null && implicitDBVersion != null) {
      JobSettingVersionUtil.setDbVersion(
          implicitDBVersion,
          String.valueOf(implicitDBType.getValue()),
          String.valueOf(implicitDBVersion.getValue()));
    }
  }