Compute the deletion score (Equation 6 in the paper).
778312
def get_deletion_score(source_counts, prediction_counts, target_counts, beta=0):
  """"""
  source_not_prediction_counts = source_counts - prediction_counts
  source_not_target_counts = source_counts - target_counts
  true_positives = sum((source_not_prediction_counts &
                        source_not_target_counts).values())
  selected = sum(source_not_prediction_counts.values())
  relevant = sum(source_not_target_counts.values())
  return _get_fbeta_score(true_positives, selected, relevant, beta=beta)
505059
def _compute_vline_scores(self):
        
        M, N, L = self.M, self.N, self.L
        vline_score = {}
        for x in range(M):
            laststart = [0 if (x, 0, 1, k) in self else None for k in range(L)]
            for y in range(N):
                block = [0] * (y + 1)
                for k in range(L):
                    if (x, y, 1, k) not in self:
                        laststart[k] = None
                    elif laststart[k] is None:
                        laststart[k] = y
                        block[y] += 1
                    elif y and (x, y, 1, k) not in self[x, y - 1, 1, k]:
                        laststart[k] = y
                    else:
                        for y1 in range(laststart[k], y + 1):
                            block[y1] += 1
                for y1 in range(y + 1):
                    vline_score[x, y1, y] = block[y1]
        self._vline_score = vline_score
199794
public static double score(ComputationGraph model, MultiDataSetIterator testData, boolean average) {
        //TODO: do this properly taking into account division by N, L1/L2 etc
        double sumScore = 0.0;
        int totalExamples = 0;
        while (testData.hasNext()) {
            MultiDataSet ds = testData.next();
            long numExamples = ds.getFeatures(0).size(0);
            sumScore += numExamples * model.score(ds);
            totalExamples += numExamples;
        }

        if (!average)
            return sumScore;
        return sumScore / totalExamples;
    }
1109855
def prunebyscore(self, score, retainequalscore=False):
        """"""
        if retainequalscore:
            if self.minimize:
                f = lambda x: x[0] <= score
            else:
                f = lambda x: x[0] >= score
        else:
            if self.minimize:
                f = lambda x: x[0] < score
            else:
                f = lambda x: x[0] > score
        self.data = filter(f, self.data)
50194
def _compute_weight_std(self, C, mag):
        
        if mag < 6.0:
            return C['a1']
        elif mag >= 6.0 and mag < 6.5:
            return C['a1'] + (C['a2'] - C['a1']) * ((mag - 6.0) / 0.5)
        else:
            return C['a2']
319915
def _compute_hline_scores(self):
        
        M, N, L = self.M, self.N, self.L
        hline_score = {}
        for y in range(N):
            laststart = [0 if (0, y, 0, k) in self else None for k in range(L)]
            for x in range(M):
                block = [0] * (x + 1)
                for k in range(L):
                    if (x, y, 0, k) not in self:
                        laststart[k] = None
                    elif laststart[k] is None:
                        laststart[k] = x
                        block[x] += 1
                    elif x and (x, y, 0, k) not in self[x - 1, y, 0, k]:
                        laststart[k] = x
                    else:
                        for x1 in range(laststart[k], x + 1):
                            block[x1] += 1
                for x1 in range(x + 1):
                    hline_score[y, x1, x] = block[x1]
        self._hline_score = hline_score
139935
def _compute_term_5(self, C, mag, R):
        
        return (
            (C['a20'] + C['a21'] * mag + C['a22'] * np.power(mag, 2) +
             C['a23'] * np.power(mag, 3)) * np.power(R, 4)
        )
633536
def compute_score(self):
        """"""
        # LOGGER.info("Begin scoring")
        cases = self.get_configured_tests() | set(self.result.cases)
        scores = DataFrame({"score": 0.0, "max": 1.0},
                           index=sorted(cases))
        self.result.setdefault("score", dict())
        self.result["score"]["sections"] = list()
        # Calculate the scores for each test individually.
        for test, result in iteritems(self.result.cases):
            # LOGGER.info("Calculate score for test: '%s'.", test)
            # Test metric may be a dictionary for a parametrized test.
            metric = result["metric"]
            if hasattr(metric, "items"):
                result["score"] = test_score = dict()
                total = 0.0
                for key, value in iteritems(metric):
                    value = 1.0 - value
                    total += value
                    test_score[key] = value
                # For some reason there are parametrized tests without cases.
                if len(metric) == 0:
                    metric = 0.0
                else:
                    metric = total / len(metric)
            else:
                metric = 1.0 - metric
            scores.at[test, "score"] = metric
            scores.loc[test, :] *= self.config["weights"].get(test, 1.0)
        score = 0.0
        maximum = 0.0
        # Calculate the scores for each section considering the individual test
        # case scores.
        for section_id, card in iteritems(
            self.config['cards']['scored']['sections']
        ):
            # LOGGER.info("Calculate score for section: '%s'.", section_id)
            cases = card.get("cases", None)
            if cases is None:
                continue
            card_score = scores.loc[cases, "score"].sum()
            card_total = scores.loc[cases, "max"].sum()
            # Format results nicely to work immediately with Vega Bar Chart.
            section_score = {"section": section_id,
                             "score": card_score / card_total}
            self.result["score"]["sections"].append(section_score)
            # Calculate the final score for the entire model.
            weight = card.get("weight", 1.0)
            score += card_score * weight
            maximum += card_total * weight
        self.result["score"]["total_score"] = score / maximum
786388
public int logPrecision(int recall) {
    int totaltaken = 0;
    int rightIndex = numSamples() - 1; //next right candidate
    int leftIndex = 0; //next left candidate
    int totalcorrect = 0;

    while (totaltaken < recall) {
      double confr = Math.abs(scores[rightIndex] - .5);
      double confl = Math.abs(scores[leftIndex] - .5);
      int chosen = leftIndex;
      if (confr > confl) {
        chosen = rightIndex;
        rightIndex--;
      } else {
        leftIndex++;
      }
      //System.err.println("chose "+chosen+" score "+scores[chosen]+" class "+classes[chosen]+" correct "+correct(scores[chosen],classes[chosen]));
      if ((scores[chosen] >= .5) && (classes[chosen] == 1)) {
        totalcorrect++;
      }
      if ((scores[chosen] < .5) && (classes[chosen] == 0)) {
        totalcorrect++;
      }
      totaltaken++;
    }

    return totalcorrect;
  }
979549
def score(self):
        ''
        working_board = np.copy(self.board)
        while EMPTY in working_board:
            unassigned_spaces = np.where(working_board == EMPTY)
            c = unassigned_spaces[0][0], unassigned_spaces[1][0]
            territory, borders = find_reached(working_board, c)
            border_colors = set(working_board[b] for b in borders)
            X_border = BLACK in border_colors
            O_border = WHITE in border_colors
            if X_border and not O_border:
                territory_color = BLACK
            elif O_border and not X_border:
                territory_color = WHITE
            else:
                territory_color = UNKNOWN  # dame, or seki
            place_stones(working_board, territory_color, territory)

        return np.count_nonzero(working_board == BLACK) - np.count_nonzero(working_board == WHITE) - self.komi
66943
private DocInfo computeParametersForDoc(ArrayList<ArrayList<TextPiece>> wordsByPage) {
    	DocInfo docInfo = new DocInfo();

    	float docTitleFont = 0;
    	float[][] scaleListsWithTextAmount = new float[5000][2]; 
    	int scaleNum = 0;
	

    	int pageNum = 0;
    	for (ArrayList<TextPiece> wordsOfAPage : wordsByPage) {
    		pageNum++;
    		// ArrayList<TextPiece> linesOfAPage = new ArrayList<TextPiece>();
    		// TextPiece line = null;
    		for (int i = 0; i < wordsOfAPage.size(); i++)
    		{
    			// TextPiece prevWord = (i == 0) ? null : wordsOfAPage.get(i -	// 1);
    			TextPiece currentWord = wordsOfAPage.get(i);
    			// get the document title font size
    			if ( (pageNum == 1) && (currentWord.getY()<400) )
    			{
    				if (docTitleFont < currentWord.getFontSize())
    					docTitleFont = currentWord.getFontSize();
    			}
    			//get the document body text font
    			if (scaleNum==0) {
    				scaleListsWithTextAmount[0][0] = Math.max(currentWord.getXScale(), currentWord.getFontSize());
    				scaleListsWithTextAmount[0][1] = currentWord.getWidth();
    				scaleNum++;
    			}
    			else {
    				boolean notExist = true; 
    				for (int m=0; m<scaleNum; m++) {
    					if (scaleListsWithTextAmount[m][0]== Math.max(currentWord.getXScale(), currentWord.getFontSize())) {
    						scaleListsWithTextAmount[m][1] = scaleListsWithTextAmount[m][1] + currentWord.getWidth();	//calculate the text width for each scale is better than just counting the line number
    						notExist=false;
    					}
    				}
    				if (notExist==true) {
    					scaleListsWithTextAmount[scaleNum][0] =  Math.max(currentWord.getXScale(), currentWord.getFontSize());
    					scaleListsWithTextAmount[scaleNum][1] = currentWord.getWidth();
    					scaleNum++;
    				}
    			}//end else
    		}//end for()
    	}//for()
    	float maxLineNum = 0;
    	int bodyTextScaleIndex=0;
    	for (int j=0; j<scaleNum; j++) {
    		if (scaleListsWithTextAmount[j][1]>maxLineNum) {
    			maxLineNum = scaleListsWithTextAmount[j][1];
    			bodyTextScaleIndex=j;
    		}
    	}
	
    	/*
    	 * Calculates other background characters----------
    	 */
    	float ave_LineGap = (float)0.1; //this is ave_LineGap_thisPage in old version
    	float ave_X_Gap_inLine = (float)0.1;
    	int lineNumInBodyFont = 1;
    	int sameLineObj=1;
    	float minX = 1000;
        float maxX = 0;
        float minY = 1000;
        float maxY = 0;
        float aveCharWidthInDoc = (float)0.0000001;
        int charNumInWholeDoc = 1;
        
    	for (ArrayList<TextPiece> wordsOfAPage : wordsByPage) {
    		for (int i = 1; i < wordsOfAPage.size(); i++) {
    			/*
    			 * Calculates ave_LineGap
    			 */
    			TextPiece currentWord = wordsOfAPage.get(i);
    			TextPiece prevWord = wordsOfAPage.get(i-1);
    			if (Math.max(currentWord.getXScale(), currentWord.getFontSize())==scaleListsWithTextAmount[bodyTextScaleIndex][0]) { //only consider the text pieces that in the body text font
    				if ( (currentWord.getY()-prevWord.getY()-prevWord.getHeight()>(float)0.0) &&
    				(currentWord.getY()-prevWord.getY()-prevWord.getHeight()<prevWord.getHeight()) ) {//reduce the big gap noise
    					ave_LineGap = ave_LineGap + (currentWord.getY()-prevWord.getY());
    					lineNumInBodyFont++;
    				}
    			
    				/*
    				 * Gets the boundary of the doc page-
    				 */
    				if ( (currentWord.getX()<minX) && (currentWord.getX()>0) )  
    					minX = currentWord.getX();    			
    				if ( (currentWord.getX()+currentWord.getWidth()+currentWord.getWidthOfSpace())>maxX) 
    					maxX = currentWord.getX()+currentWord.getWidth()+currentWord.getWidthOfSpace();
    				if ( (currentWord.getY()<minY) && (currentWord.getY()>0) ) 
    					minY =currentWord.getY();
    				if (currentWord.getY()>maxY) maxY = currentWord.getY();
				
				
    				/*
    				 * Calculates ave_X_Gap_inLine
    				 */
    				if ( (currentWord.getY()==prevWord.getY()) && 
    					(currentWord.getX()-prevWord.getX()-prevWord.getWidth()>0) ) {
    						ave_X_Gap_inLine = ave_X_Gap_inLine + currentWord.getX()-prevWord.getX()-prevWord.getWidth();
    						sameLineObj++;
    				}
    				
    				/*
    				 * calculates the average width of each character in the whole document
    				 */
    				aveCharWidthInDoc = aveCharWidthInDoc + currentWord.getWidth();
    				charNumInWholeDoc = charNumInWholeDoc + currentWord.getText().length();
    			}//end if(lines in body text font)
			}//end (for a page)
    	}//end for(all pages)
    	ave_LineGap = ave_LineGap/(float)lineNumInBodyFont;
    	ave_X_Gap_inLine = ave_X_Gap_inLine/(float)sameLineObj;
    	aveCharWidthInDoc = aveCharWidthInDoc/(float)charNumInWholeDoc;
    	docInfo.setTitleFont(docTitleFont);
    	docInfo.setBodyTextScale(scaleListsWithTextAmount[bodyTextScaleIndex][0]);
       	docInfo.setAverageLineGap(ave_LineGap);
    	docInfo.setMinX(minX);
    	docInfo.setMaxX(maxX);
    	docInfo.setMinY(minY);
    	docInfo.setMaxY(maxY);
    	docInfo.setAverageXGap(ave_X_Gap_inLine);
	   	docInfo.setAverageCharWidth(aveCharWidthInDoc);
    	//System.out.println("The text body font size is: " + docInfo.getBodyTextScale());
    	//System.out.println("ave_LineGap: " + ave_LineGap);
    	//System.out.println("ave_X_Gap_inLine: " + ave_X_Gap_inLine);
    	//System.out.println("aveCharWidthInDoc: " + aveCharWidthInDoc);
    	//System.out.println("(MinX, maxX) (MinY, MaxY): (" + minX + "," + maxX + "); (" + minY + "," + maxY +").");
    	//System.out.println();
    	
    	/*
    	 * TODO! Unfinished
    	 * Judges whether this doc only has one column
    	 */
    	float middleX = docInfo.getMinX() + (docInfo.getMaxX()-docInfo.getMinX())/2;
        docInfo.setMiddleX(middleX);
    	docInfo.setMiddleArea_X(middleX-3);
    	docInfo.setMiddleArea_EndX(middleX+3);
    	int lineNum_blockMiddle = 0;
    	for (ArrayList<TextPiece> wordsOfAPage : wordsByPage) {
    		for (int i = 1; i < wordsOfAPage.size(); i++) {
    			TextPiece currentWord = wordsOfAPage.get(i);
    			TextPiece prevWord = wordsOfAPage.get(i-1);
    			
    			//todo
    		}
    	}
    	return docInfo;
    }
1276182
function ( t, p0, p1, p2, p3 ) {

		return - 3 * p0 * ( 1 - t ) * ( 1 - t )  +
			3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
			6 * t *  p2 * ( 1 - t ) - 3 * t * t * p2 +
			3 * t * t * p3;

	}
935385
def total_marks(self):
        """"""
        total = 0
        for answer in self.answers:
            for number, part in enumerate(answer):
                if number>0:
                    if part[2]>0:
                        total+=part[2]
        return total
870421
def compute_agreement_score(num_matches, num1, num2):
    
    denom = num1 + num2 - num_matches
    if denom == 0:
        return 0
    return num_matches / denom
673781
function score(data, candidate) {
    var result = 0;
    /*
        Scoring calculations here
    */

    //Last Name
    if (!data.name.last || !candidate.name.last) {
        result = result + 0;
    } else if (data.name.last.toUpperCase() === candidate.name.last.toUpperCase()) {
        result = result + 9.58;
    } else if (data.name.last.toUpperCase().substring(0, 3) === candidate.name.last.toUpperCase().substring(0, 3)) {
        result = result + 5.18;
    } else if (data.name.last.toUpperCase().substring(0, 3) !== candidate.name.last.toUpperCase().substring(0, 3)) {
        result = result - 3.62;
    }

    //First Name
    if (!data.name.first || !candidate.name.first) {
        result = result + 0;
    } else if (data.name.first.toUpperCase() === candidate.name.first.toUpperCase()) {
        result = result + 6.69;
    } else if (data.name.first.toUpperCase().substring(0, 3) === candidate.name.first.toUpperCase().substring(0, 3)) {
        result = result + 3.37;
    } else if (data.name.first.toUpperCase().substring(0, 3) !== candidate.name.first.toUpperCase().substring(0, 3)) {
        result = result - 3.27;
    }

    //Middle Initial
    if (!data.name.middle || !candidate.name.middle) {
        result = result + 0;
    } else if (data.name.middle.toUpperCase().substring(0, 1) === candidate.name.middle.toUpperCase().substring(0, 1)) {
        result = result + 3.65;
    }

    //DOB
    if (!data.dob || !candidate.dob) {
        result = result + 0;
    } else if (data.dob.substring(0, 10) === candidate.dob.substring(0, 10)) {
        result = result + 6.22;
    }

    //Initials
    result = result + 0;

    return result;
}
839411
def deleted(self, key, value):
    
    deleted = self.get('deleted')
    book_series = self.get('book_series')

    if not deleted:
        normalized_a_values = [el.upper() for el in force_list(value.get('a'))]
        normalized_c_values = [el.upper() for el in force_list(value.get('c'))]
        if 'DELETED' in normalized_a_values or 'DELETED' in normalized_c_values:
            deleted = True

    if not book_series:
        normalized_a_values = [el.upper() for el in force_list(value.get('a'))]
        if 'BOOKSERIES' in normalized_a_values:
            book_series = True

    self['book_series'] = book_series
    return deleted
110209
protected function _calculateLetterScore()
    {
        $score = 0;

        foreach (array (self::CLASS_UPPER, self::CLASS_LOWER) as $class) {
            $letterCount = $this->_getClassCount($class);

            if ($letterCount != $this->_length) {
                if ($letterCount > 0) {
                    $score += ($this->_length - $letterCount) * 2;
                }
            }
        }

        return $score;
    }