Java Code Examples for java.util.Vector.isEmpty()

The following are Jave code examples for showing how to use isEmpty() of the java.util.Vector class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: unitimes   File: ExamsForm.java   View Source Code Vote up 7 votes
public void load(HttpSession session) {
    setSubjectArea(session.getAttribute("Exams.subjectArea")==null?null:(String)session.getAttribute("Exams.subjectArea"));
    iSessions = new Vector();
       setSession(session.getAttribute("Exams.session")==null?iSessions.isEmpty()?null:Long.valueOf(((ComboBoxLookup)iSessions.lastElement()).getValue()):(Long)session.getAttribute("Exams.session"));
       boolean hasSession = false;
    for (Iterator i=Session.getAllSessions().iterator();i.hasNext();) {
        Session s = (Session)i.next();
        if (s.getStatusType()!=null && (s.canNoRoleReportExamFinal() || s.canNoRoleReportExamMidterm()) && Exam.hasTimetable(s.getUniqueId())) {
            if (s.getUniqueId().equals(getSession())) hasSession = true;
            iSessions.add(new ComboBoxLookup(s.getLabel(),s.getUniqueId().toString()));
        }
    }
    if (!hasSession) { setSession(null); setSubjectArea(null); }
    if (getSession()==null && !iSessions.isEmpty()) setSession(Long.valueOf(((ComboBoxLookup)iSessions.lastElement()).getValue()));
    iSubjectAreas = new TreeSet(new SubjectAreaDAO().getSession().createQuery("select distinct sa.subjectAreaAbbreviation from SubjectArea sa").setCacheable(true).list());
    setExamType(session.getAttribute("Exams.examType")==null?iExamType:(Long)session.getAttribute("Exams.examType"));
    setCanRetrieveAllExamForAllSubjects(canDisplayAllSubjectsAtOnce());
}
 
Example 2
Project: GitHub   File: DecodeThread.java   View Source Code Vote up 7 votes
DecodeThread(CaptureActivity activity,
             Vector<BarcodeFormat> decodeFormats,
             String characterSet,
             ResultPointCallback resultPointCallback) {

  this.activity = activity;
  handlerInitLatch = new CountDownLatch(1);

  hints = new Hashtable<DecodeHintType, Object>(3);

  if (decodeFormats == null || decodeFormats.isEmpty()) {
  	 decodeFormats = new Vector<BarcodeFormat>();
  	 decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
  	 decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
  	 decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
  }
  
  hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);

  if (characterSet != null) {
    hints.put(DecodeHintType.CHARACTER_SET, characterSet);
  }

  hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback);
}
 
Example 3
Project: SER316-Munich   File: History.java   View Source Code Vote up 7 votes
public static void removeProjectHistory(Project prj) {
    Vector list = new Vector();
    String id;
    
    for (int i = 0; i < _list.size(); i++) {
        id = (((HistoryItem) _list.elementAt(i)).getProject()).getID();
        if (id.equals(prj.getID())) {
            list.add(_list.elementAt(i));
            p--;
            if (_list.elementAt(i).equals(prev)) {
                if (p > 0) prev = _list.get(p - 1);
                else prev = null;
            }
        }
    }
    if (!list.isEmpty()) {
        _list.removeAll(list);
        if (p < 0) {
            p = 0;
        }
        _list.setSize(p);
        next = null;
        historyBackAction.update();
        historyForwardAction.update();
    }
}
 
Example 4
Project: logistimo-web-service   File: OrderOutput.java   View Source Code Vote up 7 votes
public void fromMessageString(Vector messages) throws ProtocolException {
  if (messages == null || messages.isEmpty()) {
    throw new ProtocolException("No message specified");
  }
  // Assemble message
  String msg = MessageUtil.assemble(messages);
  if (msg == null || msg.length() == 0) {
    throw new ProtocolException("Message not assembled");
  }
  // Tokenize
  StringTokenizer st = new StringTokenizer(msg, " ");
  if (st.countTokens() < 3) {
    throw new ProtocolException("At least 3 tokens are expected");
  }
  version = st.nextToken();
  statusCode = st.nextToken();
  status = JsonTagsZ.STATUS_TRUE.equals(statusCode);
  if (!status) {
    errMsg = MessageUtil.decode(st.nextToken());
  } else {
    orderData = MessageUtil.getOrderObject(st, version);
  }
}
 
Example 5
Project: gate-core   File: AnnotationImpl.java   View Source Code Vote up 7 votes
/**
 *
 * Adds an annotation listener
 */
@Override
public synchronized void addAnnotationListener(AnnotationListener l) {
  @SuppressWarnings("unchecked")
  Vector<AnnotationListener> v = annotationListeners == null ? new Vector<AnnotationListener>(2) : (Vector<AnnotationListener>) annotationListeners.clone();

  //now check and if this is the first listener added,
  //start listening to all features, so their changes can
  //also be propagated
  if (v.isEmpty()) {
    FeatureMap features = getFeatures();
    if (eventHandler == null)
      eventHandler = new EventsHandler();
    features.addFeatureMapListener(eventHandler);
  }

  if (!v.contains(l)) {
    v.addElement(l);
    annotationListeners = v;
  }
}
 
Example 6
Project: APIJSON-Android-RxJava   File: DecodeThread.java   View Source Code Vote up 7 votes
DecodeThread(CaptureActivity activity,
             Vector<BarcodeFormat> decodeFormats,
             String characterSet,
             ResultPointCallback resultPointCallback) {

  this.activity = activity;
  handlerInitLatch = new CountDownLatch(1);

  hints = new Hashtable<DecodeHintType, Object>(3);

  if (decodeFormats == null || decodeFormats.isEmpty()) {
  	 decodeFormats = new Vector<BarcodeFormat>();
  	 decodeFormats.addAll(DecodeFormatManager.ONE_D_FORMATS);
  	 decodeFormats.addAll(DecodeFormatManager.QR_CODE_FORMATS);
  	 decodeFormats.addAll(DecodeFormatManager.DATA_MATRIX_FORMATS);
  }
  
  hints.put(DecodeHintType.POSSIBLE_FORMATS, decodeFormats);

  if (characterSet != null) {
    hints.put(DecodeHintType.CHARACTER_SET, characterSet);
  }

  hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback);
}
 
Example 7
Project: HtmlNative   File: BasicBlock.java   View Source Code Vote up 7 votes
public static BasicBlock[] findLiveBlocks(BasicBlock[] blocks) {
	// add reachable blocks
	Vector next = new Vector ();
	next.addElement( blocks[0] );
	while ( ! next.isEmpty() ) {
		BasicBlock b = (BasicBlock) next.elementAt(0);
		next.removeElementAt(0);
		if ( ! b.islive ) {
			b.islive = true;
			for ( int i=0, n=b.next!=null? b.next.length: 0; i<n; i++ )
				if ( ! b.next[i].islive )
					next.addElement( b.next[i] );
		}
	}
	
	// create list in natural order
	Vector list = new Vector();
	for ( int i=0; i<blocks.length; i=blocks[i].pc1+1 )
		if ( blocks[i].islive )
			list.addElement(blocks[i]);
	
	// convert to array
	BasicBlock[] array = new BasicBlock[list.size()];
	list.copyInto(array);
	return array;
}
 
Example 8
Project: openjdk-jdk10   File: Timer.java   View Source Code Vote up 6 votes
/**
 * Removes all the timer notifications corresponding to the specified type from the list of notifications.
 *
 * @param type The timer notification type.
 *
 * @exception InstanceNotFoundException The specified type does not correspond to any timer notification
 * in the list of notifications of this timer MBean.
 */
public synchronized void removeNotifications(String type) throws InstanceNotFoundException {

    Vector<Integer> v = getNotificationIDs(type);

    if (v.isEmpty())
        throw new InstanceNotFoundException("Timer notifications to remove not in the list of notifications");

    for (Integer i : v)
        removeNotification(i);
}
 
Example 9
Project: jmt   File: ParametricAnalysisChecker.java   View Source Code Vote up 6 votes
/**
 * Gets an array of String containing the description of available parametric simulations
 * @return the array
 */
public String[] getRunnableParametricAnalysis() {
	String[] runnable;
	Vector<String> runnableVector = new Vector<String>(0, 1);
	//check if "Number of customer" parametric analysis is runnable
	Vector<Object> temp = cd.getClosedClassKeys();
	if (!temp.isEmpty()) {
		runnableVector.add(ParametricAnalysis.PA_TYPE_NUMBER_OF_CUSTOMERS);
	}
	//check if "Population mix" parametric analysis is runnable
	if (temp.size() == 2) {
		runnableVector.add(ParametricAnalysis.PA_TYPE_POPULATION_MIX);
	}
	//check if "Service time" parametric analysis is runnable
	temp = checkForServiceTimesParametricAnalysisAvailableStations();
	if (!temp.isEmpty()) {
		runnableVector.add(ParametricAnalysis.PA_TYPE_SERVICE_TIMES);
	}
	//check if "Arrival rate" parametric analysis is runnable
	temp = checkForArrivalRatesParametricSimulationAvailableClasses();
	if (!temp.isEmpty()) {
		runnableVector.add(ParametricAnalysis.PA_TYPE_ARRIVAL_RATE);
	}
	//check if "Seed" parametric analysis is available
	if (!cd.getClassKeys().isEmpty() && !sd.getStationKeys().isEmpty()) {
		runnableVector.add(ParametricAnalysis.PA_TYPE_SEED);
	}
	//initialize runnable array
	runnable = new String[runnableVector.size()];
	for (int i = 0; i < runnable.length; i++) {
		runnable[i] = runnableVector.get(i);
	}
	return runnable;
}
 
Example 10
Project: logistimo-web-service   File: GetOrdersOutput.java   View Source Code Vote up 6 votes
public void fromMessageString(Vector messages) throws ProtocolException {
  if (messages == null || messages.isEmpty()) {
    throw new ProtocolException("No message specified");
  }
  // Assemble
  String msg = MessageUtil.assemble(messages);
  if (msg == null || msg.length() == 0) {
    throw new ProtocolException("Message not assembled");
  }
  // Tokenize
  StringTokenizer st = new StringTokenizer(msg, " ");
  if (st.countTokens() < 3) {
    throw new ProtocolException("At least 3 tokens expected in message");
  }
  version = st.nextToken();
  statusCode = st.nextToken();
  status = JsonTagsZ.STATUS_TRUE.equals(statusCode);
  if (!status) {
    errMsg = MessageUtil.decode(st.nextToken());
  } else {
    hasOrders = MODE_ORDER.equals(st.nextToken()); // mode
    if (hasOrders) {
      int numOrders = Integer.parseInt(st.nextToken()); // number of orders
      orders = new Vector();
      for (int i = 0; i < numOrders; i++) {
        orders.addElement(MessageUtil.getOrderObject(st, version));
      }
    } else {
      currency = st.nextToken();
      if (MessageUtil.DUMMY.equals(currency)) {
        currency = null;
      }
      materials = MessageUtil.getMaterialsVector(st, null);
    }
  }
}
 
Example 11
Project: logistimo-web-service   File: GetInventoryInput.java   View Source Code Vote up 6 votes
public void fromMessageString(Vector messages) throws ProtocolException {
  if (messages == null || messages.isEmpty()) {
    throw new ProtocolException("Message not specified");
  }
  String message = MessageUtil.assemble(messages);
  if (message == null || message.length() == 0) {
    throw new ProtocolException("Message not assembled");
  }
  StringTokenizer st = new StringTokenizer(message, " ");
  if (st.countTokens() < 4) {
    throw new ProtocolException("At least 4 tokens have to be present in message");
  }
  version = st.nextToken();
  String cmdM = st.nextToken();
  if (!RestConstantsZ.ACTION_GETINVENTORY.equals(cmdM)) {
    throw new ProtocolException(
        "Invalid command: " + cmdM + ". Excepted " + RestConstantsZ.ACTION_GETINVENTORY);
  }
  userId = st.nextToken();
  password = st.nextToken();
  onlyStock = "1".equals(st.nextToken());
  if (MessageHeader.VERSION03.equals(version)) {
    kid = st.nextToken();
    if (MessageUtil.DUMMY.equals(kid)) {
      kid = null;
    }
  }
  String value = null;
  if (st.hasMoreTokens()) {
    value = st.nextToken(); // check for missing response messages that did not arrive at client
  }
  if (value != null && !MessageUtil.DUMMY.equals(value)) {
    setResponseMessageNumbers(value);
  }
}
 
Example 12
Project: tap17-muggl-javaee   File: ConstraintStackElement.java   View Source Code Vote up 6 votes
/**
 * Creates a new ConstraintStackElement instance out of the passed ComposedConstraint.
 * All disjunctions (of type ConjunctiveConstrainSystem) are recursively retrieved
 * out of the {@code constraint}'s DNF.
 * </br>
 * </br>
 * Is only called by the ConstraintStack. Hence the constructor is protected.
 * 
 * @param expression the ConstraintExpression used to create the ComposedConstraint
 * @param constraint the constraint that should be added to the constraint
 * stack.
 * @param pred the lastly added ConstraintStackElement. The new
 * ConstraintStackElement instance will directly be linked behind this
 * element.
 * @see ConjunctiveConstraintSystem
 */
protected ConstraintStackElement(ConstraintExpression expression, 
 			     ComposedConstraint constraint, 
 			     ConstraintStackElement pred){

	this.pred = pred;
	this.solutionCache = new SolutionCache(this);

	// the expression is held without changing it
	this.expression = expression;

	// get systems out of composed constraint and collect them in a Vector
	Vector<ConstraintSystem> systems = new Vector<ConstraintSystem>();
	for (int i = 0; i < constraint.getSystemCount(); i++) {
		ConstraintSystem sys = constraint.getSystem(i);
		if (!sys.isContradictory())
			systems.add(sys);
	}

	// create ConstraintSystem[] nodeSystems
	if ( systems.isEmpty() ){
		this.nodeSystems = new ConstraintSystem[1];
		this.nodeSystems[0] = ConstraintSystem.FALSESYSTEM;
	} else {
		this.nodeSystems = new ConstraintSystem[systems.size()];
		for (int i = 0; i < systems.size(); i++)
			nodeSystems[i] = systems.get(i);
	}

	// update systemCount and some indexes
	if (pred == null){
		this.systemCount = nodeSystems.length;
	} else{
		int syscount = nodeSystems.length;
		this.systemCount = pred.systemCount * syscount;
		this.firstPotentiallySolvableSystemIndex = pred.firstPotentiallySolvableSystemIndex * syscount;
		this.firstNoncontradictorySystemIndex = pred.firstNoncontradictorySystemIndex * syscount;
	}
}
 
Example 13
Project: unitimes   File: BackTracker.java   View Source Code Vote up 6 votes
public static boolean doBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
	synchronized (request.getSession()) {
		String uri = request.getParameter("uri");
		Vector back = getBackList(request.getSession());
		if (back.isEmpty()) {
			if (uri != null) {
				response.sendRedirect(response.encodeURL(uri));
				return true;
			}
			return false;
		}
		if (uri==null) {
			uri = ((String[])back.lastElement())[0];
			back.remove(back.size()-1);
		} else {
			String uriNoBack = uri;
			if (uriNoBack.indexOf("backType=")>=0)
				uriNoBack = uriNoBack.substring(0, uriNoBack.indexOf("backType=")-1);
			while (!back.isEmpty() && !uriNoBack.equals(((String[])back.lastElement())[0]))
				back.remove(back.size()-1);
			if (!back.isEmpty())
				back.remove(back.size()-1);
		}
		if (uri.indexOf("backType=")<0 && request.getAttribute("backType")!=null && request.getAttribute("backId")!=null) {
			if (uri.indexOf('?')>0)
				uri += "&backType="+request.getAttribute("backType")+"&backId="+request.getAttribute("backId")+"#back";
			else
				uri += "?backType="+request.getAttribute("backType")+"&backId="+request.getAttribute("backId")+"#back";
			
		}
		response.sendRedirect(response.encodeURL(uri));
		return true;
	}
}
 
Example 14
Project: BiglyBT   File: TorrentStart.java   View Source Code Vote up 6 votes
@Override
public void execute(String commandName, ConsoleInput console, List<String> args) {
	startNow = false;
	Vector newargs = new Vector(args);
	if (!newargs.isEmpty() && newargs.contains("now") ) {
		newargs.removeElement("now");
		startNow = true;
	}
	super.execute(commandName, console, args);
}
 
Example 15
Project: QN-ACTR-Release   File: ModelChecker.java   View Source Code Vote up 6 votes
private void checkForBCMPDelayWarning() {
	Vector<Object> delays = station_def.getStationKeysDelay();
	Vector<Object> classes = class_def.getClassKeys();
	if (!delays.isEmpty()) {
		for (int i = 0; i < delays.size(); i++) {
			Object thisDelay = delays.get(i);
			for (int j = 0; j < classes.size(); j++) {
				Object thisClass = classes.get(j);
				Object service = station_def.getServiceTimeDistribution(thisDelay, thisClass);
				if (service instanceof Distribution) {
					Distribution d = (Distribution) service;
					if (d.getName().equals(CommonConstants.DISTRIBUTION_PARETO)) {
						warnings[BCMP_DELAY_WARNING] = true;
						BCMPdelaysWithNonRationalServiceDistribution.add(thisDelay);
						break;
					}
				} else if (service instanceof LDStrategy) {
					LDStrategy ld = (LDStrategy) service;
					Object[] ranges = ld.getAllRanges();
					for (Object range : ranges) {
						if (ld.getRangeDistribution(range).getName().equals(CommonConstants.DISTRIBUTION_PARETO)) {
							warnings[BCMP_DELAY_WARNING] = true;
							BCMPdelaysWithNonRationalServiceDistribution.add(thisDelay);
							break;
						}
					}
				}
			}
		}
	}
}
 
Example 16
Project: logistimo-web-service   File: MessageUtil.java   View Source Code Vote up 5 votes
public static String getMissingMessageNos(Vector messages, String outstandingMsgId)
    throws ProtocolException {
  if (messages == null || messages.isEmpty()) {
    if (outstandingMsgId == null || outstandingMsgId.length() == 0) {
      return null;
    } else {
      return outstandingMsgId;
    }
  }
  MessageHeader hd = new MessageHeader((String) messages.elementAt(0));
  String msgId = hd.getMessageId();
  int numMsgs = hd.getNumberOfMessages();
  if (numMsgs == messages.size()) {
    return ""; // no messages missing
  }
  int[] msgNos = new int[numMsgs];
  // Fill the array with 0s
  for (int i = 0; i < msgNos.length; i++) {
    msgNos[i] = 0;
  }
  // For all msg. nos. that are present, fill in 1s
  for (int i = 0; i < messages.size(); i++) {
    hd = new MessageHeader((String) messages.elementAt(i));
    if (msgId.equals(hd.getMessageId())) {
      msgNos[hd.getMessageNo() - 1] =
          1; // note: the index of message nos. starts from 1; so it is necessary to minus 1 here
    }
  }
  // Now, the array indicies with 0s are the missing message nos.
  String missingMsgNos = "";
  for (int i = 0; i < numMsgs; i++) {
    if (msgNos[i] == 0) {
      if (missingMsgNos.length() > 0) {
        missingMsgNos += ",";
      }
      missingMsgNos +=
          String.valueOf(i
              + 1); // note: the index of messages starts from 1, whereas array index starts from 0; so add 1 to index here
    }
  }
  return msgId + ";" + missingMsgNos;
}
 
Example 17
Project: logistimo-web-service   File: JsonUtil.java   View Source Code Vote up 5 votes
public static void addRelatedKioskData(JSONObject json, Vector relatedKiosks, String type)
    throws JSONException {
  if (relatedKiosks != null) {
    JSONArray relatedKiosksJson = new JSONArray();
    // If relatedKiosks is null or empty, send an empty JSONArray in the response.
    if (!relatedKiosks.isEmpty()) {
      Enumeration en = relatedKiosks.elements();
      while (en.hasMoreElements()) {
        Hashtable v = (Hashtable) en.nextElement();
        JSONObject relatedKioskJson = new JSONObject();
        relatedKioskJson.put(JsonTagsZ.KIOSK_ID, (String) v.get(JsonTagsZ.KIOSK_ID));
        relatedKioskJson.put(JsonTagsZ.NAME, (String) v.get(JsonTagsZ.NAME));
        relatedKioskJson.put(JsonTagsZ.CITY, (String) v.get(JsonTagsZ.CITY));
        String value = null;
        if ((value = (String) v.get(JsonTagsZ.STATE)) != null && value.length() > 0) {
          relatedKioskJson.put(JsonTagsZ.STATE, value);
        }
        if ((value = (String) v.get(JsonTagsZ.DISTRICT)) != null && value.length() > 0) {
          relatedKioskJson.put(JsonTagsZ.DISTRICT, value);
        }
        if ((value = (String) v.get(JsonTagsZ.TALUK)) != null && value.length() > 0) {
          relatedKioskJson.put(JsonTagsZ.TALUK, value);
        }
        if ((value = (String) v.get(JsonTagsZ.STREET_ADDRESS)) != null && value.length() > 0) {
          relatedKioskJson.put(JsonTagsZ.STREET_ADDRESS, value);
        }
        if ((value = (String) v.get(JsonTagsZ.PINCODE)) != null && value.length() > 0) {
          relatedKioskJson.put(JsonTagsZ.PINCODE, value);
        }
        if ((value = (String) v.get(JsonTagsZ.PAYABLE)) != null && value.length() > 0) {
          relatedKioskJson.put(JsonTagsZ.PAYABLE, value);
        }
        if ((value = (String) v.get(JsonTagsZ.CREDIT_LIMIT)) != null && value.length() > 0) {
          relatedKioskJson.put(JsonTagsZ.CREDIT_LIMIT, value);
        }
        if ((value = (String) v.get(JsonTagsZ.ROUTE_INDEX)) != null) {
          relatedKioskJson.put(JsonTagsZ.ROUTE_INDEX, value);
        }
        if ((value = (String) v.get(JsonTagsZ.ROUTE_TAG)) != null) {
          relatedKioskJson.put(JsonTagsZ.ROUTE_TAG, value);
        }
        if ((value = (String) v.get(JsonTagsZ.LATITUDE)) != null) {
          relatedKioskJson.put(JsonTagsZ.LATITUDE, value);
        }
        if ((value = (String) v.get(JsonTagsZ.LONGITUDE)) != null) {
          relatedKioskJson.put(JsonTagsZ.LONGITUDE, value);
        }
        if ((value = (String) v.get(JsonTagsZ.GEO_ACCURACY)) != null) {
          relatedKioskJson.put(JsonTagsZ.GEO_ACCURACY, value);
        }
        if ((value = (String) v.get(JsonTagsZ.GEO_ERROR_CODE)) != null) {
          relatedKioskJson.put(JsonTagsZ.GEO_ERROR_CODE, value);
        }
        if ((value = (String) v.get(JsonTagsZ.CUSTOM_KIOSKID)) != null) {
          relatedKioskJson.put(JsonTagsZ.CUSTOM_KIOSKID, value);
        }
        if ((value = (String) v.get(JsonTagsZ.DISABLE_BATCH_MGMT)) != null) {
          relatedKioskJson.put(JsonTagsZ.DISABLE_BATCH_MGMT, value);
        }
        // Add users, if any
        Vector users = (Vector) v.get(JsonTagsZ.USERS);
        if (users != null && !users.isEmpty()) {
          addKioskUsers(relatedKioskJson, users);
        }

        // Add to array
        relatedKiosksJson.put(relatedKioskJson);
      }
    }
    // Update kiosk object
    json.put(type, relatedKiosksJson);
  }
}
 
Example 18
Project: Yass   File: YassTimeStats.java   View Source Code Vote up 5 votes
/**
 * Description of the Method
 *
 * @param t Description of the Parameter
 * @return Description of the Return Value
 */
public float lengthPerSecond(YassTable t) {
    float bpm = (float) t.getBPM();
    if (bpm <= 0) {
        return 0;
    }

    Vector<Integer> lengths = new Vector<>();

    int i = 0;
    int n = t.getRowCount() - 1;
    while (i <= n) {
        YassRow r = t.getRowAt(i);
        if (r.isFreeStyle()) {
            i++;
            continue;
        }
        if (r.isNote()) {
            int length = r.getLengthInt();
            lengths.addElement(new Integer(length));
        }
        i++;
    }

    if (lengths.isEmpty()) {
        return 0;
    }

    int beatCount1 = 0;
    int beatCount2 = 0;
    int beatCount3 = 0;
    int dlen = lengths.size();
    int dlen2 = dlen / 2;
    for (int d = 0; d < dlen2; d++) {
        beatCount1 += lengths.elementAt(d).intValue();
        beatCount2 += lengths.elementAt(d + dlen / 4).intValue();
        beatCount3 += lengths.elementAt(Math.min(d + dlen2, dlen)).intValue();
    }

    float beat_to_sec = (4 * bpm) / 60f;
    float firsthalf = (dlen2 / (float) beatCount1) * beat_to_sec;
    float middle = (dlen2 / (float) beatCount2) * beat_to_sec;
    float secondhalf = (dlen2 / (float) beatCount3) * beat_to_sec;

    return Math.max(firsthalf, Math.max(middle, secondhalf));
}
 
Example 19
Project: jmt   File: ArrivalRateParametricAnalysis.java   View Source Code Vote up 5 votes
/**
 * Checks if the PA model is still coherent with simulation model definition. If
 * the <code>autocorrect</code> variable is set to true, if the PA model is no more
 * valid but it can be corrected it will be changed.
 *
 * @param autocorrect if true the PA model will be autocorrected
 *
 * @return 0 - If the PA model is still valid <br>
 *         1 - If the PA model is no more valid, but it will be corrected <br>
 *         2 - If the PA model can be no more used
 */
@Override
public int checkCorrectness(boolean autocorrect) {
	int code = 0;
	ParametricAnalysisChecker checker = new ParametricAnalysisChecker(classDef, stationDef, simDef);
	Vector<Object> openClasses = classDef.getOpenClassKeys();
	Vector<Object> availableClasses = checker.checkForArrivalRatesParametricSimulationAvailableClasses();
	if (availableClasses.isEmpty()) {
		code = 2;
	} else {
		//if is single class...
		if (isSingleClass()) {
			// ... and the selected closed class is no more available
			if (!availableClasses.contains(classKey)) {
				code = 1;
				if (autocorrect) {
					classKey = openClasses.get(0); //change the reference class
					setDefaultInitialValue();
					setDefaultFinalValue();
				}
			} else {
				double refRate = 1 / ((Distribution) classDef.getClassDistribution(classKey)).getMean();
				//If the arrival rate of reference class was changed...
				if (initialValue != refRate) {
					code = 1;
					if (autocorrect) {
						initialValue = refRate;
						finalValue = refRate * INCREMENT_SINGLE;
					}
				}
			}
		} else {
			if (openClasses.size() == 1 || availableClasses.size() < openClasses.size()) {
				code = 1;
				if (autocorrect) {
					classKey = availableClasses.get(0);
					singleClass = true;
					setDefaultInitialValue();
					setDefaultFinalValue();
				}
			}
		}
	}
	return code;
}
 
Example 20
Project: logistimo-web-service   File: JsonUtil.java   View Source Code Vote up 5 votes
public static void addBatchErrorData(JSONObject errorJSON, Vector batches) throws JSONException {
  if (batches == null || batches.isEmpty()) {
    return;
  }
  JSONArray batchesJson = new JSONArray();
  Enumeration en = batches.elements();
  while (en.hasMoreElements()) {
    Hashtable batch = (Hashtable) en.nextElement();
    JSONObject batchJson = new JSONObject();
    String value = null;
    if ((value = (String) batch.get(JsonTagsZ.BATCH_ID)) != null && !value.equals("")) {
      batchJson.put(JsonTagsZ.BATCH_ID, batch.get(JsonTagsZ.BATCH_ID));
    }
    if ((value = (String) batch.get(JsonTagsZ.QUANTITY)) != null && !value.equals("")) {
      batchJson.put(JsonTagsZ.QUANTITY, batch.get(JsonTagsZ.QUANTITY));
    }
    if ((value = (String) batch.get(JsonTagsZ.BATCH_EXPIRY)) != null && !value.equals("")) {
      batchJson.put(JsonTagsZ.BATCH_EXPIRY, batch.get(JsonTagsZ.BATCH_EXPIRY));
    }
    if ((value = (String) batch.get(JsonTagsZ.BATCH_MANUFACTUER_NAME)) != null && !value
        .equals("")) {
      batchJson
          .put(JsonTagsZ.BATCH_MANUFACTUER_NAME, batch.get(JsonTagsZ.BATCH_MANUFACTUER_NAME));
    }
    if ((value = (String) batch.get(JsonTagsZ.BATCH_MANUFACTURED_DATE)) != null && !value
        .equals("")) {
      batchJson
          .put(JsonTagsZ.BATCH_MANUFACTURED_DATE, batch.get(JsonTagsZ.BATCH_MANUFACTURED_DATE));
    }
    if ((value = (String) batch.get(JsonTagsZ.TIMESTAMP)) != null && !value.equals("")) {
      batchJson.put(JsonTagsZ.TIMESTAMP, batch.get(JsonTagsZ.TIMESTAMP));
    }
    if ((value = (String) batch.get(JsonTagsZ.MESSAGE)) != null && !value.equals("")) {
      batchJson.put(JsonTagsZ.MESSAGE, batch.get(JsonTagsZ.MESSAGE));
    }
    if ((value = (String) batch.get(JsonTagsZ.ERROR_CODE)) != null && !value.equals("")) {
      batchJson.put(JsonTagsZ.ERROR_CODE, batch.get(JsonTagsZ.ERROR_CODE));
    }
    batchesJson.put(batchJson);
  }
  errorJSON.put(JsonTagsZ.BATCHES, batchesJson);
}