List of usage examples for java.util List indexOf
int indexOf(Object o);
From source file:com.core.controller.AlgoritmoController.java
public static String aEstrella(Grafo g, String inicio, String fin) { String result = "Algoritmo de Busqueda A*"; List<String> abiertos = new ArrayList<>(); List<String> padresAbiertos = new ArrayList<>(); List<Integer> valorFuncionAbiertos = new ArrayList<>(); List<String> cerrados = new ArrayList<>(); List<String> padresCerrados = new ArrayList<>(); List<String> sucesores; String mejorNodo;//ww w. jav a 2 s . c o m int index; //Algoritmo A* abiertos.add(inicio); padresAbiertos.add("#"); valorFuncionAbiertos.add(g.buscarNodo(inicio).getValor() + 0); while (true) { result += "\nPadresCerrados: " + padresCerrados; result += "\nCerrados: " + cerrados; result += "\nAbiertos: " + abiertos; result += "\nValorFun: " + valorFuncionAbiertos; int costoHastaNodoActual, heuristicaNodo, valorFun; String padre; //Si esta vacia devuelve error if (abiertos.isEmpty()) { result += "\nError"; break; } //Obtengo el mejor nodo de abiertos if (abiertos.size() == 1) { mejorNodo = abiertos.get(0); } else { mejorNodo = getMejorNodo(abiertos, valorFuncionAbiertos); result += "\nMejor nodo: " + mejorNodo; } //Pregunto si es el nodo final if (mejorNodo.equals(fin)) { result += "\nNodo fin alcanzado"; //Mostrar camino cerrados.add(mejorNodo); padresCerrados.add(padresAbiertos.get(abiertos.indexOf(mejorNodo))); String nodo = mejorNodo; ArrayList<String> secuenciaResultado = new ArrayList<>(); //Mostrar el camino hasta la solucion while (true) { secuenciaResultado.add(nodo); nodo = padresCerrados.get(cerrados.indexOf(nodo)); if (nodo.equals("#")) { result += "\n" + secuenciaResultado; break; } } break; } index = abiertos.indexOf(mejorNodo); padre = padresAbiertos.get(index); //obtengo el costo hasta mejorNodo heuristicaNodo = g.buscarNodo(mejorNodo).getValor(); costoHastaNodoActual = (valorFuncionAbiertos.get(index) - heuristicaNodo); //remuevo el nodo a ser explotado abiertos.remove(index); padresAbiertos.remove(index); valorFuncionAbiertos.remove(index); //lo agrego en cerrados cerrados.add(mejorNodo); padresCerrados.add(padre); //obtenemos los sucesores de mejor nodo sucesores = g.nodosVecinos(mejorNodo); for (int i = 0; i < sucesores.size(); i++) { heuristicaNodo = g.buscarNodo(sucesores.get(i)).getValor(); valorFun = costoHastaNodoActual + (g.buscarArista(mejorNodo + "-" + sucesores.get(i))).getValor() + heuristicaNodo; //pregunto si ya existe el noso en abiertos if (abiertos.contains(sucesores.get(i))) { index = abiertos.indexOf(sucesores.get(i)); //Si ya existe pregunto si el nuevo nodo es mejor if (valorFuncionAbiertos.get(index) < valorFun) { valorFuncionAbiertos.set(index, valorFun); padresAbiertos.set(index, mejorNodo); } } else { //pregunto si esta en cerrados if (cerrados.contains(sucesores.get(i))) { //no hacer nada } else { abiertos.add(sucesores.get(i)); padresAbiertos.add(mejorNodo); valorFuncionAbiertos.add(valorFun); } } } //fin for } //fin while return result; }
From source file:de.appsolve.padelcampus.utils.BookingUtil.java
public void addWeekView(HttpServletRequest request, LocalDate selectedDate, List<Facility> selectedFacilities, ModelAndView mav, Boolean onlyFutureTimeSlots, Boolean preventOverlapping) throws JsonProcessingException { //calculate date configuration for datepicker LocalDate today = new LocalDate(DEFAULT_TIMEZONE); LocalDate firstDay = today.dayOfMonth().withMinimumValue(); LocalDate lastDay = getLastBookableDay(request).plusDays(1); List<CalendarConfig> calendarConfigs = calendarConfigDAO.findBetween(firstDay, lastDay); Collections.sort(calendarConfigs); Map<String, DatePickerDayConfig> dayConfigs = getDayConfigMap(firstDay, lastDay, calendarConfigs); List<Booking> confirmedBookings = bookingDAO.findBlockedBookingsBetween(firstDay, lastDay); //calculate available time slots List<TimeSlot> timeSlots = new ArrayList<>(); List<LocalDate> weekDays = new ArrayList<>(); for (int i = 1; i <= CalendarWeekDay.values().length; i++) { LocalDate date = selectedDate.withDayOfWeek(i); weekDays.add(date);//from w ww.j ava 2 s .com if ((!onlyFutureTimeSlots || !date.isBefore(today)) && lastDay.isAfter(date)) { try { //generate list of bookable time slots timeSlots.addAll(getTimeSlotsForDate(date, calendarConfigs, confirmedBookings, onlyFutureTimeSlots, preventOverlapping)); } catch (CalendarConfigException e) { //safe to ignore } } } SortedSet<Offer> offers = new TreeSet<>(); List<TimeRange> rangeList = new ArrayList<>(); //Map<TimeRange, List<TimeSlot>> rangeList = new TreeMap<>(); for (TimeSlot slot : timeSlots) { Set<Offer> slotOffers = slot.getConfig().getOffers(); offers.addAll(slotOffers); TimeRange range = new TimeRange(); range.setStartTime(slot.getStartTime()); range.setEndTime(slot.getEndTime()); if (rangeList.contains(range)) { range = rangeList.get(rangeList.indexOf(range)); } else { rangeList.add(range); } List<TimeSlot> slotis = range.getTimeSlots(); slotis.add(slot); range.setTimeSlots(slotis); } Collections.sort(rangeList); List<Offer> selectedOffers = new ArrayList<>(); if (selectedFacilities.isEmpty()) { selectedOffers = offerDAO.findAll(); } else { for (Facility facility : selectedFacilities) { selectedOffers.addAll(facility.getOffers()); } } Collections.sort(selectedOffers); mav.addObject("dayConfigs", objectMapper.writeValueAsString(dayConfigs)); mav.addObject("maxDate", lastDay.toString()); mav.addObject("Day", selectedDate); mav.addObject("NextMonday", selectedDate.plusDays(8 - selectedDate.getDayOfWeek())); mav.addObject("PrevSunday", selectedDate.minusDays(selectedDate.getDayOfWeek())); mav.addObject("WeekDays", weekDays); mav.addObject("RangeMap", rangeList); mav.addObject("Offers", offers); mav.addObject("SelectedOffers", selectedOffers); mav.addObject("SelectedFacilities", selectedFacilities); mav.addObject("Facilities", facilityDAO.findAll()); }
From source file:com.glaf.activiti.web.rest.ActivitiResource.java
private List<String> getHighLightedFlows() { List<String> highLightedFlows = new java.util.ArrayList<String>(); List<HistoricActivityInstance> historicActivityInstances = historyService .createHistoricActivityInstanceQuery().processInstanceId(processInstanceId) .orderByHistoricActivityInstanceStartTime().asc().list(); List<String> historicActivityInstanceList = new java.util.ArrayList<String>(); for (HistoricActivityInstance hai : historicActivityInstances) { historicActivityInstanceList.add(hai.getActivityId()); }//from w ww .j a va 2 s. c o m // add current activities to list List<String> highLightedActivities = runtimeService.getActiveActivityIds(processInstanceId); historicActivityInstanceList.addAll(highLightedActivities); // activities and their sequence-flows for (ActivityImpl activity : processDefinition.getActivities()) { int index = historicActivityInstanceList.indexOf(activity.getId()); if ((index >= 0) && ((index + 1) < historicActivityInstanceList.size())) { List<PvmTransition> pvmTransitionList = activity.getOutgoingTransitions(); for (PvmTransition pvmTransition : pvmTransitionList) { String destinationFlowId = pvmTransition.getDestination().getId(); if (destinationFlowId.equals(historicActivityInstanceList.get(index + 1))) { highLightedFlows.add(pvmTransition.getId()); } } } } return highLightedFlows; }
From source file:com.mindquarry.desktop.client.widget.task.TaskContainerWidget.java
public void refresh() { log.info("Starting task list refresh."); //$NON-NLS-1$ enableAction(false);/*from w ww . j a va 2 s.c o m*/ refreshing = true; PreferenceStore store = client.getPreferenceStore(); Profile profile = Profile.getSelectedProfile(store); // check profile if (profile == null) { log.debug("No profile selected."); //$NON-NLS-1$ enableAction(true); refreshing = false; return; } showRefreshMessage(I18N.getString("Updating task list...")); //$NON-NLS-1$ log.info("Retrieving list of tasks."); //$NON-NLS-1$ // cleanup current task list if (tasks == null) { tasks = new TaskList(); } tasks.getTasks().clear(); // retrieve tasks for all selected teams final List<Team> teams = new ArrayList<Team>(); Display.getDefault().syncExec(new Runnable() { public void run() { teams.addAll(client.getSelectedTeams()); } }); try { for (Team team : teams) { String url = profile.getServerURL(); String login = profile.getLogin(); String password = profile.getPassword(); TaskList taskList = new TaskList(url + "/tasks/" + team.getId() + "/", login, password); // set for use in onEvent(): tasksInCurrentTeamCount = taskList.getSize(); taskDownloadCount = 1; updateMessage = I18N.get("Updating task list for team \"{0}\" (team {1} of {2}): ", team.getName(), Integer.toString(teams.indexOf(team) + 1), Integer.toString(teams.size())); tasks.getTasks().addAll(taskList.getTasks()); } } catch (final NotAuthorizedException e) { log.error("Could not update list of tasks for " //$NON-NLS-1$ + profile.getServerURL(), e); getDisplay().syncExec(new Runnable() { public void run() { refreshing = client.handleNotAuthorizedException(e); } }); if (refreshing) { refresh(); } else { enableAction(true); } return; } catch (final UnknownHostException e) { log.error("Could not update list of tasks for " //$NON-NLS-1$ + profile.getServerURL(), e); getDisplay().syncExec(new Runnable() { public void run() { refreshing = client.handleUnknownHostException(e); } }); if (refreshing) { refresh(); } else { enableAction(true); } return; } catch (Exception e) { if (ExceptionUtilities.hasCause(e, ThreadDeath.class)) { // task update was cancelled by user } else { log.error("Could not update list of tasks for " //$NON-NLS-1$ + profile.getServerURL(), e); final String errMessage = I18N.getString("List of tasks could not be updated") //$NON-NLS-1$ + " " + e.getLocalizedMessage(); getDisplay().syncExec(new Runnable() { public void run() { MessageDialog.openError(getShell(), I18N.getString("Error"), errMessage); } }); showErrorMessage(errMessage); } enableAction(true); refreshing = false; return; } showEmptyMessage(tasks.getTasks().isEmpty()); if (!tasks.getTasks().isEmpty()) { // update task table log.info("Updating list of tasks."); //$NON-NLS-1$ getDisplay().syncExec(new Runnable() { public void run() { applyFacets(); } }); } refreshing = false; enableAction(true); }
From source file:main.java.edu.isistan.genCom.gui.Principal.java
private void cargarComision(int indice) { // // Carga la tabla de comisiones DefaultTableModel dtmComision = (DefaultTableModel) tbComision.getModel(); limpiarModelo(dtmComision);/*from ww w .ja v a2s . com*/ List<Ejecucion> ejecuciones = generacionCargada.getEjecuciones(); Ejecucion ejecucion = ejecuciones.get(indice); List<Investigador> comision = ejecucion.getComision(); for (Investigador inv : comision) { dtmComision.addRow(new String[] { String.valueOf(comision.indexOf(inv)), inv.toString(), String.valueOf(redSocial.getDegree(inv)), String.valueOf(redSocial.getBetweeness(inv)), String.valueOf(redSocial.getCloseness(inv)), String.valueOf(redSocial.getEigenVector(inv)) }); } }
From source file:com.google.gdt.eclipse.designer.uibinder.model.util.UiChildSupport.java
/** * @return the sorted {@link Description}s for methods of given {@link WidgetInfo}. *///from www . j a va 2 s . c o m private List<Description> getSortedDescriptions(WidgetInfo widget) throws Exception { // prepare order of tags final List<String> tagOrder; { String hideString = XmlObjectUtils.getParameter(widget, "UiChild.order"); if (hideString != null) { String[] hideSplit = StringUtils.split(hideString); tagOrder = ImmutableList.copyOf(hideSplit); } else { tagOrder = ImmutableList.of(); } } // sort descriptions List<Description> descriptions = getDescriptions(widget); Collections.sort(descriptions, new Comparator<Description>() { public int compare(Description o1, Description o2) { String tag1 = o1.getTag(); String tag2 = o2.getTag(); int index1 = tagOrder.indexOf(tag1); int index2 = tagOrder.indexOf(tag2); if (index1 != -1 && index2 != -1) { return index1 - index2; } if (index1 != -1) { return -1; } if (index2 != -1) { return 1; } return tag1.compareTo(tag2); } }); return descriptions; }
From source file:net.sf.taverna.raven.plugins.PluginManager.java
/** * Returns all the <code>Plugin</code>s available from the * <code>PluginSite</code> that haven't already been installed. * // www. ja va2s. c o m * @param pluginSite * @return all the uninstalled <code>Plugin</code>s from the * <code>PluginSite</code> */ public List<Plugin> getUninstalledPluginsFromSite(PluginSite pluginSite) { List<Plugin> uninstalledPlugins = new ArrayList<Plugin>(); List<Plugin> pluginsFromSite = getPluginsFromSite(pluginSite); for (Plugin plugin : pluginsFromSite) { if (!plugins.contains(plugin)) { if (uninstalledPlugins.contains(plugin)) { int index = uninstalledPlugins.indexOf(plugin); Plugin uninstalledPlugin = uninstalledPlugins.get(index); if (uninstalledPlugin.compareVersion(plugin) < 0) { uninstalledPlugins.remove(index); uninstalledPlugins.add(plugin); } } else { uninstalledPlugins.add(plugin); } } } return uninstalledPlugins; }
From source file:com.openshift.internal.restclient.ApiTypeMapper.java
private void addEndpoints(List<VersionedApiResource> endpoints, final String prefix, final String apiGroupName, final String version, final Collection<ModelNode> nodes) { for (ModelNode node : nodes) { String name = node.get(NAME).asString(); String capability = null; if (name.contains(FWD_SLASH)) { int first = name.indexOf(FWD_SLASH); capability = name.substring(first + 1); name = name.substring(0, first); }/* ww w.j a v a2s .c om*/ boolean namespaced = node.get("namespaced").asBoolean(); VersionedApiResource resource = new VersionedApiResource(prefix, apiGroupName, version, name, node.get(KIND).asString(), namespaced); if (!endpoints.contains(resource)) { endpoints.add(resource); } if (capability != null) { int index = endpoints.indexOf(resource); endpoints.get(index).addCapability(capability); } } }
From source file:org.ala.dao.CassandraPelopsHelper.java
/** * @see org.ala.dao.StoreHelper#put(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.Comparable) *//*from w w w . jav a 2s . c o m*/ @Override public boolean put(String table, String columnFamily, String columnName, String guid, Comparable object) throws Exception { logger.debug("Pelops put table: " + table + " colFamily: " + columnFamily + " guid: " + guid); Mutator mutator = Pelops.createMutator(pool); Selector selector = Pelops.createSelector(pool); guid = StringUtils.trimToNull(guid); if (guid == null || object == null) { logger.warn("Null or empty guid supplied. Unable to add to row [" + guid + "] column [" + columnName + "] object: " + object); return false; } Column col = null; try { col = selector.getColumnFromRow(columnFamily, guid, columnName, ConsistencyLevel.ONE); } catch (Exception e) { //expected behaviour. current thrift API doesnt seem //to support a retrieve null getter if (logger.isTraceEnabled()) { logger.trace(e.getMessage(), e); } } //initialise the object mapper ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL); //read the existing value List<Comparable> objectList = null; if (col != null) { String value = new String(col.getValue(), charsetEncoding); objectList = mapper.readValue(value, TypeFactory.collectionType(ArrayList.class, object.getClass())); } else { objectList = new ArrayList<Comparable>(); } //add to the collection and sort the objects if (objectList.contains(object)) { int idx = objectList.indexOf(object); //replace with this version Comparable objectToReplace = objectList.remove(idx); //dont lose rankings!!!!!!!!!!!!!!!!!!!!!!! if (object instanceof Rankable) { //retrieve those rankings RankUtils.copyAcrossRankings((Rankable) objectToReplace, (Rankable) object); } objectList.add(object); } else { objectList.add(object); } Collections.sort(objectList); //convert to JSON String json = mapper.writeValueAsString(objectList); //insert into table try { mutator.writeColumn(columnFamily, guid, mutator.newColumn(columnName, json)); mutator.execute(ConsistencyLevel.ONE); logger.debug("Pelops put returning"); return true; } catch (Exception e) { logger.error(e.getMessage(), e); return false; } }
From source file:org.gvnix.service.roo.addon.addon.ws.export.WSExportOperationsImpl.java
/** * Create annotations for each method parameter, if not empty. * <p>/*from w ww . ja va2 s . c om*/ * Each parameter with not empty type and name will be related a * GvNIXWebParam annotation and a WebParam annotation. * </p> * * @param method Method to update with annotations * @param targetNamespace Web Service Namespace * @return Annotation */ protected List<AnnotatedJavaType> getMethodParameterAnnotations(MethodMetadata method, String targetNamespace) { // List to store annotations for parameters List<AnnotatedJavaType> annotations = new ArrayList<AnnotatedJavaType>(); // Get method parameter types and names and return null if empty List<AnnotatedJavaType> paramsType = method.getParameterTypes(); List<JavaSymbolName> paramsName = method.getParameterNames(); if (paramsType.isEmpty() && paramsName.isEmpty()) { return annotations; } // For each parameters for (AnnotatedJavaType paramType : paramsType) { // annotation of this parameter List<AnnotationMetadata> paramsAnnotations = new ArrayList<AnnotationMetadata>(); // Get current parameter name int index = paramsType.indexOf(paramType); JavaSymbolName paramName = paramsName.get(index); // Add @GvNIXWebParam to annotation list paramsAnnotations.add(getGvNIXWebParamAnnotation(paramType, paramName)); // Add @WebParam to annotation list paramsAnnotations.add(getWebParamAnnotation(targetNamespace, paramType, paramName)); // Add annotation list to parameter annotations.add(new AnnotatedJavaType(paramType.getJavaType(), paramsAnnotations)); } return annotations; }