Weighted edit distance.
420488
private double weightedEdit(char[] x, char[] y) {
        // switch parameters to use the shorter one as y to save space.
        if (x.length < y.length) {
            char[] swap = x;
            x = y;
            y = swap;
        }

        int radius = (int) Math.round(r * Math.max(x.length, y.length));

        double[][] d = new double[2][y.length + 1];

        d[0][0] = 0.0;
        for (int j = 1; j <= y.length; j++) {
            d[0][j] = d[0][j - 1] + weight[0][y[j]];
        }

        for (int i = 1; i <= x.length; i++) {
            d[1][0] = d[0][0] + weight[x[i]][0];

            int start = 1;
            int end = y.length;

            if (radius > 0) {
                start = i - radius;
                if (start > 1)
                    d[1][start - 1] = Double.POSITIVE_INFINITY;
                else
                    start = 1;

                end = i + radius;
                if (end < y.length)
                    d[1][end+1] = Double.POSITIVE_INFINITY;
                else
                    end = y.length;
            }

            for (int j = start; j <= end; j++) {
                double cost = weight[x[i - 1]][y[j - 1]];
                d[1][j] = Math.min(
                        d[0][j] + weight[x[i - 1]][0], // deletion
                        d[1][j - 1] + weight[0][y[j - 1]], // insertion
                        d[0][j - 1] + cost); // substitution
            }

            double[] swap = d[0];
            d[0] = d[1];
            d[1] = swap;
        }

        return d[0][y.length];
    }
48457
def updateEditorGeometry(self, editor, option, index):
        """"""
        qr = editor.frameGeometry()
        cp = QtGui.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)

        editor.move(qr.topLeft())
1301848
function buildEdits (Vs, a, b) {
  var edits = []

  var p = { x: a.length, y: b.length }
  for (var D = Vs.length - 1; p.x > 0 || p.y > 0; D -= 1) {
    var V = Vs[D]
    var k = p.x - p.y

    var xEnd = V[k]

    var down = (k === -D || (k !== D && V[k - 1] < V[k + 1]))
    var kPrev = down ? k + 1 : k - 1

    var xStart = V[kPrev]
    var yStart = xStart - kPrev

    var xMid = down ? xStart : xStart + 1

    while (xEnd > xMid) {
      pushEdit(edits, a[xEnd - 1], false, false)
      xEnd -= 1
    }

    if (yStart < 0) break

    if (down) {
      pushEdit(edits, b[yStart], true, false)
    } else {
      pushEdit(edits, a[xStart], false, true)
    }

    p.x = xStart
    p.y = yStart
  }

  return edits.reverse()
}
646001
def word_diff(a,b):
  ''
  return translate_diff(a,rediff(splitpreserve(a),splitpreserve(b)))
104800
private double [] getDistanceWeightedVotes(double distances[], int[] nnIndices, Instances instances){

		double v[] = new double[this.maxClassValue +1];
        for (int nnIdx : nnIndices) {
            v[(int)instances.instance(nnIdx).classValue()] += 1./Math.max(distances[nnIdx], 0.000000001);
        }
		return v;
	}
1218958
private void diffClique(float[] weights, int p) {
		for (int t = 0; t < orders.length; t++) {
			if (data[p][t] == -1)
				continue;

			if (orders[t] == 0) {
				if (golds[p] != preds[p]) {
					int ts = data[p][t] + golds[p];
					int ps = data[p][t] + preds[p];
					adjust(weights, ts, ps);
				}
			}
			if (p > 0 && orders[t] == 1) {
				int ts = data[p][t] + (golds[p - 1] * ysize + golds[p]);
				int ps = data[p][t] + (preds[p - 1] * ysize + preds[p]);
				adjust(weights, ts, ps);
			}
		}
	}
556017
def gen_input_edit(sig_dic):
    '''
    
    '''
    if sig_dic['en'] == 'tag_file_download':
        html_str = HTML_TPL_DICT['input_edit_download'].format(
            sig_en=sig_dic['en'],
            sig_zh=sig_dic['zh'],
            sig_dic=sig_dic['dic'][1],
            sig_type=sig_dic['type']
        )
    else:
        html_str = HTML_TPL_DICT['input_edit'].format(
            sig_en=sig_dic['en'],
            sig_zh=sig_dic['zh'],
            sig_dic=sig_dic['dic'][1],
            sig_type=sig_dic['type']
        )
    return html_str
656956
def evaluate_similarity(args, token_embedding, ctx, logfile=None,
                        global_step=0):
    """"""

    results = []
    for similarity_function in args.similarity_functions:
        evaluator = nlp.embedding.evaluation.WordEmbeddingSimilarity(
            idx_to_vec=token_embedding.idx_to_vec,
            similarity_function=similarity_function)
        evaluator.initialize(ctx=ctx)
        if not args.no_hybridize:
            evaluator.hybridize()

        # Evaluate all datasets
        for (dataset_name, dataset_kwargs,
             dataset) in iterate_similarity_datasets(args):
            initial_length = len(dataset)
            dataset_coded = [[
                token_embedding.token_to_idx[d[0]],
                token_embedding.token_to_idx[d[1]], d[2]
            ] for d in dataset if d[0] in token_embedding.token_to_idx
                             and d[1] in token_embedding.token_to_idx]
            num_dropped = initial_length - len(dataset_coded)

            # All words are unknown
            if not len(dataset_coded):
                correlation = 0
            else:
                words1, words2, scores = zip(*dataset_coded)
                pred_similarity = evaluator(
                    mx.nd.array(words1, ctx=ctx), mx.nd.array(words2, ctx=ctx))
                sr = stats.spearmanr(pred_similarity.asnumpy(),
                                     np.array(scores))
                correlation = sr.correlation

            logging.info(
                'Spearman rank correlation on %s (%s pairs) %s with %s:\t%s',
                dataset.__class__.__name__, len(dataset_coded),
                str(dataset_kwargs), similarity_function, correlation)

            result = dict(
                task='similarity',
                dataset_name=dataset_name,
                dataset_kwargs=dataset_kwargs,
                similarity_function=similarity_function,
                spearmanr=correlation,
                num_dropped=num_dropped,
                global_step=global_step,
            )
            log_similarity_result(logfile, result)
            results.append(result)

    return results
1193475
def editors(self, value):
        """"""
        warnings.warn(
            _ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE),
            DeprecationWarning,
        )
        self[EDITOR_ROLE] = value
1303946
def sort_by_distance(cls, consumer_offsets_metadata):
        """"""
        sorted_offsets = sorted(
            list(consumer_offsets_metadata.items()),
            key=lambda topic_offsets: sum([o.highmark - o.current for o in topic_offsets[1]])
        )
        return OrderedDict(sorted_offsets)
547578
function getEditDistance(values) {
  if (values.length === 2) {
    console.log(dice(values[0], values[1]) || 0)
  } else {
    process.stderr.write(help())
    process.exit(1)
  }
}
849759
function editLinks(data, newPath, oldPath) {
    let newData = data;
    newData = newData.split(oldPath).join(newPath);
    return newData;
}
567818
def semantic_distance(go_id1, go_id2, godag, branch_dist=None):
    '''
        
    '''
    return min_branch_length(go_id1, go_id2, godag, branch_dist)
199921
def edit_distance(seq1, seq2, action_function=lowest_cost_action, test=operator.eq):
    
    m = len(seq1)
    n = len(seq2)
    # Special, easy cases:
    if seq1 == seq2:
        return 0, n
    if m == 0:
        return n, 0
    if n == 0:
        return m, 0
    v0 = [0] * (n + 1)     # The two 'error' columns
    v1 = [0] * (n + 1)
    m0 = [0] * (n + 1)     # The two 'match' columns
    m1 = [0] * (n + 1)
    for i in range(1, n + 1):
        v0[i] = i
    for i in range(1, m + 1):
        v1[0] = i
        for j in range(1, n + 1):
            cost = 0 if test(seq1[i - 1], seq2[j - 1]) else 1
            # The costs
            ins_cost = v1[j - 1] + 1
            del_cost = v0[j] + 1
            sub_cost = v0[j - 1] + cost
            # Match counts
            ins_match = m1[j - 1]
            del_match = m0[j]
            sub_match = m0[j - 1] + int(not cost)

            action = action_function(ins_cost, del_cost, sub_cost, ins_match,
                                     del_match, sub_match, cost)

            if action in [EQUAL, REPLACE]:
                v1[j] = sub_cost
                m1[j] = sub_match
            elif action == INSERT:
                v1[j] = ins_cost
                m1[j] = ins_match
            elif action == DELETE:
                v1[j] = del_cost
                m1[j] = del_match
            else:
                raise Exception('Invalid dynamic programming option returned!')
                # Copy the columns over
        for i in range(0, n + 1):
            v0[i] = v1[i]
            m0[i] = m1[i]
    return v1[n], m1[n]
1182169
def correction(sentence, pos):
    ""
    word = sentence[pos]
    cands = candidates(word)
    if not cands:
        cands = candidates(word, False)
    if not cands:
        return word
    cands = sorted(cands, key=lambda w: P(w, sentence, pos), reverse=True)
    cands = [c[0] for c in cands]
    return cands
16121
def edit_matching_entry(program, arguments):
    """"""
    entry = program.select_entry(*arguments)
    entry.context.execute("pass", "edit", entry.name)
387860
def edit_distance(wordA,wordB):
    "
    if not type(wordA) is list:
        lettersA = tamil.utf8.get_letters(wordA)
    else:
        lettersA = wordA
    
    if not type(wordB) is list:
        lettersB = tamil.utf8.get_letters(wordB)
    else:
        lettersB = wordB
    n_A = len(lettersA)
    n_B = len(lettersB)
    dist_AB = [[0 for i in range(0,n_B+1)] for i in range(0,(n_A+1))]
    # Target prefix reached by insertion
    for j in range(1,n_B+1):
        dist_AB[0][j] = j
    for i in range(1,n_A+1):
        dist_AB[i][0] = i
    for j in range(1,n_B+1):
        for i in range(1,n_A+1):
            if (lettersA[i-1] == lettersB[j-1]):
                new_dist = dist_AB[i-1][j-1]
            else:
                new_dist = min( [dist_AB[i-1][j]+1, dist_AB[i][j-1]+1, dist_AB[i-1][j-1]+1] ) #del, ins, or sub
            dist_AB[i][j] = new_dist 
    return dist_AB[-1][-1]