/** * Returns all Weight Reading objects that fall within the time range specified (inclusive) * * @param leftBound The Date object specifying the earliest date boundary * @param rightBound The Date object specifying the latest date boundary * @param c The application context * @note Recreates only the new objects, since Identity Map is no longer applied: the reason for * this is because whenever data is fetched, we know its usage right away and will not need to * keep it in proximity for later usage, but rather direct usage * @return The ArrayList of all weighteReading in the database that fall within range * @throws MapperException Thrown when there is either a problem with mapping or if the * Persistence layer returns an error */ public static ArrayList<WeightReading> findAllWithinRangeInclusive( Date iLeftBound, Date iRightBound, Context iC) throws MapperException { try { ArrayList<ArrayList<String>> resultTable = WeightTDG.selectBetweenDatesInclusive( String.valueOf(iLeftBound.getTime()), String.valueOf(iRightBound.getTime()), iC); ArrayList<WeightReading> resultReadings = new ArrayList<WeightReading>(resultTable.size()); for (int i = 0; i < resultTable.size(); ++i) { ArrayList<String> values = resultTable.get(i); WeightReading r; Long id = Long.valueOf(values.get(0)); Date date = new Date(Long.valueOf(values.get(1))); /** Converts from Unix time to Java Date */ int sourceInt = Integer.valueOf(values.get(2)); ReadingSource source = sourceFromInt(sourceInt); float weight = Float.valueOf(values.get(3)); r = new WeightReading(id, date, source, weight); resultReadings.add(r); } return resultReadings; } catch (PersistenceException iE) { throw new MapperException( "The Mapper failed to obtain the Weight Readings from the persistence layer. The TDG returned the following error: " + iE.getMessage()); } catch (Exception iE) { throw new MapperException( "The mapper failed to complete an operation for the following unforeseen reason: " + iE.getMessage()); } }
private void updateCentroids() { ArrayList<Record> clusterSum = new ArrayList<Record>(); for (int i = 0; i < numberClusters; i++) { double[] attributes = new double[numberAttributes]; for (int j = 0; j < numberAttributes; j++) attributes[j] = 0; clusterSum.add(new Record(attributes)); } int[] clusterSize = new int[numberClusters]; for (int i = 0; i < numberClusters; i++) clusterSize[i] = 0; for (int i = 0; i < numberRecords; i++) { int cluster = clusters[i]; Record sum = sum(clusterSum.get(cluster), records.get(i)); clusterSum.set(cluster, sum); clusterSize[cluster] += 1; } for (int i = 0; i < numberClusters; i++) { Record average = scale(clusterSum.get(i), 1.0 / clusterSize[i]); centroids.set(i, average); } }
/** * Extract blob. * * @param id ID. * @param fastBitmap Image to be processed. * @return Image with the extracted blob. */ public FastBitmap Extract(int id, FastBitmap fastBitmap) { // Check if blobs list is null. if (this.blobs == null) this.blobs = new BlobDetection().ProcessImage(fastBitmap); FastBitmap image; if (fastBitmap.isGrayscale()) { image = new FastBitmap( fastBitmap.getWidth(), fastBitmap.getHeight(), FastBitmap.ColorSpace.Grayscale); for (IntPoint p : blobs.get(id).getPoints()) { image.setGray(p.x, p.y, fastBitmap.getGray(p.x, p.y)); } } else { image = new FastBitmap(fastBitmap.getWidth(), fastBitmap.getHeight(), FastBitmap.ColorSpace.RGB); for (IntPoint p : blobs.get(id).getPoints()) { image.setRed(p.x, p.y, fastBitmap.getRed(p.x, p.y)); image.setGreen(p.x, p.y, fastBitmap.getGreen(p.x, p.y)); image.setBlue(p.x, p.y, fastBitmap.getBlue(p.x, p.y)); } } return image; }
public void writeNN(String source, String target, boolean flag) { this.loadCorpus(source, target); try { Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(source + ".nn"), "UTF-8")); Writer bw1 = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target + ".nn"), "UTF-8")); if (flag) for (int i = 0; i < nelist.size(); i++) { String ne[] = nelist.get(i).split("\t"); bw.write(this.formatStringCausal(ne[0]) + "\n"); bw1.write(this.formatStringCausal(ne[1]) + "\n"); bw.flush(); bw1.flush(); } else for (int i = 0; i < nelist.size(); i++) { String ne[] = nelist.get(i).split("\t"); bw.write(ne[0] + "\n"); bw1.write(ne[1] + "\n"); bw.flush(); bw1.flush(); } } catch (Exception ex) { ex.printStackTrace(); } }
/* * This method lines up two AI's links, aka genes, and returns the order of the lined up genes, and where they occur. * This method returns an arraylist of arraylist of Integer. * The outer arraylist contains arraylists on: * 0: neuron historical ID of links present in the two AI * 1: where in the first ai's link list the link occurs * 2: where in the second ai's link list the link occurs */ public ArrayList<ArrayList<Integer>> lineUpAILinks(NeatAI second) { ArrayList<Gene> secondL = second.getCloneLinks(); ArrayList<Integer> ai1histIDlist = new ArrayList<Integer>(); ArrayList<Integer> ai2histIDlist = new ArrayList<Integer>(); ArrayList<Integer> linkID = new ArrayList<Integer>(); ArrayList<Integer> linkList1Pos = new ArrayList<Integer>(); ArrayList<Integer> linkList2Pos = new ArrayList<Integer>(); // Get genes. int histID; for (Gene l : links) { histID = l.getHistID(); linkID.add(histID); ai1histIDlist.add(histID); } int pos; for (Gene l : secondL) { histID = l.getHistID(); pos = linkID.indexOf(histID); if (pos == -1) { // New histID found linkID.add(histID); } ai2histIDlist.add(histID); } // Sort genes // Bubble sort, meh int lowest; for (int i = 0; i < linkID.size(); i++) { lowest = i; for (int j = i + 1; j < linkID.size(); j++) { if (linkID.get(j) < linkID.get(lowest)) { lowest = j; } } int temp = linkID.get(i); linkID.set(i, linkID.get(lowest)); linkID.set(lowest, temp); } // Add gene positions for (Integer tempID : linkID) { linkList1Pos.add(ai1histIDlist.indexOf(tempID)); linkList2Pos.add(ai2histIDlist.indexOf(tempID)); } ArrayList<ArrayList<Integer>> temp = new ArrayList<ArrayList<Integer>>(); temp.add(linkID); temp.add(linkList1Pos); temp.add(linkList2Pos); return temp; }
public void menuNiveauUn(char choix) { switch (choix) { case 'J': this.lireJournal(); // Outils.afficher(monInterface.getCpt(), partieActuelle); monInterface.setCpt(monInterface.getCpt() + 1); // Outils.afficher(monInterface.getCpt(), partieActuelle); break; case 'D': if (!tabGrille.get(partieActuelle.getJoueurActuel().getIndiceCase()).getFouillee() || tabGrille .get(partieActuelle.getJoueurActuel().getIndiceCase()) .getNbZombiesRestants() == 0) { Outils.afficher(5, partieActuelle); monInterface.setCpt(monInterface.getCpt() + 3); } else { // Outils.affichage(Journal.consulterDescription(5),this.getMonInterface()); } // break; case 'I': monInterface.setCpt(monInterface.getCpt() + 5); if (partieActuelle.getJoueurActuel().getAbsysseActuelle() == partieActuelle.getGrille().getxVille() && partieActuelle.getJoueurActuel().getOrdonneeActuelle() == partieActuelle.getGrille().getyVille()) { // Outils.affichage(Journal.consulterDescription(38),partieActuelle.getMonInterface()); } else { if (partieActuelle .getMenuPartie() .getTabGrille() .get(partieActuelle.getJoueurActuel().getIndiceCase()) .getFouillee()) { // Outils.affichage(Journal.consulterDescription(39),partieActuelle.getMonInterface()); } else { // Outils.affichage(Journal.consulterDescription(40),partieActuelle.getMonInterface()); } } // Outils.affichage(Journal.consulterDescription(36),partieActuelle.getMonInterface()); // this.interagirCase(Outils.verifier(Outils.afficher(monInterface.getCpt(),partieActuelle),partieActuelle)); break; case 'F': // monInterface.getjTextArea1().setText(""); this.finirTour(); break; case 'S': Outils.afficher(4, partieActuelle); monInterface.setCpt(monInterface.getCpt() + 23); break; case 'R': this.retournerMenu(0); break; default: // Outils.affichage(Journal.consulterDescription(6),this.getMonInterface()); break; } }
public String characteristicsString() { String s = "("; for (int i = 0; i < characteristics.size() - 1; i++) s += characteristics.get(i) + ","; if (!characteristics.isEmpty()) s += characteristics.get(characteristics.size() - 1); s += ")"; return s; }
public static void quickSelect(ArrayList<Integer> a, int start, int end, int k) { int left = start, right = end; int pivot = a.get(end); while (left < right) { while (left < right && a.get(left) < pivot) { left++; } while (left < right && a.get(right) >= pivot) { right--; } swap(a, left, right); } swap(a, end, left); if (k == left + 1) { return; } else if (k < left + 1) { quickSelect(a, start, left - 1, k); } else { quickSelect(a, left + 1, end, k); } }
public void list(HttpServletRequest request, HttpServletResponse response) throws Exception { BaseEdOffice office_pop = new BaseEdOffice(db); String sql = ""; String slsql; String countsql; ArrayList<String> alcon = new ArrayList(); ArrayList<String> alin = new ArrayList(); slsql = "select OFFCODE,SHORT_NAME from ED_OFFICE where 1 = 1"; countsql = "select count(*) from ED_OFFICE where 1 = 1"; alcon.add(" AND OFFCODE like '%"); alin.add(request.getParameter("txt_offcode") + "%'"); alcon.add(" AND OFFNAME like '%"); alin.add(request.getParameter("txt_offname") + "%'"); for (int i = 0; i < alin.size(); i++) { if (alin.get(i).equals("%'")) { alcon.set(i, ""); alin.set(i, ""); } sql += alcon.get(i) + alin.get(i); } String sqlOrder = " order by offcode "; request.setAttribute("formname", request.getParameter("formname")); request.setAttribute("formcode", request.getParameter("formcode")); request.setAttribute("formpos", request.getParameter("formpos")); // add by mu Integer totalRow = office_pop.countBySql(countsql + sql, null); pageUtil.setTotalRow(totalRow); pageUtil.setPageSize(20); List office_list = office_pop.findBySql(slsql + sql + sqlOrder, null, pageUtil); // log.debug(office_list); request.setAttribute("Ed_officeList", office_list); forward("/Popup/division_pop.jsp", request, response); }
/** * 创建者:仲瑞庆 功能: 参数: 返回: 例外: 日期:(2001-6-19 下午 3:27) 修改日期,修改人,修改原因,注释标志: * * @return nc.vo.ic.pub.bill.FreeVO */ public FreeVO getFreeVO() { FreeVO fvoFVO = new FreeVO(); if ((m_alFreeItemID != null) && (m_alFreeItemID.size() == 10) && (m_alFreeItemReturnName != null) && (m_alFreeItemReturnName.size() >= 10) && (m_alFreeItemReturnValue != null) && (m_alFreeItemReturnValue.size() >= 10)) { for (int i = 1; i <= 10; i++) { fvoFVO.setAttributeValue("vfreeid" + Integer.toString(i).trim(), m_alFreeItemID.get(i - 1)); fvoFVO.setAttributeValue( "vfreename" + Integer.toString(i).trim(), m_alFreeItemReturnName.get(i - 1)); fvoFVO.setAttributeValue( "vfree" + Integer.toString(i).trim(), m_alFreeItemReturnValue.get(i - 1)); // fvoFVO.setAttributeValue( // "vfreevalue" + Integer.toString(i).trim(), // m_alFreeItemReturnValueName.get(i - 1)); } } else { for (int i = 1; i <= 10; i++) { fvoFVO.setAttributeValue("vfreeid" + Integer.toString(i).trim(), null); fvoFVO.setAttributeValue("vfreename" + Integer.toString(i).trim(), null); fvoFVO.setAttributeValue("vfree" + Integer.toString(i).trim(), null); // fvoFVO.setAttributeValue("vfreevalue" + // Integer.toString(i).trim(), null); } } fvoFVO.setAttributeValue("vfree0", this.getText() == null ? null : this.getText().trim()); return fvoFVO; }
private DraggableComponent findDraggableComponent(Component c) { for (int i = 0; i < draggableComponentList.size(); i++) if (((DraggableComponent) draggableComponentList.get(i)).getComponent() == c) return (DraggableComponent) draggableComponentList.get(i); return null; }
/** @return the uncompressed array */ public int[] toArray() { int[] returnArray; int counter = 0; // determine size of array for (int i = 0; i < compressedSequence.size(); i++) { counter += compressedSequence.get(i).getNumber(); } returnArray = new int[counter]; // adding in each value // counter is reused, because i like that word int innerCounter = 0; int outerCounter = 0; for (int i = 0; i < compressedSequence.size(); i++) { outerCounter += innerCounter; innerCounter = 0; for (int j = 0; j < compressedSequence.get(i).getNumber(); j++) { // System.out.println(i+" "+j+" "+outerCounter); returnArray[i + j + outerCounter] = compressedSequence.get(i).getValue(); if (j > 0) { innerCounter++; } } } return returnArray; }
public String[] getElements(String key) { ArrayList<String> result = new ArrayList<String>(); for (int i = 0; i < values.size(); i++) { if (values.get(i).getType().getURI().equals(key)) result.add(values.get(i).getValue()); } return result.toArray(new String[result.size()]); }
public void showDetailInfo(int clickID) { new AlertDialog.Builder(mContext) .setTitle("详情:" + appInfos.get(clickID).getText_id()) .setMessage(appInfos.get(clickID).getText_infos().toString()) .setPositiveButton("确定", null) .show(); }
private int assignClusters() { int clusterChanges = 0; for (int i = 0; i < numberRecords; i++) { Record record = records.get(i); double minDistance = distance(record, centroids.get(0)); int minIndex = 0; for (int j = 0; j < numberClusters; j++) { double distance = distance(record, centroids.get(j)); if (distance < minDistance) { minDistance = distance; minIndex = j; } } if (clusters[i] != minIndex) { clusters[i] = minIndex; clusterChanges++; } } return clusterChanges; }
/** * find the grade of a particular topic based on its difficulty level * * @param userId * @param topic * @param difficulty * @return averageQuizGrade * @throws Exception */ public static double findTopicDifficultyGrade(int userId, String topic, String difficulty) throws Exception { QuizAttempt quizAttempt = new QuizAttempt(); ArrayList<Integer> userQuizIds = quizAttempt.getUserQuizIds(userId); ArrayList<Double> userQuizGrades = new ArrayList<Double>(); for (int i = 0; i < userQuizIds.size(); i++) { QuizSlot quizSlot = new QuizSlot(); // get the question ids of questions belonging to a particular quiz ArrayList<Integer> questionIds = quizSlot.getDifficultyAndTopicWiseQuestionIdsOfAQuiz( userQuizIds.get(i), topic, difficulty); if (questionIds.size() > 0) { double quizGrade = Grade.findQuizGrade(questionIds, userId); userQuizGrades.add(quizGrade); } } double quizGrade = 0; for (int i = 0; i < userQuizGrades.size() - 1; i++) { quizGrade += userQuizGrades.get(i); } double averageQuizGrade = 0; if (quizGrade != 0) { averageQuizGrade = quizGrade / userQuizGrades.size(); } return averageQuizGrade; }
public void init() { Scanner scan = new Scanner(System.in); count = scan.nextInt(); x0 = scan.nextLong(); y0 = scan.nextLong(); int result = 0; boolean special = false; for (int i = 0; i < count; i++) { long tempx = scan.nextLong(); long tempy = scan.nextLong(); if (tempx == x0 && tempy == y0) { special = true; continue; } boolean isDuplicate = false; for (int j = 0; j < result; j++) { long x1 = xList.get(j); long y1 = yList.get(j); if ((x1 - x0) * (tempy - y0) == (y1 - y0) * (tempx - x0)) { isDuplicate = true; break; } } if (!isDuplicate) { xList.add(tempx); yList.add(tempy); result++; } } if (special && result == 0) result = 1; System.out.println(result); scan.close(); }
// A segment is added to an area if it has at least 1 common position with the area // return true if new segment added or already existing // return false if new segment can't be added. public boolean addSegment(SGSegment s) { boolean added = false; if (s == null) { SGTools.Log1(this, "Can't add null segment to WoS !"); return false; } int i = 0; while (i < rideAreas.size() && added == false) { added = rideAreas.get(i).addSegment(s); i++; } if (added == true) { // Successfully added ==> Need to check if can be added to another area. // If yes ==> merge areas boolean found = false; for (; i < rideAreas.size(); i++) { found = rideAreas.get(i).addSegment(s); if (found == true) { // the new segment matches a second area ==> need to merge ! // TODO: merge areas } } } else { // Not added ==> create new ride area } return true; }
@Override public Object instantiateItem(ViewGroup container, int position) { container.addView(viewList.get(position).root); manager.addPlaceHoderHeaderLayout( position, viewList.get(position).placeHoderHeaderLayout); return viewList.get(position).root; }
private static IJavaProject[] getProjectSearchOrder(String projectName) { ArrayList<String> projectNames = new ArrayList<String>(); projectNames.add(projectName); int nextProject = 0; while (nextProject < projectNames.size()) { String nextProjectName = projectNames.get(nextProject); IJavaProject jproject = getJavaProject(nextProjectName); if (jproject != null) { try { String[] childProjectNames = jproject.getRequiredProjectNames(); for (int i = 0; i < childProjectNames.length; i++) { if (!projectNames.contains(childProjectNames[i])) { projectNames.add(childProjectNames[i]); } } } catch (JavaModelException e) { JavaPlugin.log(e); } } nextProject += 1; } ArrayList<IJavaProject> result = new ArrayList<IJavaProject>(); for (int i = 0, size = projectNames.size(); i < size; i++) { String name = projectNames.get(i); IJavaProject project = getJavaProject(name); if (project != null) result.add(project); } return result.toArray(new IJavaProject[result.size()]); }
public void randomwalk(int v) { // weighted random walk RandomWalk rw = new RandomWalk(p_w); int status = rw.stay_move(); ArrayList<Integer> walkpath = new ArrayList<Integer>(); Integer u = v; walkpath.add(v); while (status == 1) // keep moving until status = 0 { u = rw.move(G, u); if (u == null) // no neighbors break; if (!walkpath.contains(u)) walkpath.add(u); status = rw.stay_move(); } // System.out.println("walking length: "+ Integer.toString(walkpath.size())); for (int i = 0; i < walkpath.size(); i++) for (int j = i + 1; j < walkpath.size(); j++) { int m = walkpath.get(i); int n = walkpath.get(j); if (!G.containsEdge(m, n)) { double distance = Math.abs(socialposition.get(m) - socialposition.get(n)); double prob = linkprob(distance, (j - i)); if (random.nextDouble() < prob) { G.setEdgeWeight((DefaultWeightedEdge) G.addEdge(m, n), 1); } } else { DefaultWeightedEdge edge = G.getEdge(m, n); G.setEdgeWeight(edge, G.getEdgeWeight(edge) + 1); } } return; }
private static void calculateBestProfit() { ArrayList<GraphNode> tp = graph.topologicalSort(); for (GraphNode g : tp) { for (GraphEdge e : g.goingEdges) { relax(e); } } ArrayList<GraphNode> lp = getLongestPath(); System.out.print("The longest path is "); for (int i = 0; i < lp.size(); i++) { System.out.print(lp.get(i)); if (i != lp.size() - 1) { System.out.print("-"); } } System.out.print(" and the total gain is "); int total = 0; int currentKnapsack = 0; for (int i = 0; i < lp.size(); i++) { currentKnapsack = oneZeroKnapsack(lp.get(i).room); total += currentKnapsack; System.out.print(currentKnapsack); if (i != lp.size() - 1) { System.out.print("+"); } else { System.out.print("=" + total + "TL"); } } }
/* * Used by the program to figure out which neurons should be computed first. * Bubble sort, meh */ public void bubbleSortNeurons() { int size = neurons.size(); double[] xneuron = new double[size]; neuronOrder = new ArrayList<Integer>(); for (int i = 0; i < size; i++) { xneuron[i] = neurons.get(i).getx(); neuronOrder.add(i); } int lowest; double temp; double temp2; for (int i = 0; i < size; i++) { lowest = i; for (int j = i + 1; j < size; j++) { if (xneuron[j] < xneuron[lowest]) { lowest = j; } } temp = xneuron[i]; xneuron[i] = xneuron[lowest]; xneuron[lowest] = temp; temp = neuronOrder.get(i); temp2 = neuronOrder.get(lowest); neuronOrder.set(i, (int) temp2); neuronOrder.set(lowest, (int) temp); } }
// TODO: if uploadingComplete() when activity backgrounded, won't work. public void uploadingComplete(ArrayList<String> result) { int resultSize = result.size(); boolean success = false; if (resultSize == totalCount) { Toast.makeText( this, getString(R.string.upload_all_successful, totalCount), Toast.LENGTH_SHORT) .show(); success = true; } else { String s = totalCount - resultSize + " of " + totalCount; Toast.makeText(this, getString(R.string.upload_some_failed, s), Toast.LENGTH_LONG).show(); } Intent in = new Intent(); in.putExtra(GlobalConstants.KEY_SUCCESS, success); setResult(RESULT_OK, in); // for each path, update the status FileDbAdapter fda = new FileDbAdapter(this); fda.open(); for (int i = 0; i < resultSize; i++) { Cursor c = fda.fetchFilesByPath(result.get(i), null); if (c != null) { if (c.getString(c.getColumnIndex(FileDbAdapter.KEY_STATUS)) .equals(FileDbAdapter.STATUS_COMPLETED)) fda.updateFile(result.get(i), FileDbAdapter.STATUS_SUBMITTED, null); } } fda.close(); finish(); }
@Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); // Changed to ViewHolder and Picasso error load as per feedback received ViewHolder holder = new ViewHolder(); // Inflate view if it is null if (convertView == null) { convertView = inflater.inflate(R.layout.grid_item, null); holder.imageView = (ImageView) convertView.findViewById(R.id.movie_poster); MovieDetailDO movie = movieList.get(position); convertView.setTag(holder); Picasso.with(context) .load(movie.getPoster_path()) // .placeholder(R.drawable.def_pos) .error(R.drawable.def_pos) .into(holder.imageView); } else { holder.imageView = (ImageView) convertView.findViewById(R.id.movie_poster); MovieDetailDO movie = movieList.get(position); convertView.setTag(holder); Picasso.with(context) .load(movie.getPoster_path()) // .placeholder(R.drawable.def_pos) .error(R.drawable.def_pos) .into(holder.imageView); } return convertView; }
public int valider( final List<WXSElement> sousElements, final int start, final boolean insertion) { if (elements.size() == 0) return (start); int[] occurences = new int[elements.size()]; for (int i = 0; i < elements.size(); i++) occurences[i] = 0; int nb = 0; for (int i = start; i < sousElements.size(); i++) { final WXSElement sousElement = sousElements.get(i); boolean trouve = false; for (int j = 0; j < elements.size(); j++) { if (sousElement == elements.get(j)) { trouve = true; occurences[j]++; break; } } if (!trouve) break; nb++; } for (int i = 0; i < elements.size(); i++) if (occurences[i] > 1) return (start); if (!insertion) { for (int i = 0; i < elements.size(); i++) if (occurences[i] == 0 && !elements.get(i).estOptionnel()) return (start); } return (start + nb); }
public ArrayList<SchedulePiece> toSchedulePieces() { if (isScheduleUpdated) { // schedulePieces = null; schedulePieces = new ArrayList<SchedulePiece>(); isScheduleUpdated = false; // generate initial or additional schedule pieces Collections.sort(scheduleRecords); int previousTime = scheduleRecords.get(0).time; HashSet<Integer> hset = new HashSet<Integer>(); hset.add(scheduleRecords.get(0).scIndex); for (int index = 1; index < scheduleRecords.size(); index++) { ScheduleRecord r = scheduleRecords.get(index); // found the new piece? if (r.time != previousTime) { // finish and save the old piece // schedulePieces.add(new SchedulePiece(r.time, (Integer[]) hset.toArray())); schedulePieces.add(new SchedulePiece(previousTime, hset.toArray())); previousTime = r.time; } if (r.isStart) hset.add(r.scIndex); else hset.remove(r.scIndex); } // last piece schedulePieces.add(new SchedulePiece(previousTime, hset.toArray())); } return schedulePieces; }
/** * find the progress of a particular topic based on its difficulty level * * @param userId * @param topic * @param difficulty * @return quizGradingProgress * @throws Exception */ public static double findTopicDifficultyProgress(int userId, String topic, String difficulty) throws Exception { QuizAttempt quizAttempt = new QuizAttempt(); ArrayList<Integer> userQuizIds = quizAttempt.getUserQuizIds(userId); ArrayList<Double> userQuizGrades = new ArrayList<Double>(); for (int i = 0; i < userQuizIds.size(); i++) { QuizSlot quizSlot = new QuizSlot(); // get the question ids of questions belonging to a particular quiz ArrayList<Integer> questionIds = quizSlot.getDifficultyAndTopicWiseQuestionIdsOfAQuiz( userQuizIds.get(i), topic, difficulty); double quizGradingProgress = Progress.findQuizProgress(questionIds, userId); userQuizGrades.add(quizGradingProgress); } double quizProgress = 0; for (int i = 0; i < userQuizGrades.size() - 1; i++) { if (userQuizGrades.get(i + 1) >= userQuizGrades.get(i)) { quizProgress += 1; } } double quizGradingProgress = 0; if (quizProgress != 0 && userQuizGrades.size() > 1) { quizGradingProgress = quizProgress / (userQuizGrades.size() - 1); } return quizGradingProgress; }
@Override public View getView(int position, View bankView, ViewGroup parent) { // set the rowview View rowView = bankView; // reuse views if (rowView == null) { // if the row view is not null then inflate for display LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rowView = inflater.inflate(R.layout.password_bank_item, null); } // get the text views and set the values to the values in the list TextView username = (TextView) rowView.findViewById(R.id.value_username); TextView website = (TextView) rowView.findViewById(R.id.value_website); TextView password = (TextView) rowView.findViewById(R.id.value_password); TextView expiration = (TextView) rowView.findViewById(R.id.value_expires); username.setText(PasswordInfoArrayList.get(position).getUsername()); website.setText(PasswordInfoArrayList.get(position).getWebsite()); password.setText(PasswordInfoArrayList.get(position).getPassword()); DateHelper expires = PasswordInfoArrayList.get(position).getExpiration(); boolean expired = expires.isLaterThan(DateHelper.getCurrentDate()); if (expired) { expiration.setTextColor(Color.RED); } String expStr = PasswordInfoArrayList.get(position).getExpiration().toString(); expiration.setText(expStr); return rowView; }
@Override public void reduce( Text moviePair, Iterator<Text> ratings, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { ArrayList<Double> ratings1 = new ArrayList<Double>(); ArrayList<Double> ratings2 = new ArrayList<Double>(); double numRatings = 0; double totRating1 = 0, totrating2 = 0; while (ratings.hasNext()) { String[] rating = ratings.next().toString().split(","); ratings1.add(Double.parseDouble(rating[0])); ratings2.add(Double.parseDouble(rating[1])); totRating1 += Double.parseDouble(rating[0]); totrating2 += Double.parseDouble(rating[1]); numRatings += 1; } double avgRating1 = totRating1 / numRatings; double avgRating2 = totrating2 / numRatings; double sum1 = 0.0, sum2 = 0.0, sumProduct = 0.0; for (int i = 0; i < numRatings; i++) { sum1 += Math.pow((ratings1.get(i) - avgRating1), 2); sum2 += Math.pow((ratings2.get(i) - avgRating2), 2); sumProduct += (ratings1.get(i) - avgRating1) * (ratings2.get(i) - avgRating2); } double corr = sumProduct / (Math.sqrt(sum1) * Math.sqrt(sum2)); System.out.println(sum1 + "," + sum2 + "," + sumProduct + "," + corr); if (Double.isNaN(corr)) { corr = 0; } output.collect(moviePair, new Text(corr + "")); }