/**
   * Deletes a meeting from the database
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    if (req.getMethod() == HttpMethod.Get) {

      // Get the meeting
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      MeetingManager meetingMan = new MeetingManager();
      Meeting meeting = meetingMan.get(meetingId);
      meetingMan.deleteMeeting(meetingId);

      // Update the User Session to remove meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      List<Meeting> adminMeetings = userSession.getUser().getMeetings();

      for (int i = 0; i < adminMeetings.size(); i++) {
        Meeting m = adminMeetings.get(i);
        if (m.getId() == meeting.getId()) {
          adminMeetings.remove(i);
          break;
        }
      }

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } else if (req.getMethod() == HttpMethod.Post) {
      httpNotFound(req, res);
    }
  }
Example #2
1
 protected static boolean checkIdle(final Point p) throws NimbitsException {
   final Calendar c = Calendar.getInstance();
   c.add(Calendar.SECOND, p.getIdleSeconds() * -1);
   boolean retVal = false;
   final List<Entity> result =
       EntityServiceFactory.getInstance()
           .getEntityByKey(
               UserServiceFactory.getServerInstance().getAdmin(), p.getOwner(), EntityType.user);
   if (!result.isEmpty()) {
     final User u = (User) result.get(0);
     final List<Value> v = ValueServiceFactory.getInstance().getCurrentValue(p);
     if (p.getIdleSeconds() > 0
         && !v.isEmpty()
         && v.get(0).getTimestamp().getTime() <= c.getTimeInMillis()
         && !p.getIdleAlarmSent()) {
       p.setIdleAlarmSent(true);
       EntityServiceFactory.getInstance().addUpdateEntity(u, p);
       // PointServiceFactory.getInstance().updatePoint(u, p);
       final Value va = ValueFactory.createValueModel(v.get(0), AlertType.IdleAlert);
       SubscriptionServiceFactory.getInstance().processSubscriptions(u, p, va);
       retVal = true;
     }
   }
   return retVal;
 }
	public File doAttachment(HttpServletRequest request)
			throws ServletException, IOException {
		File file = null;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if (item.isFormField()) {
					parameters
							.put(item.getFieldName(), item.getString("UTF-8"));
				} else {
					File tempFile = new File(item.getName());
					file = new File(sc.getRealPath("/") + savePath, tempFile
							.getName());
					item.write(file);
				}
			}
		} catch (Exception e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送出了异常", e);
		}
		return file;
	}
Example #4
0
  public ActionForward execute(
      ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      GpsImportForm gpsForm = (GpsImportForm) form;
      User user = (User) req.getSession().getAttribute("user");
      int entryId = gpsForm.getEntryId();
      String fileName = gpsForm.getFileName();
      String title = gpsForm.getTitle();
      String activityId = gpsForm.getActivityId();
      String xml = gpsForm.getXml();
      log.debug(xml);

      List<GpsTrack> tracks = new TcxParser().parse(xml.getBytes());
      GpsTrack track = tracks.get(0); // Horrible hack.
      createAttachment(user, entryId, fileName, title, activityId, track);
      createGeotag(fileName, track);

      req.setAttribute("status", "success");
      req.setAttribute("message", "");
      log.debug("Returning status: success.");
      return mapping.findForward("results");
    } catch (Exception e) {
      log.fatal("Error processing incoming Garmin XML", e);
      req.setAttribute("status", "failure");
      req.setAttribute("message", e.toString());
      return mapping.findForward("results");
    }
  }
Example #5
0
  public List getUserListAT() {

    List<Map> list = new ArrayList<Map>();

    String[][] data = {
      {"3537255778", "Alex Chen"},
      {"2110989338", "Brian Wang"},
      {"3537640807", "David Hsieh"},
      {"5764816553", "James Yu"},
      {"3756404948", "K.C."},
      {"2110994764", "Neil Weinstock"},
      {"6797798390", "Owen Chen"},
      {"3831206627", "Randy Chen"},
      {"6312460903", "Tony Shen"},
      {"2110993498", "Yee Liaw"}
    };

    for (int i = 0; i < data.length; i++) {

      Map map = new HashMap();

      String userRef = data[i][0];
      String userName = data[i][1];

      map.put("userObjectId", userRef);
      map.put("userName", userName);

      list.add(map);
    }

    return list;
  }
  private int[] getSelectedRows(int[] selectedRowsNumber, Map[] selectedRowsKeys, Tab tab) {
    if (selectedRowsKeys == null || selectedRowsKeys.length == 0) return new int[0];
    // selectedRowsNumber is the most performant so we use it when possible
    else if (selectedRowsNumber.length == selectedRowsKeys.length) return selectedRowsNumber;
    else {
      // find the rows from the selectedKeys

      // This has a poor performance, but it covers the case when the selected
      // rows are not loaded for the tab, something that can occurs if the user
      // select rows and afterwards reorder the list.
      try {
        int[] s = new int[selectedRowsKeys.length];
        List selectedKeys = Arrays.asList(selectedRowsKeys);
        int end = tab.getTableModel().getTotalSize();
        int x = 0;
        for (int i = 0; i < end; i++) {
          Map key = (Map) tab.getTableModel().getObjectAt(i);
          if (selectedKeys.contains(key)) {
            s[x] = i;
            x++;
          }
        }
        return s;
      } catch (Exception ex) {
        log.warn(XavaResources.getString("fails_selected"), ex);
        throw new XavaException("fails_selected");
      }
    }
  }
Example #7
0
 /**
  * 计算测试元组与训练元组之前的距离
  *
  * @param test 测试元组
  * @param trainTuple 训练元组
  * @return 距离值
  */
 public double getDistance(List<Double> test, List<Double> trainTuple) {
   double distance = 0.00;
   for (int i = 0; i < 13; i++) {
     distance += (test.get(i) - trainTuple.get(i)) * (test.get(i) - trainTuple.get(i));
   }
   return distance;
 }
Example #8
0
  public static boolean isZero(List list, String col) {
    if (list == null) {
      return false;
    }
    boolean b = false;
    int i, num = 0;
    String v = null;
    Map m = null;
    double dv = 0;

    num = list.size();
    for (i = 0; i < num; i++) {
      m = (Map) list.get(i);
      v = (String) m.get(col);
      // if(f.empty(v)){return true;}
      if (f.empty(v)) {
        continue;
      }
      // System.out.println(v);
      v = f.v(v);
      dv = f.getDouble(v, 0);
      // if(dv==0){return true;}
      if (dv > 0) {
        return false;
      }
      b = true;
    }

    return b;
  }
  public static UIComponent findPersistent(
      FacesContext context, ServletRequest req, UIComponent parent, String id) throws Exception {
    if (context == null) context = FacesContext.getCurrentInstance();

    BodyContent body = null;

    if (parent == null) {
      UIComponentClassicTagBase parentTag =
          (UIComponentClassicTagBase) req.getAttribute("caucho.jsf.parent");

      parent = parentTag.getComponentInstance();

      body = parentTag.getBodyContent();
    }

    if (parent != null) {
      List<UIComponent> children = parent.getChildren();
      int size = children.size();

      String prevId = null;
      for (int i = 0; i < size; i++) {
        UIComponent child = children.get(i);

        if (id.equals(child.getId())) {
          if (body != null) addVerbatim(parent, prevId, body);

          return child;
        }

        if (child.getId() != null) prevId = child.getId();
      }
    }

    return null;
  }
Example #10
0
  protected List<AbstractSession> filterByUserPrincipal(
      Collection<AbstractSession> values, Principal userPrincipal) throws IOException {
    List<AbstractSession> res = null;

    {
      if (values != null) {
        res = new ArrayList<AbstractSession>();

        for (AbstractSession session : values) {
          expandSessionPrincipal(session);
        }

        if (userPrincipal == null) {
          for (AbstractSession session : values) {
            Principal p = session.getUserPrincipal();
            if (p == null) {
              res.add(session);
            }
          }
        } else {
          for (AbstractSession session : values) {
            Principal p = session.getUserPrincipal();
            if (PrincipalUtil.equalsIgnoreRealm(userPrincipal, p)) {
              res.add(session);
            }
          }
        }
      }
    }

    return res;
  }
Example #11
0
  public void init() throws ServletException {
    super.init();
    // allow = ThreddsConfig.getBoolean("NetcdfSubsetService.allow", true);
    // String radarLevel2Dir = ThreddsConfig.get("NetcdfSubsetService.radarLevel2DataDir",
    // "/data/ldm/pub/native/radar/level2/");
    // if (!allow) return;
    contentPath = ServletUtil.getContentPath();
    rm = new RadarMethods(contentPath, logServerStartup);

    // read in radarCollections.xml catalog
    InvCatalogFactory factory = InvCatalogFactory.getDefaultFactory(false); // no validation
    cat = readCatalog(factory, getPath() + catName, contentPath + getPath() + catName);
    if (cat == null) {
      logServerStartup.info("cat initialization failed");
      return;
    }
    // URI tmpURI = cat.getBaseURI();
    cat.setBaseURI(catURI);
    // get path and location from cat
    List parents = cat.getDatasets();
    for (int i = 0; i < parents.size(); i++) {
      InvDataset top = (InvDataset) parents.get(i);
      datasets = top.getDatasets(); // dataset scans

      for (int j = 0; j < datasets.size(); j++) {
        InvDatasetScan ds = (InvDatasetScan) datasets.get(j);
        if (ds.getPath() != null) {
          dataLocation.put(ds.getPath(), ds.getScanLocation());
          logServerStartup.info("path =" + ds.getPath() + " location =" + ds.getScanLocation());
        }
        ds.setXlinkHref(ds.getPath() + "/dataset.xml");
      }
    }
    logServerStartup.info(getClass().getName() + " initialization complete ");
  } // end init
Example #12
0
 /**
  * Returns the values of the named parameter as a String array, or null if the parameter was not
  * sent. The array has one entry for each parameter field sent. If any field was sent without a
  * value that entry is stored in the array as a null. The values are guaranteed to be in their
  * normal, decoded form. A single value is returned as a one-element array.
  *
  * @param name the parameter name.
  * @return the parameter values.
  */
 public String[] getParameterValues(String name) {
   List<String> values = parameters.get(name);
   if (values == null || values.size() == 0) {
     return null;
   } else {
     return values.toArray(new String[values.size()]);
   }
 }
  /**
   * Returns paths constructed by rewriting pathInfo using rules from the hosted site's mappings.
   * Paths are ordered from most to least specific match.
   *
   * @param site The hosted site.
   * @param pathInfo Path to be rewritten.
   * @param queryString
   * @return The rewritten path. May be either:
   *     <ul>
   *       <li>A path to a file in the Orion workspace, eg. <code>/ProjectA/foo/bar.txt</code>
   *       <li>An absolute URL pointing to another site, eg. <code>http://foo.com/bar.txt</code>
   *     </ul>
   *
   * @return The rewritten paths.
   * @throws URISyntaxException
   */
  private URI[] getMapped(IHostedSite site, IPath pathInfo, String queryString)
      throws URISyntaxException {
    final Map<String, List<String>> map = site.getMappings();
    final IPath originalPath = pathInfo;
    IPath path = originalPath.removeTrailingSeparator();

    List<URI> uris = new ArrayList<URI>();
    String rest = null;
    final int count = path.segmentCount();
    for (int i = 0; i <= count; i++) {
      List<String> base = map.get(path.toString());
      if (base != null) {
        rest = originalPath.removeFirstSegments(count - i).toString();
        for (int j = 0; j < base.size(); j++) {
          URI uri =
              rest.equals("") ? new URI(base.get(j)) : URIUtil.append(new URI(base.get(j)), rest);
          uris.add(
              new URI(
                  uri.getScheme(),
                  uri.getUserInfo(),
                  uri.getHost(),
                  uri.getPort(),
                  uri.getPath(),
                  queryString,
                  uri.getFragment()));
        }
      }
      path = path.removeLastSegments(1);
    }
    if (uris.size() == 0)
      // No mapping for /
      return null;
    else return uris.toArray(new URI[uris.size()]);
  }
Example #14
0
 /**
  * Returns the value of the named parameter as a String, or null if the parameter was not sent or
  * was sent without a value. The value is guaranteed to be in its normal, decoded form. If the
  * parameter has multiple values, only the last one is returned (for backward compatibility). For
  * parameters with multiple values, it's possible the last "value" may be null.
  *
  * @param name the parameter name.
  * @return the parameter value.
  */
 public String getParameter(String name) {
   try {
     List<String> values = parameters.get(name);
     if (values == null || values.size() == 0) {
       return null;
     }
     return values.get(values.size() - 1);
   } catch (Exception e) {
     return null;
   }
 }
  private void handleSignupPost(Request request, HttpServletResponse httpServletResponse)
      throws Exception {
    String userId = request.getParameter(PARAM_USER_ID);
    String userName = request.getParameter(PARAM_USER_NAME);
    String email = request.getParameter(PARAM_EMAIL);
    String stringPassword = request.getParameter(PARAM_PASSWORD);
    String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM);

    if (!stringPassword.equals(stringPasswordConfirm)) {
      WebUtils.redirectToError(
          "Mismatch between password and password confirmation", request, httpServletResponse);
      return;
    }

    SecureRandom secureRandom = new SecureRandom();
    String salt = "" + secureRandom.nextLong();
    byte[] password = User.computeHashedPassword(stringPassword, salt);
    User user = userDb.get(userId);
    if (user != null) {
      WebUtils.redirectToError(
          "There already exists a user with the ID " + userId, request, httpServletResponse);
      return;
    }

    user =
        new User(
            userId,
            userName,
            password,
            salt,
            email,
            new ArrayList<String>(),
            Config.getConfig().activateAccountsAtCreation,
            false);
    // ttt2 add confirmation by email, captcha, ...
    List<String> fieldErrors = user.checkFields();
    if (!fieldErrors.isEmpty()) {
      StringBuilder bld =
          new StringBuilder("Invalid values when trying to create user with ID ")
              .append(userId)
              .append("<br/>");
      for (String s : fieldErrors) {
        bld.append(s).append("<br/>");
      }
      WebUtils.redirectToError(bld.toString(), request, httpServletResponse);
      return;
    }

    // ttt2 2 clients can add the same userId simultaneously
    userDb.add(user);

    httpServletResponse.sendRedirect("/");
  }
 public ControllerRequest(Class<? extends Controller> controllerClass, Matcher matchedUrl) {
   this.controllerClass = controllerClass;
   if (matchedUrl.groupCount() > 0) {
     List<String> argsList = new ArrayList<String>(matchedUrl.groupCount());
     for (int i = 1; i <= matchedUrl.groupCount(); i++) {
       argsList.add(matchedUrl.group(i));
     }
     this.args = argsList;
   } else {
     this.args = new ArrayList<String>(0);
   }
 }
Example #17
0
  public List getUserList() {
    List<Map> list = new ArrayList<Map>();

    try {

      /*
      String apiUrl=rallyApiHost+"/user?query="+
      	"((TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6169133135)%20or%20"+
      	"(TeamMemberships%20%3D%20https%3A%2F%2Frally1.rallydev.com%2Fslm%2Fwebservice%2F1.34%2Fproject%2F6083311244))"+
      	"&fetch=true&order=Name&start=1&pagesize=100";
      */

      String apiUrl =
          rallyApiHost
              + "/user?query=(Disabled%20=%20false)"
              + "&fetch=true&order=Name&start=1&pagesize=100";

      log.info("apiUrl=" + apiUrl);

      String responseXML = getRallyXML(apiUrl);

      org.jdom.input.SAXBuilder bSAX = new org.jdom.input.SAXBuilder();
      org.jdom.Document doc = bSAX.build(new StringReader(responseXML));
      Element root = doc.getRootElement();

      XPath xpath = XPath.newInstance("//Object");
      List xlist = xpath.selectNodes(root);

      Iterator iter = xlist.iterator();
      while (iter.hasNext()) {

        Map map = new HashMap();

        Element item = (Element) iter.next();

        String userRef = item.getAttribute("ref").getValue();
        String userName = item.getAttribute("refObjectName").getValue();
        String userObjectId = item.getChildText("ObjectID");

        map.put("userRef", userRef);
        map.put("userObjectId", userObjectId);
        map.put("userName", userName);

        list.add(map);
      }

    } catch (Exception ex) {
      log.error("", ex);
    }

    return list;
  }
Example #18
0
  protected static int processGet() throws NimbitsException {
    final List<Entity> points = EntityServiceFactory.getInstance().getIdleEntities();
    log.info("Processing " + points.size() + " potentially idle points");
    for (final Entity p : points) {
      try {
        checkIdle((Point) p);
      } catch (NimbitsException e) {

        LogHelper.logException(IdlePointCron.class, e);
      }
    }
    return points.size();
  }
  @Test
  public void receiveAnOrder() throws Exception {
    when(request.getMethod()).thenReturn("POST");
    when(request.getRequestURI()).thenReturn("/orders");
    when(request.getParameter("order_code")).thenReturn("1234");
    when(request.getParameter("article_code")).thenReturn("ABCD");
    when(request.getParameter("address")).thenReturn("Some Place");

    ordersController.service();

    assertEquals(1, orders.size());
    assertEquals(new Order("1234", "ABCD", "Some Place"), orders.get(0));
  }
Example #20
0
 void setFormData(WObject.FormData formData) {
   if (!(formData.values.length == 0)) {
     List<String> attributes = new ArrayList<String>();
     attributes = new ArrayList<String>(Arrays.asList(formData.values[0].split(";")));
     if (attributes.size() == 6) {
       try {
         this.volume_ = Double.parseDouble(attributes.get(0));
       } catch (RuntimeException e) {
         this.volume_ = -1;
       }
       try {
         this.current_ = Double.parseDouble(attributes.get(1));
       } catch (RuntimeException e) {
         this.current_ = -1;
       }
       try {
         this.duration_ = Double.parseDouble(attributes.get(2));
       } catch (RuntimeException e) {
         this.duration_ = -1;
       }
       this.playing_ = attributes.get(3).equals("0");
       this.ended_ = attributes.get(4).equals("1");
       try {
         this.readyState_ = intToReadyState(Integer.parseInt(attributes.get(5)));
       } catch (RuntimeException e) {
         throw new WException(
             "WAbstractMedia: error parsing: " + formData.values[0] + ": " + e.toString());
       }
     } else {
       throw new WException("WAbstractMedia: error parsing: " + formData.values[0]);
     }
   }
 }
Example #21
0
 /**
  * Procesa los llamados a listar marcas
  *
  * @param
  * @return
  * @throws IOException
  * @throws ServletException
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   BrandRepository brands = (BrandRepository) context.getBean("brandRepository");
   Collection data_brands = brands.findAllBrand();
   List param_brands = new ArrayList();
   Iterator itr = data_brands.iterator();
   while (itr.hasNext()) {
     Brand brand = (Brand) itr.next();
     BrandDTO dto = BrandAssembler.Create(brand);
     param_brands.add(dto);
   }
   request.setAttribute("brands", param_brands);
   forward("/ListBrands.jsp", request, response);
 }
  /**
   * Gets values referenced by sequential keys, e.g. {@code key1...keyN}.
   *
   * @param keyPrefix Key prefix, e.g. {@code key} for {@code key1...keyN}.
   * @param params Parameters map.
   * @return Values.
   */
  @Nullable
  protected List<Object> values(String keyPrefix, Map<String, Object> params) {
    assert keyPrefix != null;

    List<Object> vals = new LinkedList<>();

    for (int i = 1; ; i++) {
      String key = keyPrefix + i;

      if (params.containsKey(key)) vals.add(params.get(key));
      else break;
    }

    return vals;
  }
Example #23
0
  public List<String> getSessionIds() throws IOException {
    List<String> res = null;

    {
      synchronized (lookupSessionById) {
        Set<String> keySet = lookupSessionById.keySet();
        if (keySet != null) {
          res = new ArrayList<String>();
          res.addAll(keySet);
        }
      }
    }

    return res;
  }
Example #24
0
  public StringBuilder listToCSV(List list) {
    StringBuilder csv = new StringBuilder();
    csv.append(
        "Work Product,,Name,State,Owner,Plan Estimate,Task Estimate,Task Remaining,Time Spent\n");

    for (int i = 0; i < list.size(); i++) {
      Map map = (Map) list.get(i);
      String type = (String) map.get("type");
      String formattedId = (String) map.get("formattedId");
      String name = (String) map.get("name");
      String taskStatus = (String) map.get("taskStatus");
      String owner = (String) map.get("owner");
      String planEstimate = (String) map.get("planEstimate");
      String taskEstimateTotal = (String) map.get("taskEstimateTotal");
      String taskRemainingTotal = (String) map.get("taskRemainingTotal");
      String taskTimeSpentTotal = (String) map.get("taskTimeSpentTotal");

      if ("task".equals(type)) {
        csv.append("," + formattedId + ",");
      } else if ("userstory".equals(type)) {
        csv.append(formattedId + ",,");
      } else if ("iteration".equals(type)) {
        csv.append(",,");
      }

      if (planEstimate == null) {
        planEstimate = "";
      }

      if (taskEstimateTotal == null) {
        taskEstimateTotal = "";
      }

      if (taskRemainingTotal == null) {
        taskRemainingTotal = "";
      }

      csv.append("\"" + name + "\",");
      csv.append(taskStatus + ",");
      csv.append(owner + ",");
      csv.append(planEstimate + ",");
      csv.append(taskEstimateTotal + ",");
      csv.append(taskRemainingTotal + ",");
      csv.append(taskTimeSpentTotal + "\n");
    }

    return csv;
  }
Example #25
0
  public JSONObject filterPlacesRandomly(
      JSONObject placesJSONObject, int finalPlacesNumberPerRequest, List<String> place_ids) {
    JSONObject initialJSON = (JSONObject) placesJSONObject.clone();
    JSONObject finalJSONObject = new JSONObject();
    int numberFields = placesJSONObject.size();
    int remainingPlaces = finalPlacesNumberPerRequest;
    int keywordsProcessed = 0;

    Set<String> keywords = initialJSON.keySet();

    for (String keyword : keywords) {
      JSONArray placesForKeyword = (JSONArray) initialJSON.get(keyword);
      JSONArray finalPlacesForKeyword = new JSONArray();
      int placesForKeywordSize = placesForKeyword.size();

      int maxPlacesToKeepInFinalJSON = remainingPlaces / (numberFields - keywordsProcessed);
      int placesToKeepInFinalJSON = Math.min(maxPlacesToKeepInFinalJSON, placesForKeywordSize);
      remainingPlaces -= placesToKeepInFinalJSON;

      for (int i = 0; i < placesToKeepInFinalJSON; i++) {
        int remainingPlacesInJSONArray = placesForKeyword.size();
        int randomElementPosInArray = (new Random()).nextInt(remainingPlacesInJSONArray);
        JSONObject temp = (JSONObject) placesForKeyword.remove(randomElementPosInArray);
        place_ids.add((String) temp.get("place_id"));
        finalPlacesForKeyword.add(temp);
      }

      finalJSONObject.put(keyword, finalPlacesForKeyword);
      keywordsProcessed++;
    }

    return finalJSONObject;
  }
 private boolean calculateWithValidValues() {
   Iterator it = metaProperties.iterator();
   while (it.hasNext()) {
     MetaProperty m = (MetaProperty) it.next();
     if (m.hasValidValues()) return true;
   }
   return false;
 }
 public MutableHttpServletRequest() {
   attributeMap = new HashMap<String, Object>();
   headerMap = new HashMap<String, String[]>();
   parameterMap = new HashMap<String, String[]>();
   fileItemMap = new HashMap<String, FileItem[]>();
   locales = new ArrayList<Locale>();
   locales.add(Locale.getDefault());
 }
Example #28
0
 public void processAlgorithm() {
   List<List<Double>> testData = data.getTestData();
   int testNum = data.getTestNum();
   long begin = System.currentTimeMillis();
   for (int i = 0; i < testNum; i++) {
     List<Double> test = testData.get(i);
     result[i][0] = Arith.convertsToInt(test.get(0));
     result[i][1] = Math.round(Float.parseFloat((knn(data.getTrainData(), test, 3))));
     if (result[i][0] != result[i][1]) {
       ma.setWrong(ma.getWrong() + 1);
     }
   }
   long end = System.currentTimeMillis();
   ma.setTime(begin, end);
   ma.setAccuracyRate(ma.getWrong(), testNum);
   ma.setErrorRate(ma.getWrong(), testNum);
 }
Example #29
0
 private void expand(int row, int column, int rowSpan, int columnSpan) {
   int newRowCount = Math.max(this.getRowCount(), row + rowSpan);
   int newColumnCount = Math.max(this.getColumnCount(), column + columnSpan);
   int extraRows = newRowCount - this.getRowCount();
   int extraColumns = newColumnCount - this.getColumnCount();
   if (extraColumns > 0) {
     for (int a_row = 0; a_row < this.getRowCount(); ++a_row) {
       {
         int insertPos = this.grid_.items_.get(a_row).size();
         for (int ii = 0; ii < (extraColumns); ++ii)
           this.grid_.items_.get(a_row).add(insertPos + ii, new Grid.Item());
       }
       ;
     }
     {
       int insertPos = this.grid_.columns_.size();
       for (int ii = 0; ii < (extraColumns); ++ii)
         this.grid_.columns_.add(insertPos + ii, new Grid.Section());
     }
     ;
   }
   if (extraRows > 0) {
     {
       int insertPos = this.grid_.items_.size();
       for (int ii = 0; ii < (extraRows); ++ii)
         this.grid_.items_.add(insertPos + ii, new ArrayList<Grid.Item>());
     }
     ;
     for (int i = 0; i < extraRows; ++i) {
       final List<Grid.Item> items =
           this.grid_.items_.get(this.grid_.items_.size() - extraRows + i);
       {
         int insertPos = items.size();
         for (int ii = 0; ii < (newColumnCount); ++ii) items.add(insertPos + ii, new Grid.Item());
       }
       ;
     }
     {
       int insertPos = this.grid_.rows_.size();
       for (int ii = 0; ii < (extraRows); ++ii)
         this.grid_.rows_.add(insertPos + ii, new Grid.Section());
     }
     ;
   }
 }
Example #30
0
 /**
  * 执行KNN算法,获取测试元组的类别
  *
  * @param list 训练数据集
  * @param test 测试元组
  * @param k 设定的K值
  * @return 测试元组的类别
  */
 public String knn(List<List<Double>> list, List<Double> test, int k) {
   PriorityQueue<KNNNode> pq = new PriorityQueue<KNNNode>(k, comparator);
   for (int i = 0; i < k; i++) {
     List<Double> trainTuple = list.get(i);
     Double c = trainTuple.get(0);
     KNNNode node = new KNNNode(i, getDistance(test, trainTuple), c);
     pq.add(node);
   }
   for (int i = 0; i < list.size(); i++) {
     List<Double> t = list.get(i);
     double distance = getDistance(test, t);
     KNNNode top = pq.peek();
     if (top.getDistance() > distance) {
       pq.remove();
       pq.add(new KNNNode(i, distance, t.get(0)));
     }
   }
   return getMostClass(pq);
 }